[英]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.