将subprocess stdout写入文件:冻结之前缺少最后一行

时间:2018-06-04 11:50:18

标签: django python-3.x logging subprocess iis-7.5

子进程stdout保存在本地文件中,但是当这个进程进入无限循环时,它似乎没有在无限循环到文件之前打印最后一个stdout行。

pythonScript.py子进程在文件夹中创建文件。创建文件后,它会向stdout文件打印“file_number_78.txt is created”之类的内容。当它进入infite循环时,我可能会注意到创建的最后一个文件是“file_number_211.txt”,但是在stdout文件中读取的最后一条消息是“file_number_207.txt is created”。所以看起来一些stdout信息被卡在缓冲区中而没有(还)写入stdout文件。

我尝试过buffsize = 1和universal_newlines = True,没有buffsize参数,没有stdin或者使用creationflags = DETACHED_PROCESS但是到目前为止我没有尝试过所需的输出。

点击按钮后,从views.py在django网站上调用长时间运行的子进程:

argString=' '+user+" "+email+" "+folder
command='python '+r'D:\pythonScript.py'+argString
with open("D:\folder\stdout_"+user+".txt", "w") as stdoutFile:
    with open("D:\folder\stderr_"+user+".txt", "w") as stderrFile:
        pythonProcess = subprocess.Popen(command,bufsize=0,shell=True,stdin=subprocess.PIPE,
                                         stdout=stdoutFile,stderr=stderrFile, encoding='utf8')

0 个答案:

没有答案