您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關(guān)Python怎么使用OS模塊調(diào)用cmd的內(nèi)容。小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過來看看吧。
在os模塊中提供了兩種調(diào)用 cmd 的方法,os.popen() 和 os.system()
os.system(cmd) 是在執(zhí)行command命令時(shí)需要打開一個(gè)終端,并且無法保存command命令的執(zhí)行結(jié)果。
os.popen(cmd,mode) 打開一個(gè)與command進(jìn)程之間的管道。返回值是一個(gè)文件對(duì)象,可以讀或者寫(由mode決定,默認(rèn)是'r')。如果mode為'r',可以使用此函數(shù)的返回值調(diào)用read()來獲取command命令的執(zhí)行結(jié)果。
os.system()
定義:
def system(*args, **kwargs): # real signature unknown """ Execute the command in a subshell. """ pass
簡(jiǎn)單的來說就是在shell中執(zhí)行command命令
示例:
(venv) C:\Users\TynamYang>python Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> >>> import os >>> cmd = 'echo "I am tynam"' >>> os.system(cmd) "I am tynam" >>>
os.popen()
定義:
# Supply os.popen() 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)
也是在shell中執(zhí)行command命令,但是返回的結(jié)果卻是一個(gè)文件對(duì)象,可以對(duì)其讀寫
其中的三個(gè)參數(shù)含義:
command -- 執(zhí)行的shell命令
mode -- 模式權(quán)限,讀(‘r')或者寫(‘w'),默認(rèn)為讀(‘r')
bufsize -- 如果將緩沖值設(shè)置為0則不會(huì)進(jìn)行緩沖。 如果緩沖值為1則在訪問文件時(shí)將執(zhí)行行緩沖。 如果將緩沖值設(shè)置為大于1的整數(shù)則以設(shè)置的緩沖大小執(zhí)行緩沖操作。 如果為負(fù)則緩沖區(qū)大小為系統(tǒng)默認(rèn)值(默認(rèn)行為)。
示例:
>>> import os >>> cmd = 'echo "I am tynam"' >>> f = os.popen(cmd, 'r') >>> f.read() '"I am tynam"\n' >>>
感謝各位的閱讀!關(guān)于“Python怎么使用OS模塊調(diào)用cmd”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。