Log in to raw_input automatically

As an example, this may seem counterintuitive. I have a get_name function, as shown below, and you want to write an automatic script to call this function and automatically enter raw_input .

 def get_name (): name = raw_input("Please enter your name : ") print "Hi " + name 

An automated script, as shown below, which command should be added to automatically enter my value?

 def run (): get_name () // what should I add here? 
+7
python
source share
4 answers

You can redirect your stdin to a file and then raw_input() will read from that file.

Example -

 def run(): import sys f1 = sys.stdin f = open('input.txt','r') sys.stdin = f get_name() f.close() sys.stdin = f1 

Please note: after you do - f = open('input.txt','r') and sys.stdin = f , raw_input () will read from the file <filename> .

Once you are done with get_name (), close the file and restore stdin with sys.stdin = sys.__stdin__ if you want to restore it back to console input, otherwise you can restore it to f1 , which will restore it to a state that was before the test.

Note that you must be careful when redirecting input.

+5
source share

For testing, you can call your script from the command line with IO redirection - see the subprocess in the manuals, but for a quick solution you can change your code like this, note that this does not check raw_input, but allows you to simply test the surrounding code:

 def get_name (name=''): """ Code to get the name for testing supply name int the call """ if len(name) == 0: name = raw_input("Please enter your name : ") print "Hi " + name def run (): get_name ("Fred") 
+2
source share

You can also replace stdin with StringIO (aka memory file) instead of the real file. Thus, the entered text will be in your test code instead of a separate text file.

based on Anand S Kumar (+1):

 def run(): import sys import StringIO f1 = sys.stdin f = StringIO.StringIO('entered text') # <-- HERE sys.stdin = f get_name() f.close() sys.stdin = f1 

In addition, for more complex testing of functions / tools of the interactive command line, you can check the pyexpect package.

+2
source share

Another option is to make the input function a parameter, by default raw_input :

 def get_name(infunc=raw_input): name = infunc("Please enter your name : ") print "Hi " + name 

Then, for testing purposes, you can pass in a function that does everything you need:

 get_name(lambda prompt: "John Smith") 
+1
source share

All Articles