我可以使用下面的代碼在實時通過「Popen
捕捉的處理稱爲輸出:的Python - 捕捉實時多POPEN子進程的標準輸出到文件
p = subprocess.Popen(args,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
for line in iter(p.stdout.readline,''):
sys.stdout.write(line)
output, error = p.communicate()
這個偉大的工程。不過,我現在已經使用下面的代碼運行多個進程,所以我需要捕獲標準輸出爲每個進程文件:
for mapped_file in range(1,3):
#Fire the command in parallel
stdout = open(outfile + '.stdout', 'w')
p = subprocess.Popen(args,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout_list.append(stdout)
process_list.append(p)
#for line in iter(p.stdout.readline,''):
# stdout.write(line)
#Wait for all processes to continue
while len(process_list) > 0:
for process in process_list:
#Loop through the process to wait until all tasks finished
if not process.poll() is None:
output, error = process.communicate()
#Remove the process from the list because it has finished
process_list.remove(process)
#Sleep for 1 second in between iterations
time.sleep(1)
包括for line in iter(p.stdout.readline,''):...
代碼保持僅在第一循環執行代碼。
我怎樣才能將stdout
(並且大概是stderr
)實時的在我的循環內執行的每個進程捕獲到一個文件中?
你的第一個代碼示例可能死鎖如果子進程將在stderr上產生足夠的輸出的例子
。如果任何*子進程在stdout *或* stderr上產生足夠的輸出,則第二個代碼示例可能會死鎖。 – jfs