设为首页 收藏本站
查看: 1007|回复: 0

python调用shell命令小结

[复制链接]
累计签到:1 天
连续签到:1 天
发表于 2014-9-18 09:00:09 | 显示全部楼层 |阅读模式
在写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:
1
2
3
4
5
6
7
8
9
10
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的源码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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。可以对上面的代码进行组合

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# -*- 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()





运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-24996-1-1.html 上篇帖子: 使用PowerShell定时批量结束Citrix Xen App Session 下篇帖子: shell脚本计算任意个数的加减乘除 python
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表