簡體   English   中英

Python:使用子流程向另一個程序提供輸入

[英]Python: Using subprocess to give input to another program

我正在嘗試使用Python自動重復運行另一個程序。 現在,我在命令行中一次輸入以下內容(數字來自文件“ Avals”):

advisersProgram
input1
0.01
input1
0.015
exit

當我嘗試使其自動化時,我可以啟動advisorsProgram,但是不能將其發送給它。

這是我嘗試過的:

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(我不確定這是否有用,但是我在閱讀的其中一個堆棧交換答案中提出了建議),但是我沒有安裝該文件,也沒有安裝它的權限。

我不需要捕獲任何輸出; advisorrsProgram生成等高線圖,並將其保存在目錄中。

考慮通過命令行參數列表中的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")))  

當然,如果不需要任何輸出,請刪除此類行,但是您可能希望跟蹤哪個子進程有效。

啊,我錯了-這不是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()

暫無
暫無

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

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