仅杀死 python 在 CMD 上创建的子进程

Kill only a subprocess created by python on CMD

我制作了一个 python 脚本,它使用 aria2 下载器通过 运行 a [=50 下载=] 命令可以在 Windows 和 Linux.

上工作
os.system("aria2c " + url + options)
#some code I want to run if the process is stopped

现在,我想测试我的程序在无法下载文件时的情况。因此,在命令提示符 (cmd.exe) Windows 上执行 'python downloader.py' 后,我按 Ctrl+C 仅停止下载 ('aria2c.exe' 仅处理)但保留 运行 我的 python 代码。

Ubuntu 终端 上执行此操作效果很好!但是在 cmd windows 上,Ctrl+C 停止 'aria2c.exe'进程,但也会停止我的 python 代码。我想知道我可以在命令提示符下实现吗?

如果你需要知道,这就是 cmd 上显示的内容:

    File "downloader.py", line 106, in download
      os.system(myCommand)
Keyboard interrupt

您可以捕获 KeyboardInterrupt 异常,然后执行您想要的代码。

if __name__ == '__main__':
    try:
        os.system("aria2c " + url + options)
    except KeyboardInterrupt:
        print('Keyboard Interrupt Detected')
            # the rest of your code
            pass

如果您的 os 是 windows,此代码将在单独的命令提示符中打开您的 EXE。

import os

if os.name == 'nt':
 os.system("start /wait cmd /c aria2c " + url + options)
else
 os.system("aria2c " + url + options)