Python how to read output from pexpect child?

后端 未结 6 1766
攒了一身酷
攒了一身酷 2020-12-29 22:51
child = pexpect.spawn (\'/bin/bash\')
child.sendline(\'ls\')
print(child.readline())
print child.before, child.after

All I get with this code in my

相关标签:
6条回答
  • 2020-12-29 22:55

    In pexpect the before and after attributes are populated after an expect method. The most common thing used in this situation is waiting for the prompt (so you'll know that the previous command finished execution). So, in your case, the code might look something like this:

    child = pexpect.spawn ('/bin/bash')
    child.expect("Your bash prompt here")
    child.sendline('ls')
    #If you are using pxssh you can use this
    #child.prompt()
    child.expect("Your bash prompt here")
    print(child.before)
    
    0 讨论(0)
  • 2020-12-29 23:04

    Try the following:

    import pexpect
    child = pexpect.spawn('ls')
    print child.read() # not readline
    

    The read() will give you the entire output of the ls.

    0 讨论(0)
  • 2020-12-29 23:07
    #!/usr/bin/env python
    
    import pexpect
    child = pexpect.spawn("ssh root@172.16.0.120c -p 2222")
    child.logfile = open("/tmp/mylog", "w")
    child.expect(".*assword:")
    child.send("XXXXXXX\r")
    child.expect(".*\$ ")
    child.sendline("ls\r")
    child.expect(".*\$ ")
    

    go to open your logfile:- go to terminal

    $gedit /tmp/mylog
    

    As Per https://pexpect.readthedocs.io/en/stable/api/pexpect.html#spawn-class

    # In Python 3, we'll use the ``encoding`` argument to decode data
    # from the subprocess and handle it as unicode:
     child = pexpect.spawn('some_command', encoding='utf-8')
     child.logfile = sys.stdout
    
    0 讨论(0)
  • 2020-12-29 23:10
    import sys
    import pexpect
    child = pexpect.spawn('ls')
    child.logfile = sys.stdout
    child.expect(pexpect.EOF)
    

    See the manual entry on the subject.

    0 讨论(0)
  • 2020-12-29 23:11

    copy from class spawn(SpawnBase) docstring, maybe example-2 is what you want.

    Example log input and output to a file::

    child = pexpect.spawn('some_command')
    fout = open('mylog.txt','wb')
    child.logfile = fout
    

    Example log to stdout::

    # In Python 2:
    child = pexpect.spawn('some_command')
    child.logfile = sys.stdout
    
    # In Python 3, we'll use the ``encoding`` argument to decode data
    # from the subprocess and handle it as unicode:
    child = pexpect.spawn('some_command', encoding='utf-8')
    child.logfile = sys.stdout
    
    0 讨论(0)
  • 2020-12-29 23:13

    I think all you need is:

    p = pexpect.spawn('ls')
    p.expect(pexpect.EOF)
    print(p.before)
    

    or

    p = pexpect.spawn('/bin/ls')
    p.expect(pexpect.EOF)
    print(p.before)
    

    or

    p = pexpect.spawn('/bin/bash -c "ls"')
    p.expect(pexpect.EOF)
    print(p.before)
    

    or even

    print(pexpect.run('ls'))
    
    0 讨论(0)
提交回复
热议问题