• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell
您的位置:首页 > 脚本语言 >python > python中执行shell的两种方法总结

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

作者: 字体:[增加 减小] 来源:互联网

通过本文主要向大家介绍了python执行shell命令,python 执行shell,python 执行shell脚本,python shell,python shell是什么等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

一、使用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"))
</div>

二、使用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")
</div>

也可以在Popen中指定stdin和stdout为一个变量,这样就能直接接收该输出变量值。

总结

在python中执行SHELL有时候也是很必须的,比如使用Python的线程机制启动不同的shell进程,目前subprocess是Python官方推荐的方法,其支持的功能也是最多的,推荐大家使用。

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

</div>

您可能想查找下面的文章:

  • python中执行shell的两种方法总结
  • python中执行shell的两种方法总结
  • 日常整理python执行系统命令的常见方法(全)
  • 日常整理python执行系统命令的常见方法(全)
  • python执行shell获取硬件参数写入mysql的方法
  • python中执行shell命令的几个方法小结

相关文章

  • Python 常用的安装Module方式汇总
  • Python正则表达式教程之三:贪婪/非贪婪特性
  • Pycharm学习教程(1) 定制外观
  • Python基于PycURL实现POST的方法
  • python中将阿拉伯数字转换成中文的实现代码
  • 详解Python中的元组与逻辑运算符
  • python代码制作configure文件示例
  • python实现计算倒数的方法
  • Python查找相似单词的方法
  • Python函数式编程指南(四):生成器详解

文章分类

  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell

最近更新的内容

    • Python编写简单的HTML页面合并脚本
    • Django的信号机制详解
    • Python字符串处理之count()方法的使用
    • 教你如何在Django 1.6中正确使用 Signal
    • Python单例模式实例分析
    • python打开网页和暂停实例
    • Python的SQLalchemy模块连接与操作MySQL的基础示例
    • Python常用正则表达式符号浅析
    • 在Python中操作列表之List.append()方法的使用
    • Python实现删除Android工程中的冗余字符串

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有