python中执行shell的两种方法总结

作者:Crazyant 时间:2023-03-12 15:20:39 

一、使用python内置commands模块执行shell

commands对Python的os.popen()进行了封装,使用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官方推荐的方法,其支持的功能也是最多的,推荐大家使用。

好了,以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。

来源:http://www.crazyant.net/1319.html

标签:python,shell,命令
0
投稿

猜你喜欢

  • Jquery练习之表单验证实现代码

    2023-07-02 05:30:59
  • Script块放在另一个Script 块内方法

    2009-02-04 15:43:00
  • 再谈Python中的字符串与字符编码(推荐)

    2023-06-15 23:25:08
  • Python 聊聊socket中的listen()参数(数字)到底代表什么

    2022-10-17 00:49:25
  • 发现IE6下URL path不会自动补全

    2009-03-31 12:52:00
  • div+css实现圆角边框

    2007-10-21 08:55:00
  • 将Django项目部署到CentOs服务器中

    2021-07-30 20:11:11
  • ubuntu系统下 python链接mysql数据库的方法

    2024-01-19 22:05:20
  • pytorch掉坑记录:model.eval的作用说明

    2023-01-07 11:52:18
  • 实例讲解Python中SocketServer模块处理网络请求的用法

    2021-04-16 13:25:27
  • python如何求解两数的最大公约数

    2021-01-16 07:38:18
  • 完美解决jupyter由于无法import新包的问题

    2021-09-19 01:21:11
  • 详解duck typing鸭子类型程序设计与Python的实现示例

    2022-12-26 07:12:19
  • MySQL实现SQL Server的sp_executesql

    2008-11-20 15:01:00
  • 浅谈beego默认处理静态文件性能低下的问题

    2024-04-25 13:21:19
  • Mootools常用方法扩展(五)

    2009-03-03 12:12:00
  • Django应用程序中如何发送电子邮件详解

    2023-11-04 02:07:54
  • python正则表达式re之compile函数解析

    2022-12-03 04:24:02
  • django框架创建应用操作示例

    2022-07-15 22:07:33
  • Python format函数详谈

    2023-12-24 03:57:59
  • asp之家 网络编程 m.aspxhome.com