首页 > 解决方案 > Popen 的上下文管理器

问题描述

我对 Python 很陌生。我在上下文管理器上尝试了一个解决方案,如下所示: 问题陈述: 定义一个函数 run_process 接受系统命令,在后台运行命令并返回结果

我试过的解决方案:

def run_process:
    with subprocess.Popen(cmd_args) as proc:
        proc.communicate()

if __name__ == "__main__":
    f = open(os.environ['OUTPUT_PATH'], 'w')

    cmd_args_cnt = 0
    cmd_args_cnt = int(input())
    cmd_args_i = 0
    cmd_args = []
    while cmd_args_i < cmd_args_cnt:
        try:
            cmd_args_item = str(input())
        except:
            cmd_args_item = None
        cmd_args.append(cmd_args_item)
        cmd_args_i += 1

    res = run_process(cmd_args);

    if 'with' in inspect.getsource(run_process):
        f.write("'with' used in 'run_process' function definition.\n")

    if 'Popen' in inspect.getsource(run_process):
        f.write("'Popen' used in 'run_process' function definition.\n")
        f.write('Process Output : %s\n' % (res.decode("utf-8")))

    f.close()

预期输入: 3 python -c print("Hello")

预期输出: “run_process”函数定义中使用的“with”。'run_process' 函数定义中使用的'Popen'。过程输出:你好

标签: python-3.x

解决方案


def run_process(cmd_args):
    with subprocess.Popen(cmd_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as p:
        out, err = p.communicate()
    return out

推荐阅读