2016-01-21 161 views
1

我正在尝试使用Python来自动运行另一个程序。现在我键入以下到命令行,一次一个(数字来自文件“Avals”):Python:使用子进程为其他程序提供输入

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的(我不知道如果这会很有用,但是在我阅读的堆栈交换答案中提到了这一点),但我并不是e安装​​并且没有权限安装它。

我不需要捕获任何输出; advisersProgram生成保存在目录中的等高线图。

回答

-2

啊,我错了 - 它不是communicate()。你只是想设置stdinsubprocess.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() 
0

考虑通过命令行参数的清单中ARGS说法subprocess.Popen,而不是在标准输入说法。下面显示了如何使用stdin(标准输入)向Python控制台输出子进程的输出和/或错误。

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"))) 

当然,如果你不需要任何输出,删除这样的行,但你可能想跟踪哪些子进程工作与否。

+0

#注意:f从来没有用过,应该公开()? 对不起,我用f来改变目录;我编辑了原始问题。 – mle

+0

这是你的问题。 “Avals”是多个glob文件之一吗?如果你只打开一个文件,不需要循环。如果有许多文件中的一个,然后用'open(f)'包含循环。 – Parfait

+0

当我在命令行中输入'advisersProgram'或者使用'subprocess.call('advisersProgram')',我得到以下结果: PV-WAVE v10.1 UNIX/Windows/VMS %编译模块:X 。 WAVE>' 在print('OUTPUT:\ n {0}')格式中使用你的建议format.output.decode(“utf-8”)))',我得到一堆: 'PV -WAVE v10.1 UNIX/Windows/VMS' 每个A值在终端上出现一次。也就是说,它不足以让我输入。 – mle