我不太熟悉计算机软件术语(抱歉)。
- 我用 Python 设计了一个 GUI,当按下适当的按钮(在 GUI 上)时,它会执行和/或终止脚本。
当我按下 GUI 上的“开始”按钮 (QPushButton) 时,以下命令会在命令提示符中执行脚本 filename.dut,如下所示:
subprocess.call ('launcher.exe localhost filename.dut', shell=True)。我希望能够以类似的方式终止脚本,即按 GUI 上的“停止”按钮,该按钮将在命令提示符中写入适当的命令来终止脚本。 我想我可以在这个线程中找到解决方案:Ending external programs with Python 。建议的解决方案是:
import subprocess taskname = '...' task = 'taskkill /im ' + taskname + ' /f' subprocess.check_call(task, shell=True)
我的问题是如何获取任务名称?
任何建议或替代解决方案将不胜感激。
最佳答案
如果您使用subprocess
,则无需调用任何外部实用程序。
subprocess.Popen
类提供 terminate
方法。
为了使用它,您需要将 subprocess.call(...)
替换为 subprocess.Popen(...)
,它返回一个Popen
实例。例如,
task = subprocess.Popen('launcher.exe localhost filename.dut', shell=True)
# some time later
task.terminate()
请注意,与 call
不同,普通 Popen
不会等待进程完成。
关于Python:使用 Python 从命令提示符杀死(终止)进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17956190/