How do I have a Python script that can accept user input and how do I make it read in arguments if run from the command line?
-
9The answer will depend upon your version of Python. Python 3.x does this a little differently than Python 2.7 – steampowered Oct 26 '12 at 21:23
-
4And Python 2.7 also does this a bit differently than the versions before 2.7, e.g. `argparse` instead of `optparse`. – HelloGoodbye Jan 22 '14 at 09:56
-
3Duplicate of [How do you read from stdin in Python?](https://stackoverflow.com/questions/1450393/how-do-you-read-from-stdin-in-python), [How to read/process command line arguments?](https://stackoverflow.com/questions/1009860/how-to-read-process-command-line-arguments). [Discussed on meta](https://meta.stackoverflow.com/questions/373879/how-should-we-handle-popular-canonicals-that-ask-two-separate-questions). – user202729 Sep 10 '18 at 00:43
-
It's not really a duplicate of the first: user input comes from `/dev/tty`, which is no always the same as standard input. – reinierpost Apr 24 '22 at 21:13
-
Concordant with the meta discussion cited by @user202729, I have cleaned up other questions that were linked here as a duplicate (in most cases, by changing them to link to one of the other two canonicals), and cast the first delete vote. – Karl Knechtel Feb 05 '23 at 12:16
12 Answers
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.

- 12,743
- 8
- 69
- 138

- 9,918
- 2
- 22
- 18
-
73`raw_input` was renamed to `input` in Python 3.x - [documentation here](http://docs.python.org/py3k/whatsnew/3.0.html#builtins) – steampowered Nov 30 '11 at 22:49
-
2My favourite source for this: http://www.tutorialspoint.com/python/python_command_line_arguments.htm and this looks good too: http://www.cyberciti.biz/faq/python-command-line-arguments-argv-example/ – Jordan Stewart Apr 20 '16 at 01:30
-
1sys.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] – Aravind Krishnakumar Feb 10 '17 at 20:10
-
This 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. – reinierpost Apr 13 '22 at 11:56
var = raw_input("Please enter something: ")
print "you entered", var
Or for Python 3:
var = input("Please enter something: ")
print("You entered: " + var)
-
31It should be noted that you don't have to import `raw_input`, it's a builtin function. – Dennis Golomazov Jul 02 '14 at 12:39
-
7You don't have to use str() in print concatenation since all entered data will be str(ing) type by default (even numbers). – Goujon Nov 08 '17 at 11:50
-
This does not work well: it reads from standard input, which is not always a tty. – reinierpost Apr 13 '22 at 11:54
-
@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 Jun 01 '22 at 04:20
-
@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). – reinierpost Jun 01 '22 at 09:47
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)

- 11,809
- 12
- 78
- 98
-
24In 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 "
", line 1, in – IgorGanapolsky Feb 22 '12 at 17:55NameError: name 'bad' is not defined -
input_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. – Deepak Dubey May 08 '13 at 08:11
-
You 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)` – Stefan Gruenwald Feb 08 '14 at 04:59
-
Here is more of the history and the rationale: https://www.python.org/dev/peps/pep-3111/ – Julian Jul 16 '16 at 23:34
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.

- 124,188
- 49
- 220
- 267

- 190,537
- 57
- 313
- 299
-
-
6
-
It'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 over `sys.argv[1:]` – tripleee Jun 01 '22 at 04:23
-
Thanks for recommending argparse. A great improvement over argument parsing I used many years ago in C. Much better than any quick hand-coded stuff I ever tried, even for simple command lines with just a few options, and --help is built in for free! – Roland Nov 18 '22 at 10:37
This simple program helps you in understanding how to feed the user input from command line and to show help on passing invalid argument.
import argparse
import sys
try:
parser = argparse.ArgumentParser()
parser.add_argument("square", help="display a square of a given number",
type=int)
args = parser.parse_args()
#print the square of user input from cmd line.
print args.square**2
#print all the sys argument passed from cmd line including the program name.
print sys.argv
#print the second argument passed from cmd line; Note it starts from ZERO
print sys.argv[1]
except:
e = sys.exc_info()[0]
print e
1) To find the square root of 5
C:\Users\Desktop>python -i emp.py 5
25
['emp.py', '5']
5
2) Passing invalid argument other than number
C:\Users\bgh37516\Desktop>python -i emp.py five
usage: emp.py [-h] square
emp.py: error: argument square: invalid int value: 'five'
<type 'exceptions.SystemExit'>

- 4,674
- 2
- 28
- 45
Use 'raw_input' for input from a console/terminal.
if you just want a command line argument like a file name or something e.g.
$ python my_prog.py file_name.txt
then you can use sys.argv...
import sys
print sys.argv
sys.argv is a list where 0 is the program name, so in the above example sys.argv[1] would be "file_name.txt"
If you want to have full on command line options use the optparse module.
Pev

- 4,128
- 3
- 32
- 37
If you are running Python <2.7, you need optparse, which as the doc explains will create an interface to the command line arguments that are called when your application is run.
However, in Python ≥2.7, optparse has been deprecated, and was replaced with the argparse as shown above. A quick example from the docs...
The following code is a Python program that takes a list of integers and produces either the sum or the max:
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
print args.accumulate(args.integers)

- 25,981
- 9
- 51
- 65

- 1,911
- 1
- 18
- 27
As of Python 3.2 2.7, there is now argparse for processing command line arguments.

- 18,244
- 7
- 53
- 79
-
1argparse has also been backported and is available on PyPi http://pypi.python.org/pypi/argparse/1.2.1 – Sebastian Blask Apr 20 '11 at 14:27
If it's a 3.x version then just simply use:
variantname = input()
For example, you want to input 8:
x = input()
8
x will equal 8 but it's going to be a string except if you define it otherwise.
So you can use the convert command, like:
a = int(x) * 1.1343
print(round(a, 2)) # '9.07'
9.07

- 113
- 2
- 7
In Python 2:
data = raw_input('Enter something: ')
print data
In Python 3:
data = input('Enter something: ')
print(data)
import six
if six.PY2:
input = raw_input
print(input("What's your name? "))

- 862
- 10
- 11
-
1Perhaps 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 Jun 01 '22 at 04:21
-