1997-04-02 13:47:11 +08:00
|
|
|
"""Filename globbing utility."""
|
1991-01-02 02:17:49 +08:00
|
|
|
|
1992-01-13 07:26:24 +08:00
|
|
|
import os
|
1991-01-02 02:17:49 +08:00
|
|
|
import fnmatch
|
1997-10-23 05:00:49 +08:00
|
|
|
import re
|
1991-01-02 02:17:49 +08:00
|
|
|
|
2001-01-21 07:34:12 +08:00
|
|
|
__all__ = ["glob"]
|
1992-01-13 07:26:24 +08:00
|
|
|
|
1991-01-02 02:17:49 +08:00
|
|
|
def glob(pathname):
|
2001-01-15 07:47:14 +08: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.exists(pathname):
|
|
|
|
return [pathname]
|
|
|
|
else:
|
|
|
|
return []
|
|
|
|
dirname, basename = os.path.split(pathname)
|
|
|
|
if has_magic(dirname):
|
|
|
|
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.exists(name):
|
|
|
|
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-02 02:17:49 +08:00
|
|
|
|
|
|
|
def glob1(dirname, pattern):
|
2001-01-15 07:47:14 +08:00
|
|
|
if not dirname: dirname = os.curdir
|
|
|
|
try:
|
|
|
|
names = os.listdir(dirname)
|
|
|
|
except os.error:
|
|
|
|
return []
|
|
|
|
result = []
|
|
|
|
for name in names:
|
|
|
|
if name[0] != '.' or pattern[0] == '.':
|
|
|
|
if fnmatch.fnmatch(name, pattern):
|
|
|
|
result.append(name)
|
|
|
|
return result
|
1991-01-02 02:17:49 +08:00
|
|
|
|
1992-01-13 07:32:11 +08:00
|
|
|
|
1997-10-23 05:00:49 +08:00
|
|
|
magic_check = re.compile('[*?[]')
|
1992-01-13 07:32:11 +08:00
|
|
|
|
1991-01-02 02:17:49 +08:00
|
|
|
def has_magic(s):
|
2001-01-15 07:47:14 +08:00
|
|
|
return magic_check.search(s) is not None
|