Python subprocess.Popen和异步输出

Yur*_*sov 8 python subprocess asynchronous

我有简单的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()
Run Code Online (Sandbox Code Playgroud)

它工作正常,但脚本在写入所有输出文件之前完成其工作.实际上,我获得了数百个零大小的文件,并且完成编写输出和关闭句柄需要一些时间.任何人都可以解释为什么它的工作如此奇怪,是否有同步方式来做同样的工作?

谢谢

glg*_*lgl 17

之前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()
Run Code Online (Sandbox Code Playgroud)

要不就

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()
Run Code Online (Sandbox Code Playgroud)

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

[...]
    with open(file_path, "w") as f:
        subprocess.call(params_list, stdout=f)
Run Code Online (Sandbox Code Playgroud)