【问题标题】:Python subprocess.Popen and asynchronous outputPython subprocess.Popen 和异步输出
【发布时间】:2011-11-26 18:32:38
【问题描述】:

我有简单的 Python 脚本来在 Windows 和 Linux 下执行测试套件。 每个测试都将其输出写入单独的文件。 我使用 subprocess.Popen 类循环执行shell命令。

每个 shell 命令都是这样开始的:

def system_execute(self, command, path, out_file):
    params_list = command.split(' ') 
    file_path = os.path.join(path, out_file)
    f = open(file_path, "w")
    subprocess.Popen(params_list, stdout=f)
    f.close()

它工作正常,但脚本在所有输出文件被写入之前完成它的工作。 实际上,我得到了数百个零大小的文件,完成写入输出和关闭句柄需要一些时间。 谁能解释它为什么如此奇怪的原因,是否有同步的方式来做同样的工作?

谢谢

【问题讨论】:

    标签: python asynchronous subprocess


    【解决方案1】:

    f.close() 之前,您必须为我们的子流程wait()

    def system_execute(self, command, path, out_file):
        params_list = command.split(' ') 
        file_path = os.path.join(path, out_file)
        f = open(file_path, "w")
        sp = subprocess.Popen(params_list, stdout=f)
        sp.wait()
        f.close()
    

    或者只是

    def system_execute(self, command, path, out_file):
        params_list = command.split(' ') 
        file_path = os.path.join(path, out_file)
        f = open(file_path, "w")
        subprocess.call(params_list, stdout=f)
        f.close()
    

    (或者,为了更容易处理文件,

    [...]
        with open(file_path, "w") as f:
            subprocess.call(params_list, stdout=f)
    

    【讨论】: