場景
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是[]中的數字)
一圖總結上文
