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.
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
回答 5
这个简单的程序可以帮助您了解如何从命令行输入用户输入以及如何显示有关传递无效参数的帮助。
import argparse
import sys
try:
parser = argparse.ArgumentParser()
parser.add_argument("square", help="display a square of a given number",
type=int)
args = parser.parse_args()#print the square of user input from cmd line.print args.square**2#print all the sys argument passed from cmd line including the program name.print sys.argv
#print the second argument passed from cmd line; Note it starts from ZEROprint sys.argv[1]except:
e = sys.exc_info()[0]print e
This simple program helps you in understanding how to feed the user input from command line and to show help on passing invalid argument.
import argparse
import sys
try:
parser = argparse.ArgumentParser()
parser.add_argument("square", help="display a square of a given number",
type=int)
args = parser.parse_args()
#print the square of user input from cmd line.
print args.square**2
#print all the sys argument passed from cmd line including the program name.
print sys.argv
#print the second argument passed from cmd line; Note it starts from ZERO
print sys.argv[1]
except:
e = sys.exc_info()[0]
print e
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…
The following code is a Python program that takes a list of integers
and produces either the sum or the max:
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
print args.accumulate(args.integers)