python - 使用 getopt() 获取从命令行传递的值

标签 python unix command-line command-line-arguments getopt

我正在编写一个 Python 脚本来为给定的术语和类(class)创建目录。我想利用 Python 模块 os、sys 和 getopt(具有短格式和长格式选项),以便运行脚本如下所示:

>python directory.py –t fall2013 –c cs311-400 
>python directory.py –-term fall2013 –-class cs311-400

我现在编写的代码如下所示:

import os
import sys
import getopt

term = ""
course = ""

options, args = getopt.getopt(sys.argv[1:], 't:c:', ['term=', 'course='])

for opt, arg in options:
    if opt in ('-t', '--term'):
        term = arg
    elif opt in ('-c', '--course'):
         course = arg

在此之后,我有一个函数,它接受术语和类(class)并使用 os.mkdir 等:

def make_folders(term, course):
    if not os.path.isdir(term + course):
        os.mkdir(term + course)
        path = os.path.join(term + course, "assignments")
        os.makedirs(path)

        path = os.path.join(term + course, "examples")
        os.makedirs(path)

        path = os.path.join(term + course, "exams")
        os.makedirs(path)

        path = os.path.join(term + course, "lecture_notes")
        os.makedirs(path)

        path = os.path.join(term + course, "submissions")
        os.makedirs(path)

make_folders(term, course)

由于某种原因,生成的文件夹仅具有代表术语的名称,而不是同时代表术语和类(class)的名称。我觉得这可能与我使用 getopt 有关,但我不确定。有什么建议吗?

最佳答案

os.path.join 是一个聪明的函数。只需传递所需数量的文件夹即可:

>>> import os
>>> os.path.join("first", "second", "third")
'first/second/third'

关于python - 使用 getopt() 获取从命令行传递的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19352035/

相关文章:

unix - 用另一个值替换 unix 文件中的最后一列

c# - 在 C# 中调试命令行参数

command-line - 如何从 Raku 命令行获取多个文件名?

python - 如何在python爬虫中保存存储(常用字符串)

c - 线程只会对数组的第一个分区进行排序(冒泡排序,Pthread)

java - JSoup 从 unix 中的 HTML 选择

command-line - 如何从命令行运行 Exchange 2007 PowerShell 脚本?

python - 如果遇到异常则跳过 XML 读取循环的迭代 Python

python - 在列表/集合中存储变音符号

Python 包层次结构