2009-04-01 4 views
33

Pythonスクリプトで外部プログラムを呼び出し、出力と戻りコードを取得するにはどうすればよいですか? subprocessモジュールでPythonで外部プログラムを呼び出し、出力と戻りコードを取得する方法は?

+2

あなたに役立ついくつかの既存の質問と答えがあります:http://stackoverflow.com/questions/89228/how-to-call-external-command-in-python –

+0

可能な重複[Pythonで外部コマンドを呼び出す](http://stackoverflow.com/questions/89228/calling-an-external-command-in-python) –

答えて

45

ルック:簡単な例は以下の...

from subprocess import Popen, PIPE 

process = Popen(["ls", "-la", "."], stdout=PIPE) 
(output, err) = process.communicate() 
exit_code = process.wait() 
+10

私はアンブロズの提案を反映するために上記の答えを編集しましたコメントを読んでいないし、以前は間違ったコードを使用する。 –

+0

何らかの理由でこれが機能しない場合は、shell = Trueをパラメータに追加することができます(ウィンドウ内の場合) – ntg

+0

[上記の解決策](https://stackoverflow.com/a/707001/1321680) )は単純なcall ['subprocess.run()'](https://docs.python.org/dev/library/subprocess.html#subprocess.run)に置き換えることができます(Python> = 3.5が必要です)。 –

13

アンブロスBizjakの以前のコメントに続き、ここで私のために働いたソリューションです:いくつかの研究の後

import shlex 
from subprocess import Popen, PIPE 

cmd = "..." 
process = Popen(shlex.split(cmd), stdout=PIPE) 
process.communicate() 
exit_code = process.wait() 
+3

これははるかに良い答えです。 – dotancohen

+3

私はプロセスから3つのものを得る方法を示す類似の投稿[here](https://stackoverflow.com/questions/1996518/retrieving-the-output-of-subprocess-call/21000308#21000308)を持っています:exitcode 、stdout、stderr。 – Jabba

2

、私は私のために非常によく動作し、次のコードを持っています。基本的にstdoutとstderrの両方をリアルタイムで表示します。それが必要な人を助けることを願っています。

stdout_result = 1 
stderr_result = 1 


def stdout_thread(pipe): 
    global stdout_result 
    while True: 
     out = pipe.stdout.read(1) 
     stdout_result = pipe.poll() 
     if out == '' and stdout_result is not None: 
      break 

     if out != '': 
      sys.stdout.write(out) 
      sys.stdout.flush() 


def stderr_thread(pipe): 
    global stderr_result 
    while True: 
     err = pipe.stderr.read(1) 
     stderr_result = pipe.poll() 
     if err == '' and stderr_result is not None: 
      break 

     if err != '': 
      sys.stdout.write(err) 
      sys.stdout.flush() 


def exec_command(command, cwd=None): 
    if cwd is not None: 
     print '[' + ' '.join(command) + '] in ' + cwd 
    else: 
     print '[' + ' '.join(command) + ']' 

    p = subprocess.Popen(
     command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd 
    ) 

    out_thread = threading.Thread(name='stdout_thread', target=stdout_thread, args=(p,)) 
    err_thread = threading.Thread(name='stderr_thread', target=stderr_thread, args=(p,)) 

    err_thread.start() 
    out_thread.start() 

    out_thread.join() 
    err_thread.join() 

    return stdout_result + stderr_result 
3

あなたは、外部のプログラムを実行し、出力し、リターンコードを取得し、同時にリアルタイムでコンソールの出力を取得することができます小さなライブラリ(py-executeを)Iを開発しました:

>>> from py_execute.process_executor import execute 
>>> ret = execute('echo "Hello"') 
Hello 
>>> ret 
(0, 'Hello\n') 

あなたはモックuser_ioを渡してコンソールに印刷を避けることができます。

>>> from mock import Mock 
>>> execute('echo "Hello"', ui=Mock()) 
(0, 'Hello\n') 

(Pythonの2.7で)、プレーンpopenので、私はトラブルCOMMの実行を持っていたので、私はそれを書きました長い出力を持つと

関連する問題