这篇文章主要介绍了 python 中执行 shell 的两种方法,有两种方法可以在 Python 中执行 SHELL 程序,方法一是使用 Python 的 commands 包,方法二则是使用 subprocess 包,这两个包均是 Python 现有的内置模块。需要的朋友可以参考借鉴,下面来一起看看吧。
Python 是一种面向对象、解释型计算机程序设计语言,由 Guido van Rossum 于 1989 年底发明,第一个公开发行版发行于 1991 年。Python 语法简洁而清晰,具有丰富和强大的类库。它常被昵称为胶水语言,它能够把用其他语言制作的各种模块(尤其是 C/C++)很轻松地联结在一起。
一、使用 python 内置 commands 模块执行 shell
commands 对 Python 的 {aa0aa} 进行了封装,使用 SHELL 命令字符串作为其参数,返回命令的结果数据以及命令执行的状态;
该命令目前已经废弃,被 subprocess 所替代;
- # coding=utf-8
- '''
- Created on 2013年11月22日
- @author: crazyant.net
- '''
- import commands
- import pprint
- def cmd_exe(cmd_String):
- print "will exe cmd,cmd:"+cmd_String
- return commands.getstatusoutput(cmd_String)
- if __name__=="__main__":
- pprint.pprint(cmd_exe("ls -la"))
二、使用 python 最新的 subprocess 模块执行 shell
Python 目前已经废弃了 os.system,os.spawn*,os.popen*,popen2.*,commands.* 来执行其他语言的命令,subprocesss 是被推荐的方法;
subprocess 允许你能创建很多子进程,创建的时候能指定子进程和子进程的输入、输出、错误输出管道,执行后能获取输出结果和执行状态。
- # coding=utf-8
- '''
- Created on 2013年11月22日
- @author: crazyant.net
- '''
- import shlex
- import datetime
- import subprocess
- import time
- def execute_command(cmdstring, cwd=None, timeout=None, shell=False):
- """执行一个SHELL命令
- 封装了subprocess的Popen方法, 支持超时判断,支持读取stdout和stderr
- 参数:
- cwd: 运行命令时更改路径,如果被设定,子进程会直接先更改当前路径到cwd
- timeout: 超时时间,秒,支持小数,精度0.1秒
- shell: 是否通过shell运行
- Returns: return_code
- Raises: Exception: 执行超时
- """
- if shell:
- cmdstring_list = cmdstring
- else:
- cmdstring_list = shlex.split(cmdstring)
- if timeout:
- end_time = datetime.datetime.now() + datetime.timedelta(seconds=timeout)
- #没有指定标准输出和错误输出的管道,因此会打印到屏幕上;
- sub = subprocess.Popen(cmdstring_list, cwd=cwd, stdin=subprocess.PIPE,shell=shell,bufsize=4096)
- #subprocess.poll()方法:检查子进程是否结束了,如果结束了,设定并返回码,放在subprocess.returncode变量中
- while sub.poll() is None:
- time.sleep(0.1)
- if timeout:
- if end_time <= datetime.datetime.now():
- raise Exception("Timeout:%s"%cmdstring)
- return str(sub.returncode)
- if __name__=="__main__":
- print execute_command("ls")
也可以在 Popen 中指定 stdin 和 stdout 为一个变量,这样就能直接接收该输出变量值。
总结
在 python 中执行 SHELL 有时候也是很必须的,比如使用 Python 的线程机制启动不同的 shell 进程,目前 subprocess 是 Python 官方推荐的方法,其支持的功能也是最多的,推荐大家使用。
来源: