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?


Asked by: Ada615 | Posted: 24-09-2021






Answer 1

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.

Answered by: Lyndon800 | Posted: 25-10-2021



Answer 2

var = raw_input("Please enter something: ")
print "you entered", var

Or for Python 3:

var = input("Please enter something: ")
print("You entered: " + var)

Answered by: John893 | Posted: 25-10-2021



Answer 3

raw_input is no longer available in Python 3.x. But raw_input was renamed input, so the same functionality exists.

input_var = input("Enter something: ")
print ("you entered " + input_var) 

Documentation of the change

Answered by: Chelsea450 | Posted: 25-10-2021



Answer 4

The best way to process command line arguments is the argparse module.

Use raw_input() to get user input. If you import the readline module your users will have line editing and history.

Answered by: Kimberly819 | Posted: 25-10-2021



Answer 5

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

Answered by: Carlos544 | Posted: 25-10-2021



Answer 6

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

1) To find the square root of 5

C:\Users\Desktop>python -i emp.py 5
25
['emp.py', '5']
5

2) Passing invalid argument other than number

C:\Users\bgh37516\Desktop>python -i emp.py five
usage: emp.py [-h] square
emp.py: error: argument square: invalid int value: 'five'
<type 'exceptions.SystemExit'>

Answered by: Arthur911 | Posted: 25-10-2021



Answer 7

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.

$ python my_prog.py file_name.txt

then you can use sys.argv...

import sys
print 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

Answered by: Emma117 | Posted: 25-10-2021



Answer 8

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)

Answered by: Chloe612 | Posted: 25-10-2021



Answer 9

As of Python 3.2 2.7, there is now argparse for processing command line arguments.

Answered by: Kimberly797 | Posted: 25-10-2021



Answer 10

If it's a 3.x version then just simply use:

variantname = input()

For example, you want to input 8:

x = 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:

a = int(x) * 1.1343
print(round(a, 2)) # '9.07'
9.07

Answered by: Tess424 | Posted: 25-10-2021



Answer 11

In Python 2:

data = raw_input('Enter something: ')
print data

In Python 3:

data = input('Enter something: ')
print(data)

Answered by: Miranda370 | Posted: 25-10-2021



Answer 12

import six

if six.PY2:
    input = raw_input

print(input("What's your name? "))

Answered by: David526 | Posted: 25-10-2021



Similar questions

python - pass command-line arguments to runpy

I have two files, one which has a side effect I care about that occurs within the if __name__ == "__main__" guard: # a.py d = {} if __name__ == "__main__": d['arg'] = 'hello' The second file imports the first (using runpy) and prints the dictionary: # b.py import runpy m ...


python - Docker pass command-line arguments

I really just want to pass an argument via docker run My Dockerfile: FROM python:3 # set a directory for the app WORKDIR /usr/src/app # copy all the files to the container COPY . . # install dependencies RUN pip install --no-cache-dir -r requirements.txt # tell the port number the container should expose EXPOSE 5000 # run the command CMD ["python", "./app.py"] My python ...


How to pass command-line arguments to a python script from within another script?

I've got a python script that is named code.py and this takes two command line arguments --par_value xx --out_dir /path/to/dir where par_value is a certain parameter and out_dir is the output directory. I want to run this script for different values of the input parameter. So I want to use the array: par_vector = np.array([1,2,3]) an...


python - command-line options and arguments using getopt

I'm trying to write a piece of code in python to get command-line options and arguments using getopt module. Here is my code: import getopt import sys def usage (): print('Usage') def main(): try: opts, args = getopt.getopt(sys.argv[1:], 'xy:') except getopt.GetoptError as err: print(err) usage() sys.exit() for o,a in opts: if o in ("-x", "--xxx"):...


ruby on rails - UTF-8 minus sign rejected in python command-line arguments

I am running python 2.6 on Ubuntu Lucent and having trouble getting the minus sign in negative command-line arguments to be interpreted properly, especially when the call to the script is initiated through the OS via Rails (using backquotes). In particular, the minus sign seems to be coming in as UTF-8. When command-line arguments are interpreted manually, as in: lng = float(sys.argv[4])


python - Passing Command-line Arguments in C++

I've been trying to learn how to extend Python 3 with C++, and I was recommended using Boost. I believe I've followed the procedure of setting up Boost::Python correctly so far, and I have the following code from here (saved as example.cpp) which builds successfully: #incl...


python - How can I get the command-line arguments in an embedded Pig script?

I'm writing an embedded pig script in python, and I'd like to pass arguments like this: $ pig myscript.py arg1 arg2 I'd expect sys.argv to be ['myscript.py', 'arg1', 'arg2'], but it's empty. Any idea how I can pass command-line arguments to an embedded pig script?


python - Parsing command-line arguments similar to archlinux pacman

I'm creating a python script with usage in the same style as pacman in Arch Linux, summarized by: prog &lt;operation&gt; [options] [targets] operations are of the form -X (hyphen, uppercase letter), and one is required when calling the script. options are of the form -x ...


How to access command-line arguments from a Python script?

I am writing code in Python that I should run with the command line and when I call the script i should give some arguments that I would use in the code. What can I use to achieve that? To run the script it would be something like this: python myscript.py s1 s2 s4 where s1, s2 and s4 would be the arguments that I would use in my code.


Passing Strings as Python command-line arguments

I’m able to pass ints and chars as Python command-line args, but can’t pass Strings successfully to the following: if __name__ == '__main__' : try : print(len(sys.argv)) arg1 = ast.literal_eval(sys.argv[1]) arg2 = ast.literal_eval(sys.argv[2]) print(arg1) print(arg2) except Exception : print('error') The following works:


Parsing command-line arguments in Python: array of variable length?

is it possible to create an array in Python with an variable length? I'm getting different kind of length from sys.argv when I start the program and I need as much array field as long as the string from sys.argv is. EDIT for better understanding: I wrote a python script which can controle the GPIO Ports of a Raspberry Pi Until now, the script is just able to control one port at the same time...


Can I pass command-line arguments to Abaqus python?

I have an abaqus python script I've been using for a parametric study. It is exhausting to go into the code and edit it every time I want to run different options. I'd like to be able to pass the script arguments so that I can run different options without needing to change the code. I'd like to do something like this... abaqus cae script='Script.py --verbose --data=someData.dat' I...


python - Provide command-line arguments for function in file

This question already has answers here:


linux - How to make a python, command-line program autocomplete arbitrary things NOT interpreter

I am aware of how to setup autocompletion of python objects in the python interpreter (on unix). Google shows many hits for explanations on how to do this. Unfortunately, there are so many references to that it is difficult to find what I need to do, which is slightly different. I need to know how to enable, tab/auto completion of arbitrary items in a command-line program written in ...


java - OCSP command-line test tool?

Closed. This question does not meet Stack Overflow guid...


eclipse - Integrating command-line generated python .coverage files with PyDev

My build environment is configured to compile, run and create coverage file at the command line (using Ned Batchelder coverage.py tool). I'm using Eclipse with PyDev as my editor, but for practical reasons, it's not possible/convenient for me to convert my whole build environment to Eclipse (and thus generate the coverage data directly from the IDE, as it's designed to do) PyDev seems to be using the same ...


c++ - How do I compile a Visual Studio project from the command-line?

I'm scripting the checkout, build, distribution, test, and commit cycle for a large C++ solution that is using Monotone, CMake, Visual Studio Express 2008, and custom tests. All of the other parts seem pretty straight-forward, but I don't see how to compile the Visu...


How to make a simple command-line chat in Python?

I study network programming and would like to write a simple command-line chat in Python. I'm wondering how make receving constant along with inputing available for sending at any time. As you see, this client can do only one job at a time: from socket import * HOST = 'localhost' PORT = 21567 BUFSIZE = 1024 ADDR = (HOST, PORT) tcpCliSock = socket(AF_INET, SOCK_STREAM) tcpCliSock.connect(A...


interpreter - Persistent Python Command-Line History

I'd like to be able to "up-arrow" to commands that I input in a previous Python interpreter. I have found the readline module which offers functions like: read_history_file, write_history_file, and set_startup_hook. I'm not quite savvy enough to put this into practice though, so could someone please help? My thoughts on the solution are: (1) Modify .login PYTHO...


data structures - Processing command-line arguments in prefix notation in Python

I'm trying to parse a command-line in Python which looks like the following: $ ./command -o option1 arg1 -o option2 arg2 arg3 In other words, the command takes an unlimited number of arguments, and each argument may optionally be preceded with an -o option, which relates specifically to that argument. I think this is called a "prefix notation". In the Bourne shell I wo...


Display constantly updating information in-place in command-line window using python?

I am essentially building a timer. I have a python script that monitors for an event and then prints out the seconds that have elapsed since that event. Instead of an ugly stream of numbers printed to the command line, I would like to display only the current elapsed time "in-place"-- so that only one number is visible at any given time. Is there a simple way to do this? If possible I'd like to u...


python - How to write script output to file and command-line?

I have a long-running Python script that I run from the command-line. The script writes progress messages and results to the standard output. I want to capture everything the script write to the standard output in a file, but also see it on the command line. Alternatively, I want the output to go to the file immediately, so I can use tail to view the progress. I have tried this: python MyLongRu...


python - Linux command-line call not returning what it should from os.system?

I need to make some command line calls to linux and get the return from this, however doing it as below is just returning 0 when it should return a time value, like 00:08:19, I am testing the exact same call in regular command line and it returns the time value 00:08:19 so I am confused as to what I am doing wrong as I thought this was how to do it in python. import os...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top