【问题标题】:Python3: option parser, check if a boolean option has been setPython3:选项解析器,检查是否设置了布尔选项
【发布时间】:2011-10-15 05:41:43
【问题描述】:

我想为我的程序设置一个真/假选项 (-w)。 如果设置了选项,我将对输出进行排序。

我添加了以下选项:

parser.add_option("-w", "--without-replacement",
                  action="store_true", dest="replacement", default=False,
                  help="outpt lines without replacement")

replacement = options.replacement

if replacement
    if self.lines:
        self.lines.sort()
        last = self.lines[-1]
        for i in range(len(self.lines)-2, -1, -1):
            if last == self.lines[i]: del self.lines[i]
            else: last=self.lines[i]

当我运行程序时,出现以下错误:

  File "randline.py", line 65
    if replacement
                 ^
SyntaxError: invalid syntax

你能帮我找出正确的语法吗? parser.add_option 编程是否正确?

【问题讨论】:

  • 你想在迭代中做什么?

标签: python python-3.x python-2.x


【解决方案1】:

语法错误是因为你忘记了'if replacement'后面的冒号。

您必须在选项可用之前实际调用解析器:

options = parser.parse_args()

如果您在最后尝试删除 for 循环中的重复项,请尝试以下操作:

if replacement and self.lines:
    self.lines = list(set(self.lines))
    self.lines.sort()

【讨论】:

    【解决方案2】:
    if replacement
    

    需要:

    if replacement:
    

    注意冒号 (:)

    【讨论】:

      猜你喜欢
      • 2014-03-28
      • 1970-01-01
      • 1970-01-01
      • 2012-09-13
      • 2017-05-08
      • 2013-03-17
      • 2014-09-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多