For the following Python script named ex13.py:
from sys import argv
script, first, second, third = argv
print("The script is called:", script)
print("Your first variable is:", first)
print("Your second variable is:", second)
print("Your third variable is:", third)
I have a question about the following line of code:
script, first, second, third = argv
We are saying assign argv to four variables on the left in this order.
Then when I, use this script in my terminal:
python ex13.py first 2nd 3rd
I understand that we are passing variables to a script using the terminal as an input method. However what's confusing me is this.
When I was writing basic Python scripts the way I would call them is with:
python ex3.py
Am I correct in saying that this python ex3.py is not passing a single command line argument and python ex13.py first 2nd 3rd is passing several?
When working from the command line, argv returns a list of the command line arguments, where the first (at place zero argv[0] we get the python file name that was used after the pyhton name).
from place one and up, the values are related to the order in which arguments was recieved. take note that if you use optional arguments (python myscript.py -p 127.0.0.1) those are counted in argv too. so you will get argv[1] == -p
Am I correct in saying that this python ex3.py is not passing a single
command line argument and python ex13.py first 2nd 3rd is passing
several?
no, you are incorrect, python ex3.py is passing 1 argument, argv[0] = ex3.py.
Related
I'm running the code below in Spyder.
I have typed it in a py file and simply hit the run button.
When I try to run it I get the error:
ValueError: need more than 1 value to unpack
As shown here you are meant to give the inputs for the argv variable before running the program but I don't know how to do this is spyder?
http://learnpythonthehardway.org/book/ex13.html
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 "Your third variable is:", third
To pass argv to a script in Spyder, you need to go the menu entry
Run > Configuration per file
or press the Ctrl+F6 key, then look for the option called
Command line options
on the dialog that appears after that, and finally enter the command line arguments you want to pass to the script, which in this case could be
one two three
In addition to configuring in the Run->Configure as explained in other answers,
you can use "runfile" directly from the console.
Run the following:
runfile('ex13.py', args='first second third')
In Spyder, go Run > Configure and define your argv values as showing in following diagram and to run the script just press F6
Read the FAQ at the bottom of the page, it specifically mentions this error.
Common Student Questions
Q. When I run it I get ValueError: need more than 1 value to unpack.
Remember that an important skill is paying attention to details. If you look at the What You Should See section you see that I run the script with parameters on the command line. You should replicate how I ran it exactly.
Make sure you run the command:
$ python ex13.py first 2nd 3rd
>> The script is called: ex13.py
>> Your first variable is: first
>> Your second variable is: 2nd
>> Your third variable is: 3rd
You can ensure that the arguments are supplied.
if __name__ == '__main__':
if len(argv) == 4:
script, first, second, third = argv
print 'The script is called:', script
print 'Your first variable is:', first
print 'Your second variable is:', second
print 'Your third variable is:', third
else:
print 'You forgot the args...'
I started to learn Python with learn Python the Hard Way and I am facing some issues with ex13. I would like to now if it is a mistake of mine or because of the way PyCharm works.
Basically to make the script work as the exercise suggests I saw I have to manually enter the parameters names in PyCharm with run>edit configuration
I put "first" "second" and "third"
But I would like to combine raw_input and argv so I can let the user choose the name of the parameters. Here's what I wrote:
from sys import argv
first = raw_input("First argument: ")
second = raw_input("Second argument: ")
third = raw_input("Third argument: ")
script, first, second, third = argv
print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third
It runs but it returns:
ValueError: need more than 1 value to unpack
It seems that in PyCharm I have to enter manually all the script parameters ? There is no way to combine it with raw input ?
Thanks for your help.
note check out Joran's answer which shows a good combination of using command line args and prompting for user inputs. Below is a break down of what is going on:
This is expected behaviour in PyCharm to specify the parameters you want PyCharm to execute your script with. Think of it like PyCharm doing something like this:
python my_script.py
However, PyCharm does not know the arguments you want to pass, you need to provide this, so it knows how to run your script. If you look near the bottom of your PyCharm window, there is a Terminal tab. You can use that to quickly execute your script and provide args.
Secondly, the reason why you are getting the error you are getting is because you are not handling your script inputs properly when trying to use argv.
You are mixing up using raw_input, which takes in user input when your Python script is running, as opposed to argv which takes parameters in to your Python script when you run it.
So, what you are looking to actually do here, is not use raw_input, but simply argv. Here is a small demo to clarify all this:
from sys import argv
script, first, second, third = argv
print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third
Now, go in to your command prompt and do this:
python my_script one two three
You will get:
The script is called: my_script.py
Your first variable is: one
Your second variable is: two
Your third variable is: three
This is a very simplified example, and you're probably going to need to add some handling of your inputs, or you're going to get a lot of errors with different inputs to your script. With that, I suggest maybe looking at argparse instead
Im not sure i understand the question ... but the code below will use the command line arguments if there are 3(or more) ... otherwise it will prompt and split the same way as the shell splits command line arguments
import shlex # shlex.split will split the string the same way that the shell would for command line args
if len(sys.argv) < 3:
args = (list(sys.argv) + shlex.split(raw_input("Enter Args:")))[:3]
else:
args = sys.argv[:3]
print "Using Args:",args
one,two,three = args
I'm reading "Learn Python the Hard Way" and I'm on exercise 13, but I'm running into a little trouble. Whenever I open up the command line and run the script and enter my argument variables, it's always duplicated on every line like this:
C:\users\blah\> program.py first second third
The script is called:['program.py','first','second','third']
Your first variable is:['program.py','first','second','third']
Your second variable is:['program.py','first','second','third']
Your third variable is:['program.py','first','second','third']
So instead of seeing this on every line I'm aiming for something that doesn't duplicate every line like this (without brackets):
C:\users\blah\> program.py first second third
The script is called:'program.py'
Your first variable is:'first'
Your second variable is:'second'
Your third variable is:'third'
This is my original code. Note I'm on Python 3.5, even though it's specified to use 2.7.
from sys import argv
script = argv
first = argv
second = argv
third = argv
print("The script is called:", script)
print("Your first variable is:", first)
print("Your second variable is:", second)
print("Your third variable is:", third)
Pretty sure the whole variable part is off.
The code in the example is:
from sys import argv
script, first, second, third = argv
When you execute your script with program.py first second third argv becomes a list containing the name of your script followed by each of the scripts arguments. So argv becomes this:
argv = ['program.py', 'first', 'second', 'third']
The line in the original code 'unpacks' the members of that list and assigns them to individual variables. It is equivalent to:
script = argv[0]
first = argv[1]
second = argv[2]
third = argv[3]
It is simply a more concise way of expressing the above. This unpacking syntax is one of the things Zed Shaw is trying to teach with that example. When you changed the program to:
script = argv
first = argv
second = argv
third = argv
the 'unpacking' went away - each of your variables simply refers to the whole list, as you can see from the output of your modified program.
You have not posted the code but this is a very simple issue. When you provide command line arguments python takes it as a list. So when I say
import sys
print sys.argv
Then from the command line i type:
python program.py first second third
the output is what you are getting i.e. all the variables as a list.In order to get the words seperately use list indices. So to get the first argument you use sys.argv[0] which would give program.py
So your code would be like this:
import sys
print 'script name:', sys.argv[0]
print '1st var:', sys.argv[1]
#and so on
I'm new to python and i'm just reading practicing different things and i'm trying to figure out why argv isn't working for me
from sys import argv
script, bike, car, bus = argv
print ("The script is called:"), script
print ("The first variable is:"), bike
print ("The second variable is "), car
print ("Your third variable is : "),bus
I'm getting an error of need more than 1 value to unpack
Traceback (most recent call last):
File "ex13.py", line 6, in <module>
script, bike, car, bus = argv
ValueError: need more than 1 value to unpack
I am running my example program from the command-line by calling:
python ex13.py
Your example is better written as (to cope with arbitrary usages):
from sys import argv
script, args = argv[0], argv[1:]
print("The script is called: ", script)
for i, arg in enumerate(args):
print("Arg {0:d}: {1:s}".format(i, arg))
The reason you'd be getting an error (place show Traceback) is because you're calling your script with fewer arguments than you are trying to "unpack".
See: Python Packing and Unpacking and Tuples and Sequences where it says:
This is called, appropriately enough, sequence unpacking and works for
any sequence on the right-hand side. Sequence unpacking requires the
list of variables on the left to have the same number of elements as
the length of the sequence. Note that multiple assignment is really
just a combination of tuple packing and sequence unpacking.
To demonstrate what's going on with your example adn eht error you get back:
>>> argv = ["./foo.py", "1"]
>>> script, a = argv
>>> script
'./foo.py'
>>> a
'1'
>>> script, a, b = argv
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: need more than 2 values to unpack
The error should be obvious here; You are trying to unpack more values than you have!
To fix your example I'd do this:
from sys import argv
if len(argv) < 4:
print ("usage: {0:s} <bike> <car> <bus>".format(script))
raise SystemExit(-1)
script, bike, car, bus = argv
print ("The script is called:", script)
print ("The first variable is:", bike)
print ("The second variable is ", car)
print ("Your third variable is : ", bus)
Update: I just noticed this; but all your print()(s) are wrong. You need to either use str.format() or put the argument inside the print() function.
Pycharm is an ide and i just click run and it runs the program, but in powershell i type in python ex13.py and that runs the program
OK, then you aren't passing any arguments. So, what were you expecting to find as as the first, second, and third arguments? PowerShell isn't going to guess what bike, car, and bus you wanted to pass the program, any more than it's going to go out and buy you a bike, car, and bus. So, if you want to run this program with arguments representing your bike, car, and bus, you have to actually do that:
python ex13.py CR325 Elise VW
Then your script will output those arguments.
Well, actually, it may not, because your print calls are wrong. If this is Python 2.7, those parentheses don't do anything, so you'll see:
The script is called: ex13.py
The first variable is: CR325
The second variable is Elise
The third variable is : VW
If it's Python 3.x, the parentheses wrap the arguments to the print, just like any other function, so the , script and so forth aren't part of the print, so you'll just see:
The script is called:
The first variable is:
The second variable is
The third variable is :
I've looked through the questions that have already been answered but I am still confused. I've run the code 100 times and I keep getting the same "ValueError: need more than 1 value to unpack" error so obviously something is not computing (see what I did there?) for me. Can someone look at my code and explain to me like you would a child what i've screwed up?
Obviously i've deviated from the terms in the lesson out of sheer frustration
What I have written is:
from sys import argv
script, called, coding, confusing = argv
print "The script is called:", script
print "Your first variable is:", called
print "Your second variable is:", coding
print "Your third variable is:", confusing
Is there a special something I should type in terminal or am I just missing bits of code?
argv is a tuple containing the argument the script was called with. You need to pass your script the necessary number of arguments when you call it:
python myscript.py param_called param_coding param_confusing
To go further:
You are using a syntax called unpacking. This means the left hand side is not a single variable but rather a "sequence" (tuple) of variables. On the left hand side you need a sequence too that has the same number of elements, like a list or tuple. Each variable on the left hand side will be assigned the corresponding value from the right hand side. See the tutorial about tuples and sequences (last paragraph).
About your left hand side, argv or better sys.argv, this is a tuple that contains the script name as first element and the command line parameters. See argv.
All put together: you want to unpack sys.argv which is in the above example ("script.py", "param_called", "param_coding", "param_confusing") into script,called,coding,confusing, so the variable script will be affected the string "script.py", called the string "param_called", etc.
The drawback of this method is that if the command line has too few or too many arguments, the unpacking fails.
Your code is correct, but as specified in the instructions you must put 3 "arguments" into the command prompt
ex: $ python ex13.py called coding confusing
the above prints this out to the command prompt:
The script is called: ex13.py
Your first variable is: called
Your second variable is: coding
Your third variable is: confused