python2.7執行shell命令


python學習——python中執行shell命令
2013-10-21 17:44:33
標簽: python  shell命令
原創作品,允許轉載,轉載時請務必以超鏈接形式標明文章  原始出處 、作者信息和本聲明。否則將追究法律責任。 http://zhou123.blog.51cto.com/4355617/1312791

這里介紹一下python執行shell命令的四種方法:

1、os模塊中的os.system()這個函數來執行shell命令

1
2
3
>>> os.system( 'ls' )
anaconda - ks.cfg  install.log  install.log.syslog  send_sms_service.py  sms.py
0

注,這個方法得不到shell命令的輸出。

 

2、popen()#這個方法能得到命令執行后的結果是一個字符串,要自行處理才能得到想要的信息。

1
2
3
4
5
>>>  import  os
>>>  str  =  os.popen( "ls" ).read()
>>> a  =  str .split( "\n" )
>>>  for  in  a:
         print  b

這樣得到的結果與第一個方法是一樣的。

3、commands模塊#可以很方便的取得命令的輸出(包括標准和錯誤輸出)和執行狀態位

1
2
3
4
5
6
7
8
9
10
11
12
import  commands
a,b  =  commands.getstatusoutput( 'ls' )
a是退出狀態
b是輸出的結果。
>>>  import  commands
>>> a,b  =  commands.getstatusoutput( 'ls' )
>>>  print  a
0
>>>  print  b
anaconda - ks.cfg
install.log
install.log.syslog

commands.getstatusoutput(cmd)返回(status,output)

commands.getoutput(cmd)只返回輸出結果

commands.getstatus(file)返回ls -ld file 的執行結果字符串,調用了getoutput,不建議使用這個方法。

 

4、subprocess模塊

 

使用subprocess模塊可以創建新的進程,可以與新建進程的輸入/輸出/錯誤管道連通,並可以獲得新建進程執行的返回狀態。使用subprocess模塊的目的是替代os.system()、os.popen*()、commands.*等舊的函數或模塊。

import subprocess

1、subprocess.call(command, shell=True)

#會直接打印出結果。

2、subprocess.Popen(command, shell=True) 也可以是subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) 這樣就可以輸出結果了。

如果command不是一個可執行文件,shell=True是不可省略的。

shell=True意思是shell下執行command

 

這四種方法都可以執行shell命令。

 

 

本文出自 “linux學習” 博客,請務必保留此出處http://zhou123.blog.51cto.com/4355617/1312791


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM