cat pants
cat pants

Reputation: 1563

How do you get stdout from pexpect?

import pexpect

domain = "test"
username = "user"
password = "password"

child = pexpect.spawn("virsh console " + domain)

# ensure we get a login prompt:
child.sendline()

# log in:
child.expect("login:")
child.sendline(username)
child.expect("Password:")
child.sendline(password)

# run command:
child.sendline("touch foo.txt")
child.sendline("exit") 

This works perfectly. The problem now is that I want to do an ls (after touch) and get the output but I can't figure out how to do that.

I saw an example using child.logfile = sys.stdout right after spawn (and changing the spawn line to include encoding="utf-8") and this does produce some output, but doesn't show the output from ls.

From here:

Python how to read output from pexpect child?

I tried the following:

import pexpect

domain = "test"
username = "user"
password = "password"

child = pexpect.spawn("virsh console " + domain)

# ensure we get a login prompt:
child.sendline()

# log in:
child.expect("login:")
child.sendline(username)
child.expect("Password:")
child.sendline(password)

# run command:
child.sendline("touch foo.txt")
child.sendline("ls")
child.expect(pexpect.EOF)
print(child.before)

child.sendline("exit")

But this just times out.

I also tried:

import pexpect

domain = "test"
username = "user"
password = "password"

child = pexpect.spawn("virsh console " + domain)

# ensure we get a login prompt:
child.sendline()

# log in:
child.expect("login:")
child.sendline(username)
child.expect("Password:")
child.sendline(password)

# run command:
child.sendline("touch foo.txt")
child.sendline("ls")
child.expect(".*") # the shell prompt varies extensively
print(child.before)

child.sendline("exit")

And this returns the following line:

b''

Which is clearly not the expected output from ls. How do I get stdout from ls in this case?

All the examples from: Python how to read output from pexpect child? do not have this extra layer of virsh console in the equation, which I think makes my problem much more difficult to solve.

Upvotes: 0

Views: 23

Answers (0)

Related Questions