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?
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?
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 optparseargparse 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.
var = raw_input("Please enter something: ")
print "you entered", var
Or for Python 3:
var = input("Please enter something: ")
print("You entered: " + var)
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.
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
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