I have a problem with the following code:
cmd, arg, arg1 = input("> ").split(" ")
I want to get the input into these three vars.
But if I leave arg
and arg1
empty, Python complains:
not enough values to unpack (expected 3, got 1)
How can I avoid this?
I want to make arg
and arg1
optional.
you cannot unpack into variables if the size varies. Well, not like this.
You can, using extended iterable unpacking (also known as star unpacking) (Python 3 only):
cmd, *args = input("> ").split(" ")
now if you enter only a command, args
is empty, else it unpacks the arguments you're entering into a list.
if not args:
# there are no arguments
pass
elif len(args)>2:
print("too many args")
else:
print("args",args)
note that you'll find split(" ")
limited. I'd do split()
(no argument: groups blanks to avoid empty args), or handle quoting with shlex.split(input("> "))
Note: with python 2, you'd have to split and test length. Less elegant, but would work.
You can set the variables separately after getting the input string:
inp=input("> ").split(" ")
l = len(inp)
if l >= 1:
cmd = inp[0]
if l >= 2:
arg1 = inp[1]
if l >= 3:
arg2 = inp[2]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With