2016-10-27 13 views
1

I持って私のPythonスクリプトで、次のステートメント:Pythonのサブプロセス

def run_command(command):          
    process = subprocess.Popen([sys.executable, command], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
    retcode = process.wait() 
    if retcode != 0: 
    raise Exception, "Problem running command: " + command 
    stdout, stderr = process.communicate() 
    return stdout 

次の出力が生成されます:

TypeError: unsupported operand type(s) for |: 'str' and 'str' 
fun_command()が関数である

year = '1966' 
file = 'test.txt' 
cmd = "awk '{FS="|"}{if ($2 == %s) print $1}' %s | sort -n | uniq | wc" % (year, file) 
bla = run_command(cmd) 

何が間違っていますか?

+0

を使用しています。 – cdarke

+0

知っていますが、プロトタイプ作成にのみ使用します(唯一)。 – Andrej

+0

リストと 'shell = True'を組み合わせることは、普通は悪い考えです。しかし、 'sys.executable'はシェルインタプリタではなく* Python *インタプリタが実行されています。代わりに 'Popen(command、shell = True、...)'を使用してください。 – chepner

答えて

3

"awk '{FS="|"}{if ($2 == %s) print $1}' %s | sort -n | uniq | wc"
ここでは、"|"

"awk '{FS=\"|\"}{if ($2 == %s) print $1}' %s | sort -n | uniq | wc"

+0

空の文字列(つまり、 'b''')が返される理由は何か。私はシェルのコマンドをテストし、正常に動作します。 – Andrej

+1

'wait()'はプロセスが終了するのを待ちます。 'communicate()'はプロセスとやりとりしますが、待ってからはすでに終了しています。パイプがまだ有効かどうかを確認してください。 – teivaz

1

sys.executableはあなたがPythonコードとしてあなたのシェルコードを実行しようとしているので、現在、実行中のパイソンインタプリタである内部エスケープする必要があります。ちょうど私が `` python`はそれで頭の上に誰かを打つウジ機関銃を持つ(Larry Wall氏をmisquoteする)のようなものですからawk`を呼び出し、これを言わなければならない

def run_command(command):          
    process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
    retcode = process.wait() 
    if retcode != 0: 
    raise Exception, "Problem running command: " + command 
    stdout, stderr = process.communicate() 
    return stdout