[英]Python/Batch: Use Python to press any key to continue
我正在使用 python 腳本來自動化涉及批處理文件的過程。 這些是用於其他應用程序的批處理文件,我不允許編輯它們。
在批處理文件的末尾,它提示以下內容:
“按任意鍵繼續……”
如何使用python識別何時出現此提示,以及如何響應? 我希望能夠關閉該文件,以便我可以運行下一個批處理文件。
目前我找到了以下解決方案,但它很糟糕,讓我覺得里面很臟:
#Run the batch file with parameter DIABFile
subprocess.Popen([path + '\\' + batchFile, path + '\\' + DIABFile])
#Sit here like an idiot until I'm confident the batch file is finished
time.sleep(4)
#Press any key
virtual_keystrokes.press('enter')
有什么想法嗎?
p = subprocess.Popen([path + '\\' + batchFile, path + '\\' + DIABFile],
bufsize=1, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
while p.poll() is None:
line = p.stdout.readline()
print(line)
if line.startswith('Press any key to continue'):
p.communicate('\r\n')
導致以下輸出和錯誤:
b'\r\n'
Traceback (most recent call last):
File "C:\workspace\Perform_QAC_Check\Perform_QAC_Check.py", line 341, in <module>
main()
File "C:\workspace\Perform_QAC_Check\Perform_QAC_Check.py", line 321, in main
run_setup_builderenv(sandboxPath, DIABFile)
File "C:\workspace\Perform_QAC_Check\Perform_QAC_Check.py", line 126, in run_setup_builderenv
if line.startswith('Press any key to continue'):
TypeError: startswith first arg must be bytes or a tuple of bytes, not str
The process tried to write to a nonexistent pipe.
對我來說最奇怪的部分是開始的第一個 arg 必須是字節或字節元組,而不是 str。 我查看了文檔,它肯定應該是一個字符串? 開始教程
於是上網查了一下,發現了一點。
錯誤消息似乎是 Python 中的一個錯誤,因為它恰恰相反。 但是,這里沒有問題,在 indian.py 的第 75 行之后添加
try:
line = line.decode()
except AttributeError:
pass
所以我做到了。
p = subprocess.Popen([path + '\\' + batchFile, path + '\\' + DIABFile],
bufsize=1, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
while p.poll() is None:
line = p.stdout.readline()
print(line)
try:
line = line.decode()
if line.startswith('Press any key to continue'):
p.communicate('\r\n')
except AttributeError:
pass
導致以下輸出:
b'\r\n'
b'Build Environment is created.\r\n'
b'\r\n'
b'Please Refer to the directory: C:/directory\r\n'
b'\r\n'
然后它掛在那里......這是“請按任意鍵繼續”之前的最后一個輸出,但它永遠不會出現。
從那以后,我采用了第二個腳本並要求它找到“請參考”,它確實做到了。 不幸的是,腳本再次掛在該行:
p.communicate('\r\n')
再次結束程序,打印錯誤:
The process tried to write to a nonexistent pipe.
我認為這與此錯誤有關。
我無法想象我正在嘗試做的事情與眾不同。 由於這似乎比預期的要復雜一些,我想說我使用的是 XP 和 Python 3.3 版。
像下面這樣的東西應該工作:
p = subprocess.Popen([path + '\\' + batchFile, path + '\\' + DIABFile],
bufsize=1, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
while p.poll() is None:
line = p.stdout.readline()
if line.startswith('Press any key to continue'):
p.communicate('\r\n')
正如 OP 中所述,沒有一個解決方案可以解決問題。 所以最后布萊斯的解決方案為我解決了這個問題:
subprocess.call([path + '\\' + batchFile, path + '\\' + DIABFile], stdin=subprocess.DEVNULL)
這篇文章中的解決方案對我有用:
嘗試執行
cmd.exe /c YourCmdFile < nul
YourCmdFile
- 批處理腳本的完整路徑
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.