最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
python中执行shell的两种方法总结
时间:2017-01-10 编辑:简简单单 来源:一聚教程网
一、使用python内置commands模块执行shell
commands对Python的os.popen()进行了封装,使用SHELL命令字符串作为其参数,返回命令的结果数据以及命令执行的状态;
该命令目前已经废弃,被subprocess所替代;
# coding=utf-8 ''' Created on 2013年11月22日
@author: crazyant.net ''' importcommands importpprint
defcmd_exe(cmd_String): print"will exe cmd,cmd:"+cmd_String returncommands.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 ''' importshlex importdatetime importsubprocess importtime
defexecute_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: 执行超时 """ ifshell: cmdstring_list=cmdstring else: cmdstring_list=shlex.split(cmdstring) iftimeout: 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变量中 whilesub.poll()isNone: time.sleep(0.1) iftimeout: ifend_time <=datetime.datetime.now(): raiseException("Timeout:%s"%cmdstring)
returnstr(sub.returncode)
if__name__=="__main__": printexecute_command("ls") |
也可以在Popen中指定stdin和stdout为一个变量,这样就能直接接收该输出变量值。
总结
在python中执行SHELL有时候也是很必须的,比如使用Python的线程机制启动不同的shell进程,目前subprocess是Python官方推荐的方法,其支持的功能也是最多的,推荐大家使用。
-
上一个: PHP实现接收二进制流转换成图片的方法
-
下一个: php实现36进制与10进制转换功能示例
相关文章
- PHP导出数据超时的优化建议解读 10-31
- PHP之mysql位运算解析 10-31
- Laravel实现登录跳转功能解析 10-31
- php双向队列解读 10-31
- Laravel异常上下文解决教程 10-24
- php数组查询元素位置方法介绍 10-24