[英]Kill only a subprocess created by python on CMD
我制作了一个python脚本,它通过运行可以在 Windows 和 Linux 上运行的 shell 命令使用aria2下载器进行下载。
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窗口上, 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
如果您的操作系统是 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.