blob: 8a70f0eb3a49a7f7aa3be0727cbbbfe829854625 [file] [log] [blame]
Guido van Rossum65a96201991-01-01 18:17:49 +00001# Module 'glob' -- filename globbing.
2
3import posix
4import path
5import fnmatch
6
7def glob(pathname):
8 if not has_magic(pathname): return [pathname]
9 dirname, basename = path.split(pathname)
10 if dirname[-1:] = '/' and dirname <> '/':
11 dirname = dirname[:-1]
12 if has_magic(dirname):
13 list = glob(dirname)
14 else:
15 list = [dirname]
16 if not has_magic(basename):
17 result = []
18 for dirname in list:
19 if basename or path.isdir(dirname):
20 name = path.cat(dirname, basename)
21 if path.exists(name):
22 result.append(name)
23 else:
24 result = []
25 for dirname in list:
26 sublist = glob1(dirname, basename)
27 for name in sublist:
28 result.append(path.cat(dirname, name))
29 return result
30
31def glob1(dirname, pattern):
32 if not dirname: dirname = '.'
33 try:
34 names = posix.listdir(dirname)
35 except posix.error:
36 return []
37 result = []
38 for name in names:
39 if name[0] <> '.' or pattern[0] = '.':
40 if fnmatch.fnmatch(name, pattern): result.append(name)
41 return result
42
43def has_magic(s):
44 return '*' in s or '?' in s or '[' in s