How to pass a String sentence as Command Line Argument

18,786

Solution 1

argv will be a list of all the arguments that the shell parses.

So if I make

#script.py
from sys import argv
print argv

$python script.py hello, how are you
['script.py','hello','how','are','you]

the name of the script is always the first element in the list. If we don't use quotes, each word will also become an element of the list.

print argv[1]
print argv[2]
$python script.py hello how are you
hello
how

But if we use quotes,

$python script.py "hello, how are you"
 ['script.py','hello, how are you']

The all words are now one item in the list. So do something like this

print "The script is called:", argv[0] #slicing our list for the first item
print "Your first variable is:", argv[1]

Or if you don't want to use quotes for some reason:

print "The script is called:", argv[0] #slicing our list for the first item
print "Your first variable is:", " ".join(argv[1:]) #slicing the remaining part of our list and joining it as a string.

$python script.py hello, how are you
$The script is called: script.py
$Your first variable is: hello, how are you

Solution 2

Multi word command line arguments, that is single value arguments that contain multiple ASCII sequences separated by the space character %20 have to be enclosed with quotes on the command line.

$ python test.py "f i r s t a r g u m e n t"
The script is called:test.py
Your first variable is:f i r s t a r g u m e n t

This is actually not related to Python at all, but to the way your shell parses the command line arguments.

Share:
18,786
Richard Smith
Author by

Richard Smith

Updated on June 28, 2022

Comments

  • Richard Smith
    Richard Smith almost 2 years

    The following code takes single String values which can be retrieved on the Python side. How can one do this with a sentence String with spaces?

    from sys import argv
    
    script, firstargument = argv
    
    print "The script is called:", script
    print "Your first variable is:", firstargument
    

    To run that I would pass arguments as such :

    $ python test.py firstargument
    

    Which would output

    The script is called:test.py
    Your first variable is:firstargument
    

    An example input could be "Hello world the program runs" and I want to pass this as a command line argument to be stored in the 'first' variable.