[英]How to run executable with file input/output in Python using subprocess?
我想使用 Python 中的子进程运行已编译的 Fortran 代码。 我尝试了 run() 或 Popen() 但终端只是挂在那里(没有 output 或终止)这是我尝试的代码:
bashCommand = 'cp2xsf.x < cp2xsf.in > cp2xsf.out'
# I put cp2xsf.x in local bin, this command is to show that it can be found
process = subprocess.run('which cp2xsf.x', shell=True)
# files needed for the executable are in ./out
process = subprocess.run(bashCommand.split(), cwd='./out', shell=True)
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE, cwd='./out', shell=True)
# I used either run or Popen not together
我哪里做错了?
- -更新 - -
在 Don 的帮助下,它现在可以工作了。 如果我设置shell=True
,我不需要split()
。 但是,如果我使用process = subprocess.run(bashCommand.split(), cwd='./out', shell=False)
,它将不起作用。 不知道为什么...
如果您使用的是shell=True
,那么我认为您不需要拆分 bash 命令。 此外,如果您知道当前目录中存在cp2xsf.x
,则无需更改cwd
参数。 您可以尝试像这样运行:
process = subprocess.run(bashCommand, shell=True)
让我知道 output 的样子。
另外,你需要使用subprocess
吗? 也许您可以尝试致电:
os.system(bashCommand)
尽管使用os.system()
您将只捕获返回码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.