Reputation:
I am new to python and working on putting arguments into variables. I was trying to only allow three variables as arguments and put them into a
, b
and c
as a string.
#!/usr/bin/python
import sys
x = sys.argv[1:]
x = ' '.join(x)
if len(x) > 3:
print "Only three arguments"
else:
print "Too many arguments"
a,b,c=[[y] for y in x.split()]
print a
print b
print c
Upvotes: 1
Views: 374
Reputation: 4863
Here's the working code:
import sys
args = sys.argv[1:]
if len(args) > 3:
print "Too many arguments"
for arg in args:
print(arg)
Upvotes: 0
Reputation: 311143
Since you want the arguments as scalars, you don't need the []
around y
:
a,b,c = [y for y in x.split()]
But frankly, you don't even need to go through the joining a splitting - you can assign an array to a series of comma-delimited scalars:
a,b,c = sys.argv[1:]
Similarly, you shouldn't check len
on a joined string, but on the array. A complete example:
#!/usr/bin/python
import sys
x = sys.argv[1:] # no joining!
if len(x) == 3:
print "Only three arguments"
a,b,c = x
print a
print b
print c
else:
print "Too many arguments"
Upvotes: 1
Reputation: 44828
#!/usr/bin/python
import sys
if len(sys.argv)!=4:
print "Need to get 3 arguments"
sys.exit()
a=str(sys.argv[1])
b=str(sys.argv[2])
c=str(sys.argv[3])
print a
print b
print c
Upvotes: 0