后台启动Python脚本
可以使用下面的命令来启动上面的脚本,让Python在后台运行。
nohup python -u main.py > test.out 2>&1 &
nohup python FlaskWx.py >/dev/null 2>&1 &
来解释一下这几个命令的参数。
其中 0、1、2分别代表如下含义:
0 – stdin (standard input)
1 – stdout (standard output)
2 – stderr (standard error)
nohup python -u main.py > test.out 2>&1 &
nohup+最后面的& 是让命令在后台执行
>out.log 是将信息输出到out.log日志中
2>&1 是将标准错误信息转变成标准输出,这样就可以将错误信息输出到out.log 日志里面来。
运行命令后,会返回一个pid。像下面这样:
[1] 9208
后续可以学习Hadoop它们,把pid存起来,到时候stop的时候就把它杀掉。
跟踪输出文件变化
为了验证脚本可以在后台继续运行,我们退出当前会话。然后重新连接一个Session,然后输入下面的命令来跟踪文件的输出:
tail -f test.out
输出内容如下:
output to the console
2017-03-21 20:15:02,632 main.py[line:11] DEBUG output the debug log
2017-03-21 20:15:02,632 main.py[line:12] INFO output the info log
output to the console
2017-03-21 20:15:05,635 main.py[line:11] DEBUG output the debug log
2017-03-21 20:15:05,636 main.py[line:12] INFO output the info log
output to the console
说明我们的脚本确实在后台持续运行。
结束程序
可以直接通过之前的那个pid杀掉脚本,或者可以通过下面的命令查找pid。
方法1:
ps -ef | grep python
方法2:
ps -x
输出的内容如下:
root 1659 1 0 17:40 ? 00:00:00 /usr/bin/python /usr/lib/python2.6/site-packages/ambari_agent/AmbariAgent.py start
root 1921 1659 0 17:40 ? 00:00:48 /usr/bin/python /usr/lib/python2.6/site-packages/ambari_agent/main.py start
user 8866 8187 0 20:03 ? 00:00:06 /usr/bin/python3 /usr/bin/update-manager --no-update --no-focus-on-map
root 9208 8132 0 20:12 pts/16 00:00:00 python -u main.py
root 9358 8132 0 20:17 pts/16 00:00:00 grep --color=auto python
可以看到我们的pid是9208,调用kill杀掉就可以了。
kill -9 9208