from sys import argv - what is the function of “script”

后端 未结 4 1715
悲哀的现实
悲哀的现实 2020-12-30 04:35

I am reading \"Learn Python the Hard Way\" and was confused by the \"script\" part of the second line.

from sys import argv
script, filename = argv
         


        
4条回答
  •  南方客
    南方客 (楼主)
    2020-12-30 05:16

    Others have explained what is script, but the python statement is called unpacking and is usually applied to tuples or sequences.

    It is a shortcut way of assigning a variable for each value that is in the tuple (or sequence) to the right of the = sign.

    It is not something specific to argv:

    >>> a,b = ('Hello','World')
    >>> a
    'Hello'
    >>> b
    'World'
    

    One thing to keep in mind is that the number of variables on the left side must match the number of items in the sequence on the right, else you get:

    >>> a,b,c = ('Hello','World')
    Traceback (most recent call last):
      File "", line 1, in 
    ValueError: need more than 2 values to unpack
    >>> a,b = ('Hello','World','!')
    Traceback (most recent call last):
      File "", line 1, in 
    ValueError: too many values to unpack
    

提交回复
热议问题