How to prompt for user input and read command-line arguments

1,295,098

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: optparse (deprecated since Python 2.7, use 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) 

Documentation of the change

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

Share:
1,295,098
Teifion
Author by

Teifion

I am a Software Engineer in a UK Car Insurance provider. I mainly work in Python and PHP.

Updated on July 08, 2022

Comments

  • Teifion
    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
    Sebastian Blask about 13 years
    argparse has also been backported and is available on PyPi pypi.python.org/pypi/argparse/1.2.1
  • steampowered
    steampowered over 12 years
    raw_input was renamed to input in Python 3.x - documentation here
  • IgorGanapolsky
    IgorGanapolsky over 12 years
    In 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
    Deepak Dubey about 11 years
    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.
  • demented hedgehog
    demented hedgehog over 10 years
    readline only available on unix out of the box though.
  • Stefan Gruenwald
    Stefan Gruenwald over 10 years
    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)
  • Dennis Golomazov
    Dennis Golomazov about 10 years
    It should be noted that you don't have to import raw_input, it's a builtin function.
  • Niels Bom
    Niels Bom over 9 years
    argparse is the new optparse
  • Jordan Stewart
    Jordan Stewart about 8 years
  • Julian
    Julian almost 8 years
    Here is more of the history and the rationale: python.org/dev/peps/pep-3111
  • Aravind Krishnakumar
    Aravind Krishnakumar over 7 years
    sys.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
    Goujon over 6 years
    You don't have to use str() in print concatenation since all entered data will be str(ing) type by default (even numbers).
  • reinierpost
    reinierpost about 2 years
    This does not work well: it reads from standard input, which is not always a tty.
  • reinierpost
    reinierpost about 2 years
    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.
  • tripleee
    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
    tripleee about 2 years
    Perhaps 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
    tripleee about 2 years
    This duplicates earlier answers without adding anything.
  • tripleee
    tripleee about 2 years
    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:]
  • reinierpost
    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
    Will Charlton about 2 years
    Agreed! I can't remember the last time I used Python 2.