您的位置:首页 > 编程语言 > Python开发

python 调用系统命令

2015-10-12 16:45 656 查看
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()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: