Fix Python – How to prompt for user input and read command-line arguments [closed]

Question

Asked By – Teifion

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?

Now we will see solution for issue: How to prompt for user input and read command-line arguments [closed]


Answer

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.

This question is answered By – Antti Rasinen

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0