python-3.x - 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'。过程输出:你好
解决方案
def run_process(cmd_args):
with subprocess.Popen(cmd_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as p:
out, err = p.communicate()
return out
推荐阅读
- python - ModuleNotFoundError:没有名为“apiclient”的模块
- angular - 在 NGXS 操作中调用后尝试关闭材料小吃吧不起作用
- javascript - 转换 JSON 对象
- c - 如何扫描和打印最多包含 20 个变量的数组?
- html - 从特定时间重现 html5 视频流
- multithreading - 沙盒环境如何从故障中恢复?
- python-3.x - 如何修复 AttributeError:'NoneType' 对象没有属性 'text'...循环时
- apache-flink - Flink 异步流处理异常处理,用于将来某个时间重播消息
- javascript - 如何在 sweetalert2 确认对话框中访问 axios 响应
- reactjs - 我如何在提交表单时将结果重定向到 React 中的另一个页面