简体   繁体   中英

Python Subprocess : Send a sequence of commands to a process depending on the output of the previous command

I am trying to execute a sequence of commands with the program xfoil .

I've got to the point of getting all the commands I'm sending so that it can be directly loaded without control to xfoil with input redirection ex : "xfoil < inputfile"

load sd7032.dat   
oper  
iter 100   
type 2  
visc 100000  
alfa 0.0  
dump target_sd7032_alfa_0.0_Re_100000_Type2.dmp  

With subprocess or some other means, is there a way for me to send one command at a time, such that the output of the first load command is checked before sending the second?

preferably with something similar to:

ps = sp.Popen(['xfoil.exe'], stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE)
for command in commdand_list:
    ps.stdin.write(cmd+'\n')

You can try the following:

import subprocess
for command in command_list:
    res = subprocess.run(f'xfoil {command}', shell=True, capture_output=True)
    print(f"return code is: {res.returncode}")
    print(f"stdout is: {res.stdout}")
    print(f"stderr is: {res.stderr}")

if you want to fail the loop if a specific command failed, you can add check=True as a parameter to subprocess.run(...,check=True) function.

In addition, if xfoil is runnable only from specific directory, you can cwd="path/to/run" to subprocess.run() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM