1

我制作了一个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 windows 上,Ctrl+C会停止“ aria2c.exe ”进程,但也会停止我的 python 代码。我想知道我可以在命令提示符下实现这个吗?

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

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

2 回答 2

1

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

if __name__ == '__main__':
    try:
        os.system("aria2c " + url + options)
    except KeyboardInterrupt:
        print('Keyboard Interrupt Detected')
            # the rest of your code
            pass
于 2020-03-27T21:03:27.840 回答
1

如果您的操作系统是 Windows,此代码将在单独的命令提示符下打开您的 EXE。

import os

if os.name == 'nt':
 os.system("start /wait cmd /c aria2c " + url + options)
else
 os.system("aria2c " + url + options)
于 2020-03-27T21:08:09.037 回答