Does 'argv' in python always use script name as the first argument? How can it be avoided?
For example, I'll call this sample.py:
from sys import argv
one, two, three = argv
print "My first number is ", one
print "My second number is ", two
print "My third number is ", three
When entered into the terminal
python sample.py one two three
It returns:
ValueError: too many values to unpack
And when entered into terminal:
python sample.py one two
It returns:
python seq1.py ONE TWO
My first number is seq1.py
My second number is ONE
My third number is TWO
When running in the terminal, can you avoid the first variable always being assigned to script name?
Is there a way to have input and use just the variables you want without the script name? Or even, in some way, "mute" the printing of a throw away line with the script name?
you can do
argv[1:]
to have a list of arguments without the filename.
What this does is slicing the argv list and returning a new one without the first element. You can read more about list slicing here
Here's an example
from sys import argv
one, two, three = argv[1:]
print "My first number is ", one
print "My second number is ", two
print "My third number is ", three
Related
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.
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
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.
Why whole argument in print function along with paranthesis is printed when only the string should have been
This is Python 2.7.9
import os
alist = [ 'A' ,'B']
print('Hello there')
print('The first item is ',alist[0])
print('Good Evening')
root#justin:/python# python hello.py
Hello there
('The first item is ', 'A')
Good Evening
In python 2 print isn't a function it's a statement. When you write
print('The first item is ',alist[0])
it's actually means "print me a tuple of 2 elements: 'The first item is ' and alist[0]"
it's equivalent to
a = ('The first item is ',alist[0])
print a
if you want to print only strings you should remove the parentheses like that:
print 'The first item is ',alist[0]
EDIT:
As guys in comments tell, you can also add
from __future__ import print_statement
This will make print a function like in python 3 and your examples will work as you expected without any changes.
But I think it's useful to understand what is going on in both cases.
Earlier answers have explained that
print('The first item is ', alist[0])
in Python 2 is equivalent to
print ('The first item is ', alist[0])
so it prints a tuple of two items. That's because print is a statement in Python 2, not a function, so parentheses following print are not interpreted as indicating a function call.
In Python, an expression consisting of several items separated by commas creates a tuple. In some cases, parentheses are required to group the tuple into a single unit; and the print statement is one of those cases, otherwise each item in the comma-separated sequence is treated as a separate argument to the print statement.
The standard string representation of a tuple prints the enclosing parentheses and the repr of each tuple item. Thus any string items in the tuple are printed with their quote marks, and various escape sequences are used to represent non-ASCII characters.
If you wish to use the print() syntax in latter versions of Python 2 in order to make your code compatible with Python 3 then you should put
from __future__ import print_function
as the first executable statement in your script. That will mask the print statement and allow the print name to refer to the print function instead. Here's a short demo, running on Python 2.6.6. First, without the import:
print('one', 'two\n', 'three')
output
('one', 'two\n', 'three')
And with the import:
from __future__ import print_function
print('one', 'two\n', 'three')
output
one two
three
FWIW, you might as well do
from __future__ import print_function, division
So you get Python 3-style behaviour of the / division operator too.
Remember You're using python 2.7.x in python 2, print is a statement, not a function.
You might ask why
print('Good Evening')
doesn't print
('Good Evening')
You're passing only 1 string argument hence the print statement understands that the string needs to be printed and not the parentheses.
when you do
print ('The first item is ',alist[0])
The whole output is printed thinking that there are different parts of the string having , as the delimiter, hence the output is
('The first item is ', 'A')
Remove parentheses while dealing with python 2 because it is not a function oriented version
I'm stuck at this point. here is the code:
from sys import argv
script, first, second, third = argv
print "The script is called:", script
print "The first variable is:", first
print "The second variable is:", second
print "The third variable is:", third
my problem is this, when I run it I get:
value error need more than one value to unpack
as far as I can see I have three values and the code is good, could someone explain where I am going wrong please.
So, in chat #Ricky troubleshooted his way to successfully determining that argv was splitting on whitespace and not , comma. Changing his command line params from
$python myprog.py one,two,three
to
$python myprog.py one two three
made everything fine.
For those who wish to learn the mysteries of the argparse.
In Learn Python The Hard Way (Exercise 13) the 3rd Study Drill says to "Combine raw_input with argv to make a script that gets more input from a user."
I wrote this script below, intending to have the terminal prompt the user for answers to three questions, then it would print back phrases with those answers integrated into them. However, I get an error about not having enough values to unpack when I try to run it with the following command:
python ex13.py
I understand that I need more variables to unpack in order for the script to work, so when I type this then the script works but never outputs the variables "first", "second" or "third" (which I don't want it to anyway):
python ex13.py first second third
I know how to write a script without importing argument variables, but how else can I interpret the study drill? I know I am not understanding the prompt of the study drill correctly but I'm not sure how to write the script differently or even if I am going in the right direction.
Can anyone offer some tips or advice? You don't have to give me the answer outright (I like figuring things out) but I am at a loss for the moment.
MY SCRIPT:
from sys import argv
script, color, number, shape = argv
color = raw_input("What is your favorite color? ")
number = raw_input("What is your favorite number? ")
shape = raw_input("What is your favorite shape? ")
print """
This program is called %r and it will determine your
favorite color, number and shape.
""" % script
print "Based on your answers, your favorite color is:", color
print "Your favorite number is:", number
print "And your favorite shape is a:", shape
What exactly do you want your code to do? If you want to have
$ python ex13.py
$ What is your favorite color? <yourColor>
..........
$ Your favorite color is <yourColor>
Then you need to get rid of the part where you set all those values from argv. argv is a list of the arguments passed to python when you invoke it in the command line. The fix you have in your comments sets script = ['ex13.py'] instead of 'ex13.py' for precisely this reason, you're setting script to be a list as opposed to a string.
If you want your code to run so that you pass the script arguments when you run it, you could get rid of your sections calling for raw_input (or you could leave them in, but that would overwrite their values from what you passed in the command line) Try running the code you've posted with
$ python ex13.py <yourColor> <yourNumber> <yourShape>
It should work much more closely to what you want.
As you have already solved one problem by removing the variables before the =, now the only problem is you are getting square brackets around ex13.py.
You see you have to add another variable after script before = that is without input() and the problem is solved.
I am new to Python. I'm running Raspbian and calling a Python script this way:
python testarguments.py "Here is a test parameter"
My script:
import sys
print sys.argv[1:]
Output:
['Here is a test parameter']
Question:
What is the most efficient way to remove beginning and ending brackets and single quotes from sys.argv output?
You are slicing with
sys.argv[1:]
It means that get all the elements from 1 till the end of the sequence. That is why it creates a new list.
To get only the first item, simply do
sys.argv[1]
This will get the element at index 1.
The : sort of means 'and onwards' so it of course will return a list. Just do:
>>> sys.argv[1]
'Here is a test parameter'
Thus returning your first argument to executing the program, not a part of the list.
The other answers have addressed the actual issue for you, but in case you ever do encounter a string that contains characters you want to remove (like square brackets, for example), you could do the following:
my_str = "['Here is a test parameter']"
my_str.translate(None, "[]")
In other words, if the output you saw were actually a string, you could use the translate method to get what you wanted.