cpython/Lib/glob.py

46 lines
1.0 KiB
Python
Raw Normal View History

1991-01-01 14:17:49 -04:00
# Module 'glob' -- filename globbing.
import posix
import path
import fnmatch
def glob(pathname):
if not has_magic(pathname): return [pathname]
dirname, basename = path.split(pathname)
1992-01-01 15:35:13 -04:00
if dirname[-1:] == '/' and dirname <> '/':
1991-01-01 14:17:49 -04:00
dirname = dirname[:-1]
if has_magic(dirname):
list = glob(dirname)
else:
list = [dirname]
if not has_magic(basename):
result = []
for dirname in list:
if basename or path.isdir(dirname):
1991-08-16 10:28:23 -03:00
name = path.join(dirname, basename)
1991-01-01 14:17:49 -04:00
if path.exists(name):
result.append(name)
else:
result = []
for dirname in list:
sublist = glob1(dirname, basename)
for name in sublist:
1991-08-16 10:28:23 -03:00
result.append(path.join(dirname, name))
1991-01-01 14:17:49 -04:00
return result
def glob1(dirname, pattern):
if not dirname: dirname = '.'
try:
names = posix.listdir(dirname)
except posix.error:
return []
1992-01-01 15:35:13 -04:00
names.sort()
1991-01-01 14:17:49 -04:00
result = []
for name in names:
1992-01-01 15:35:13 -04:00
if name[0] <> '.' or pattern[0] == '.':
1991-01-01 14:17:49 -04:00
if fnmatch.fnmatch(name, pattern): result.append(name)
return result
def has_magic(s):
return '*' in s or '?' in s or '[' in s