import subprocess
cmd = subprocess.Popen('tracert -d 192.168.1.125', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
for info in iter(cmd.stdout.readline, 'b'):
if info == b'':
pass
else:
print(str(info, encoding='gbk'))
python代码如上,保存在test.py中,在Linux中执行python test.py 一直没有反应,直接ctrl后提示错误:
^CTraceback (most recent call last):
File "test.py", line 4, in <module>
for info in iter(cmd.stdout.readline, 'b'):
KeyboardInterrupt
请问是什么原因,如何chu'li
使用类似try——except结构捕获KeyboardInterrupt
的异常.然后continue重新开始新一轮的迭代训练
Python中的一种机制,按Ctrl+C显示这种异常,可以捕获的。
KeyboardInterrupt是使用 ctrl+c 强行停止程序后报的错误。
按照你说的运行文件一直没有结果,建议看看 cmd.stderr,如果 tracert 运行报错的话,报错信息会显示在 stderr 里,而 stdout 中不会有信息。
你是不是不小心按到了ctrl+c?