在 Linux 中,您可以使用 nohup 命令将 Python 脚本在后台运行,即使关闭终端或断开连接也不会中断
打开终端。
使用 cd 命令导航到包含您的 Python 脚本的目录。例如:
cd /path/to/your/python/script
使用以下命令在后台运行 Python 脚本:
nohup python script_name.py &
其中,script_name.py 是您的 Python 脚本的文件名。& 符号表示将进程放入后台运行。
运行此命令后,您将看到一个类似于以下的输出:
nohup: ignoring input and appending output to 'nohup.out'
这意味着脚本的输出将被重定向到名为 nohup.out 的文件中。如果您想将输出重定向到其他文件,可以使用以下命令:
nohup python script_name.py > output_file.txt &
现在,您的 Python 脚本将在后台运行,即使您关闭终端或断开连接也不会中断。
若要检查脚本的输出,可以使用 tail 命令查看 nohup.out 文件的内容:
tail -f nohup.out
如果您想要停止后台运行的 Python 脚本,可以使用 ps 和 kill 命令找到并终止进程。首先,使用以下命令查找进程 ID(PID):
ps aux | grep script_name.py
然后,使用 kill 命令终止进程:
kill PID
其中,将 PID 替换为您在上一步中找到的进程 ID。