用Python 執(zhí)行cmd命令
更新時間:2020年12月18日 17:09:43 作者:小菠蘿測試筆記
這篇文章主要介紹了用Python 執(zhí)行cmd命令的方法,幫助大家更好的理解和使用python,感興趣的朋友可以了解下
我們通常可以使用os模塊的命令進行執(zhí)行cmd
方法一:os.system
os.system(執(zhí)行的命令) # 源碼 def system(*args, **kwargs): # real signature unknown """ Execute the command in a subshell. """ pass
方法二:os.popen(執(zhí)行的命令)
os.popen(執(zhí)行的命令)
# 源碼
def popen(cmd, mode="r", buffering=-1):
if not isinstance(cmd, str):
raise TypeError("invalid cmd type (%s, expected string)" % type(cmd))
if mode not in ("r", "w"):
raise ValueError("invalid mode %r" % mode)
if buffering == 0 or buffering is None:
raise ValueError("popen() does not support unbuffered streams")
import subprocess, io
if mode == "r":
proc = subprocess.Popen(cmd,
shell=True,
stdout=subprocess.PIPE,
bufsize=buffering)
return _wrap_close(io.TextIOWrapper(proc.stdout), proc)
else:
proc = subprocess.Popen(cmd,
shell=True,
stdin=subprocess.PIPE,
bufsize=buffering)
return _wrap_close(io.TextIOWrapper(proc.stdin), proc)
兩者區(qū)別
- system只把能輸入的內(nèi)容給返回回來了,其中代碼 0 表示執(zhí)行成功。但是我們沒有辦法獲取輸出的信息內(nèi)容
- popen可以獲取輸出的信息內(nèi)容,它是一個對象,可以通過 .read() 去讀取
以上就是用Python 執(zhí)行cmd命令的詳細內(nèi)容,更多關(guān)于python 執(zhí)行cmd命令的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python實現(xiàn)WebP格式轉(zhuǎn)成JPG、PNG和JPEG的方法
平時在網(wǎng)上搜索圖片,另存為時常常遇到 WebP 格式,而非常見的 JPG、PNG、JPEG 格式,所以以此文記錄一下WebP的讀取和轉(zhuǎn)換方法,希望對大家有所幫助,需要的朋友可以參考下2024-06-06
單鏈表反轉(zhuǎn)python實現(xiàn)代碼示例
這篇文章主要介紹了單鏈表反轉(zhuǎn)python實現(xiàn),分享了相關(guān)代碼示例,小編覺得還是挺不錯的,具有一定借鑒價值,需要的朋友可以參考下2018-02-02

