Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scripting and interactive terminal client in Python

Tags:

python

I need to script/automate an interactive terminal client using Python. The client accepts three arguments and runs as follows:

>./myclient <arg1> <arg2> <arg3>
Welcome...
blah...
blah..
[user input]
some more blah... blah... for the input entered
blah.. 
blah..
[basically it accepts input and puts the output in the console until the user types 'quit']

Now I need to automate this in Python and the console output saved in a file.

like image 349
confused1 Avatar asked Jul 09 '26 15:07

confused1


1 Answers

You probably want to use pexpect (which is a pure-python version of the venerable expect).

import pexpect
proc = pexpect.spawn('./myclient <arg1> <arg2> <arg3>')
proc.logfile = the_logfile_you_want_to_use
proc.expect(['the string that tells you that myclient is waiting for input'])
proc.sendline('line you want to send to myclient')
proc.expect(['another line you want to wait for'])
proc.sendline('quit') # for myclient to quit
proc.expect([pexpect.EOF])

Something like this should be enough to solve your case. pexpect is capable of a lot more though, so read up on the documentation for more advanced use-cases.

like image 159
dnaq Avatar answered Jul 11 '26 08:07

dnaq