2017-12-26 3 views
0

다음 명령으로 bash에서 pw.x를 실행하고 싶습니다 : mpirun -np 4 pw.x < python 스크립트를 통해 input.in. 나는이 사용 :파이썬 스크립트에서 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' 

가 어떻게 파이썬 스크립트에서 "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의 모든 유형은 하나 일 수 있지만 문자열은 시퀀스의 단일 요소로 취급됩니다. 이는 귀하의 경우에 발생하며 전체 mpirun -np 4 pw.x 문자열이 실행 파일 이름으로 취급됩니다.

  • 사용 shell=True하고있는 그대로 다른 모든 것들을 유지, 그러나 이것은 쉘에서 직접 실행할 수 것이고 어떤이 작업을 수행하지 않아야로 보안 문제의주의 :

    는이 문제를 해결하려면 다음을 수행 할 수 있습니다 신뢰할 수없는 실행 파일

  • 예를 들어 적절한 순서를 사용하십시오. cmdPopen에 대한 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) 

당신이 이전 파이썬 버전에 붙어있는 경우, 어쩌면 subprocess.check_output()

+0

https://stackoverflow.com/questions/3172470/actual-meaning-of-shell-true-in-subprocess 또한'shell = True'를 피하기 위해 – tripleee

+0

감사합니다. 당신의 대답,하지만 그것은 나를 위해 작동하지 않으며 출력에 아무것도 표시되지 않습니다. – user3578884

관련 문제