How can I simulate a key press in a Python subprocess?

空扰寡人 提交于 2020-03-23 02:02:31

问题


The scenario is, I have a Python script which part of it is to execute an external program using the code below:

subprocess.run(["someExternalProgram", "some options"], shell=True)

And when the external program finishes, it requires user to "press any key to exit".

Since this is just a step in my script, it would be good for me to just exit on behalf of the user.

Is it possible to achieve this and if so, how?


回答1:


from subprocess import Popen, PIPE

p = Popen(["someExternalProgram", "some options"], stdin=PIPE, shell=True)
p.communicate(input=b'\n')

If you want to capture the output and error log

from subprocess import Popen, PIPE

p = Popen(["someExternalProgram", "some options"], stdin=PIPE, stdout=PIPE, stderr=PIPE shell=True)
output, error = p.communicate(input=b'\n')


来源:https://stackoverflow.com/questions/60502312/how-can-i-simulate-a-key-press-in-a-python-subprocess

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!