【发布时间】:2014-03-18 15:01:02
【问题描述】:
我有一个执行系统调用的 Python 脚本(调用实际上是一个java 程序)。
我正在使用Popen.communicate() 来尝试 捕获stdout 和stderr。但是,它仅适用于某些Java 应用程序(其中,我调用的所有java 应用程序在直接在shell 中执行时都会在屏幕上显示一些内容)。
我使用的代码如下:
# Perform the java call
try:
p = subprocess.Popen(args,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
except OSError as e:
error_msg = ' Error reading file while executing system command: {0}'.format(e.message)
except ValueError as e:
error_msg = ' Error in arugments while executing system command: {0}'.format(e.message)
else:
# Display the results in real time
for line in iter(p.stdout.readline, ''):
sys.stdout.write(line)
# Grab the stdout and stderr from the process.
output, err = p.communicate()
finally:
# Check to see if an internal error occurred. If not, flip the flag
if not err and not error_msg:
java_completed = True
else:
java_completed = False
在某些情况下,sys.stdout.write(line) 行永远不会被调用,而在其他情况下却是。
有人有这方面的经验吗?
【问题讨论】:
标签: python subprocess