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

前端 未结 4 1918
无人及你
无人及你 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 05:55

    Using pexpect:

    2.py:

    import sys
    
    if sys.stdout.isatty():
        print('hello')
    else:
        print('goodbye')
    

    subprocess:

    import subprocess
    
    p = subprocess.Popen(
        ['python3.4', '2.py'],
        stdout=subprocess.PIPE
    )
    
    print(p.stdout.read())
    
    --output:--
    goodbye
    

    pexpect:

    import pexpect
    
    child = pexpect.spawn('python3.4 2.py')
    
    child.expect(pexpect.EOF)
    print(child.before)  #Print all the output before the expectation.
    
    --output:--
    hello
    

    Here it is with grep --colour=auto:

    import subprocess
    
    p = subprocess.Popen(
        ['grep', '--colour=auto', 'hello', 'data.txt'],
        stdout=subprocess.PIPE
    )
    
    print(p.stdout.read())
    
    import pexpect
    
    child = pexpect.spawn('grep --colour=auto hello data.txt')
    child.expect(pexpect.EOF)
    print(child.before)
    
    --output:--
    b'hello world\n'
    b'\x1b[01;31mhello\x1b[00m world\r\n'
    

提交回复
热议问题