How to Prompt For User Input and Read Command-Line Arguments

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

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.

How to get a user input in command prompt and pass it to R

From the documentation of readline():

This can only be used in an interactive session. [...] In non-interactive use the result is as if the response was RETURN and the value is "".

For non-interactive use - when calling R from the command line - I think you've got two options:

  1. Use readLines(con = "stdin", n = 1) to read user input from the terminal.
  2. Use commandArgs(trailingOnly = TRUE) to supply the input as an argument from the command line when calling the script instead.

Under is more information.

1. Using readLines()

readLines() looks very similar to readline() which you're using, but is meant to read files line by line. If we instead of a file points it to the standard input (con = "stdin") it will read user input from the terminal. We set n = 1 so that it stops reading from the command line when you press Enter (that is, it only read one line).

Example

Use readLines() in a R-script:

# some-r-file.R

# This is our prompt, since readLines doesn't provide one
cat("Please write something: ")
args <- readLines(con = "stdin", n = 1)

writeLines(args[[1]], "output.txt")

Call the script:

Rscript.exe "some-r-file.R"

It will now ask you for your input. Here is a screen capture from PowerShell, where I supplied "Any text!".

Print screen from PowerShell

Then the output.txt will contain:

Any text!


2. UsingcommandArgs()

When calling an Rscript.exe from the terminal, you can add extra arguments. With commandArgs() you can capture these arguments and use them in your code.

Example:

Use commandArgs() in a R-script:

# some-r-file.R
args <- commandArgs(trailingOnly = TRUE)

writeLines(args[[1]], "output.txt")

Call the script:

Rscript.exe "some-r-file.R" "Any text!"

Then the output.txt will contain:

Any text!

Prompt for user input in bash script and read it like command line arguments?

This will not handle quotes, but should otherwise work:

doStuff() {
echo first of $# args is $1
}

read VARS
doStuff $VARS

This works because variable expansion takes place on $VARS before calling doStuff, and the expanded command will be something like doStuff foo bar baz 42 23 fin.

How do I accept user input on command line for python script instead of prompt

Replace src = input('Enter Path to src: ') with:

import sys
src = sys.argv[1]

Ref: http://docs.python.org/2/library/sys.html

If your needs are more complex than you admit, you could use an argument-parsing library like optparse (deprecated since 2.7), argparse (new in 2.7 and 3.2) or getopt.

Ref: Command Line Arguments In Python


Here is an example of using argparse with required source and destination parameters:

#! /usr/bin/python
import argparse
import shutil

parser = argparse.ArgumentParser(description="Copy a file")
parser.add_argument('src', metavar="SOURCE", help="Source filename")
parser.add_argument('dst', metavar="DESTINATION", help="Destination filename")
args = parser.parse_args()

shutil.copyfile(args.src, args.dst)

Run this program with -h to see the help message.

Get user input with arguments in Python

The built-in argparse module as @ToTheMax said can create complex command line interfaces.

By default argparse.ArgumentParser.parse_args() will read the command line arguments to your utility from sys.argv, but if you pass in an array, it will use it instead.

You can lex (split into an array of "words") a string just like the shell is using shlex.split() which is also built in. If you use quotation marks like in your example, the words between them won't be split apart, just as in the shell.

Here's a complete example. Refer to the documentation, because this is a bit of an advance usage of argparse. There is a section that talks about "subcommands" which is what this example is based on.

import argparse
import shlex

def do_say(args):
print(args.what)

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
say_command = subparsers.add_parser('say')
say_command.add_argument('what')
say_command.set_defaults(func=do_say)

command = 'say "hi this is a test"'

args = parser.parse_args(shlex.split(command))
args.func(args)

The cmd module is another built-in way to make a command prompt, but it doesn't do the parsing for you, so you'd maybe combine it with argparse and shlex.

Command Line Arguments vs Input - What's the Difference?

Command line arguments and input are two different things.

Command line arguments are given to the application that is being run, before it is run. Let's look at an example:

$ java JavaProgram 30 91

First we give the app JavaProgram the command line arguments 30, 91, only then do we hit Enter and run it as a Java program.

Meaning:

  1. The command line arguments are a part of a specific invocation of the application. (we can give it other command line arguments in other times we run it)
  2. Command line arguments are given to a program BEFORE it starts running.

Contrary to that, input can be given to an application during its run, because it can only ask for input after it started running.
For that reason, we can print some text to the user before asking for input, indicating what input we are expecting for, etc.

But we can't do it with command line arguments, as an app that isn't running - can't do anything, and in particular can't print messages to the user.

Command line arguments are taken once - either zero, three, ninety, or whatever number of command line arguments. (actually there's a limit to that number, but it's very big and irrelevant)

Input can be taken any number of times.
For that reason, input can be interactive - the system can take input, then respond according to it, then take more input, etc.
Command line arguments are taken once, therefore can not be used to manage any interactiveness.

All the above, narrows the conversation "what’s the difference between command line arguments and input?" to the very specific cases where we wish to take input once, and do not wish to print anything prior to that. Even in that case, a command line argument would still be given before the program starts running, comparing to input which would be given after the program starts running.



Related Topics



Leave a reply



Submit