p.stdout.read() :用於讀取標准輸出,會一次性讀取所有內容,返回一個字符串
p.stdout.readline() :用於讀取標准輸出,一次只讀取一行內容,返回一個字符串
p.stdout.readlines() :用於讀取標准輸出,一次性讀取所有內容,返回一個列表,每一行是列表的一個元素
from subprocess import Popen, PIPE p = Popen('ls /data', stdout=PIPE, shell=True) for line in p.stdout.readlines(): print(line),
[root@localhost ~]$ python 1.py 1.txt 2.txt 3.txt
p.wait() :等待子進程結束,並返回狀態碼。如下,如果沒有加上 p.wait(),則 sleep 100 還沒有執行完,就會執行 print('End'),如果加上就會等待 sleep 100 執行完
from subprocess import Popen, PIPE p = Popen('sleep 100', stdout=PIPE, shell=True) p.wait() print('End')
p.pid :用於查看子進程的PID
from subprocess import Popen, PIPE p = Popen('sleep 100', stdout=PIPE, shell=True) print(p.pid)
[root@localhost ~]$ python 1.py 35327 [root@localhost ~]$ ps aux | grep 35327 root 35327 0.0 0.0 107904 612 pts/0 S 17:56 0:00 sleep 100 root 35329 0.0 0.0 112676 984 pts/0 S+ 17:57 0:00 grep --color=auto 35327
p.poll() :用於檢查子進程(命令)是否已經執行結束,沒結束返回None,結束后返回狀態碼
#!/usr/bin/env python #-*- coding:utf-8 -*- import time from subprocess import Popen, PIPE p = Popen('sleep 3', stdout=PIPE, shell=True) while True: if p.poll() == None: print('程序執行中...') time.sleep(1) else: print('程序執行完畢, 狀態碼為:%s' % p.poll()) break
[root@localhost ~]$ python 1.py
程序執行中...
程序執行中...
程序執行中...
程序執行完畢, 狀態碼為:0
p.returncode :用於返回命令執行完之后的狀態碼
#!/usr/bin/env python #-*- coding:utf-8 -*- import time from subprocess import Popen, PIPE p = Popen('sleep 3', stdout=PIPE, shell=True) while True: if p.poll() == None: print('程序執行中...') time.sleep(1) else: print('程序執行完畢, 狀態碼為:%s' % p.returncode) break
[root@localhost ~]$ python 1.py
程序執行中...
程序執行中...
程序執行中...
程序執行完畢, 狀態碼為:0
p.kill() :用於殺死子進程
from subprocess import Popen, PIPE p = Popen('sleep 100', stdout=PIPE, shell=True) print(p.pid) p.kill()
[root@localhost ~]$ python 1.py 35403 [root@localhost ~]$ ps aux | grep 35403 # 可以看到子進程已經不在了 root 35405 0.0 0.0 112676 980 pts/0 S+ 18:12 0:00 grep --color=auto 35403
p.terminate() :用於終止子進程,與 kill() 差不多
from subprocess import Popen, PIPE p = Popen('sleep 100', stdout=PIPE, shell=True) print(p.pid) p.terminate()
[root@localhost ~]$ python 1.py 35403 [root@localhost ~]$ ps aux | grep 35403 # 可以看到子進程已經不在了 root 35405 0.0 0.0 112676 980 pts/0 S+ 18:12 0:00 grep --color=auto 35403
p.communicate() :該方法可用來與子進程進行交互,比如發送數據到stdin,結果會返回一個元組,這個元組包含stdout和stderr
from subprocess import Popen, PIPE p = Popen('cat', stdin=PIPE, stdout=PIPE, shell=True) print p.communicate('hello world')
[root@localhost ~]$ python 1.py ('hello world', None)