简体   繁体   English

只杀死一个由 py​​thon 在 CMD 上创建的子进程

[英]Kill only a subprocess created by python on CMD

I have made a python script which downloads using aria2 downloader by running a shell command which can work on Windows and Linux.我制作了一个python脚本,它通过运行可以在 Windows 和 Linux 上运行的 shell 命令使用aria2下载器进行下载。

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

Now, I want to test my program for the situation when file could not be downloaded.现在,我想测试我的程序是否存在无法下载文件的情况。 So, after executing the 'python downloader.py' on command-prompt (cmd.exe) Windows, I press Ctrl+C to stop only the download (' aria2c.exe ' process only) but keep running my python code.因此,在命令提示符 (cmd.exe) Windows 上执行“python downloader.py”后,我按Ctrl+C仅停止下载(仅“ aria2c.exe ”进程)但继续运行我的 python 代码。

Doing this on Ubuntu terminal works fine!Ubuntu终端上执行此操作可以正常工作! But on cmd windows, Ctrl+C stops ' aria2c.exe ' process but also stops my python code.但是在cmd窗口上, Ctrl+C 会停止“ aria2c.exe ”进程,但也会停止我的 python 代码。 I want to know I can achieve this on command prompt?我想知道我可以在命令提示符下实现这个吗?

If you need to know, this is what shows up on cmd:如果您需要知道,这就是 cmd 上显示的内容:

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

You could catch the KeyboardInterrupt exception, then execute the code you want to afterward.您可以捕获KeyboardInterrupt异常,然后执行您想要的代码。

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

This code will open your EXE in the separate command prompt if your os is windows.如果您的操作系统是 windows,此代码将在单独的命令提示符下打开您的 EXE。

import os

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM