使用 subprocess.popen 和 subprocess.run 时得到不同的结果
Got different result when using subprocess.popen and subprocess.run
当我执行下面的程序时,它正确地列出了文件。
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"],
shell=True,
executable="/bin/bash",
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE)
my_std_out = foo.stdout.read().decode("utf-8")
请问我的第二部分程序有问题吗?
提前谢谢你!
我认为 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")
来自 python 文档:
“communicate() returns 元组 (stdout_data, stderr_data)。如果流以文本模式打开,则数据将为字符串;否则为字节。”
因此,如果你想通过 Popen 获得输出,你必须像这样从 communicate() 中解压返回的元组:
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"
当我执行下面的程序时,它正确地列出了文件。
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"],
shell=True,
executable="/bin/bash",
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE)
my_std_out = foo.stdout.read().decode("utf-8")
请问我的第二部分程序有问题吗?
提前谢谢你!
我认为 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")
来自 python 文档: “communicate() returns 元组 (stdout_data, stderr_data)。如果流以文本模式打开,则数据将为字符串;否则为字节。” 因此,如果你想通过 Popen 获得输出,你必须像这样从 communicate() 中解压返回的元组:
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"