管道popen stderr和stdout

wag*_*lix 23 python

我想通过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
Run Code Online (Sandbox Code Playgroud)

现在我想要的是:假设我有一个带启动功能的bash脚本.我打电话给他

回声"某事"

现在我想在sys.stdout和退出代码上看到echo.我相信你用.communicate()来做这件事,但我的工作方式与我想象的不同.

我究竟做错了什么?

任何帮助深表感谢

Jan*_*cke 60

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
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我会改变测试

    if script.endswith('.*~') or script == 'README':
         continue
Run Code Online (Sandbox Code Playgroud)

积极的:

if not filename.endswith(".sh"):
    continue
Run Code Online (Sandbox Code Playgroud)

最好是要明确你想比做明确你做什么要执行什么想要执行.

此外,您应该以更一般的方式命名变量,因此script应该filename首先.由于listdir还列出了目录,你可以明确地检查这些.try/except只要您不处理特定异常,您当前的块就不合适.相反的abspath,你应该正好连接initdirfilename,这往往是在环境中应用的一个概念os.listdir().出于安全原因,仅在您完全确定需要它时才shell=TruePopen对象的构造函数中使用.我建议如下:

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
Run Code Online (Sandbox Code Playgroud)