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?
option. You can test command line arguments by running an executable from the "Command Prompt" in Windows or from the "DOS prompt" in older versions of Windows. You can also use command line arguments in program shortcuts, or when running an application by using Start -> Run.
Python provides developers with built-in functions that can be used to get input directly from users and interact with them using the command line (or shell as it is often called). In Python 2, raw_input() and in Python 3, we use input() function to take input from Command line.
To take input (or arguments) from the command line, the simplest way is to use another one of Python's default modules: sys. Specifically, you're interested in sys. argv, a list of words (separated by space) that's entered at the same time that you launch the script.
scanf() function is used to read input from the console or standard input of the application in C and C++ programming language. scanf() function can read different data types and assign the data into different variable types. The input data can be read in different formats by using format specifiers.
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 optparse
argparse
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With