Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prompt for user input and read command-line arguments [closed]

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?

like image 516
Teifion Avatar asked Sep 16 '08 09:09

Teifion


People also ask

How do I open command line arguments?

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.

What function does Python use to get the input from the command line?

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.

How do you give a Python script a command line input?

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.

What function is used to get user input from the command window?

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.


1 Answers

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.

The Python library reference is your friend.

like image 54
Antti Rasinen Avatar answered Oct 05 '22 15:10

Antti Rasinen