Python 3.4.3 subprocess.Popen get output of command without piping?

前端 未结 4 1921
无人及你
无人及你 2021-02-06 05:32

I am trying to assign the output of a command to a variable without the command thinking that it is being piped. The reason for this is that the command in question gives unform

4条回答
  •  一整个雨季
    2021-02-06 06:04

    A working polyglot example (works the same for Python 2 and Python 3), using pty.

    import subprocess
    import pty
    import os
    import sys
    
    master, slave = pty.openpty()
    # direct stderr also to the pty!
    process = subprocess.Popen(
        ['ls', '-al', '--color=auto'],
        stdout=slave,
        stderr=subprocess.STDOUT
    )
    
    # close the slave descriptor! otherwise we will
    # hang forever waiting for input
    os.close(slave)
    
    def reader(fd):
        try:
            while True:
                buffer = os.read(fd, 1024)
                if not buffer:
                    return
    
                yield buffer
    
        # Unfortunately with a pty, an 
        # IOError will be thrown at EOF
        # On Python 2, OSError will be thrown instead.
        except (IOError, OSError) as e:
            pass
    
    # read chunks (yields bytes)
    for i in reader(master):
        # and write them to stdout file descriptor
        os.write(1, b'' + i + b'')
    

提交回复
热议问题