如何在 Python 子进程中模拟按键? [英] How can I simulate a key press in a Python subprocess?

查看:39
本文介绍了如何在 Python 子进程中模拟按键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

场景是,我有一个 Python 脚本,它的一部分是使用以下代码执行外部程序:

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?

推荐答案

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')

这篇关于如何在 Python 子进程中模拟按键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