【问题标题】:Terminating a long command and continue the script终止长命令并继续执行脚本
【发布时间】:2022-01-20 09:04:50
【问题描述】:
我正在使用 Python 开发一个测试自动化工具,它打开 CMD 并通过它发送命令以听到设备发出的声音。基于该声音,用户可以点击声音是否存在(即通过/失败)。不幸的是,我传递的命令一直在无休止地运行。我想把它停在(假设是 5 秒),这是测试人员确定是否有声音的合适时间。
网上的大多数方法要么使用多处理退出,这将导致应用程序完全关闭,这不是我想要的,因为在用户确定声音存在后,程序需要运行另一个命令来测试例如 LED 灯,或者他们使用signal.SIGALRM,它可以与计时器一起使用,该计时器会在一段时间后终止进程,但它不适用于 Windows。你觉得我应该怎么做?如果您可以粘贴执行此操作的代码示例,那就太好了。谢谢!
【问题讨论】:
标签:
python
windows
command-line
automation
【解决方案1】:
也许你可以从线程模块 (https://docs.python.org/3/library/threading.html) 中使用 Timer。这是一个简单的例子:
import subprocess
import threading
def terminate(process):
print('terminating process',process)
process.kill()
print('done')
cmd = [<your command>, <your arguments>,...]
process = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
kill_timer = threading.Timer(1, terminate, [process])
try:
kill_timer.start()
stdout, stderr = process.communicate()
print(stdout, stderr)
finally:
kill_timer.cancel()
它应该可以在 Windows 机器上运行。