Linux 后台执行Python脚本和nohub命令的用法

发布时间 2023-03-28 07:22:48作者: 技术改变命运Andy

示例:

nohup ./python /root/.jenkins/workspace/AutotestFramework/test_run/main.py > /root/.jenkins/workspace/AutotestFramework/test_run/main.out 2>&1 &

nohub用法

nohup /root/runoob.sh &

解释:以下命令在后台执行 root 目录下的 runoob.sh 脚本:、
在终端如果看到以下输出说明运行成功:
appending output to nohup.out
这时我们打开 root 目录 可以看到生成了 nohup.out 文件。

停止

如果要停止运行,你需要使用以下命令查找到 nohup 运行脚本到 PID,然后使用 kill 命令来删除:
ps -aux | grep "runoob.sh"
kill -9 进程号PID

nohup /root/runoob.sh > runoob.log 2>&1 &

解释:以下命令在后台执行 root 目录下的 runoob.sh 脚本,并重定向输入到 runoob.log 文件

2>&1 解释:
将标准错误 2 重定向到标准输出 &1 ,标准输出 &1 再被重定向输入到 runoob.log 文件中。
0 – stdin (standard input,标准输入)
1 – stdout (standard output,标准输出)
2 – stderr (standard error,标准错误输出)

nohup: ignoring input and appending output to ‘nohup.out‘

问题:在执行命令nohup sh xxx.sh &的时候,提示
nohup: ignoring input and appending output to nohup.out’ 意思是 :忽略输入并将输出附加到nohup.out’
程序也能正常启动。
如果不想看到这个提示可以使用:
nohup sh xxx.sh >a.log 2>& 1 &
或者
nohup sh xxx.sh &>a.log &
如果不想输入到a.log 可以使用
nohup sh xxx.sh >/dev/null 2>& 1 &

其中:
nohup放到命令开头表示不挂起,表示即使退出终端该进程也不会掉, & 放在命令到结尾,表示后台运行
/dev/null 表示空设备文件 (位桶(bit bucket)或者黑洞(black hole)的地方)
0 表示stdin标准输入
1 表示stdout标准输出
2 表示stderr标准错误
2>&1标识将错误输出重定向到标准输出,注意>& 不能分开

实际应用

echo "-----切到自动化Python虚拟环境-----" 
pwd
cd /home/crs-dev/.virtualenvs
. qzautotest/bin/activate
pwd
cd  /home/crs-dev/.virtualenvs/qzautotest/bin/
pwd
echo "-----查看是否有运行的master服务-----" 
PIDS_MAIN=`ps -ef|grep AutotestFramework/test_run/main.py|grep -v grep|cut -c 9-15`
if [ "$PIDS_MAIN" != "" ]; then
echo "-----有master服务,关闭所有的服务-----" 
ps -ef|grep AutotestFramework/test_run/main.py|grep -v grep|cut -c 9-15|xargs kill -9
fi
BUILD_ID=dontKillMe
echo "-----启动master服务-----" 
nohup ./python /root/.jenkins/workspace/AutotestFramework/test_run/main.py >/dev/null 2>& 1 &
ps -ef|grep AutotestFramework/test_run/main.py

echo "-----查看是否有运行的slave服务-----" 
PIDS_RUN=`ps -ef|grep AutotestFramework/test_run/run.py|grep -v grep|cut -c 9-15`
if [ "$PIDS_RUN" != "" ]; then
echo "-----有slave服务,关闭所有的服务-----"
ps -ef|grep AutotestFramework/test_run/run.py|grep -v grep|cut -c 9-15|xargs kill -9
fi
BUILD_ID=dontKillMe
echo "-----启动slave服务-----" 
nohup ./python /root/.jenkins/workspace/AutotestFramework/test_run/run.py >/dev/null 2>& 1 &
ps -ef|grep AutotestFramework/test_run/run.py