簡體   English   中英

等待用戶輸入后與 python 子進程交互

[英]Interact with python subprocess once waits for user input

我正在編寫一個腳本來自動化某個軟件的測試,作為其中的一部分,我需要檢查它是否正確運行命令。

我目前正在使用子進程啟動可執行文件並傳遞初始參數。 我的代碼是: subprocess.run("program.exe get -n WiiVNC", shell=True, check=True)據我了解,這運行可執行文件,如果退出代碼為 1,則應該返回異常.

現在,程序啟動,但在某些時候等待用戶輸入,如下所示: 所需的用戶輸入

我的問題是,我如何 go 關於使用子進程提交用戶輸入“y”一次,文本“繼續下載“WiiVNC”?(y/n)>“出現,或者一旦程序等待用戶輸入.

您應該使用 pexpect 模塊進行所有復雜的子處理。 特別是,該模塊旨在處理將輸入傳遞給當前進程以供用戶回答和/或允許您的腳本為用戶回答輸入並繼續子進程的復雜情況。

為示例添加了一些代碼:

### File Temp ### 
# #!/bin/env python
# x = input('Type something:')
# print(x)

import pexpect

x = pexpect.spawn('python temp') #Start subprocess. 
x.interact()                     #Imbed subprocess in current process. 

# or

x = pexpect.spawn('python temp') #Start subprocess.
find_this_output = x.expect(['Type something:'])
if find_this_output is 0:
    x.send('I type this in for subprocess because I found the 0th string.')

嘗試這個:

import subprocess

process = subprocess.Popen("program.exe get -n WiiVNC", stdin=subprocess.PIPE, shell=True)
process.stdin.write(b"y\n")
process.stdin.flush()
stdout, stderr = process.communicate()

暫無
暫無

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

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