iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >python调用shell命令小结
  • 951
分享到

python调用shell命令小结

小结命令python 2023-01-31 07:01:14 951人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

 在写python脚本的时候,经常需要调用系统命令,常用的Python调用系统命令的方法主要有subprocess.call和os.popen。默认情况下subprocess.call的方法结果是返回值,即1或0,而os.popen则是命令

 在写python脚本的时候,经常需要调用系统命令,常用的Python调用系统命令的方法主要有subprocess.call和os.popen。默认情况下subprocess.call的方法结果是返回值,即1或0,而os.popen则是命令运行的结果,可以用readlines(读取所有行,返回数组)或者read(读读取所有行,返回str)来读取。

subprocess类总主要的方法有:

subprocess.call:开启子进程,开启子进程,运行命令,默认结果是返回值,不能try 

subprocess.check_call:运行命令,默认结果是返回值,可以try 

subprocess.check_out(2.7中才有这个方法) 开启子进程,运行命令,可以获取命令结果,可以try 
subprocess.Popen 开启子进程,运行命令,没有返回值,不能try,可以获取命令结果

subprocess.PIPE 初始化stdin,stdout,stderr,表示与子进程通信的标准流
Popen.poll 检查子进程是否结束,并返回returncode
Popen.wait等待子进程是否结束,并返回retrurncode

比如check_call的sample:

import subprocess
import traceback
cmd='hadoop fs -ls hdfs://xxxxx'
try:
    e=subprocess.check_call(cmd,shell=True,stdout=subprocess.PIPE)
    print "return code is: %s"%(str(e))
    #print stdout.read()
except Exception,re:
    print "message is:%s" %(str(re))
    traceback.print_exc()

分析subprocess的源码

class CalledProcessError(Exception):   #首先定义了一个exception,用来在check_call和 check_output中raise exception
    def __init__(self, returncode, cmd, output=None):
        self.returncode = returncode
        self.cmd = cmd
        self.output = output
    def __str__(self):
        return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
..........
def call(*popenargs, **kwargs): 
    return Popen(*popenargs, **kwargs).wait()  #call方法调用wait
def check_call(*popenargs, **kwargs):
    retcode = call(*popenargs, **kwargs)  #调用call,返回返回值
    if retcode:
        cmd = kwargs.get("args")
        if cmd is None:
            cmd = popenargs[0]
        raise CalledProcessError(retcode, cmd)  #可以抛出异常
    return 0
def check_output(*popenargs, **kwargs):
    if 'stdout' in kwargs:
        raise ValueError('stdout argument not allowed, it will be overridden.')
    process = Popen(stdout=PIPE, *popenargs, **kwargs)
    output, unused_err = process.communicate()  #获取标准输出和标准错误输出
    retcode = process.poll()   #检查子进程是否结束,并返回returncode
    if retcode:
        cmd = kwargs.get("args")
        if cmd is None:
            cmd = popenargs[0]
        raise CalledProcessError(retcode, cmd, output=output)
    return output
有时候我们需要在运行命令时可以获取返回值,获取结果,并且能够try。

可以对上面的代码进行组合

# -*- coding: utf8 -*-
import exceptions
import subprocess
import traceback
class CalledCommandError(Exception):
    def __init__(self, returncode, cmd, errorlog,output):
        self.returncode = returncode
        self.cmd = cmd
        self.output = output
        self.errorlog = errorlog
    def __str__(self):
        return "命令运行错误:'%s',返回值: %s,错误信息: %s" % (self.cmd, str(self.returncode) ,self.errorlog)
def run_command_all(*popenargs, **kwargs):
    allresult = {}
    cmd = popenargs[0]
    if 'stdout' in kwargs or 'stderr' in kwargs :
        raise ValueError('标准输出和标准错误输出已经定义,不需设置。')
    process = subprocess.Popen(stdout=subprocess.PIPE,shell=True,stderr = subprocess.PIPE,*popenargs, **kwargs)
    output, unused_err = process.communicate()
    retcode = process.poll()
    if retcode:
        #print retcode,cmd,unused_err,output
        raise CalledCommandError(cmd,retcode,errorlog=unused_err,output=output)
    allresult['cmd'] = cmd
    allresult['returncode'] = retcode
    allresult['errorlog'] = unused_err
    allresult['outdata'] = output
    return allresult
if __name__ == '__main__':
    cmd = 'hadoop fs -ls xxxx|wc -l'
    try:
        e=run_command_all(cmd)
        print "ok"
    except Exception,re:
        print (str(re))
        print "failed"
        traceback.print_exc()

--结束END--

本文标题: python调用shell命令小结

