tags:

views:

6425

answers:

6

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?

+7  A: 
var = raw_input("Enter something: ")
print "you entered ", var
Luca
+5  A: 

The best way to process command line arguments is the optparse module.

Use raw_input() to get user input. If you import the readline module your users will have line editing and history.

Dave Webb
+19  A: 

To read user input you can try the cmd module for fancy stuff and raw_input for less fancy stuff.

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 and getopt. If you just want to input files to your script, behold the power of fileinput.

The Python library reference is your friend.

Antti Rasinen
+1  A: 

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

Pev
+2  A: 

Careful not to use the input function , unless you know what you're doing . Unlink raw_input , input will accept any python expression , so it's kinda like eval

Vhaerun
+1  A: 

As of Python 3.2, there is now argparse for processing command line arguments.

GreenMatt