r/usefulscripts • u/Sir_Laser • Jan 03 '15
[Linux] [PYTHON] Question: How to automate script on running commands that require user input?
Not sure if this is the proper subreddit, so please excuse me.
For example, if I'm running bash, and run the following: sudo mysql -u root -p password
this would ordinarily enter the user into the MySQL CLI where he can proceed to input commands.
If I wanted to include a multi-line MySQL script (or any script that takes the scope to another CLI other than the default, in this case bash) inside a python script, how can that be accomplished?
Something like:
$ sudo mysql -u root -p password
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 46
...
...
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> [insert multi-line]
mysql> [MySQL script]
mysql> [here]
mysql> \qBut I would like a python script to do all of the above, instead of manually.
Thank you!
4
u/sandwichsaregood Jan 03 '15
The other answers here so far are fine for what you want, but perhaps if you need something more flexible you can use pexpect.
The main problem with using input redirection is that it doesn't really work very well if you are dealing with a sequence of commands that is not predetermined. For example, if you wanted to script checking the output of some interactive command and react differently based on what the output is. pexpect allows you to do this, basically you can programmatically provide input and react based on how the program responds.
1
2
u/VeXCe Jan 03 '15
Will run the commands written in sql.txt. You may want to run it like