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
The best way to process command line arguments is the
argparse
module.Use
raw_input()
to get user input. If you import thereadline module
your users will have line editing and history.As of Python
3.22.7, there is now argparse for processing command line arguments.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.
then you can use 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
In Python 2:
In Python 3:
If it's a 3.x version then just simply use:
For example, you want to input 8:
x will equal 8 but it's going to be a string except if you define it otherwise.
So you can use the convert command, like: