How to prompt for user input and read command-line arguments
Solution 1
To read user input you can try the cmd
module for easily creating a mini-command line interpreter (with help texts and autocompletion) and raw_input
(input
for Python 3+) for reading a line of text from the user.
text = raw_input("prompt") # Python 2
text = input("prompt") # Python 3
Command line inputs are in sys.argv
. Try this in your script:
import sys
print (sys.argv)
There are two modules for parsing command line options: (deprecated since Python 2.7, use optparse
argparse
instead) and getopt
. If you just want to input files to your script, behold the power of fileinput
.
The Python library reference is your friend.
Solution 2
var = raw_input("Please enter something: ")
print "you entered", var
Or for Python 3:
var = input("Please enter something: ")
print("You entered: " + var)
Solution 3
raw_input
is no longer available in Python 3.x. But raw_input
was renamed input
, so the same functionality exists.
input_var = input("Enter something: ")
print ("you entered " + input_var)
Solution 4
The best way to process command line arguments is the argparse
module.
Use raw_input()
to get user input. If you import the readline module
your users will have line editing and history.
Solution 5
Careful not to use the input
function, unless you know what you're doing. Unlike raw_input
, input
will accept any python expression, so it's kinda like eval
Teifion
I am a Software Engineer in a UK Car Insurance provider. I mainly work in Python and PHP.
Updated on July 08, 2022Comments
-
Teifion about 2 years
How do I have a Python script that a) can accept user input and how do I make it b) read in arguments if run from the command line?
-
Sebastian Blask about 13 yearsargparse has also been backported and is available on PyPi pypi.python.org/pypi/argparse/1.2.1
-
steampowered over 12 years
-
IgorGanapolsky over 12 yearsIn Python 2.7, input() doesn't convert values to strings. So if you try to do this: input_variable1 = input ("Enter the first word or phrase: "), you will get an error: Traceback (most recent call last): return eval(raw_input(prompt)) File "<string>", line 1, in <module> NameError: name 'bad' is not defined
-
Deepak Dubey about 11 yearsinput_var = input ("Press 'E' and 'Enter' to Exit: ") NameError: name 'e' is not defined I am using Python 2.5. How, I can overcome this error.
-
demented hedgehog over 10 yearsreadline only available on unix out of the box though.
-
Stefan Gruenwald over 10 yearsYou can avoid the Traceback notice by using the following import which comes with Python 2.7:
import fileinput result=[] for line in fileinput.input(): result.append(line)
-
Dennis Golomazov about 10 yearsIt should be noted that you don't have to import
raw_input
, it's a builtin function. -
Niels Bom over 9 yearsargparse is the new optparse
-
Jordan Stewart about 8 yearsMy favourite source for this: tutorialspoint.com/python/python_command_line_arguments.htm and this looks good too: cyberciti.biz/faq/python-command-line-arguments-argv-example
-
Julian almost 8 yearsHere is more of the history and the rationale: python.org/dev/peps/pep-3111
-
Aravind Krishnakumar over 7 yearssys.argv needs to be supplied with argument number, if suppose you pass a parameter as a value eg. python file_name.py 2017-02-10 and you want to use the date , it should be sys.argv[1] else it will be a list such as [file_name.py,2017-02-10]
-
Goujon over 6 yearsYou don't have to use str() in print concatenation since all entered data will be str(ing) type by default (even numbers).
-
reinierpost about 2 yearsThis does not work well: it reads from standard input, which is not always a tty.
-
reinierpost about 2 yearsThis won't read from tty if standard input comes from somewhere else. The question doesn't make it clear what should happen in that case.
-
tripleee about 2 years@reinierpost What do you mean? There are certainly other ways to read input, too, but this works fine in the terminal. Some IDEs might have trouble because they don't let you interact with a process which reads stuff from stdin, but then that's more of a flaw of those IDEs.
-
tripleee about 2 yearsPerhaps emphasize that
import six
is a facility for creating code which is compatible with both Python 2 and Python 3. These days, you probably don't need that if you are writing new code; just focus on Python 3. -
tripleee about 2 yearsThis duplicates earlier answers without adding anything.
-
tripleee about 2 yearsIt's hard to imagine a sentence where "best" and
argparse
can be combined. It is the standard argument parser, but it is complex and hairy, and huge overkill if you simply want to loop oversys.argv[1:]
-
reinierpost about 2 years@tripleee: All of my scripts are written to write their output to stdout, so I can redirect it to file or to a pipe. When these scripts ask questions to the user, they must go to tty (the user), not to the file or pipe (stdout). Likewise, the user's answers should be read from tty even if the script is reading stdin from elsewhere (although that use case is rare enough that none of my scripts need to make this distinction).
-
Will Charlton about 2 yearsAgreed! I can't remember the last time I used Python 2.