我正在尝试使用Python自动重复运行另一个程序。现在我在命令行输入以下内容,一次一个(数字来自文件“Avals”):
advisersProgram
input1
0.01
input1
0.015
exit
当我尝试自动化时,我可以启动advisersProgram但我无法发送输入。
这就是我的尝试:
import os
import glob
import subprocess
files = sorted(glob.glob("*"))
for f in files:
os.chdir(f)
As = [float(line.strip()) for line in open("Avals")]
subprocess.call('advisersProgram')
for A in As:
subprocess.call('input1')
subprocess.call(A)
subprocess.call('exit')
os.chdir("..")
我也试过
for f in files:
As = [float(line.strip()) for line in open("Avals")]
subprocess.call(['advisersProgram','input1',A[0],'input1,A[1]','exit'])
和
for f in files:
As = [float(line.strip()) for line in open("Avals")]
subprocess.Popen('advisersProgram',stdin=['input1','0.01','input1','0.015','exit'])
其他信息: 我查看了Pexpect(我不确定这是否有用,但我在其中一个堆栈交换答案中建议),但我没有安装,也没有权限安装它。
我不需要捕获任何输出; advisersProgram生成保存在目录中的等高线图。
答案 0 :(得分:0)
考虑在subprocess.Popen的 args 参数中传递命令行参数列表,而不是在 stdin 参数中。下面显示了如何使用stdin(标准输入)向子控制台输出子进程的输出和/或错误。
import glob, os, subprocess
# PATH OF PY SCRIPT (CHANGE IF CHILD PROCESS IS NOT IN SAME DIRECTORY)
curdir = os.path.dirname(os.path.abspath(__file__))
files = sorted(glob.glob("*"))
for f in files: # NOTE: f IS NEVER USED BELOW, SHOULD IT BE IN OPEN()?
As = [float(line.strip()) for line in open("Avals")]
for A in As:
p = subprocess.Popen(['advisersProgram', 'input1', A], cwd=curdir,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output,error = p.communicate()
if p.returncode == 0:
print('OUTPUT:\n {0}'.format(output.decode("utf-8")))
else:
print('ERROR:\n {0}'.format(error.decode("utf-8")))
当然,如果您不需要任何输出,请删除此类行,但您可能想要跟踪哪些子进程有效。
答案 1 :(得分:-2)
啊,我错了 - 它不是communicate()
。您只想将stdin
设置为subprocess.PIPE
import sys
import subprocess
def call_myself():
print('Calling myself...')
p = subprocess.Popen([sys.executable, __file__], stdin=subprocess.PIPE)
for command in ['input1', '0.01', 'input1', '0.015', 'exit']:
p.stdin.write((command+'\n').encode())
def other_program():
command = None
while command != 'exit':
command = input()
print(command)
print('Done')
if __name__ == '__main__':
try:
if sys.argv[1] == 'caller':
call_myself()
except IndexError:
other_program()