【发布时间】:2015-02-13 22:11:18
【问题描述】:
我正在运行一个 Python 脚本,该脚本旨在在 Windows 7 上启动一个 .bat 文件。该批处理文件运行某种蒙特卡洛程序 2 分钟。在这 2 分钟结束时,程序必须更新一个数据文件,我稍后将在同一个 Python 脚本中读取该文件,对输出进行一些数据分析,并在必要时重新启动同一个 .bat 文件。
我会无限期地执行此过程,直到获得满意的输出。
Python 代码如下所示
import os
import numpy as np
os.system('myBatch.bat > messages.txt')
while True:
# force flushing
fd = open("output.txt",'a')
fd.flush()
os.fsync(fd.fileno())
fd.close()
# read data
data = np.loadtxt("output.txt")
# some data analysis ...
# testing
if dataSatisfactory:
break
else:
os.system('myBatch.bat > messages.txt')
如您所见,我正在尝试强制刷新必须由程序在批处理文件中写入的 output.txt 文件。由于我无法控制这个已编译的可执行程序,因此在命令os.system('myBatch.bat > messages.txt') 之后输出文件没有得到更新,但只有在我杀死整个 python 进程之后才会更新。
我尝试在 #force flushing 之后添加 4 行,但显然仍然无法正常工作。
为了清楚起见,可执行文件的输入是output.txt以及输出,因此可执行文件必须覆盖文件output.txt.
messages.txt文件用于将可执行文件的所有消息从标准输出重定向到messages.txt。
有什么建议或提示吗?
注意:批处理文件如下所示
.\TheExecutable %output.txt
【问题讨论】:
-
TheExecutable %output.txt: 你为什么有一个百分号?
标签: windows python-2.7 batch-file