Python 按时间顺序输出脚本/子流程
我正在开发一个python脚本,它以两种方式生成图像:首先创建基本图像,然后创建新图像与原始图像进行比较,如果两者之间存在差异,则输出。主脚本调用第二个脚本,该脚本执行实际比较 不过,我遇到的问题是,这两个脚本的输出没有按顺序排列。例如,下面是运行比较的输出:Python 按时间顺序输出脚本/子流程,python,python-2.7,subprocess,popen,Python,Python 2.7,Subprocess,Popen,我正在开发一个python脚本,它以两种方式生成图像:首先创建基本图像,然后创建新图像与原始图像进行比较,如果两者之间存在差异,则输出。主脚本调用第二个脚本,该脚本执行实际比较 不过,我遇到的问题是,这两个脚本的输出没有按顺序排列。例如,下面是运行比较的输出: DIFFERENTIAL RUNNING NOW 16:52:02.062000 *** image05.jpg MATCHES *** MARKER ONE: Differential happened yet? 16:51:51.82
DIFFERENTIAL RUNNING NOW 16:52:02.062000
*** image05.jpg MATCHES ***
MARKER ONE: Differential happened yet? 16:51:51.821000
MARKER TWO: Where's the Diff? 16:51:51.824000
==== Test\Dir ====
Copy Input
Start Comparison
Doing Comparison
我想要的格式更像这样:
MARKER ONE: Differential happened yet? 16:51:51.821000
MARKER TWO: Where's the Diff? 16:51:51.824000
==== Test\Dir ====
Copy Input
Start Comparison
Doing Comparison
DIFFERENTIAL RUNNING NOW 16:52:02.062000
*** image05.jpg MATCHES ***
所以我得到了我需要的输出,但是看看时间戳,它们是无序的(对于适当的组织,结果需要在“进行比较”部分之后出现)
代码流程如下(通常):
此时将启动第二个python脚本,它比较两个图像(主目录中的图像和临时目录中同名的图像)之间的像素,并报告有多少像素不同,将它们存储在.txt文件中,然后打印到控制台:
if os.path.isfile(tempImg):
try:
ouput = Popen(command, shell=True)
stdout, stderr = output.communicate()
if stdout is not None:
print stdout
if stderr is not None:
print "Error occurred during execution:"
print stderr
except OSError as e:
print "Execution failed: " + e
with open(output) as r:
result = r.read()
if result == '0':
print "*** {} MATCHES ***".format(Base)
else:
message = "*** {0} DOES NOT MATCH: {1} pixels differ***".format(Base, result)
print message
out = open("{}\img_errs.txt".format(temp), "a")
out.write(message + "\n")
else:
message = "*** {} DOES NOT EXIST ***".format(tempImg)
print message
out = open("{}\img_errs.txt".format(temp), "a")
out.write(message + "\n")
父脚本中的子进程由函数以此处显示的相同try/except格式完成。我尝试使用subprocess.call()代替Popen/.communicate()部分,以及Popen.wait()。stdout没有输出任何内容,它的输出只是print语句,但它们似乎优先于父脚本并首先打印,即使时间戳证明父行首先出现
有没有办法让父脚本的打印语句在子流程之前显示?这些都是在EclipseMars中使用Python2.7完成的。这在评论中得到了回答,但我想把它放在这里以便更容易看到。第一部分的功劳来自CasualDemon的评论(这是我最后使用的): 在此处添加flush()行:
else: (comparison)
print "Start Comparison"
# create new images to be compared
# Repeat same 3 subprocesses
print "Doing Comparison"
sys.stdout.flush() <-- new
# Comparison Subprocess
新的:
尝试在子进程调用之前添加一个
sys.stdout.flush()
。若要禁用缓冲,请使用-u
标志运行脚本:python-u your_script.py
按照此脚本的实现方式,我选择了sys.stdout.flush()
选项,但这两个选项都非常有效。感谢你们两位令人惊讶的简单修复!
else: (comparison)
print "Start Comparison"
# create new images to be compared
# Repeat same 3 subprocesses
print "Doing Comparison"
sys.stdout.flush() <-- new
# Comparison Subprocess
script.py ${folder_prompt}
-u script.py ${folder_prompt}