[英]Looking to raise an exception if disconnect occurs and restart the main method in a separate file. How should I implement this?
If disconnect is called, I want to restart the main method from the connection.py file. 如果调用了断开连接,我想从connection.py文件重新启动main方法。 Main method does not restart with existing code when disconnect occurs. 断开连接时,main方法不会使用现有代码重新启动。
connection.py file* connection.py文件*
def disconnect(flags):
#do something
raise RuntimeError('You have been disconnected')
main.py file* main.py文件*
import connection
def main():
while True:
try:
#do something to invoke disconnect
except RuntimeError('You have been disconnected'):
main()
main()
Your try-except block is wrong. 您的try-except块是错误的。 I ran your code in python3, and it raised a very clear error, "builtins.TypeError: catching classes that do not inherit from BaseException is not allowed" Because of that unhandled exception, you exit main. 我在python3中运行了您的代码,它引发了一个非常明显的错误:“ builtins.TypeError:不允许捕获不继承自BaseException的类”。由于该未处理的异常,您退出了main。
Try these: 试试这些:
try:
raise RuntimeError('You have been disconnected')
except RuntimeError:
print ('caught')
try:
raise RuntimeError('You have been disconnected')
except RuntimeError as e:
print (str(e))
Because you already have a while loop in main, there's no need to recursively call main again. 因为您已经在main中建立了while循环,所以无需再次递归调用main。 Just let the while loop do its job: 只需让while循环执行其工作即可:
def main():
while True:
connect()
try:
raise RuntimeError('You have been disconnected')
except RuntimeError as e:
print (str(e))
If the error is caught, then you will still be inside the while loop. 如果发现错误,那么您仍将处于while循环内。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.