本文链接: https://www.lsjlt.com/news/191454.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • python调用shell命令小结
     在写python脚本的时候,经常需要调用系统命令,常用的python调用系统命令的方法主要有subprocess.call和os.popen。默认情况下subprocess.call的方法结果是返回值,即1或0,而os.popen则是命令...
    99+
    2023-01-31
    小结 命令 python
  • python怎么调用shell命令
    在Python中,可以使用`subprocess`模块来调用shell命令。下面是一个简单的示例:```pythonimport s...
    99+
    2023-08-30
    python shell
  • Python中判断subprocess调起的shell命令是否结束
    前言 最近在使用subprocess遇到个问题,折腾了好半天才找到简单的解决办法,在这里记录下。 环境 Python:2.7.10 库:subprocess, logging 问题 ...
    99+
    2024-04-02
  • golang如何调用shell命令
    这篇文章主要介绍了golang如何调用shell命令的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇golang如何调用shell命令文章都会有所收获,下面我们一起来看看吧。普通用法(一次性获取所有输出)pack...
    99+
    2023-07-05
  • perl怎么调用shell命令
    在Perl中,可以使用反引号或`qx//`操作符来调用shell命令。使用反引号调用shell命令的示例:```perlmy $ou...
    99+
    2023-10-07
    perl
  • java怎么调用shell命令
    Java中可以通过`Runtime`类或者`ProcessBuilder`类来调用shell命令。1. 使用`Runtime`类调用...
    99+
    2023-09-29
    java
  • node.js调用脚本(python/shell)和系统命令
    每种语言都有自己的优势,互相结合起来各取所长程序执行起来效率更高或者说哪种实现方式较简单就用哪个,nodejs是利用子进程来调用系统命令或者文件,文档见http://nodejs.o...
    99+
    2024-04-02
  • Linux中SELinux、Shell简介、touch命令的应用小结
    目录 SElinux⛳️ SELinux的规则与概念⛳️ 查看SELinux⛳️ SELinux策略⛳️ SELinux模式⛳️ SELinux设置 Shell简介⛳️ Shell分类⛳️ BASH基础 touch命令的...
    99+
    2023-02-03
    linux  SELinux linuxShell简介 linux touch命令
  • python调用调用Linux命令
    如何调用Linux命令下面代码演示了调用一个shell命令, 其中,命令的输出会存储到result变量中, 而命令的返回值,则存储到exitcode中,由此可见,调用shell命令还是很方便的:import commandsexitcode...
    99+
    2023-01-31
    命令 python Linux
  • Linux常用命令小结
    这篇文章主要讲解了“Linux常用命令小结”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Linux常用命令小结”吧!Linux常用命令使用CRT / Xshell 软件连接VM,编写虚拟机1...
    99+
    2023-06-03
  • Python调用Dos命令
    写了几个批处理,主要是一些Android调试命令,现在想用python来搞,感觉更酷一些吧。O(∩_∩)O~ 比如Ping命令: ping www.baidu.com 用python来做,主要是使用了python标准库中的os库。 参见P...
    99+
    2023-01-31
    命令 Python Dos
  • Linux下常用的shell命令总结
    这篇文章主要介绍“Linux下常用的shell命令总结”,在日常操作中,相信很多人在Linux下常用的shell命令总结问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Linux下常用的shell命令总结”的疑...
    99+
    2023-06-16
  • beeline的常用命令小结
    本篇内容主要讲解“beeline的常用命令小结”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“beeline的常用命令小结”吧! &l...
    99+
    2024-04-02
  • Java怎么调用Shell命令和脚本
    这篇文章主要为大家展示了Java怎么调用Shell命令和脚本,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带大家一起来研究并学习一下“Java怎么调用Shell命令和脚本”这篇文章吧。Java可以用来干什么Java主要应用于...
    99+
    2023-06-06
  • python调用外部命令
    python调用外部命令os.system:  输出在终端上,捕捉不到os.popen:  只能捕捉到标准输出,捕捉不到标准错误输出os.popen2: 返回2个对象,一个是标准输入,一个是标准输出os.popen3: 返回3个对象,标准输...
    99+
    2023-01-31
    命令 python
  • python中调用dos命令
    本文是基于window系统下的调用dos命令,在centos下也类似 #encoding:utf-8 ''' Created on 2015年10月10日 @author: ZHOUMEIXU204 ''' import os impo...
    99+
    2023-01-31
    命令 python dos
  • golang调用shell命令(实时输出,终止)
    目录背景普通用法(一次性获取所有输出)实时显示可关闭+实时输出执行Python脚本(阻塞)其他仍有缺陷windows输出乱码问题最后给一个解决windows乱码的完整案例概述一般命令...
    99+
    2023-02-21
    golang调用shell命令 golang调用shell
  • Python shell 有哪些常用命令?
    Python shell 是一个交互式的命令行工具,可以让用户在命令行中直接运行 Python 代码。Python shell 在 Python 开发过程中非常常用,可以快速地测试代码的正确性,同时也可以作为一个简单的计算器使用。在本文中...
    99+
    2023-09-27
    关键字 shell django
  • golang调用shell命令失败怎么解决
    如果在Golang中调用shell命令失败,可以尝试以下几种解决办法: 检查命令是否正确:确保调用的shell命令是正确的,可以...
    99+
    2023-10-26
    golang shell
  • python 之 shell命令执行
    python中有几种常用的执行shell命令的模块1,os.system()2, os.popen()3,pexpect.run()下面介绍3个模块的差别1,os.system() 直接执行>>> os.system('l...
    99+
    2023-01-31
    命令 python shell
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作