Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get user input and save it to up to three variables

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.

like image 853
Alessandro Avatar asked Jan 03 '23 14:01

Alessandro


2 Answers

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.

like image 149
Jean-François Fabre Avatar answered Jan 14 '23 12:01

Jean-François Fabre


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]
like image 38
0liveradam8 Avatar answered Jan 14 '23 11:01

0liveradam8