cpython/Lib/glob.py

57 lines
1.4 KiB
Python
Raw Normal View History

1997-04-02 01:47:11 -04:00
"""Filename globbing utility."""
1991-01-01 14:17:49 -04:00
1992-01-12 19:26:24 -04:00
import os
1991-01-01 14:17:49 -04:00
import fnmatch
import re
1991-01-01 14:17:49 -04:00
2001-01-20 19:34:12 -04:00
__all__ = ["glob"]
1992-01-12 19:26:24 -04:00
1991-01-01 14:17:49 -04:00
def glob(pathname):
2001-01-14 19:47:14 -04:00
"""Return a list of paths matching a pathname pattern.
The pattern may contain simple shell-style wildcards a la fnmatch.
"""
if not has_magic(pathname):
if os.path.lexists(pathname):
2001-01-14 19:47:14 -04:00
return [pathname]
else:
return []
dirname, basename = os.path.split(pathname)
if not dirname:
return glob1(os.curdir, basename)
elif has_magic(dirname):
2001-01-14 19:47:14 -04:00
list = glob(dirname)
else:
list = [dirname]
if not has_magic(basename):
result = []
for dirname in list:
if basename or os.path.isdir(dirname):
name = os.path.join(dirname, basename)
if os.path.lexists(name):
2001-01-14 19:47:14 -04:00
result.append(name)
else:
result = []
for dirname in list:
sublist = glob1(dirname, basename)
for name in sublist:
result.append(os.path.join(dirname, name))
return result
1991-01-01 14:17:49 -04:00
def glob1(dirname, pattern):
2001-01-14 19:47:14 -04:00
if not dirname: dirname = os.curdir
try:
names = os.listdir(dirname)
except os.error:
return []
if pattern[0]!='.':
names=filter(lambda x: x[0]!='.',names)
return fnmatch.filter(names,pattern)
1991-01-01 14:17:49 -04:00
magic_check = re.compile('[*?[]')
1991-01-01 14:17:49 -04:00
def has_magic(s):
2001-01-14 19:47:14 -04:00
return magic_check.search(s) is not None