Capture output from C program on stdout using Python subprocess? Pexpect?

后端 未结 2 1547
失恋的感觉
失恋的感觉 2021-01-15 16:04

I want to capture output from a C program I\'m launching like this:

p = subprocess.Popen([\"make\", \"run_pci\"],
                     stdout=subprocess.PIPE         


        
2条回答
  •  情话喂你
    2021-01-15 17:00

    The reason you need to use pexpect is that the program's stdio will use block buffering if it is not connected to a tty. pexpect uses a pseudo-tty (pty) so stdio will use line buffering and you will be able to access lines as they are output.

    Change your code to:

    p = pexpect.spawn('make', ['run_pci'], cwd="/home/ecorbett/hello_world_pthread")
    for ln in p:
        ...
    

    You can use pexpect.spawn.expect to just get the output you're interested in:

    while p.expect('Thread on Tile (\d+):', pexpect.EOF) == 0:
        print("Tile {0}".format(int(p.group[1])))
    

提交回复
热议问题