在Python中重新运行函数可以通过以下几种方法:
使用循环结构
while True:
函数调用
your_function()
使用递归函数
def repeat_function(n):
if n > 0:
your_function()
repeat_function(n-1)
使用定时器 (例如使用`time`模块):import time
while True:
函数调用
your_function()
time.sleep(your_desired_time_in_seconds)
使用命令行
import time
while True:
函数调用
your_function()
time.sleep(your_desired_time_in_seconds)
```bash
python your_script.py
```
使用交互式Python解释器
```python
import your_script
your_script.your_function()
```
使用集成开发环境(IDE)
大多数IDE如PyCharm、Visual Studio Code等都提供了重新运行程序的快捷键或菜单选项。
使用异常调用函数本身
```python
def restart():
try:
your_function()
except EOFError as e:
print(e)
finally:
restart()
```
使用`execfile()`或`exec()`函数(不推荐,因为可能存在安全问题):
execfile('your_script.py')
或
exec('your_script.py')