zoukankan      html  css  js  c++  java
  • python标准库:subprocess——子进程管理

    subprocess是py2.4引入的功能,可以代替一些老旧的模块与功能:

    os.system
    os.spawn*
    os.popen*
    popen2.*
    commands.*
    

    优先考虑使用call方法,如果call不满足需求,可以使用更底层的Popen接口。

    call

    subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

    call方法会执行args指定的命令,等命令完成后,返回一个returncode

    用法

    >>> subprocess.call(["ls", "-l"])
    0
    
    >>> subprocess.call("exit 1", shell=True)  # 不建议使用shell=True的这种方法。
    1
    

    不要在call中使用stdout=PIPE或stderr=PIPE,这样可能会导致死锁,可以使用Popen的communicate()方法进行管道操作。

    check_call

    subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False)

    和call方法一样,不同的是当返回值非0时会抛出CalledProcessError异常。

    check_output

    subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)

    返回命令输出的字节序列,如果返回值非0,会抛出CalledProcessError异常。

  • 相关阅读:
    Codeforces 1132D
    Codeforces 670F
    Codeforces 670E
    Codeforces 670E
    Codeforces 670E
    Codeforces 670
    Codeforces 1138
    Codeforces 1114E
    力扣21.合并两个有序链表
    力扣538.把二叉树转换为累加树
  • 原文地址:https://www.cnblogs.com/CheeseZH/p/12574479.html
Copyright © 2011-2022 走看看