的原因是因为子进程的输出默认是通过标准输出(stdout)进行的,而在循环中调用子进程时,标准输出并不会立即刷新到文件中,而是在缓冲区中累积一定量的数据后才会进行刷新。
要解决这个问题,可以通过以下几种方式:
subprocess.Popen
的stdout
参数将子进程的输出重定向到一个文件对象,然后手动刷新文件对象。示例代码如下:import subprocess
with open('output.txt', 'w') as f:
process = subprocess.Popen(['command'], stdout=f)
while True:
# 循环中的其他操作
f.flush() # 刷新文件对象
subprocess.Popen
的universal_newlines=True
参数,将子进程的输出转换为文本模式,这样输出会立即刷新到文件中。示例代码如下:import subprocess
with open('output.txt', 'w') as f:
process = subprocess.Popen(['command'], stdout=f, universal_newlines=True)
while True:
# 循环中的其他操作
sys.stdout.flush()
手动刷新标准输出。示例代码如下:import subprocess
import sys
process = subprocess.Popen(['command'], stdout=subprocess.PIPE)
while True:
# 循环中的其他操作
sys.stdout.flush() # 刷新标准输出
以上是解决子进程在循环中调用时不会输出到文件的几种方法,根据具体情况选择适合的方式。
领取专属 10元无门槛券
手把手带您无忧上云