A summary of several ways of taking Python _ log
- 2021-07-26 08:20:40
- OfStack
1. Use the. logfile method
#!/usr/bin/env python
import pexpect
import sys
host="146.11.85.xxx"
user="inteuser"
password="xxxx"
command="ls -l"
child = pexpect.spawn('ssh -l %s %s %s'%(user, host, command))
child.expect('password:')
child.sendline(password)
childlog = open('promp.log',"ab") # The file attribute must be 2 Binary writing +, Otherwise an error will be reported
child.logfile = childlog
child.expect(pexpect.EOF)# If the subprocess is finished, you can go again child.expect(pattern) A newspaper EOF Error, the module provides 1 A method, child.expect(pexpect.EOF), No error will be reported if the child process ends and returns 0
childlog.close()
2. Change the output object of standard output sys. stdout to file log print
#!/usr/bin/env python
import pexpect
import sys
host="146.11.85.xxx"
user="inteuser"
password="xxxx"
command="ls -l"
child = pexpect.spawn('ssh -l %s %s %s'%(user, host, command))
child.expect('password:')
child.sendline(password)
__console__ = sys.stdout # Back up the current standard output to the command line
childlog = open('promp.log',"w") # The file attribute here cannot be 2 Binary system, otherwise error is reported TypeError: a bytes-like object is required, not 'str'
sys.stdout = childlog # Will childlog Set as the object of standard output
child.expect(pexpect.EOF)
print(child.before.decode()) # Use here decode() Function to format the output directory information
#child.before This value contains text from the beginning 1 Until the matching position
childlog.close()
sys.stdout = __console__ # Restore the standard output object to the command line