[英]Piping popen stderr and stdout
我想通过python从目录(它们是可执行的shell脚本)调用脚本。
到现在为止还挺好:
for script in sorted(os.listdir(initdir), reverse=reverse):
if script.endswith('.*~') or script == 'README':
continue
if os.access(script, os.X_OK):
try:
execute = os.path.abspath(script)
sp.Popen((execute, 'stop' if reverse else 'start'),
stdin=None, stderr=sp.PIPE,
stdout=sp.stderr, shell=True).communicate()
except:
raise
现在我想要的是:假设我有一个带启动功能的bash脚本。 我打电话给他
回声“某事”
现在我想在sys.stdout和退出代码上看到echo。 我相信你用.communicate()来做这件事,但我的工作方式与我想象的不同。
我究竟做错了什么?
任何帮助深表感谢
Confer http://docs.python.org/library/subprocess.html 。
communic()返回一个元组(stdoutdata,stderrdata)。
子进程完成后,您可以从Popen实例获取返回代码:
Popen.returncode:子返回码,由poll()和wait()设置(间接由communic()设置)。
同样,您可以实现这样的目标:
sp = subprocess.Popen([executable, arg1, arg2], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = sp.communicate()
if out:
print "standard output of subprocess:"
print out
if err:
print "standard error of subprocess:"
print err
print "returncode of subprocess:"
print sp.returncode
顺便说一句,我会改变测试
if script.endswith('.*~') or script == 'README':
continue
积极的:
if not filename.endswith(".sh"):
continue
最好是要明确你想比显式说明你不想执行什么要执行的。
此外,您应该以更一般的方式命名变量,因此script
应该首先是filename
。 由于listdir
还列出了目录,因此您可以明确检查这些目录。 只要您不处理特定异常,您当前的try/except
块就不合适。 取而代之的abspath
,你应该正好连接initdir
和filename
,这是一个概念,往往在环境中应用os.listdir()
。 出于安全原因,只有在您完全确定需要它时才在Popen
对象的构造函数中使用shell=True
。 我建议如下:
for filename in sorted(os.listdir(initdir), reverse=reverse):
if os.path.isdir(filename) or not filename.endswith(".sh"):
continue
if os.access(script, os.X_OK):
exepath = os.path.join(initdir, filename)
sp = subprocess.Popen(
(exepath, 'stop' if reverse else 'start'),
stderr=subprocess.PIPE,
stdout=subprocess.PIPE)
out, err = sp.communicate()
print out, err, sp.returncode
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.