我正在尝试解析命令行参数,以便下面的三种可能性是可能的:
script
script file1 file2 file3 …
script -p pattern
Run Code Online (Sandbox Code Playgroud)
因此,文件列表是可选的.如果-p pattern
指定了一个选项,则命令行上不能有任何其他选项.以"用法"格式表示,它可能看起来像这样:
script [-p pattern | file [file …]]
Run Code Online (Sandbox Code Playgroud)
我认为用Python的argparse
模块做到这一点的方法是这样的:
parser = argparse.ArgumentParser(prog=base)
group = parser.add_mutually_exclusive_group()
group.add_argument('-p', '--pattern', help="Operate on files that match the glob pattern")
group.add_argument('files', nargs="*", help="files to operate on")
args = parser.parse_args()
Run Code Online (Sandbox Code Playgroud)
但Python抱怨我的位置参数需要是可选的:
Traceback (most recent call last):
File "script", line 92, in <module>
group.add_argument('files', nargs="*", help="files to operate on")
…
ValueError: mutually exclusive arguments must be optional
Run Code Online (Sandbox Code Playgroud)
但argparse文档说该"*"
参数 …
我正在尝试编写一个Python函数,它将递归删除所有空目录.这意味着如果目录"a"仅包含"b",则应删除"b",则应删除"a"(因为它现在不包含任何内容).如果目录包含任何内容,则会跳过该目录.图说:
top/a/b/
top/c/d.txt
top/c/foo/
Run Code Online (Sandbox Code Playgroud)
鉴于此,应删除三个目录"b","a"和"foo",因为"foo"和"b"现在为空,并且"a"在删除"b"后将变为空.
我试图通过os.walk
和shutil.rmtree
.不幸的是,我的代码只删除了第一级目录,但没有删除过程中新清空的目录.
我正在使用topdown=false
参数os.walk
.该文档的os.walk
说:"如果自上而下为False,三联供的目录是三元的所有子目录后生成(目录生成由下而上)." 那不是我所看到的.
这是我的代码:
for root, dirs, files in os.walk(".", topdown=False):
contents = dirs+files
print root,"contains:",contents
if len(contents) == 0:
print 'Removing "%s"'%root
shutil.rmtree(root)
else:
print 'Not removing "%s". It has:'%root,contents
Run Code Online (Sandbox Code Playgroud)
如果我有上面描述的目录结构,这是我得到的:
./c/foo contains: []
Removing "./c/foo"
./c contains: ['foo', 'd.txt']
Not removing "./c". It has: ['foo', 'd.txt']
./a/b contains: []
Removing "./a/b"
./a contains: ['b']
Not removing "./a". It has: ['b']
. …
Run Code Online (Sandbox Code Playgroud)