1. nohup
原来跑程序关了终端,程序就停了,咱的目的是后台挂起,关了终端,只要电脑不关程序就一直再跑,可以借助nohup
指令,接下来给个例子看看:
新建一个 shanchu.py
文件:
import time
while(1):
time.sleep(3)
print(time.time())
with open("x.txt", "a+") as f:
f.write("{}\n".format(time.time()))
shanchu.py
运行会将时间戳写入 x.txt
nohup python shanchu.py &
&:让命令在后台执行,终端退出后命令仍旧执行。
可以看下x.txt
的内容,以验证该程序是否在后台运行
2. 日志+错误重定向
但是这样在后台,要是程序报错了怎么办,要看程序输出怎么办,所以需要这样,将将输出写入log且错误重定向:
nohup python shanchu.py > log.log 2>&1 &
2>&1 解释:
将标准错误 2 重定向到标准输出 &1 ,标准输出 &1 再被重定向输入到 runoob.log 文件中。
- 0 – stdin (standard input,标准输入)
- 1 – stdout (standard output,标准输出)
- 2 – stderr (standard error,标准错误输出)
再来做个实验,修改一下python文件,多两个打印print
,最后print(ee)
故意报错
import time
while(1):
print(12)
print(23)
time.sleep(3)
print(time.time())
with open("x.txt", "a+") as f:
f.write("{}\n".format(time.time()))
print(ee)
执行:
nohup python shanchu.py > log.log 2>&1 &
来查看一下输出:
$ cat log.log
nohup: ignoring input
12
23
1665317182.0910141
Traceback (most recent call last):
File "shanchu.py", line 9, in <module>
print(ee)
NameError: name 'ee' is not defined
可以看到输出和错误都在log文件中
3. 手动结束该后台进程
原来后台运行程序,咱们可以用jobs -l
来查看
但是 jobs 命令只看当前终端生效的,关闭终端后,在另一个终端jobs已经无法看到后台跑得程序了,此时只能利用ps(进程查看命令)
ps -aux|grep shanchu.py
- a:显示所有程序
- u:以用户为主的格式来显示
- x:显示所有程序,不以终端机来区分
$ ps -aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
......
xxx 1028204 0.0 0.0 9440 7428 pts/0 Ss 12:21 0:00 -bash
xxx 1028402 0.8 0.0 12984 10736 pts/0 S 12:23 0:00 python shanchu.py
xxx 1028405 0.0 0.0 7892 3420 pts/0 R+ 12:23 0:00 ps -aux
$ ps -aux | grep shanchu.py
xxx 1028402 0.4 0.0 12984 10736 pts/0 S 12:23 0:00 python shanchu.py
xxx 1028409 0.0 0.0 5200 668 pts/0 S+ 12:23 0:00 grep shanchu.py
用ps -def | grep查找进程很方便,最后一行总是会grep自己
用grep -v参数可以将grep命令排除掉
$ ps -aux | grep shanchu.py | grep -v grep
xxx 1028402 0.0 0.0 12984 10736 pts/0 S 12:23 0:00 python shanchu.py
再用awk提取一下进程ID
$ ps -aux | grep shanchu.py | grep -v grep | awk '{print $2}'
1028402
然后 kill 结束进程即可
kill -9 进程号
有参考
https://www.runoob.com/linux/linux-comm-nohup.html
https://www.cnblogs.com/baby123/p/6477429.html