Skip to main content
 首页 » 编程设计

python之Raspberry Pi之如果发生错误并中断正在运行的代码,是否可以重新启动 python 程序

2025年02月15日9zhujiabin

我想知道是否有可能重新启动 python 程序(自动 ofc,最好使用简单的脚本),以防遇到问题并关闭它。我的算法有时无法按照我希望的方式运行,但我是否能够让它重新启动并不重要。

代码:

dongle = serial.Serial(port='/dev/ttyUSB0',baudrate=9600,timeout=0,rtscts=0,xonxoff=0) 
ard = serial.Serial(port="/dev/ttyACM0", baudrate=9600) 
time.sleep(0.5) 
while True: 
#       ard.open() 
        discard = ard.readline() 
        string = ard.readline() 
        print discard 
        print string 
        time.sleep(0.5) 
        temperature, truebung, latitude, longtitude  = string.split(",") 

基本上,每 10 次发生一次,“字符串”已损坏。它没有给我想要的数据。它遗漏了一些东西或给了我一个随机值。通常,该字符串应类似于“24.04,0.23,18.92442,40.25255”,但有时它会损坏并类似于“40.25255”或“.25255”。我“ard.readline”两次,因为最初“丢弃”总是损坏,现在字符串也损坏了。我该怎么做才能解决这个问题?如果字符串每 10 次不正确一次并不重要,但它会使我的程序崩溃,而这正是我不希望它做的事情。

请您参考如下方法:

我要在这里冒险并假设您的程序因最后一行的 ValueError 而崩溃:

temperature, truebung, latitude, longtitude  = string.split(",") 

当没有足够的元素时。错误应该类似于 ValueError: not enough values to unpack (expected 4, got [x]) 如果是这样,修复非常简单。如果我猜对了您的错误代码,下面的代码应该可以防止您的程序崩溃。

try: 
    temperature, truebung, latitude, longtitude  = string.split(",") 
except ValueError: 
    print "corrupt string" # and whatever else you want to do to handle the error