如何等待标准输出写入文件完成

2 投票
1 回答
2200 浏览
提问于 2025-04-16 23:47

我想等到程序把输出写入文件后再继续。有没有人知道我该怎么做?

这是相关的代码:

代码:选择全部

session = open("c:\\sessionID.txt", "w")

#Execute previous exe and output session to text file from the current directory
cmd = os.path.realpath(os.getcwd()) +"\\Program.exe"

cmd = [os.getcwd() + '\\AOSLaunch.exe']

Execute the cmd which executes the program.exe and the output is saved to the sessionID.txt file
process = subprocess.Popen(cmd, stdout=session)
session.close()

这里的问题是,程序.exe 启动并把输出保存到 stdout 可能需要一些时间,有时候 sessionID.txt 文件会是空的,因为花的时间太长了。我想确保 sessionID.txt 文件已经被 stdout 写入。

任何帮助都非常感谢。谢谢!

1 个回答

5

在启动进程后,使用 process.wait() 方法(具体可以参考Popen文档),这样它就会等到执行结束再继续进行其他操作....

撰写回答