Google 的 Python 练习 'Copyspecial' 的默认编程错误

Error in default programming of Google's Python exercise 'Copyspecial'

在 Google 的 Python 练习 copyspecial.py 中使用 --todir 选项时出现 IndexError: list index out of range 错误。我该如何解决这个问题?最让我困惑的是导致它的代码部分是讲师写的(来自Google/Standford)。我只能假设一些语法错误已经蔓延到其他代码行,或者自 Python 2.7 以来内置函数语法发生了变化。本练习代码是2.7写的

该文件在不使用任何选项时有效,如下所示:

Printing list of special files

C:.\gpe\copyspecial\xyz__hello__.txt

C:.\gpe\copyspecial\zz__something__.jpg

done

这是错误:

代码:

def main():
  # This basic command line argument parsing code is provided.
  # Add code to call your functions below.

  # Make a list of command line arguments, omitting the [0] element
  # which is the script itself.
  args = sys.argv[1:]
  if not args:
    print "usage: [--todir dir][--tozip zipfile] dir [dir ...]";
    sys.exit(1)

  # todir and tozip are either set from command line
  # or left as the empty string.
  # The args array is left just containing the dirs.
  todir = ''
  if args[0] == '--todir':
    todir = args[1]
    del args[0:2]

  tozip = ''
  if args[0] == '--tozip':
    tozip = args[1]
    del args[0:2]

  if len(args) == 0:
    print "error: must specify one or more dirs"
    sys.exit(1)

  # +++your code here+++
  # Call your functions

上述所有代码均直接来自 google.com。我的代码出现在定义 main() 之前和定义 # +++your code here+++

之后

我花了几个小时试图解决这个问题。我学到了很多,但不是解决方案。

  1. 我试过更改缩进。
  2. 我试过 sys.exit(1) 嵌套在 '--todir' 'if' 下,但程序将 运行 保留在 'if tozip' 部分,这让我相信它是句法的。但是我找不到放错地方的 ():。我还检查了缩进。
  3. 我试过添加一个'if args[0]:'检查,但它不起作用,因为正如我后来了解到的,虽然空列表('args[0]' = [])、Python不起作用将其解释为实际的“False”值。
  4. 不胜枚举

我非常感谢有机会在 Whosebug 上让社区听到我的问题,作为第一次发布者更是如此。

据我所知,如果你做对了,你的第三次尝试应该会奏效:

tozip = ''
if args and args[0] == '--tozip':
  tozip = args[1]
  del args[0:2]

这实际上检查了列表 args。如果它是空的 ([]),它被认为是假的,第二个测试 args[0] == '--tozip' 不会被评估。

你的问题是 args 本身是一个空列表, 的计算结果为 False(参见 https://docs.python.org/2/library/stdtypes.html#truth-value-testing),因此你不能访问 args[0] 并检查它会产生相同的 Indexerror.

但是,如果您只传递其中一个参数而没有参数,您仍然会得到一个 IndexError,因为您访问 args[1] 没有经过测试。

编辑(为什么代码 运行 不是原样?): 我不认为任何 python 版本 >=2.4 会解释这不同,但我没有证据。这种参数传递是非常基本的。检查格式错误的用户输入总是相当 "annoying" 因为您必须处理每一个可能的输入,这会导致大量代码。如果您想深入了解参数传递的更多细节,我推荐使用 argparse 模块 (2.7, 3.5)。我的感觉是,为了避免练习文件中有很大一部分与练习无关,他们就让它变得如此简单。如果您没有提供至少一个文件路径作为参数,您将在下一步中收到一条错误消息:

if len(args) == 0:
  print "error: must specify one or more dirs"
  sys.exit(1)

所以代码 照原样执行 运行。您只需提供正确的参数即可。