18

subprocessモジュールを使用check_output()してPythonスクリプトで仮想シェルを作成しています。終了ステータスがゼロのコマンドでは正常に機能しますが、そうでないコマンドでは、で表示されたはずのエラーを出力せずに例外が返されます。通常のシェルでの出力。

たとえば、私は次のように機能することを期待します。

>>> shell('cat non-existing-file')
cat: non-existing-file: No such file or directory

しかし、代わりに、これは起こります:

>>> shell('cat non-existing-file')
CalledProcessError: Command 'cat non-existing-file' returned non-zero exit status 1 (file "/usr/lib/python2.7/subprocess.py", line 544, in check_output)

tryとを使用してPython例外メッセージを削除することはできますがexcept、それでもcat: non-existing-file: No such file or directoryユーザーに表示したいです。

どうすればこれを行うことができますか?

shell()

def shell(command):
    output   = subprocess.check_output(command, shell=True)
    finished = output.split('\n')

    for line in finished:
      print line
    return
4

1 に答える 1

18

おそらくこのようなものですか?

def shell(command):
    try:
        output = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT)
    except Exception, e:
        output = str(e.output)
    finished = output.split('\n')
    for line in finished:
        print line
    return
于 2012-08-18T04:32:52.207 に答える