python
nohup python my.py >> my.log 2>&1 &
# 或者
nohup python my.py >> nohup.out 2>&1 &
matlab
nohup matlab -nodisplay -nosplash -nodesktop <my.m &
nohup matlab -nodisplay -nosplash -nodesktop <my.m >nohup.out 2 >& 1 &
nohup matlab -nodisplay -nosplash -r matlab_script > outfile.txt &
nohup
(no hang up)命令用于在后台运行进程,即使用户注销或关闭终端,进程也不会被终止。nohup
通常与 &
(后台运行符号)结合使用,以确保命令在后台运行,并将输出重定向到一个文件(默认为 nohup.out
)。
使用 nohup
运行 Python 脚本
以下是如何使用 nohup
运行 Python 脚本 my.py
的示例:
nohup python my.py &
示例说明
nohup
: 确保命令在用户退出或终端关闭后继续运行。python my.py
: 执行my.py
脚本。&
: 将命令放在后台运行。
输出文件
默认情况下,nohup
将标准输出和标准错误输出重定向到 nohup.out
文件。如果你希望将输出重定向到其他文件,可以这样做:
nohup python my.py > my_output.log 2>&1 &
nohup python 2024_5_16.py > result_6_16.txt
重定向说明
> my_output.log
: 将标准输出重定向到my_output.log
文件。2>&1
: 将标准错误输出重定向到标准输出(即my_output.log
文件)。
完整示例
假设你的脚本 my.py
内容如下:
import time
for i in range(10):
print(f"Iteration {i}")
time.sleep(1)
运行以下命令:
nohup python my.py > my_output.log 2>&1 &
这样,my.py
脚本将在后台运行,输出和错误信息将被写入 my_output.log
文件中。你可以在脚本运行期间查看 my_output.log
文件,了解脚本的运行状态:
tail -f my_output.log
查看运行中的进程
你可以使用 ps
命令查看后台运行的进程,例如:
ps -ef | grep my.py
停止后台运行的进程
如果你需要停止后台运行的进程,可以使用 kill
命令。例如,如果你知道进程 ID(PID),可以执行:
kill <PID>
如果不确定进程 ID,可以结合 ps
和 grep
查找并停止进程:
ps -ef | grep my.py
kill <PID>
小结
使用 nohup
和 &
可以确保 Python 脚本在后台运行,即使用户退出或终端关闭,进程仍然会继续运行。这对于长时间运行的任务特别有用。