如何让程序在错误停止后自动重启?

2 投票
2 回答
990 浏览
提问于 2025-04-20 14:22

在Python中,我经常使用try-except语句来处理特定的情况。不过,有时候会出现一些意想不到的错误,而我无法预见所有的错误。那么,在像Linux这样的环境中,当我的Python程序停止运行时,我该如何让它重新启动呢?

2 个回答

0

你可以试着把你的Python代码放在一个无限循环的while循环里,这样在命令行中就能一直运行:

$ while :
do
python -c '1 + []'
done
Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'

你也可以很简单地把同样的做法应用到一个Python脚本里:

$ while :
do
python mycode.py
done
1

你可以捕捉到 BaseException 这个类。它是所有错误的基础类,所以你可以处理所有类型的错误。

如果你想在遇到一些严重问题时,比如内存泄漏或者段错误,仍然让程序继续运行,你应该写一个监视程序。监视程序就是一个会检查指定进程是否在运行的程序,如果没有运行,就会重新启动它。

撰写回答