How do I have a Python script that can accept user input (assuming this is possible) and how do I make it read in arguments if run from the command line?
Join them; it only takes a minute:
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 for less fancy stuff (just reading a line of text from the user). Command line inputs are in sys.argv. Try this in your script for Python 2:
For Python 3:
Since print has changed from a keyword in Python 2 into a function call in Python 3. There are two modules for parsing command line options: optparse and getopt. If you just want to input files to your script, behold the power of fileinput. |
|||||||||||||
|
|
|||||
|
|
|||||||||||||||||
|
The best way to process command line arguments is the Use |
|||||||||
|
Careful not to use the |
||||
|
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...
|
||||
|
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.
then you can use 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 |
|||
|
As of Python |
|||||
|
This simple program helps you in understanding how to feed the user input from command line and to show help on passing invalid argument.
1) To find the square root of 5
2) Passing invalid argument other than number
|
|||
|
argparse
instead ofoptparse
. – HelloGoodbye Jan 22 '14 at 9:56