Python標(biāo)準(zhǔn)庫系列之subprocess模塊

本系列文章來源:<a>https://blog.ansheng.me/article/python-full-stack-way</a>

常用方法實例

call()
執(zhí)行命令,并返回狀態(tài)碼,狀態(tài)碼0代表命令執(zhí)行成功,其他的都表示命令執(zhí)行不成功

>>> ret = subprocess.call(["ls", "-l"], shell=False)
total 4
-rw-r--r-- 1 root root 172 May 25 21:21 file.conf
>>> ret
0

另一種執(zhí)行方式

# shell=True表示調(diào)用原生的shell命令去執(zhí)行
>>> ret = subprocess.call("ls -l", shell=True)
total 4
-rw-r--r-- 1 root root 172 May 25 21:21 file.conf
>>> ret
0

check_call()
執(zhí)行命令,如果執(zhí)行狀態(tài)碼是0,則返回0,否則拋異常

# 執(zhí)行一個正確的命令就會返回執(zhí)行結(jié)果和狀態(tài)碼
>>> subprocess.check_call(["ls", "-l"])
total 4
-rw-r--r-- 1 root root 172 May 25 21:21 file.conf
0
# 如果執(zhí)行的是一個錯誤的命令,那么就會返回錯誤信息
>>> subprocess.check_call(["ls", "a"])  
ls: cannot access a: No such file or directory
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib64/python2.6/subprocess.py", line 505, in check_call
    raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['ls', 'a']' returned non-zero exit status 2

check_output()

執(zhí)行命令,如果狀態(tài)碼是0,則返回執(zhí)行結(jié)果,否則拋異常

# 執(zhí)行成功就把執(zhí)行的結(jié)果賦值給變量V
>>> V = subprocess.check_output("python -V", shell=True)
# 執(zhí)行錯誤的命令就會輸出異常
>>> subprocess.check_output("pasas", shell=True)
'pasas' 不是內(nèi)部或外部命令,也不是可運行的程序
或批處理文件。
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python35\lib\subprocess.py", line 629, in check_output
    **kwargs).stdout
  File "C:\Python35\lib\subprocess.py", line 711, in run
    output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command 'pasas' returned non-zero exit status 1

以上的三種執(zhí)行方式在執(zhí)行命令的時候,shell默認(rèn)等于True,等于True的時候,括號內(nèi)的命令是一行的,如果shell等于False,那么[]內(nèi)的字符串就是命令的一個元素,執(zhí)行的時候會把[]內(nèi)的字符串拼接起來執(zhí)行。

subprocess.Popen()

call()、check_call()、check_output()默認(rèn)內(nèi)部調(diào)用的都是subprocess.Popen(),而subprocess.Popen()則用于執(zhí)行更復(fù)雜的系統(tǒng)命令。

參數(shù)

參數(shù)  說明
stdin   標(biāo)準(zhǔn)輸入
stdout  標(biāo)準(zhǔn)輸出
stderr  錯誤句柄
cwd 用于設(shè)置子進(jìn)程的當(dāng)前目錄
env 用于指定子進(jìn)程的環(huán)境變量。如果env = None,子進(jìn)程的環(huán)境變量將從父進(jìn)程中繼承

執(zhí)行普通命令

In [1]: import subprocess

In [2]: subprocess.Popen("python -V",shell=True)
Out[2]: <subprocess.Popen at 0x2a00d656860>
# Python 3.5.2是輸出出來的結(jié)果
Python 3.5.2

執(zhí)行命令分為兩種:
1.輸入即可得到輸出,如:ifconfig
2.輸入進(jìn)行某交互式環(huán)境,依賴再輸入,如:python

# 先進(jìn)入'/tmp'目錄,然后在創(chuàng)建subprocess文件夾,shell=True可有可無
>>> subprocess.Popen("mkdir subprocess", shell=True, cwd='/tmp',)
<subprocess.Popen object at 0x7f267cc3d390>
>>> import os
>>> os.system("ls /tmp")
subprocess
subprocess.Popen()實例
# 導(dǎo)入subprocess模塊
import subprocess

# 執(zhí)行python命令,進(jìn)入python解釋器,stdin標(biāo)準(zhǔn)輸入、stdout標(biāo)準(zhǔn)輸出、stderr錯誤輸出,universal_newlines=True自動輸入換行符
obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)

# 執(zhí)行標(biāo)準(zhǔn)輸入,write后面是輸入的命令
obj.stdin.write("print(1)\n")
obj.stdin.write("print(2)")
# 輸入之后關(guān)閉
obj.stdin.close()

# 讀取標(biāo)準(zhǔn)輸出的內(nèi)容,賦值給cmd_out對象
cmd_out = obj.stdout.read()
# 關(guān)閉標(biāo)準(zhǔn)輸出
obj.stdout.close()

# 讀取錯誤輸出的內(nèi)容,賦值給cmd_error對象
cmd_error = obj.stderr.read()

# 關(guān)閉錯誤輸出
obj.stderr.close()

# 輸出內(nèi)容
print(cmd_out)
print(cmd_error)

執(zhí)行結(jié)果

C:\Python35\python.exe F:/Python_code/sublime/Week5/Day02/sub.py
1
2

Process finished with exit code 
# 導(dǎo)入subprocess模塊
import subprocess

# 執(zhí)行python命令,進(jìn)入python解釋器,stdin標(biāo)準(zhǔn)輸入、stdout標(biāo)準(zhǔn)輸出、stderr錯誤輸出,universal_newlines=True自動輸入換行符
obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)

# 執(zhí)行兩條命令
obj.stdin.write("print(1)\n")
obj.stdin.write("print(2)")

# communicate把錯誤輸出或者標(biāo)準(zhǔn)輸出的內(nèi)容賦值給out_error_list對象,如果有錯誤就賦值錯誤輸出,否則就復(fù)制標(biāo)準(zhǔn)輸出
out_error_list = obj.communicate()

# 輸出out_error_list對象的內(nèi)容
print(out_error_list)

執(zhí)行結(jié)果

C:\Python35\python.exe F:/Python_code/sublime/Week5/Day02/sub.py
('1\n2\n', '')

Process finished with exit code 0
# 導(dǎo)入subprocess模塊
import subprocess

# 執(zhí)行python命令,進(jìn)入python解釋器,stdin標(biāo)準(zhǔn)輸入、stdout標(biāo)準(zhǔn)輸出、stderr錯誤輸出,universal_newlines=True自動輸入換行符
obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)


# 直接執(zhí)行print("hello")命令,然后把錯誤或者正確的結(jié)果賦值給out_error_list對象
out_error_list = obj.communicate('print("hello")')

# 輸出out_error_list對象的內(nèi)容
print(out_error_list)

執(zhí)行結(jié)果

C:\Python35\python.exe F:/Python_code/sublime/Week5/Day02/sub.py
('hello\n', '')

Process finished with exit code 0
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容