[英]Unexpected output with glob.glob
Im trying to provide wildcard support to one of CLI
scripts and I am using pythons glob
module for it. 我试图为其中一个CLI
脚本提供通配符支持,我正在使用pythons glob
模块。 For a test i tried this: 对于测试我试过这个:
>>> 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
This works perfectly and gives the right output as i do have the 3 files given above. 这完美地工作,并提供正确的输出,因为我有上面给出的3个文件。 However when I have the same code under my argument in the CLI
it fails. 但是,当我在CLI
使用相同的代码时,它会失败。 I do this 我这样做
#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)
I run this as 我这样做
python cli.py -f /Users/odin/Desktop/test_folder/*.log
This gives me the error: 这给了我错误:
cli.py: error: unrecognized arguments: /Users/odin/Desktop/test_folder/test2.log /Users/odin/Desktop/test_folder/test3.log
I dont understand why all files are being added to the argument at once when I am going through the list one by one. 当我逐一浏览列表时,我不明白为什么所有文件都被立即添加到参数中。
EDIT- 编辑-
nargs
was a step in the right direction but now this error shows up: 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'`
Here's what your script receives: 这是您的脚本收到的内容:
python cli.py -f file1 file2 file3 fileN
Where N is a total number of files matched by that pattern (Shell expands wildcards automatically). 其中N是该模式匹配的文件总数(Shell会自动扩展通配符)。 On the other hand, your file argument is configured to receive just one file/pattern, thus the simplest (and the best, in my opinion) solution is to add the nargs='+'
argument : 另一方面,你的文件参数被配置为只接收一个文件/模式,因此最简单的(在我看来最好的)解决方案是添加nargs='+'
参数 :
parser.add_argument('-f', '--file', type=str, help='...', nargs='+')
# code
for f in args.file:
print(f)
This will allow you to remove all glob
calls and if args.file
checks. 这将允许您删除所有glob
调用以及if args.file
检查。
Another option is to quote your command line argument: 另一个选择是引用命令行参数:
python cli.py -f '/Users/odin/Desktop/test_folder/*.log'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.