Python3 使用 subprocess.call 时未按所需顺序打印输出

Python3 is not printing the output in the desired order when using subprocess.call

我试图用 Python3 编写一个自动化任务并使用 subprocess.call 因为我需要 运行 一些 shell 命令作为脚本的一部分,但是发现其中一个输出没有按我预期的正确顺序打印。

部分:

在 Python2:

[root@server101 ~]# cat check_kernel.py
#!/usr/bin/env python
import subprocess
print "Current running kernel version on the system is:\n", subprocess.call(["uname", "-r"])

输出:

[root@server101 ~]# ./check_kernel.py
Current running kernel version on the system is:
3.10.0-1160.45.1.el7.x86_64
0

在 Python3:

[root@server101 ~]# cat check_kernel.py
#!/usr/bin/env python3
import subprocess
print ("Current running kernel version on the system is:\n", subprocess.call(["uname", "-r"]))

输出:

[root@server101 ~]# ./check_kernel.py
3.10.0-1160.45.1.el7.x86_64
Current running kernel version on the system is:
 0

那么 subprocess.call 与 Python3 的真正区别是什么?

我是不是遗漏了什么或者我不应该将 subprocess.call 与 Python3 一起使用并将其更改为 subprocess.runsubprocess.Popen 是让子流程工作的唯一方法用 Python3 ?.

您的子进程自行打印输出,函数 return 是 return 代码。打印顺序可能会受到 Python 的输出缓冲设置的影响。

只需使用 subprocess.check_output 即可获得命令打印的输出。

import subprocess, shutil
print ("Current running kernel version on the system is:\n", subprocess.check_output([shutil.which("uname"), "-a"]))

编辑

和我想象的一样,Python2版本是

print "Current running kernel version on the system is:\n", subprocess.call(["uname", "-r"])

Python 2 print 语句按顺序计算并打印每个表达式。

Python 3 print function 只是一个普通的函数,所以参数先求值,函数打印求值

由于调用 uname 的副作用是打印 uname,它首先被打印,然后 print 做它的事情 - 打印文本和 call 的 return 值,零return代码。