Python调用外部系统命令

  利用Python调用外部系统命令的方法可以提高编码效率。调用外部系统命令完成后可以通过获取命令执行返回结果码、执行的输出结果进行进一步的处理。本文主要描述Python常见的调用外部系统命令的方法,包括os.system()、os.popen()、subprocess.Popen()等。

1、subprocess模块

  优先介绍subprocess模块的是由于该模块可以替代旧模块的方法,如os.system()、os.popen()等,推荐使用。subporcess模块可以调用外部系统命令来创建新子进程,同时可以连接到子进程的nput/output/error管道上,并得到子进程的返回值。subprocess模块主要有call()、check_call()、check_output()、Popen()函数,简要描述如下:

    Main API
    ========
    call(...): Runs a command, waits for it to complete, then returns the return code.
    check_call(...): Same as call() but raises CalledProcessError() if return code is not 0
    check_output(...): Same as check_call() but returns the contents of stdout instead of a return code
    Popen(...): A class for flexibly executing a command in a new process

  下面开始介绍subprocess函数的使用方法。

  subprocess.Popen类

 构造函数:subprocess.Popen(args, stdin=None, stdout=None, stderr=None, shell=False) #参数太多,仅列举关键参数

 说明:

 (1)args参数为要调用的外部系统命令。

 (2)shell参数值为False时,Linux上通过调用os.execvp执行对应的程序。为Trule时,Linux上直接调用系统shell来执行程序。在Windows上,无论shell为False还是True,都是调用CreateProcess来执行执行指定外部程序。

(3)stdin、stdout、stdout分别用来指定子进程的标准输入、标准输出和标准错误。其值可以为PIPE、文件描述符和None等。默认值为None。

  使用实例如下:

import subprocess

p = subprocess.Popen(args='ping -n 2 -w 3 192.168.1.104',stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.PIPE, shell=True)
p.wait()
print p.stdout.read()

  说明:获取输出后,p.stdout(<open file '<fdopen>',mode 'rb'>)成为一个可读的文件对象,可以使用文件操作函数来读取。

subprocess.call()

  函数原型:call(*popenargs, **kwargs)。call()调用外部系统命令执行,并返回程序执行结果码。

import subprocess

retcode = subprocess.call('ping -n 2 -w 3 192.168.1.104', shell=True)
print retcode

subprocess.check_call()

   使用方法同call()。如果调用命令执行成功,返回结果码0,如果执行失败,抛出CalledProcessError.异常。举例如下:

>>> p = subprocess.check_call('ping -n 2 -w 3 192.168.1.105', shell=True)

正在 Ping 192.168.1.105 具有 32 字节的数据:
请求超时。
请求超时。

192.168.1.105 的 Ping 统计信息:
    数据包: 已发送 = 2,已接收 = 0,丢失 = 2 (100% 丢失),
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\Python27\lib\subprocess.py", line 186, in check_call
    raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command 'ping -n 2 -w 3 192.168.1.105' returned non-zero exit status 1

 subprocess.check_output()

  函数原型:check_output(*popenargs, **kwargs)。用法与call()相同。区别是如果执行成功返回的是标准输出内容。如果失败,抛CalledProcessError.异常。

import subprocess

output = subprocess.check_output('ping -n 2 -w 3 192.168.1.104', shell=True)
print output

2、os模块

  os.system()

  os.system(command) 。调用外部系统命令,返回命令结果码,但是无法获取命令执行输出结果。

import os

ip = '192.168.1.104'
ping_cmd  = 'ping -n 2 -w 3 %s > null' % (ip,)
retcode = os.system('ping -n 2 -w 3 192.168.1.104')
if retcode == 0:
    print "%s Success" % (ip,)
else:
    print "%s Fail" % (ip,)

os.popen()

os.popen(command) 。调用外部系统命令,返回命令执行输出结果,但不返回结果吗

import os

ip = '192.168.1.104'
ping_cmd  = 'ping -n 2 -w 3 %s > null' % (ip,)
output = os.popen('ping -n 2 -w 3 192.168.1.104')
print output

3、commands模块

  commands模块主要有如下3个函数

getoutput(cmd): Return output (stdout or stderr) of executing cmd in a shell.
getstatus(file):Return output of "ls -ld <file>" in a string.
getstatusoutput(cmd):Return (status, output) of executing cmd in a shell.

猜你喜欢

转载自www.cnblogs.com/linyfeng/p/8973277.html
今日推荐