简体   繁体   English

Subprocess.Popen 读取标准输出但执行未完成

[英]Subprocess.Popen reading stdout but execution not finishing

Having a few troubles when using subprocess.Popen.使用 subprocess.Popen 时遇到一些麻烦。

Here is the code I am using:这是我正在使用的代码:

def parse_replay(rep_record):
    rep_path = rep_record['rep_path']
    screp_cmd = f"{cwd}/screp -cmds -mapres -maptiles '{rep_path.replace('..', os.path.dirname(cwd))}'"
    p = subprocess.Popen(screp_cmd, shell=True)
    out = p.stdout.read()
    rep_action_log = json.loads(out)
    return rep_action_log

If I use shell=False I get a file not found error.如果我使用 shell=False 我得到一个文件未找到错误。 When using shell=True the command gets executed but the function doesn't return (it keeps listening for the output of the command apparently).使用 shell=True 时,命令被执行,但 function 没有返回(它显然一直在监听命令的 output)。

Do you know of any way to be able to capture the stdout of my command whilst correctly finishing the execution of my function?你知道有什么方法可以在正确完成我的 function 的执行的同时捕获我的命令的标准输出吗?

PS: screp is a CLI that outputs json info to stdout https://github.com/icza/screp PS:screp 是一个 CLI,它输出 json 信息到标准输出https://github.com/icza/screp

So Charles' comments work!所以查尔斯的评论有效!

First formatting in list of tokens lets you avoid using shell=True.标记列表中的第一个格式可让您避免使用 shell=True。 Second stoud=subprocess.PIPE lets you capture the stdout.第二个 stoud=subprocess.PIPE 让您捕获标准输出。

def parse_replay(rep_record):
    rep_path = rep_record['rep_path']
    screp_cmd = [f"{cwd}/screp", "-cmds", "-mapres", "-maptiles", f"{rep_path.replace('..', os.path.dirname(cwd))}"]
    p = subprocess.Popen(screp_cmd, stdout=subprocess.PIPE)
    out = p.stdout.read()
    rep_action_log = json.loads(out)
    return rep_action_log

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM