【问题标题】:ValueError: not enough values to unpack (expected 4, got 1)ValueError:没有足够的值来解包(预期 4,得到 1)
【发布时间】:2016-07-05 17:22:30
【问题描述】:

错误位于script, first, second, third = argv。我想了解我收到错误的原因以及如何解决它。

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)

【问题讨论】:

  • 您只是在没有任何参数的情况下运行了脚本,为了让您的代码正常工作,您应该传递至少 3 个参数,例如 python script.py arg1 arg2 arg3
  • 你遇到了什么错误?
  • 我收到 ValueError: not enough values to unpack (expected 4, got 1),是因为我在 pycharm 中运行它而不是使用 cmd?
  • 你需要告诉 pycharm 传入参数/参数,否则它只会执行不带任何参数的脚本。
  • 我在运行“Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful World of Computers and Code”中的示例时遇到了同样的错误,当我发现你的问题时,我说,“我知道那个代码”。

标签: python pycharm


【解决方案1】:

像这样从 shell 运行它:

python script.py arg1 arg2 arg3

【讨论】:

  • 当您在运行命令时没有在命令上添加足够的参数时会发生这种情况。
【解决方案2】:

argv 变量包含命令行参数。在您的代码中,您期望 4 个参数,但只有 1 个(第一个参数始终是脚本名称)。您可以在pycharm 中配置参数。转到Run -> Edit Configurations。然后创建一个新的python配置。在那里你可以指定Script parameters 字段。或者您可以按照 dnit13 的说明从命令行运行脚本。

【讨论】:

    【解决方案3】:

    你可以这样运行它:python script.py first, second, third

    【讨论】:

      【解决方案4】:

      我认为您正在运行以下命令:

      python script.py
      

      您正在编写一个要求 4 个输入的程序,而您只给出一个。这就是您收到错误消息的原因。您可以使用以下命令:

      python script.py Hello How Are
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-04-10
        • 2020-02-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-28
        相关资源
        最近更新 更多