问题描述
当我执行以下程序时,它会正确列出文件。
import subprocess
foo = subprocess.run("ls /home/my_home",shell=True,executable="/bin/bash",stdout=subprocess.PIPE,stdin=subprocess.PIPE,stderr=subprocess.PIPE)
my_std_out = foo.stdout.decode("utf-8")
但是在下面的程序中执行时,stdout中没有任何内容。
import subprocess
foo = subprocess.Popen(["ls /home/my_home"],stderr=subprocess.PIPE)
my_std_out = foo.stdout.read().decode("utf-8")
我想知道我的第二部分程序有什么问题吗?
预先谢谢!
解决方法
来自 python 文档: “communicate() 返回一个元组(stdout_data,stderr_data)。如果以文本模式打开流,则数据将为字符串;否则为字节。” 因此,如果您想通过 Popen 获得输出,您必须像这样从communication() 中解压返回的元组:
out,err = foo.communicate()
In [150]: out
Out[150]: b''
In [151]: err
Out[151]: b"ls: cannot access '/home/my_home': No such file or directory\n"
,
当您使用如下括号时,我认为bash命令和路径应放在引号之间
import subprocess foo = subprocess.Popen(["ls","/home/my_home"],shell=True,executable=/bin/bash,stdout=subprocess.PIPE,stdin=subprocess.PIPE,stderr=subprocess.PIPE) my_std_out = foo.stdout.read().decode("utf-8")