Teifion Teifion - 1 year ago 65
Python Question

Python: user input and commandline arguments

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?

Answer Source

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:

import sys
print sys.argv

For Python 3:

import sys

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 Python library reference is your friend.