繁体   English   中英

在python脚本中使用mpirun -np

[英]using mpirun -np in python script

我想使用以下命令在bash中运行pw.x:mpirun -np 4 pw.x <input.in通过python脚本。 我用这个:

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 ...”?

Popen构造函数中的shell=False时,它期望cmd是一个序列; 任何类型的str都可以是一个,但随后将字符串视为序列的单个元素-在您的情况下会发生这种情况,整个mpirun -np 4 pw.x字符串将被视为可执行文件名。

要解决此问题,您可以:

  • 使用shell=True并保持其他所有状态不变,但请注意安全性问题,因为它将直接在shell中运行,并且您不应对任何不受信任的可执行文件执行此操作

  • 使用适当的序列,例如Popen cmd list

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

两者都假设mpirun存在于您的PATH

如何改变

shell=False

shell=True

使用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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM