zoukankan      html  css  js  c++  java
  • python shell 执行

    os.system

    system方法会创建子进程运行外部程序,方法只返回外部程序的运行结果。这个方法比较适用于外部程序没有输出结果的情况。

    import os
    os.system('ls')
    

    os.popen

    当需要得到外部程序的输出结果时,本方法非常有用。比如使用urllib调用Web API时,需要对得到的数据进行处理。os.popen(cmd) 要得到命令的输出内容,只需再调用下read()或readlines()等 如a=os.popen(cmd).read()

    import os
    ls = os.popen('ls')
    print ls.read()
    

    commands.getstatusoutput

    使用commands模块的getoutput方法,这种方法同popend的区别在于popen返回的是一个文件句柄,而本方法将外部程序的输出结果当作字符串返回,很多情况下用起来要更方便些。
    主要方法:

    • commands.getstatusoutput(cmd) 返回(status, output)
    • commands.getoutput(cmd) 只返回输出结果
    • commands.getstatus(file) 返回ls -ld file的执行结果字符串,调用了getoutput,不建议使用此方法
    import commands
    commands.getstatusoutput('ls -lt')      # 返回(status, output)
    

    subprocess.call

    根据Python官方文档说明,subprocess模块用于取代上面这些模块。有一个用Python实现的并行ssh工具—mssh,代码很简短,不过很有意思,它在线程中调用subprocess启动子进程来干活。

    from subprocess import call
    call(["ls", "-l"])
    
    import shlex, subprocess
    def shell_command(cmd, timeout) :
        data = {"rc":False, "timeout":False, "stdout":"", "stderr":""}
        try :
            process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            try:
                outs, errs = process.communicate(timeout=timeout)
                data["stdout"] = outs.decode("utf-8") 
                data["stderr"] = errs.decode("utf-8") 
                data["rc"] = True
    
            except subprocess.TimeoutExpired :
                process.kill()
                outs, errs = process.communicate()
                data["rc"] = False 
                data["stdout"] = outs.decode("utf-8") 
                data["stderr"] = "timeout"
                data["timeout"] = True 
    
        except Exception as e :
            data["rc"] = False 
            data["stderr"] = e 
    
        finally : 
            return data 
    
  • 相关阅读:
    【刷题】BZOJ 4059 [Cerc2012]Non-boring sequences
    【刷题】BZOJ 3745 [Coci2015]Norma
    【刷题】BZOJ 2734 [HNOI2012]集合选数
    【刷题】BZOJ 2287 【POJ Challenge】消失之物
    【刷题】BZOJ 2151 种树
    【刷题】BZOJ 2134 单选错位
    【刷题】BZOJ 1924 [Sdoi2010]所驼门王的宝藏
    【刷题】BZOJ 1823 [JSOI2010]满汉全席
    【刷题】BZOJ 1124 [POI2008]枪战Maf
    编程之美 ---> 1.2中国象棋将帅问题
  • 原文地址:https://www.cnblogs.com/iFanLiwei/p/12833836.html
Copyright © 2011-2022 走看看