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.
Related
I probably have conjured up some sloppy code trying to get this resolved but what I really want to accomplish is take an IP Address from the command line and fit it into a string variable (theargis).
I am working with a code snippet to assure myself that I have the code worked out before integrating it into my main program, so I am printing the result to the screen.
It is working as such, but the problem is that I am seeing ['123.123.123.123'] instead of 123.123.123.123.
I have tried several ways to attempt to convert the list value in to a raw string without additional formatting, but I am losing the battle.
The question is how I get the final line of this to produce: The argument is: 123.123.123.123
Here is what I have right now...
import sys
theargis = ''
theargis +=str(sys.argv[1:])
print ("The argument is: " + theargis)
I'm fairly sure I am displaying just how green I am to Python but I want to resolve this! Thanks!
import sys
theargis = ''
theargis +=str(sys.argv[1])
print ("The argument is: " + theargis)
I am a total newbie in programming so I was hoping anyone could help me. I am trying to write program in python that, given an integer n, returns me the corresponding term in the sylvester sequence. My code is the following:
x= input("Enter the dimension: ")
def sylvester_term(n):
""" Returns the maximum number of we will consider in a wps of dimension n
>>> sylvester_term(2)
7
>>> sylvester_term(3)
43
"""
if n == 0:
return 2
return sylvester_term(n-1)*(sylvester_term(n-1)-1)+1
Now, my questions are the following, when trying to run this in GitBash, I am asked to input the n but then the answer is not showing up, do you know what I could do to receive the answer back? I plan to continue the code a bit more, for calculating some other data I need, however, I am not sure if it is possible for me to, after coding a certain piece, to test the code and if so, how could I do it?
You will need to add:
print(sylvester_term((int(x)))
to the end of your program to print the answer.
You will need to cast to int because the Python Input() function stores a string in the variable. So if you input 5 it will return "5"
This does not handle exceptions, e.g if the user inputs a letter, so you should put it in a try and except statement.
Here's an example of how I'd handle it. You can use sys.argv to get the arguments passed via the command line. The first argument is always the path to the python interpreter, so you're interested in the second argument, you can get it like so:
sys.argv[1]
Once that is done, you can simply invoke your function like so
print(sylvester_term(int(sys.argv[1]))
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
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.
EDIT: I know there were previous similar questions. Except that it was asked by people who already know Python. I did try the duplicated answer you suggested and it is not working (nothing display in console when I ran it with command line argument). That solution seems to ignore input value via cmd line arg. I could do the job easily in other languages. But for this exercise, I need a Python script. Please help me to write a script ready for use. Sorry if this sounds like a careless request. I do know programming, the trouble here is that I don't know anything about Python.
This is to be used in a streaming exercise with the Hive language (part of Hadoop). Here is the specs:
The script take the value from the command line argument and return the result to standard output
Add thousand separator when the value is compatible with numerical value, otherwise re-output the same input value unchanged.
Example:
$ InsertThousandSeparator.py 386
386
$ InsertThousandSeparator.py 1234567
1,234,567
$ InsertThousandSeparator.py 123ABC
123ABC
$ InsertThousandSeparator.py 123ABC456
123ABC456
$ InsertThousandSeparator.py Hello
Hello
$ InsertThousandSeparator.py 12345.67
12,345.67
The last example with decimal, if it's too complicate to code, this could be skipped.
Thank you very much in advance for any help.
OK, here you are - a script for Python 2.7. But please try to ask one question at a time next time, OK?
import sys
arg = sys.argv[1] # get first command line parameter
if arg.isdigit(): # integer value
value = int(sys.argv[1])
else:
try:
value = float(sys.argv[1]) # try float conversion
except ValueError: # if that fails
value = None # mark value as unusable
if value is not None:
print "{:,}".format(value) # print with thousands separator
else: # or, if not a number
print arg # print as-is.