JuanPabloMF
JuanPabloMF

Reputation: 497

Subprocess.Popen reading stdout but execution not finishing

Having a few troubles when using 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. When using shell=True the command gets executed but the function doesn't return (it keeps listening for the output of the command apparently).

Do you know of any way to be able to capture the stdout of my command whilst correctly finishing the execution of my function?

PS: screp is a CLI that outputs json info to stdout https://github.com/icza/screp

Upvotes: 0

Views: 164

Answers (1)

JuanPabloMF
JuanPabloMF

Reputation: 497

So Charles' comments work!

First formatting in list of tokens lets you avoid using shell=True. Second stoud=subprocess.PIPE lets you capture the stdout.

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

Upvotes: 0

Related Questions