Python实践 - subprocess

rick    2018-07-08 15:37

python是个很强大的工具, 一些实践经验记录分享下,欢迎讨论

 

1. subprocess

subprocess模块用于和系统交互, 通过这个模块我们可以执行一些操作并读取返回输出

subprocess.Popen()创建并返回一个子进程, 并在该子进程中执行制定程序

常用参数如下, 具体使用方法百度有很多

subprocess.Popen(
    args,  # 需执行的命令。str或List,
    bufsize=0,          # 指定的文件缓冲大小
    shell=False         # 布尔型变量,明确要求使用shell运行程序
    stdin=None,         # 指定子进程的标准输入
    stdout=None,        # 指定子进程的标准输出
    stderr=None,        # 指定子进程的标准错误输出
)

用python脚本调用程序的一般函数如下:

def subExcuter(cmd):
    # 将stderr(错误信息)也定位为标准输出
    p = subprocess.Popen(cmd, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    res = []
    while True:
        line = p.stdout.readline()
        if res == '' and p.poll() is not None:
            break
        # 输出执行信息
        print(line)
        # 这里可以添加判断以区分执行结果和错误
        if line:
            res.append(line)
    p.stdout.close()
    # 判断是否执行成功
    if p.wait() != 0:
        sys.exit(p.returncode)
    return res

具体使用时踩得坑记录下

1. shell=True会导致出现一些问题, 当执行语句中存在shell命令时会报错.

2. 一般使用p.communicate 具体用法为

        out, err=p.communicate()

获取正确以及错误输出, 但是不会实时的到输出, 如果需要实时输出还需使用上述方法.

3. 实时输出当定位stderr为管道输出时, 当out量大会有个p.stderr.readline()卡死的bug, 具体表现为stderr读取结束之后无法读取到输出结尾, 查了很久也没找到解决方法, 因此改为将err定位到标准输出人工分析(正则或其他).

 

Views: 2.3K

[[total]] comments

Post your comment
  1. [[item.time]]
    [[item.user.username]] [[item.floor]]Floor
  2. Click to load more...
  3. Post your comment