Python:使用 Python 从命令提示符杀死(终止)进程

标签 python user-interface abort kill-process taskkill

我不太熟悉计算机软件术语(抱歉)。

  • 我用 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 不会等待进程完成。

更多详情请参阅手册:http://docs.python.org/2/library/subprocess.html

关于Python:使用 Python 从命令提示符杀死(终止)进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17956190/

相关文章:

jquery - 如何使用 Rails 作为带有 Backbone UI 的纯粹 JSON 应用程序服务器?

c# - HttpWebResponse:关闭流

delphi - 取消 ADO 连接的连接尝试吗?

user-interface - 函数式GUI编程

c++ - 从其初始化程序中止加载共享库

python elementtree xml追加

python - 如何在多层 python 字典中找到最小值,以及它的 "path"(即叶值的键列表)

Python:使用 Win32 COM Api 打开 Excel 工作簿

python - 全局名称未在 Python 中定义

java - MVP、JFrame、JDialog : GUI is freezing