我正在 Windows 上使用 Python 3 编写一些代码,如下所示:
try:
do something that takes a long time
(training a neural network in TensorFlow, as it happens)
except KeyboardInterrupt:
print('^C')
print a summary of results
still useful even if the training was cut short early
如果使用 python foo.py
直接从控制台运行,则效果非常好。
但是,如果对 Python 的调用是在批处理文件中,它最终会执行上述所有操作,但仍然会向控制台发送“终止批处理作业”提示。
有办法阻止这种情况发生吗?通过在Python中完全吃掉^C,直接跳出批处理文件还是其他方式?
最佳答案
在批处理文件中使用 break
( More info here ) 命令,这将禁用 CTRL+C 停止文件
编辑:根据this site中断命令
Newer versions of Windows (Windows ME, Windows 2000, Windows XP, and higher) only include this command for backward compatibility and turning the break off has no effect.
我亲自对此进行了测试,并且可以确认,当我找到解决方法时我会进行编辑
编辑#2:如果您可以有第二个批处理脚本来运行start ""/b/wait cmd/c "yourfile.bat"
,那么这是已知会导致其他嵌套批处理文件出现故障
禁用 Ctrl+C 的标志由子进程继承,因此 Python 将不再引发键盘中断。另外,如果从控制台的读取被 Ctrl+C 中断而没有从 CRT 获得 SIGINT,那么 Python 中仍然存在错误。 Python 脚本应通过 ctypes 手动启用 Ctrl+C。使用导入ctypes; kernel32 = ctypes.WinDLL('kernel32', use_last_error=True);成功 = kernel32.SetConsoleCtrlHandler(None, False)
编辑 #3 正如 Eryksyn(在评论中)所指出的,您可以使用 cytpes 启用它;
import ctypes;
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True); success = kernel32.SetConsoleCtrlHandler(None, False)
编辑#4:我想我找到了它,试试这个(尽管它可能不起作用)你可以使用 threading进口?
import time
from threading import Thread
def noInterrupt():
for i in xrange(4):
print i
time.sleep(1)
a = Thread(target=noInterrupt)
a.start()
a.join()
print "done"
关于python - 停止键盘中断到达批处理文件处理器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47600301/