簡體   English   中英

Python 子進程:根據上一個命令的輸出向進程發送一系列命令

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

我正在嘗試使用程序xfoil執行一系列命令。

我已經到了獲取我發送的所有命令的地步,以便它可以直接加載而無需控制輸入重定向到 xfoil,例如:“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  

使用子進程或其他方式,有沒有辦法讓我一次發送一個命令,以便在發送第二個命令之前檢查第一個加載命令的輸出?

最好有類似的東西:

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

您可以嘗試以下操作:

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

如果您想在特定命令失敗時使循環失敗,您可以將check=True作為參數添加到subprocess.run(...,check=True)函數。

此外,如果xfoil只能從特定目錄運行,您可以cwd="path/to/run"subprocess.run()

暫無
暫無

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

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