国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 開(kāi)發(fā) > Linux Shell > 正文

Python執(zhí)行Linux系統(tǒng)命令的4種方法

2020-07-27 19:13:05
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

(1) os.system

僅僅在一個(gè)子終端運(yùn)行系統(tǒng)命令,而不能獲取命令執(zhí)行后的返回信息

復(fù)制代碼 代碼如下:

system(command) -> exit_status
Execute the command (a string) in a subshell.

如果再命令行下執(zhí)行,結(jié)果直接打印出來(lái)
復(fù)制代碼 代碼如下:

>>> 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í)行后的信息對(duì)象

復(fù)制代碼 代碼如下:

popen(command [, mode='r' [, bufsize]]) -> pipe
Open a pipe to/from a command returning a file object.

例如:

復(fù)制代碼 代碼如下:

>>>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

復(fù)制代碼 代碼如下:

>>> import subprocess
>>> subprocess.call(["cmd", "arg1", "arg2"],shell=True)

獲取返回和輸出:
復(fù)制代碼 代碼如下:

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

復(fù)制代碼 代碼如下:

>>> 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則會(huì)出現(xiàn)下面的錯(cuò)誤:

復(fù)制代碼 代碼如下:

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)

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 二连浩特市| 阿城市| 吉安县| 邵武市| 若羌县| 仁寿县| 榆林市| 郑州市| 上思县| 扶沟县| 家居| 新沂市| 龙海市| 三门县| 大城县| 连平县| 建德市| 祥云县| 库伦旗| 沅江市| 香格里拉县| 寿宁县| 福海县| 敦煌市| 保亭| 景宁| 丘北县| 桂阳县| 丰城市| 宝兴县| 高安市| 潜江市| 财经| 襄樊市| 紫阳县| 穆棱市| 瑞金市| 龙海市| 炉霍县| 铁力市| 银川市|