2017-12-26 54 views
0

このコマンドでbashでpw.xを実行したいのですが、mpirun -np 4 pw.x pythonスクリプトを使用してinput.inを実行します。 私はこの使用:pythonスクリプトでmpirun -npを使用する

from subprocess import Popen, PIPE 

process = Popen("mpirun -np 4 pw.x", shell=False, universal_newlines=True, 
        stdin=PIPE, stdout=PIPE, stderr=PIPE) 
output, error = process.communicate(); 
print (output); 

を、それは私に、このエラーを与える:

Original exception was: 
Traceback (most recent call last): 
    File "test.py", line 6, in <module> 
    stdin=PIPE, stdout=PIPE, stderr=PIPE) 
    File "/usr/lib/python3.6/subprocess.py", line 709, in __init__ 
    restore_signals, start_new_session) 
    File "/usr/lib/python3.6/subprocess.py", line 1344, in _execute_child 
    raise child_exception_type(errno_num, err_msg, err_filename) 
FileNotFoundError: [Errno 2] No such file or directory: 'mpirun -np 4 pw.x': 'mpirun -np 4 pw.x' 

私はPythonスクリプトで "... mpirunの-np" を使用するにはどうすればよいですか?

+0

https://docs.python.org/2/library/subprocess.html#popen-constructorを試してみてください:あなたのコマンドとパスを分割しましたそれは 'Popen'へのリストとして – Pavel

答えて

0

どの程度変化する

shell=False 

shell=True 
1

あなたはPopenコンストラクタでshell=Falseを持っているし、それはcmdはシーケンスであることを期待します。任意のタイプのstrは1つでもかまいませんが、文字列はシーケンスの単一要素として扱われます。これはあなたのケースで起こり、mpirun -np 4 pw.x文字列全体が実行可能ファイル名として扱われます。この問題を解決するには

、次のことができます。

  • 使用shell=Trueと、そのまま他のすべてを維持するが、これはシェルで直接実行されるだろうし、あなたが任意のためにこれを行うべきではないとセキュリティ上の問題に注意信頼できない実行可能ファイル

  • 適切なシーケンスを使用してください。 Popencmdためlist

    import shlex 
    process = Popen(shlex.split("mpirun -np 4 pw.x"), shell=False, ...) 
    

どちらmpirunがあなたのPATHに存在すると仮定。

0

shell=Falseとすると、コマンドラインを自分でリストに解析する必要があります。

また、subprocess.run()があなたのニーズに適さない場合を除き、subprocess.Popen()を直接呼び出すことは避けてください。

inp = open('input.in') 
process = subprocess.run(['mpirun', '-np', '4', 'pw.x'], 
    # Notice also the stdin= argument 
    stdin=inp, stdout=PIPE, stderr=PIPE, 
    shell=False, universal_newlines=True) 
inp.close() 
print(process.stdout) 

古いPythonのバージョンで立ち往生している場合は、多分subprocess.check_output()

+0

https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocessも参照してください。なぜ' shell = True'を避けたいのですか – tripleee

+0

ありがとうあなたの答えは、それは私のために動作しないし、出力に何も表示されません。 – user3578884

関連する問題