互联网中断后,python脚本将停止,并且不会再次启动

时间:2018-08-30 13:56:50

标签: python python-3.x

我有一个python3脚本,一旦我连接到互联网,该脚本就可以正常运行,但是一旦调制解调器重置,它就会停止工作。我在动态IP环境中工作,需要在服务器上的数据库中不断插入数据。

需要指导,如果我的连接断开了,那么我的脚本应该等待直到出现,然后再次开始将数据插入服务器。

1 个答案:

答案 0 :(得分:0)

好吧,您尚未提供任何可使用的代码,因此此建议将是相当通用的,但是处理此类问题的标准方法是将连接代码包装在while循环内。

keep_running = true
while keep_running:
    # here establish_connection() is something you will have written
    connection = establish_connection()
    insert_into_database(some_data, connection)

要解决连接不可用的可能性,请将该位包装在try / except

try:
    establish_connection()
except ConnectionError: # or whatever error you have
    # Do nothing and just cycle, maybe sleep if you  don't want to burn up your CPU
    pass

将所有内容放在一起

keep_running = true
while keep_running:
    # here establish_connection() is something you will have written
    try:
        connection = establish_connection()
        insert_into_database(some_data, connection)
    except ConnectionError:
        # Do nothing and just cycle, maybe sleep if you  don't want to burn up your CPU
        pass