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