python - pexpect - multiple expect, spawn, kill child
pexpect - multiple expect:
i = child.expect(['first', 'second'])
The expect() method returns the index of the pattern that was matched. So in your example:
if i == 0:
# do something with 'first' match
else: # i == 1
# do something with 'second' match
Spawn:
- The more powerful interface is the spawn class.
- You can use this to spawn an external child command and then interact with the child by sending lines and expecting responses.
child = pexpect.spawn('scp foo myname@host.example.com:.')
child.expect ('Password:')
child.sendline (mypassword)
close(force=True)
- This closes the connection with the child application.
- Note that calling close() more than once is valid.
- This emulates standard Python behavior with files.
- Set force to True if you want to make sure that the child is terminated (SIGKILL is sent if the child ignores SIGHUP and SIGINT).
child.close()
or child.close(force=true)
Program:
import pexpect
import getpass
import sys
PASSWORD = "admin123"
def child_kill(child_pro):
if child_pro.isalive():
print "Still child is live 1 \n"
child_pro.close() # Kill the child, give argument as force=true then also same behaviour
if child_pro.isalive():
print "Still child is live 2\n\n"
else:
print "Child is dead"
def child_read_command(child_pro, command, expect_str):
child_pro.sendline (command)
child_pro.expect (expect_str)
# use list format, string format is not working
output = []
done = False
while True:
try:
if not child_pro.isalive():
line = child_pro.readline()
done = True
else:
# Wait on multiple expect eg: i = child.expect(['first', 'second'])
# i retrun 0 for first, and 1 for second
i = child_pro.expect(['\n', expect_str])
if i == 0:
line = child_pro.before
print(line)
else:
line = child_pro.before
print(line)
break
output.append(line)
if done:
raise pexpect.EOF(0)
print "Rasie the pexect EOF"
except pexpect.EOF:
print "Break of EOF"
break
print "\n\nOutput value = ", output
child_kill(child_pro)
No comments:
Post a Comment