簡體   English   中英

使用Python運行可執行文件並填寫用戶輸入

[英]Using Python to run executable and fill in user input

我正在嘗試使用Python自動執行一個過程,該過程涉及調用Fortran可執行文件並提交一些用戶輸入。 我已經花了幾個小時閱讀類似的問題並嘗試了不同的嘗試,但是沒有運氣。 這是顯示我上次嘗試的最小示例

#!/usr/bin/python

import subprocess

# Calling executable 
ps = subprocess.Popen('fortranExecutable',shell=True,stdin=subprocess.PIPE)
ps.communicate('argument 1')
ps.communicate('argument 2')

但是,當我嘗試運行此命令時,出現以下錯誤:

  File "gridGen.py", line 216, in <module>
    ps.communicate(outputName)
  File "/opt/apps/python/epd/7.2.2/lib/python2.7/subprocess.py", line 737, in communicate
    self.stdin.write(input)
ValueError: I/O operation on closed file

任何建議或指示,將不勝感激。

編輯:

當我調用Fortran可執行文件時,它要求用戶輸入如下:

fortranExecutable
Enter name of input file: 'this is where I want to put argument 1'
Enter name of output file: 'this is where I want to put argument 2'

不知何故,我需要運行可執行文件,等到它要求用戶輸入然后提供該輸入。

如果輸入不取決於先前的答案,則可以使用.communicate()一次全部傳遞它們:

import os
from subprocess import Popen, PIPE

p = Popen('fortranExecutable', stdin=PIPE) #NOTE: no shell=True here
p.communicate(os.linesep.join(["input 1", "input 2"]))

.communicate()等待進程終止,因此您最多可以調用一次。

就像規范說的那樣, communicate()等待子進程終止,因此第二個調用將尋址到完成的進程。

如果要與該進程進行交互,請改用p.stdin &Co(注意死鎖警告)。

到您到達ps.communicate('argument 2')時,由於ps.communicate('argument 1')等待EOF,因此ps進程已關閉。 我認為,如果您想在stdin上多次編寫,則可能必須使用:

ps.stdin.write('argument 1')
ps.stdin.write('argument 2')

您的論點不應傳遞給交流。 應該在對Popen的調用中給出它們,例如: http : //docs.python.org/2/library/subprocess.html#subprocess.Popen

>>> import shlex, subprocess
>>> command_line = raw_input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print args
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM