我试图为其中一个CLI脚本提供通配符支持,我正在使用pythons glob模块。为了做一个测试,我尝试了这个:
>>> import glob
>>> for f in glob.glob('/Users/odin/Desktop/test_folder/*.log'):
... print f
...
/Users/odin/Desktop/test_folder/test1.log
/Users/odin/Desktop/test_folder/test2.log
/Users/odin/Desktop/test_folder/test3.log这是完美的工作,并提供了正确的输出,因为我有上面的3个文件。但是,当我在CLI中的参数下有相同的代码时,它会失败。我做这个
#code...
parser.add_argument( "-f", "--file", type=str, help="Full path to the file to upload." )
#code...
if args.file:
for f in glob.glob(args.file):
_upload_part(f)我把这个当作
python cli.py -f /Users/odin/Desktop/test_folder/*.log这给了我一个错误:
cli.py: error: unrecognized arguments: /Users/odin/Desktop/test_folder/test2.log /Users/odin/Desktop/test_folder/test3.log我不明白为什么当我一个一个地浏览这个列表时,为什么所有的文件都会同时被添加到这个参数中。
编辑-
nargs朝着正确的方向迈出了一步,但现在出现了这个错误:
`Traceback (most recent call last):
File "cli.py", line 492, in <module>
for f in glob.glob(args.file):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/glob.py", line 27, in glob
return list(iglob(pathname))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/glob.py", line 38, in iglob
dirname, basename = os.path.split(pathname)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/posixpath.py", line 92, in split
i = p.rfind('/') + 1
AttributeError: 'list' object has no attribute 'rfind'`发布于 2015-05-01 18:07:10
以下是您的脚本所收到的信息:
python cli.py -f file1 file2 file3 fileN其中N是与该模式匹配的文件总数(Shell自动扩展通配符)。另一方面,您的文件参数被配置为只接收一个文件/模式,因此最简单(在我看来,也是最好的)解决方案是添加 argument。
parser.add_argument('-f', '--file', type=str, help='...', nargs='+')
# code
for f in args.file:
print(f)这将允许您删除所有glob调用和if args.file检查。
另一个选项是引用命令行参数:
python cli.py -f '/Users/odin/Desktop/test_folder/*.log'https://stackoverflow.com/questions/29992414
复制相似问题