Linux 后台执行命令

场景

python 代码,打印1~3000,每秒打印一次

## file_name: test.py
import time
i = 0 
while 1:
    time.sleep(1)
    i = i + 1 
    print(i)
    if i > 3000:
        break

问题:直接在终端执行:python test.py, 需要在这个终端一直等,没法干别的事了。如何让代码在后端执行?

&——让命令后台执行

python test.py &

在命令后面加&,可以让命令在后台执行

问题:打印的东西还是会在终端显示,这明显干扰正常的工作啊,如何把打印的东西打打到指定的文件?

>——输出重定向

python test.py >out.txt &

这样就会把输出打印到out.txt

问题:如果中间发生了异常,错误信息就丢啦,比如下面的代码,如何把错误信息也打印到out.txt呢?

import time
i = 0 
while 1:
    time.sleep(1)
    i = i + 1 
    print(i)
    if i == 10: 
        i = i / 0 
    if i > 3000:
        break

2>&1 ——将标准出错重定向到标准输出

python test.py > out.txt 2>&1 &

执行可以看到错误

2
3
4
5
6
7
8
9
10
Traceback (most recent call last):
  File "test.py", line 8, in <module>
    i = i / 0 
ZeroDivisionError: integer division or modulo by zero

欧耶,搞定,书归正传,把异常代码干掉继续

问题:关闭本终端,后台程序终止了,尴尬。如何在关闭本终端是程序可以依然执行

nohup——退出终端后,程序依然后台执行

nohup python test.py > out.txt 2>&1 &

关闭终端,再重新进入终端,可以可以看到进程是或者的,目前查看进程存活的方式是ps -ef | grep test。

问题:能否有专门的命令,看到所有后台执行的命令

jobs——查看后台执行的进程

$ jobs
[1]+  Running                 nohup python test.py > out.txt 2>&1 &

如果有多个呢?再起一个类似的后台进程test2, test3,另外把具体的pid也打出来

[1]  192415 Running           nohup python test.py > out.txt 2>&1 &
[2]- 192646 Running           nohup python test2.py > out.txt 2>&1 &
[3]+ 192647 Running           nohup python test3.py > out.txt 2>&1 &

可以看到,[1][2][3]后面的状态是不同的,最后启动的放在最后边

问题:怎么把后台执行的命令重新调到前端执行呢?

fg——把后台执行的命令

$ fg
nohup python test3.py > out.txt 2>&1

可以看到调入前台重新执行的是[3]+, 状态是+的。 刚才jobs里的能否指定某一个呢,可以的

$ fg %1
nohup python test.py > out.txt 2>&1

注意:%1, 中间没有空格,1,就是上面的[1]编号

如何把调入前台执行的命令终止呢?Ctrl + C

问题:如何暂停某个进程?

Ctrl+z——暂停某个进程

目前在执行test, Ctrl+Z暂停,然后看看现在进程的状态

$ jobs
[1]+  Stopped                 nohup python test.py > out.txt 2>&1
[2]-  Running                 nohup python test2.py > out.txt 2>&1 &

问题:如何继续执行暂停的进程

bg——继续执行后台暂停的进程

$ bg %1
[1]+ nohup python test.py > out.py 2>&1 &
t$ jobs
[1]-  Running                 nohup python test.py > out.py 2>&1 &
[2]+  Running                 nohup python test2.py > out.py 2>&1 &

问题:是继续执行,还是重新执行呢?

继续执行,以下代码验证下

import time
import datetime

i = 0 
while 1:
    time.sleep(1)
    i = i + 1 
    print(i)
    now = datetime.datetime.now()
    print(now.strftime('%a, %b %d %H:%M:%S'))
    if i > 3000:
        break

可以看到在打印到20后,是暂停的,后面执行时,数字接着执行,如果是这样感觉这个命令好强大

除了程序执行结束,如何杀死进程

kil——终止进程

根据jobs -l 得到的进程号,直接kill pid 或者 kill jobno (这里的jobno是[]中的数字)

一图总结上文

posted @ 2020-06-06 16:49  jihite  阅读(8133)  评论(0编辑  收藏  举报