我正在使用我的實驗室開發的軟體,我們稱之為cool_software。當我cool_software在終端上輸入時,基本上我會得到一個新提示cool_software >,我可以從終端向這個軟體輸入命令。
現在我想在 Python 中自動執行此操作,但是我不確定如何將cool_software命令傳遞給它。這是我的 MWE:
import os
os.system(`cool_software`)
os.system(`command_for_cool_software`)
上面代碼的問題在于它command_for_cool_software是在通常的 unix shell 中執行的,而不是由cool_software.
uj5u.com熱心網友回復:
根據評論中的@Barmar 建議,使用pexpect非常簡潔。從檔案:
spawn 類是 Pexpect 系統的更強大的介面。您可以使用它來生成子程式,然后通過發送輸入和期望回應(等待子程式輸出中的模式)與它進行互動。
這是一個使用python提示作為示例的作業示例:
import pexpect
child = pexpect.spawn("python") # mimcs running $python
child.sendline('print("hello")') # >>> print("hello")
child.expect("hello") # expects hello
print(child.after) # prints "hello"
child.close()
在你的情況下,它會是這樣的:
import pexpect
child = pexpect.spawn("cool_software")
child.sendline(command_for_cool_software)
child.expect(expected_output) # catch the expected output
print(child.after)
child.close()
筆記
child.expect()僅匹配您的期望。如果您不期望任何事情并希望獲得自開始以來的所有輸出spawn,那么您可以使用child.expect('. ')which 將匹配所有內容。
這是我得到的:
b'Python 3.8.10 (default, Jun 2 2021, 10:49:15) \r\n[GCC 9.4.0] on linux\r\nType "help", "copyright", "credits" or "license" for more information.\r\n>>> print("hello")\r\nhello\r\n>>> '
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/317388.html
