使用 nohup
命令可以在后台运行 Python 脚本,并且即使关闭终端,脚本也会继续运行。以下是具体步骤:
打开终端。
使用 nohup
命令运行 Python 脚本。基本语法如下:
nohup python your_script.py &
其中:
nohup
是 “no hang up” 的缩写,表示不挂起。python your_script.py
是你要运行的 Python 脚本。&
符号将命令放入后台运行。运行上述命令后,终端会显示类似以下的输出:
nohup: ignoring input and appending output to 'nohup.out'
这意味着脚本的输出会被重定向到当前目录下的 nohup.out
文件中。
你可以随时查看 nohup.out
文件来检查脚本的输出:
tail -f nohup.out
如果你想在特定的目录下运行脚本并输出到特定的文件,可以这样做:
nohup python your_script.py > output.log 2>&1 &
其中:
>
将标准输出重定向到 output.log
文件。2>&1
将标准错误输出重定向到标准输出,这样错误信息也会写入 output.log
文件。通过这些步骤,你可以确保 Python 脚本在后台运行,并且即使关闭终端,脚本也会继续执行。