python 调用系统命令

Python执行系统命令一般的用到了四种方法,

第一种是 os.system(),  这个方法比较常用, 使用也简单, 会自动的生成一个进程,在进程完成后会自动退出, 需要注意的是

os.system() 只返回命令执行的状态, 并不返回命令执行的结果,例如:

>>> import os

 

>>> s = os.system('date')

 

2015年 3月 3日 星期二 00时27分11秒 CST

 

>>> s

 

0

其次需要注意的是 os.system()  创建的是进程, 会等待命令执行完, 不适合需要常时间等待的命令执行

 

第二种是os.popen(), 相对上一个命令, 他能得到命令执行的输出, 但是他的问题也是明显的,比如命令输入错误的时候,

这个os.popen() 就没有办法处理了:

>>> s = os.popen('date').readlines()

 

>>> print s

 

['2015\xe5\xb9\xb4 3\xe6\x9c\x88 3\xe6\x97\xa5 \xe6\x98\x9f\xe6\x9c\x9f\xe4\xba\x8c 00\xe6\x97\xb630\xe5\x88\x8618\xe7\xa7\x92 CST\n']

这个会以异常的方式出现:

>>> s = os.popen('date1').read()

 

sh: date1: command not found

 

第三种比较好用的方法是: commands 类

>>> import commands

>>> status, results = commands.getstatusoutput('date')

 

>>> print status, results

 

0 2015年 3月 3日 星期二 00时35分40秒 CST

>>> status, results = commands.getstatusoutput('date2' )

 

>>> print status, results

 

32512 sh: date2: command not found

对于这个错误的命令会被自动识别, 然后将错误的信息保存到results, 将错误的状态值保存在status.

 

第四种,使用模块subprocess,第四种未测试

>>> import subprocess

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

 

 

#!/bin/python

 

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

 

posted @ 2015-10-12 16:45  weiokx  阅读(1125)  评论(0编辑  收藏  举报