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

['2015xe5xb9xb4 3xe6x9cx88 3xe6x97xa5 xe6x98x9fxe6x9cx9fxe4xbax8c 00xe6x97xb630xe5x88x8618xe7xa7x92 CST ']

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

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

原文地址:https://www.cnblogs.com/weiok/p/4872112.html