linux 命令 抛后台,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
問題:直接在終端執(zhí)行:python test.py, 需要在這個終端一直等,沒法干別的事了。如何讓代碼在后端執(zhí)行?
&——讓命令后臺執(zhí)行
python test.py &
在命令后面加&,可以讓命令在后臺執(zhí)行
問題:打印的東西還是會在終端顯示,這明顯干擾正常的工作啊,如何把打印的東西打打到指定的文件?
>——輸出重定向
python test.py >out.txt &
這樣就會把輸出打印到out.txt
問題:如果中間發(fā)生了異常,錯誤信息就丟啦,比如下面的代碼,如何把錯誤信息也打印到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 ——將標(biāo)準(zhǔn)出錯重定向到標(biāo)準(zhǔn)輸出
python test.py > out.txt 2>&1 &
執(zhí)行可以看到錯誤
2
3
4
5
6
7
8
9
10
Traceback (most recent call last):
File "test.py", line 8, in
i = i / 0
ZeroDivisionError: integer division or modulo by zero
歐耶,搞定,書歸正傳,把異常代碼干掉繼續(xù)
問題:關(guān)閉本終端,后臺程序終止了,尷尬。如何在關(guān)閉本終端是程序可以依然執(zhí)行
nohup——退出終端后,程序依然后臺執(zhí)行
nohup python test.py > out.txt 2>&1 &
關(guān)閉終端,再重新進入終端,可以可以看到進程是或者的,目前查看進程存活的方式是ps -ef | grep test。
問題:能否有專門的命令,看到所有后臺執(zhí)行的命令
jobs——查看后臺執(zhí)行的進程
$ 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]后面的狀態(tài)是不同的,最后啟動的放在最后邊
問題:怎么把后臺執(zhí)行的命令重新調(diào)到前端執(zhí)行呢?
fg——把后臺執(zhí)行的命令
$ fg
nohup python test3.py > out.txt 2>&1
可以看到調(diào)入前臺重新執(zhí)行的是[3]+, 狀態(tài)是+的。 剛才jobs里的能否指定某一個呢,可以的
$ fg %1
nohup python test.py > out.txt 2>&1
注意:%1, 中間沒有空格,1,就是上面的[1]編號
如何把調(diào)入前臺執(zhí)行的命令終止呢?Ctrl + C
問題:如何暫停某個進程?
Ctrl+z——暫停某個進程
目前在執(zhí)行test, Ctrl+Z暫停,然后看看現(xiàn)在進程的狀態(tài)
$ jobs
[1]+ Stopped nohup python test.py > out.txt 2>&1
[2]- Running nohup python test2.py > out.txt 2>&1 &
問題:如何繼續(xù)執(zhí)行暫停的進程
bg——繼續(xù)執(zhí)行后臺暫停的進程
$ 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 &
問題:是繼續(xù)執(zhí)行,還是重新執(zhí)行呢?
繼續(xù)執(zhí)行,以下代碼驗證下
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后,是暫停的,后面執(zhí)行時,數(shù)字接著執(zhí)行,如果是這樣感覺這個命令好強大
除了程序執(zhí)行結(jié)束,如何殺死進程
kil——終止進程
根據(jù)jobs -l 得到的進程號,直接kill pid 或者 kill jobno (這里的jobno是[]中的數(shù)字)
一圖總結(jié)上文
總結(jié)
以上是生活随笔為你收集整理的linux 命令 抛后台,Linux 后台执行命令的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux字体如何删除不了,如何彻底替换
- 下一篇: linux系统的4个部分,以下是Linu