Python中os.system()、subprocess.run()、call()、check_output()的使用案例
1.os.system()
os.system() 是對(duì) C 語(yǔ)言中 system() 系統(tǒng)函數(shù)的封裝,允許執(zhí)行一條命令,并返回退出碼(exit code),命令輸出的內(nèi)容會(huì)直接打印到屏幕上,無(wú)法直接獲取。
示例:
# test.py import os os.system("ls -l | grep test") # 允許管道符 # 測(cè)試執(zhí)行 $ ll <======== 列出當(dāng)前目錄中的內(nèi)容 drwxr-xr-x 2 foo foo 4096 Feb 13 09:09 __pycache__ -rw-r--r-- 1 foo foo 359 Feb 19 09:21 test.py $ python test.py -rw-r--r-- 1 foo foo 359 Feb 19 09:21 test.py <======== 只有名字包含 test 的文件被列出
2.subprocess.run()
Python 3.5 開(kāi)始推薦使用這個(gè)方法執(zhí)行命令,其原型如下:
subprocess.run( args, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, text=None, env=None, universal_newlines=None )
其中:
args: 可以是一個(gè)字符串(當(dāng) shell=True 時(shí)),也可以是一個(gè)列表(當(dāng) shell=False 時(shí))
- stdin, stdout, stderr: 用于指定標(biāo)準(zhǔn)IO文件句柄,可以是:
subprocess.PIPE: 用作 stdout, stderr 參數(shù)的值時(shí),可以從返回值對(duì)象中的 stdout 和 stderr 屬性中讀取輸出內(nèi)容 subprocess.STDOUT: 用作 stderr 參數(shù)的值時(shí),相當(dāng)于把標(biāo)準(zhǔn)錯(cuò)誤重定向到標(biāo)準(zhǔn)輸入中) subprocess.DEVNULL: 用作 stdout, stderr 參數(shù)的值時(shí),相當(dāng)于把輸出內(nèi)容重定向到 /dev/null 用戶已經(jīng)打開(kāi)的文件對(duì)象或描述符(整型數(shù)字)
capture_output: 當(dāng)設(shè)置為 True 時(shí),相當(dāng)于 stdout 和 stderr 參數(shù)都設(shè)置為 True 了,可以通過(guò)返回值對(duì)象訪問(wèn)標(biāo)準(zhǔn)輸出和標(biāo)準(zhǔn)錯(cuò)誤內(nèi)容
shell: 當(dāng)設(shè)置為 True 時(shí),args 參數(shù)會(huì)當(dāng)做一條命令字符串(支持管道、重定向操作);當(dāng)它為 False 時(shí),args 需是一個(gè)列表(并且不支持管道、重定向操作)
cwd: 指定執(zhí)行命令的目錄,默認(rèn)為當(dāng)前目錄
timeout: 指定命令執(zhí)行超時(shí)時(shí)間(按妙計(jì)),若執(zhí)行超時(shí)了,會(huì) kill 掉命令并拋出 TimeoutExpired 異常
check: 當(dāng)設(shè)置為 True 時(shí),會(huì)自動(dòng)檢測(cè)執(zhí)行退出碼,若不為0,則拋出 CalledProcessError 異常
text: 當(dāng)設(shè)置為 True 時(shí),stdin、stdout、stderr 會(huì)以“文本”模式打開(kāi)(返回值對(duì)象中的 stdout、stderr 存儲(chǔ)文本內(nèi)容),否則返回值對(duì)象中 stdout、stderr 存儲(chǔ)的是字節(jié)序列
env: 用于設(shè)置程序執(zhí)行時(shí)繼承的環(huán)境變量等,默認(rèn)與當(dāng)前進(jìn)程相同
該方法返回一個(gè) CompletedProcess 對(duì)象,其中包含以下屬性:
- returncode: 執(zhí)行命令的退出碼
- stdout: 捕獲的標(biāo)準(zhǔn)輸出內(nèi)容(當(dāng) stdout 參數(shù)為 PIPE 時(shí))。其格式默認(rèn)為字節(jié)序列,除非 text 參數(shù)為 True (此時(shí)為文本格式)。
- stderr: 捕獲的標(biāo)準(zhǔn)錯(cuò)誤內(nèi)容(當(dāng) stderr 參數(shù)為 PIPE 時(shí))。其格式默認(rèn)為字節(jié)序列,除非 text 參數(shù)為 True (此時(shí)為文本格式)。
- args: 同參數(shù) args 。
示例:
import subprocess subprocess.run(["ls", "-l"]) # 默認(rèn)時(shí),args 參數(shù)需是一個(gè)列表 subprocess.run("ls -l", shell=True) # 當(dāng) shell 為 True 時(shí),args 是一個(gè)字符串 ret = subprocess.run("ls -l", shell=True, capture_output=True, text=True) # 以文本模式捕獲輸出內(nèi)容 print("Return code:", ret.returncode) # Return code: 0 print("STDOUT:", ret.stdout) # STDOUT: ...當(dāng)前目錄內(nèi)容... print("STDERR:", ret.stderr) # STDERR: <空> ret = subprocess.run("abcdefg", shell=True, text=True, # 注意:這里必須 shell=True 才能捕獲到 /bin/sh 的輸出錯(cuò)誤 # 當(dāng) shell=False 時(shí),是要去捕獲 "abcdefg" 命令自身輸出的內(nèi)容,但是它不存在,python 會(huì)報(bào)錯(cuò) stdout=subprocess.PIPE, stderr=subprocess.STDOUT # 標(biāo)準(zhǔn)錯(cuò)誤重定向到標(biāo)準(zhǔn)輸出 ) print("STDOUT:", ret.stdout) # STDOUT: /bin/sh: abcdefg: command not found
另一個(gè)用于測(cè)試 shell 參數(shù)區(qū)別的示例如下:
import sys, re, subprocess if len(sys.argv) == 1: # parent process cmd = ["python", sys.argv[0], "--run-child"] ret = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) print(ret) # CompletedProcess(args=['python', 'test.py', '--run-child'], returncode=0, stdout='stdout output\n', stderr='stderr output') assert re.match("stdout output", ret.stdout) assert re.match("stderr output", ret.stderr) # 如果 cmd 中的命令不存在,這里是捕獲不到的,subprocess.run()自己就會(huì)報(bào)錯(cuò) ret = subprocess.run(" ".join(cmd), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) print(ret) # CompletedProcess(args='python test.py --run-child', returncode=0, stdout='stdout output\n', stderr='stderr output') assert re.match("stdout output", ret.stdout) assert re.match("stderr output", ret.stderr) # 如果 cmd 中的命令不存在,這里也是可以捕獲到的,內(nèi)容可能是 xxx command not found print("Passed!") else: # child process print("stdout output") sys.stderr.write("stderr output")
3.subprocess.call()
Python 3.5 以前(包括 2.x 版本)沒(méi)有 subprocess.run() 方法,可以使用 subprocess.call() 來(lái)執(zhí)行命令,該方法原型如下:
subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None)
注意:這個(gè)方法的返回值是命令的退出碼,而不是一個(gè)對(duì)象,所以無(wú)法像 subprocess.run() 一樣捕獲命令輸出內(nèi)容(不要設(shè)置 stdout=PIPE 或 stderr=PIPE,否則可能造成命令卡死)。
該方法的其它參數(shù)與 subprocess.run() 類似。
4.subprocess.check_output()
Python 3.5 以前的版本,要想捕獲命令輸出內(nèi)容,可以使用 subprocess.check_output() 方法,它的原型如下:
subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, cwd=None, encoding=None, errors=None, universal_newlines=None, timeout=None, text=None)
注意:參數(shù)中沒(méi)有 stdout ,因?yàn)檫@個(gè)函數(shù)的返回值默認(rèn)就是標(biāo)準(zhǔn)輸出內(nèi)容,也可以將設(shè)置 stderr=subprocess.STDOUT 將標(biāo)準(zhǔn)錯(cuò)誤重定向到標(biāo)準(zhǔn)輸出,但是好像沒(méi)有辦法單獨(dú)捕獲標(biāo)準(zhǔn)錯(cuò)誤內(nèi)容呢!
示例:
import sys, re, subprocess if len(sys.argv) == 1: # parent process cmd = ["python", sys.argv[0], "--run-child"] ret = subprocess.check_output(cmd, stderr=subprocess.STDOUT) print("[" + ret + "]") # 輸出內(nèi)容中包含標(biāo)準(zhǔn)輸出和標(biāo)準(zhǔn)錯(cuò)誤,輸出順序在 windows 下和 linux 下可能會(huì)有差異 assert re.search("stdout output", ret) assert re.search("stderr output", ret) print("Passed!") else: # child process print("stdout output") sys.stderr.write("stderr output")
到此這篇關(guān)于Python中os.system()、subprocess.run()、call()、check_output()的使用方法的文章就介紹到這了,更多相關(guān)Python中os.system()、subprocess.run()、call()、check_output()內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用Python和大模型進(jìn)行數(shù)據(jù)分析和文本生成
Python語(yǔ)言以其簡(jiǎn)潔和強(qiáng)大的特性,成為了數(shù)據(jù)科學(xué)、機(jī)器學(xué)習(xí)和人工智能開(kāi)發(fā)的首選語(yǔ)言之一,在這篇文章中,我將介紹如何用Python連接和使用大模型,并通過(guò)示例展示如何在實(shí)際項(xiàng)目中應(yīng)用這些技術(shù),需要的朋友可以參考下2024-05-05Python實(shí)現(xiàn)獲取照片拍攝日期并重命名的方法
這篇文章主要介紹了Python實(shí)現(xiàn)獲取照片拍攝日期并重命名的方法,涉及Python針對(duì)文件屬性及文件名相關(guān)操作技巧,需要的朋友可以參考下2017-09-09Python處理Excel文件遇到的常見(jiàn)問(wèn)題解析與解決
Python 的 pandas 庫(kù)提供了便捷的 read_excel() 方法,但在實(shí)際使用中,我們可能會(huì)遇到各種問(wèn)題,本文將分析這些常見(jiàn)錯(cuò)誤,并提供 Python 和 Java 的解決方案,有需要的可以參考下2025-04-04