glob.py 1.17 KB
Newer Older
Guido van Rossum's avatar
Guido van Rossum committed
1
"""Filename globbing utility."""
Guido van Rossum's avatar
Guido van Rossum committed
2

Guido van Rossum's avatar
Guido van Rossum committed
3
import os
Guido van Rossum's avatar
Guido van Rossum committed
4
import fnmatch
5
import re
Guido van Rossum's avatar
Guido van Rossum committed
6

Guido van Rossum's avatar
Guido van Rossum committed
7

Guido van Rossum's avatar
Guido van Rossum committed
8
def glob(pathname):
Guido van Rossum's avatar
Guido van Rossum committed
9 10 11 12 13
	"""Return a list of paths matching a pathname pattern.

	The pattern may contain simple shell-style wildcards a la fnmatch.

	"""
14 15 16 17 18
	if not has_magic(pathname):
		if os.path.exists(pathname):
			return [pathname]
		else:
			return []
Guido van Rossum's avatar
Guido van Rossum committed
19
	dirname, basename = os.path.split(pathname)
Guido van Rossum's avatar
Guido van Rossum committed
20 21 22 23 24 25 26
	if has_magic(dirname):
		list = glob(dirname)
	else:
		list = [dirname]
	if not has_magic(basename):
		result = []
		for dirname in list:
Guido van Rossum's avatar
Guido van Rossum committed
27 28 29
			if basename or os.path.isdir(dirname):
				name = os.path.join(dirname, basename)
				if os.path.exists(name):
Guido van Rossum's avatar
Guido van Rossum committed
30 31 32 33 34 35
					result.append(name)
	else:
		result = []
		for dirname in list:
			sublist = glob1(dirname, basename)
			for name in sublist:
Guido van Rossum's avatar
Guido van Rossum committed
36
				result.append(os.path.join(dirname, name))
Guido van Rossum's avatar
Guido van Rossum committed
37 38 39
	return result

def glob1(dirname, pattern):
Guido van Rossum's avatar
Guido van Rossum committed
40
	if not dirname: dirname = os.curdir
Guido van Rossum's avatar
Guido van Rossum committed
41
	try:
Guido van Rossum's avatar
Guido van Rossum committed
42 43
		names = os.listdir(dirname)
	except os.error:
Guido van Rossum's avatar
Guido van Rossum committed
44 45 46
		return []
	result = []
	for name in names:
47 48 49
		if name[0] != '.' or pattern[0] == '.':
			if fnmatch.fnmatch(name, pattern):
				result.append(name)
Guido van Rossum's avatar
Guido van Rossum committed
50 51
	return result

52

53
magic_check = re.compile('[*?[]')
54

Guido van Rossum's avatar
Guido van Rossum committed
55
def has_magic(s):
56
	return magic_check.search(s) is not None