這篇文章將為大家詳細(xì)講解有關(guān)Python中怎么執(zhí)行Linux系統(tǒng)命令,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。
(1) os.system
僅僅在一個子終端運行系統(tǒng)命令,而不能獲取命令執(zhí)行后的返回信息
代碼如下:
system(command) -> exit_status
Execute the command (a string) in a subshell.
如果再命令行下執(zhí)行,結(jié)果直接打印出來
代碼如下:
>>> os.system('ls')
04101419778.CHM bash document media py-django video
11.wmv books downloads Pictures python
all-20061022 Desktop Examples project tools
(2) os.popen
該方法不但執(zhí)行命令還返回執(zhí)行后的信息對象
代碼如下:
popen(command [, mode='r' [, bufsize]]) -> pipe
Open a pipe to/from a command returning a file object.
例如:
代碼如下:
>>>tmp = os.popen('ls *.py').readlines()
>>>tmp
Out[21]:
['dump_db_pickle.py ',
'dump_db_pickle_recs.py ',
'dump_db_shelve.py ',
'initdata.py ',
'__init__.py ',
'make_db_pickle.py ',
'make_db_pickle_recs.py ',
'make_db_shelve.py ',
'peopleinteract_query.py ',
'reader.py ',
'testargv.py ',
'teststreams.py ',
'update_db_pickle.py ',
'writer.py ']
好處在于:將返回的結(jié)果賦于一變量,便于程序的處理。
(3) 使用模塊 subprocess
代碼如下:
>>> import subprocess
>>> subprocess.call(["cmd", "arg1", "arg2"],shell=True)
獲取返回和輸出:
代碼如下:
import subprocess
p = subprocess.Popen('ls', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in p.stdout.readlines():
print line,
retval = p.wait()
(4) 使用模塊 commands
代碼如下:
>>> import commands
>>> dir(commands)
['__all__', '__builtins__', '__doc__', '__file__', '__name__', 'getoutput', 'getstatus','getstatusoutput', 'mk2arg', 'mkarg']
>>> commands.getoutput("date")
'Wed Jun 10 19:39:57 CST 2009'
>>>
>>> commands.getstatusoutput("date")
(0, 'Wed Jun 10 19:40:41 CST 2009')
注意: 當(dāng)執(zhí)行命令的參數(shù)或者返回中包含了中文文字,那么建議使用subprocess,如果使用os.popen則會出現(xiàn)下面的錯誤:
代碼如下:
Traceback (most recent call last):
File "./test1.py", line 56, inmain()
File "./test1.py", line 45, in main
fax.sendFax()
File "./mailfax/Fax.py", line 13, in sendFax
os.popen(cmd)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 46-52: ordinal not inrange(128)
關(guān)于Python中怎么執(zhí)行Linux系統(tǒng)命令就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
分享標(biāo)題:Python中怎么執(zhí)行Linux系統(tǒng)命令-創(chuàng)新互聯(lián)
轉(zhuǎn)載注明:http://jinyejixie.com/article10/dededo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制開發(fā)、網(wǎng)站改版、全網(wǎng)營銷推廣、Google、外貿(mào)建站、微信公眾號
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容