简体   繁体   English

如果发生断开连接,希望引发异常,然后在另一个文件中重新启动main方法。 我应该如何实施呢?

[英]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.

相关问题 发生异常时,我应该提出还是冒犯? - When exception occurs should I raise or bubble it up? 如何在主要方法中正确引发自定义异常? - how to raise a custom exception in main method proper? 如何检查参数是否“看起来像” yaml 文件的路径。 在 python 中引发异常 - How to check if the argument "looks like" a path to a yaml file. Raise exception in python 如果发生异常如何重新启动try循环 - How to restart try loop if exception occurs Python:如何在 function 中正确实施引发异常 - Python : How to properly implement a raise an exception in a function 如何正确引发文件异常 - How to properly raise a file exception 使用eventlet.GreenPool.spawn时,如何在主线程中引发异常 - How can I raise exception in main thread when using eventlet.GreenPool.spawn 我希望重新组织 CSV 文件中的数据。 CSV 文件具有多行字段,数据如下所示: - I am looking to reorganize the data in CSV file. CSV file has multiline fields and this is how data looks like: 当芹菜发生异常时,如何不调用方法? - how not to call a method when an exception occurs in celery? 哪个异常通知子类应该实现一个方法? - Which Exception for notifying that subclass should implement a method?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM