我已经进行了一些调试,并且在跟踪以下代码中未正确获取命令行参数的原因时遇到了一些麻烦:
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 时会在循环中弹出。