简体   繁体   English

Python子进程中的按键?

[英]key press in a Python subprocess?

try:
    subprocess.run(exe_path)
    keyboard.press_and_release('enter')
    print('Successful Extracted')
except Exception as exe:
    print(exe.args)
    keyboard.press_and_release('enter')

The point is to run the EXE of windows but it needs input of keyboard to end it's process, and it will remain stuck over there unless a keyboard input given physically.关键是运行windows的EXE,但它需要键盘输入来结束它的进程,除非物理给出键盘输入,否则它会一直卡在那里。 Right now i am facing issue as现在我面临的问题是

subprocess.run('some_exe')

is running the process and after successfully run asking正在运行该进程并成功运行后询问

Press Any Key To Exit

while i have already mentioned next to subprocess.run虽然我已经在subprocess.run旁边提到过

keyboard.press_and_release('enter')

and it's coming to next line unless we press the button from keyboard manually除非我们手动按下键盘上的按钮,否则它会进入下一行

NOTE: python3.8注意:python3.8

You can create a .vbs file to run your .exe file or python script without console debugging window:您可以创建一个 .vbs 文件来运行您的 .exe 文件或 python 脚本,而无需控制台调试窗口:

Set oShell = CreateObject ("Wscript.Shell") 
Dim strArgs
strArgs = "cmd /c  python main.py"
oShell.Run strArgs, 0, false

If you have .exe file just replace python main.py with yourFile.exe .如果您有 .exe 文件,只需将python main.py替换为yourFile.exe

For the sake of a reproducible example, say we want to run the following Python script as a subprocess, let's call it script.py .为了一个可重现的示例,假设我们希望将以下 Python 脚本作为子进程运行,我们将其命名为script.py

input('Press Enter to exit.')

It won't terminate until the user presses the Enter key.它不会终止,直到用户按下Enter键。 If we want to emulate the key press, we can just send a newline character to the subprocess's stdin using Popen.communicate .如果我们想模拟按键,我们可以使用Popen.communicate向子Popen.communicatestdin发送一个换行符。 Like so:像这样:

from subprocess import Popen, PIPE

process = Popen(['python', 'script.py'], stdin=PIPE, text=True)
process.communicate('\n')

Obviously this also works if the external program accepts any key to exit.显然,如果外部程序接受任何退出键,这也有效。 Only sending special keys which don't have an obvious text representation, such as F1 , would complicate things.只发送没有明显文本表示的特殊键,例如F1 ,会使事情复杂化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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