美文网首页
python3 subprocess.check_output的

python3 subprocess.check_output的

作者: a50426d44eac | 来源:发表于2019-02-12 14:57 被阅读0次

    demo

    
    import shlex, subprocess
    command_line = "echo 'hello' "
    args = shlex.split(command_line)
    print(args)
    try:
        p = subprocess.check_output(args,stderr=subprocess.STDOUT,timeout=5)
        print(p)
    except subprocess.TimeoutExpired as time_e:
        print(time_e)
    except subprocess.CalledProcessError as call_e:
        print(e.output.decode(encoding="utf-8"))
    
    

    注意点

    1.timeout参数不能和shell=True一起使用,不然就算是时间到了,还是会继续执行,等执行结束以后才会抛出subprocess.TimeoutExpired异常,timeout的单位是秒。

    2.check_output返回的是子程序的执行结果(上述demo返回的就应该是helo),也是unicode编码,如果程序执行报错的话,会直接抛出异常CalledProcessError,并且异常当中会有output属性,该属性为unicode编码的,要当字符串使用的时候需要转码,如e.output.decode(encoding="utf-8")

    3.想要执行的命令command_line不能有类似<的重定向符号,会报错。

    相关文章

      网友评论

          本文标题:python3 subprocess.check_output的

          本文链接:https://www.haomeiwen.com/subject/qrkkeqtx.html