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 to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Careful not to use the
input
function, unless you know what you're doing. Unlikeraw_input
,input
will accept any python expression, so it's kinda likeeval
This simple program helps you in understanding how to feed the user input from command line and to show help on passing invalid argument.
1) To find the square root of 5
2) Passing invalid argument other than number
raw_input
is no longer available in Python 3.x. Butraw_input
was renamedinput
, so the same functionality exists.Documentation of the change
To read user input you can try the
cmd
module for easily creating a mini-command line interpreter (with help texts and autocompletion) andraw_input
(input
for Python 3+) for reading a line of text from the user.Command line inputs are in
sys.argv
. Try this in your script:There are two modules for parsing command line options:
(deprecated since Python 2.7, useoptparse
argparse
instead) andgetopt
. If you just want to input files to your script, behold the power offileinput
.The Python library reference is your friend.
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...
Or for Python 3: