pip" />

日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

日常整理python執行系統命令的常見方法(全)

系統 2193 0

具體內容如下:

1 os.system

例如 ipython中運行如下命令,返回運行狀態status

os.system('cat /etc/passwdqc.conf')
min=disabled,24,11,8,7
max=40
passphrase=3
match=4
similar=deny
random=47
enforce=everyone
retry=3
Out[6]: 0

2 os.popen()

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

運行返回結果

In [20]: output = os.popen('cat /proc/cpuinfo')
In [21]: lineLen = []
In [22]: for line in output.readlines():
??? lineLen.append(len(line))
?? ....:????
In [23]: line
line???? lineLen?
In [23]: lineLen
Out[23]:
[14,
?25,
...

3 如何同時返回結果和運行狀態,commands模塊:

            
#String form: 
            
              
File: /usr/lib64/python2.7/commands.py
Docstring:
Execute shell commands via os.popen() and return status, output.
Interface summary:
import commands
outtext = commands.getoutput(cmd)
(exitstatus, outtext) = commands.getstatusoutput(cmd)
outtext = commands.getstatus(file) # returns output of "ls -ld file"
A trailing newline is removed from the output string.
Encapsulates the basic operation:
pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
text = pipe.read()
sts = pipe.close()
            
          

commands示例如下:

In [24]: (status, output) = commands.getstatusoutput('cat /proc/cpuinfo')
In [25]: status
Out[25]: 0
In [26]: len(output)
Out[26]: 3859

4 使用模塊subprocess

ipython 中運行"?subprocess"可以發現subprocess是python用來替換os.popen()等管道操作命令的新模塊

A more real-world example would look like this:

            
try:
  retcode = call("mycmd" + " myarg", shell=True)
  if retcode < 0:
    print >>sys.stderr, "Child was terminated by signal", -retcode
  else:
    print >>sys.stderr, "Child returned", retcode
except OSError, e:
  print >>sys.stderr, "Execution failed:", e
          

相對于上面幾種方式,subprocess便于控制和監控進程運行結果,subprocess提供多種函數便于應對父進程對子進程不同要求:

4.1.1 subprocess.call()

父進程父進程等待子進程完成,返回exit code

4.1.2 subprocess.check_call()

父進程等待子進程完成,返回0,如果returncode不為0,則舉出錯誤subprocess.CalledProcessError,該對象包含有returncode屬性,可用try...except...來檢查

4.1.3 subprocess.check_output()

父進程等待子進程完成

返回子進程向標準輸出的輸出結果

檢查退出信息,如果returncode不為0,則舉出錯誤subprocess.CalledProcessError,該對象包含有returncode屬性和output屬性,output屬性為標準輸出的輸出結果,可用try...except...來檢查

例如:

In [32]: out = subprocess.call("ls -l", shell=True)
total 42244
-rw-rw-r--.? 1 *** ***???? 366 May 26 09:10 ChangeLog

4.2.1

上面三個函數都是源于Popen()函數的wapper(封裝),如果需要更加個性化應用,那么就需要使用popen()函數

Popen對象創建后,主程序不會自動等待子進程完成。我們必須調用對象的wait()方法,父進程才會等待 (也就是阻塞block)

            
[wenwt@localhost syntax]$ rm subprocess.pyc 
[wenwt@localhost syntax]$ python process.py 
parent process
[wenwt@localhost syntax]$ PING www.google.com (173.194.219.99) 56(84) bytes of data.
^C
[wenwt@localhost syntax]$ 
--- www.google.com ping statistics ---
5 packets transmitted, 0 received, 100% packet loss, time 3999ms
          

加上wait方法:

            
[wenwt@localhost syntax]$ python process.py 
PING www.google.com (173.194.219.103) 56(84) bytes of data.
--- www.google.com ping statistics ---
5 packets transmitted, 0 received, 100% packet loss, time 3999ms
parent process
          

以上內容就是本文的全部敘述,希望大家喜歡。


更多文章、技術交流、商務合作、聯系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯系: 360901061

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦?。?!

發表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 宁河县| 都江堰市| 高邮市| 滨海县| 册亨县| 霍林郭勒市| 通州区| 新巴尔虎左旗| 仙游县| 墨江| 台江县| 江阴市| 平陆县| 丽江市| 南靖县| 高雄市| 徐州市| 阳东县| 本溪| 新干县| 海原县| 文登市| 五指山市| 白山市| 赣州市| 广安市| 宾川县| 滦平县| 金门县| 尉氏县| 长兴县| 沈阳市| 汉沽区| 和硕县| 千阳县| 乌恰县| 永城市| 麻城市| 石狮市| 昆明市| 全椒县|