Popen的上下文管理器

时间:2018-08-16 12:06:06

标签: python-3.x

我是Python的新手。我正在尝试使用Context Manager的解决方案,如下所示: 问题陈述: 定义一个功能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 蟒蛇 -C print(“ Hello”)

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

3 个答案:

答案 0 :(得分:1)

def run_process(cmd_args):     使用subprocess.Popen(cmd_args,stdout = subprocess.PIPE,stderr = subprocess.PIPE)为p:         出,err = p.communicate()     退回

答案 1 :(得分:0)

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

答案 2 :(得分:0)

def run_process(cmd_args):
    with subprocess.Popen(cmd_args,stdout=subprocess.PIPE) as proc:
        return proc.communicate()[0]