2012-05-21 27 views
16

私はpythonを介してディレクトリからスクリプトを実行します(実行可能なシェルスクリプトです)。popen stderrとstdoutをパイプ

これまでのところ良い:

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 

は今、私が欲しいものです:私はスタートfunctiontでbashスクリプトを持って言うことができます。そこから私は

は、今私はsys.stdoutの上でそのエコーと終了コードを見てみたい

エコー「何か」と呼びます。私はあなたが.communicate()でこれをやっていると信じていますが、私の考え方はうまくいきません。

私は間違っていますか?

すべてのヘルプははるかに与えるhttp://docs.python.org/library/subprocess.html

答えて

49

を高く評価しています。

communicate()はタプル(stdoutdata、stderrdata)を返します。

サブプロセスが終了した後、あなたはpopenのインスタンスからの戻りコードを取得することができます

Popen.returncode:世論調査(によって設定された子のリターンコードを、)と(待つ)(および間接的に通信()によって)。

if not filename.endswith(".sh"): 
    continue 

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 

テストを変更します同様に、あなたがそのようなあなたの目標を達成することができます

あなたが元にしたいことを明示する方が良いあなたが何をしているかについて明白であるよりも徹底的である実行したい。

また、より一般的な方法で変数の名前を付ける必要があります。scriptは、最初はfilenameである必要があります。 listdirにもディレクトリがリストされているので、明示的にそれらのディレクトリをチェックすることができます。あなたの現在のtry/exceptブロックは、特定の例外を処理しない限り、適切ではありません。 abspathの代わりに、os.listdir()のコンテキストでよく適用される概念であるinitdirfilenameを連結するだけです。セキュリティ上の理由から、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 
+0

はどうもありがとうございまし –

+0

うん、私はあなたの質問には関係がないので、私はちょうどでそれらを入力していなかった特定の例外があります。しかし、あなたは変数の名前について正しいです、私はいつも正しい名前で苦労しています。もう一度ありがとう –

関連する問題