【问题标题】:Python Command Arguments getting lostPython 命令参数丢失
【发布时间】:2013-10-22 16:15:07
【问题描述】:

我已经进行了一些调试,但在追踪以下代码中命令行参数未正确提取的原因时遇到了一些问题:

def ensure_dir(f):
   d = os.path.dirname(f)
   if not os.path.exists(d):
     os.makedirs(d)

def main(argv):
   files = ["assignments", "examples", "exams", "lecture_notes", "submissions"]

   selectterm = ""
   selectclass = ""
   try:
       opts, args = getopt.getopt(argv, "c:t:", ["class","term"])
   except getopt.GetoptError as e:
       print 'Question2.py -c <class> -t <term>'
       system.exit(2)
   for opt, arg in opts:
       print arg
       print opt
       if opt in ("c", "class"):
           selectclass = arg
       if opt in ("t", "term"):
           selectterm = arg


   print selectclass
   print selectterm
   filename = selectterm + "/" + selectclass + "/src/"

   for  x in files:
       directory = str(filename + x +"/")
       ensure_dir(directory)
       print directory
   symblink = "/usr/local/classes/eecs/" + selectterm + "/" + selectclass + "/src/README"
   os.symlink(symblink, "README")





if __name__ == "__main__":
    main(sys.argv[1:])

问题似乎出在 for opt, arg in opts: 循环中,因为命令行参数从未放入 selectclass 和 selectterm,但语法对我来说是正确的。这些值存在于 argv 数组中,并且在我打印 arg 和 opt 时会在循环中弹出。

【问题讨论】:

  • 代码的意图不正确,这意味着您的块可能在与您预期不同的地方结束。请发布正确缩进的代码。

标签: python command-line-arguments


【解决方案1】:

您需要在长选项的末尾添加一个等号,以表明您希望它们取值——例如,["class=", "term="]

其次,返回的 opt 包含前缀破折号。例如,

...
if opt in ("-c", "--class"):
    ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-10
    • 2013-07-29
    • 2016-12-16
    • 2012-02-20
    • 1970-01-01
    • 2017-02-23
    • 1970-01-01
    • 2018-01-25
    相关资源
    最近更新 更多