我在pycharm 3.8中处理异常时遇到了困难。
当我按ctrl+c运行我的程序时,它不工作,所以有人告诉我用pycharm控制台来测试,它确实工作,中断了键盘输入。
def readFloat(msg):
while True:
return float(input(f'{msg}'))
except (ValueError, TypeError):
print(f'\033[31mError. Not valid.\033[m')
continue
except KeyboardInterrupt:
print('\033[31mYou didn\'t type a number.\033[m')
return 0
b = readFloat('Your Number: ')
print(f'\nThat\'s your number: {b}')
但现在,当我尝试Control+C时,它没有捕捉到我的除外,也没有打印我的自定义错误报告,返回0。
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.1.1\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile
pydev_imports.execfile(filename, global_vars, local_vars) # execute the script
File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.1.1\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Users/User/PycharmProjects/Curso/Aula 23/ex113.py", line 35, in <module>
b = readFloat('Your Number: ')
File "C:/Users/User/PycharmProjects/Curso/Aula 23/ex113.py", line 26, in readFloat
return float(input(f'{msg}'))
File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.1.1\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_stdin.py", line 64, in readline
requested_input = self.rpc_client.requestInput()
File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.1.1\plugins\python-ce\helpers\pydev\_pydev_comm\pydev_transport.py", line 226, in _req
return super(TSyncClient, self)._req(_api, *args, **kwargs)
File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.1.1\plugins\python-ce\helpers\third_party\thriftpy\_shaded_thriftpy\thrift.py", line 160, in _req
return self._recv(_api)
File "C:\Program Files\JetBrains\PyCharm Community Edition 2020.1.1\plugins\python-ce\helpers\third_party\thriftpy\_shaded_thriftpy\thrift.py", line 192, in _recv
raise v
console_thrift.KeyboardInterruptException: KeyboardInterruptException()
所以我试着添加一个通用的异常,只是为了打印错误类,结果是这样的。
Error found: <class 'console_thrift.KeyboardInterruptException'>
所以我不能设法检测到一个除键盘中断并与之合作,只是使用一个通用的异常,有什么想法?
我添加的唯一一个插件是一个主题用户界面,用于完全黑色地运行pycharm,其余的都是安装时附带的,我想。我用CMD运行了.py文件,它工作得很好,可以检测到键盘中断。
2 个回答
0 人赞同
Try this:
from console_thrift import KeyboardInterruptException as KeyboardInterrupt
except ImportError: