使用 subprocess.call 的 Python 执行顺序

标签 python subprocess

我在文件 abc.py 中有以下代码:

import subprocess
def evaluate():
    for i in range(5):
        print("Printing", i)
        subprocess.call(['ls', '-lrt'])
        print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
evaluate()

现在,当我使用 python abc.py > out.dat 调用时,输出文件包含五次“ls -lrt”的结果,然后是代码中的打印语句。 为什么会发生这种情况,如果我需要输出为:

printing 0

(results of ls -lrt here)

~~~~~~~~~~~~~~~~~~~~~~~

printing 1

.
.
.

等等..?

谢谢你..

最佳答案

在调用子进程之前,您需要刷新流:

import subprocess, sys
def evaluate():
    for i in range(5):
        print("Printing", i)
        sys.stdout.flush()
        subprocess.call(['ls', '-lrt'])
        print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
evaluate()

只要您写入终端(无需重定向),刷新就会自动逐行进行。然后您就不会注意到这个问题,因为 print() 在换行符处刷新。

一旦将输出重定向到文件,print() 语句就会注意到这一点,并仅在某个缓冲区已满时(以及终止时)自动刷新。

子进程 (ls) 执行相同的操作,但使用自己的缓冲区。它首先终止,因此它的输出首先在文件中。

关于使用 subprocess.call 的 Python 执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42644990/

相关文章:

python - 使用 python 子进程时 ANSI 颜色丢失

python-3.x - 如何获取用户的桌面位置

Python os.st_uid 只返回值 0

python - 为什么 Python 有最大递归深度?

python - twinx 杀死蜱标签颜色

python - 计算 for 循环期间的运行总计 - Python

python - uWSGI 无法识别 --http 或 --wsgi-file 选项

python - Linux 管道读完但想丢弃其余部分

python - 您可以只与子流程通信一次吗?

python-3.x - PythonPDF : FileNotFoundError: [WinError 2] The system cannot find the file specified