cpython/Lib/glob.py

75 lines
2.0 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
__all__ = ["glob", "iglob"]
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.
"""
return list(iglob(pathname))
def iglob(pathname):
"""Return a list of paths matching a pathname pattern.
The pattern may contain simple shell-style wildcards a la fnmatch.
2001-01-14 19:47:14 -04:00
"""
if not has_magic(pathname):
if os.path.lexists(pathname):
yield pathname
return
2001-01-14 19:47:14 -04:00
dirname, basename = os.path.split(pathname)
if not dirname:
for name in glob1(os.curdir, basename):
yield name
return
if has_magic(dirname):
dirs = iglob(dirname)
2001-01-14 19:47:14 -04:00
else:
dirs = [dirname]
if has_magic(basename):
glob_in_dir = glob1
2001-01-14 19:47:14 -04:00
else:
glob_in_dir = glob0
for dirname in dirs:
for name in glob_in_dir(dirname, basename):
yield os.path.join(dirname, name)
# These 2 helper functions non-recursively glob inside a literal directory.
# They return a list of basenames. `glob1` accepts a pattern while `glob0`
# takes a literal basename (so it only has to check for its existence).
1991-01-01 14:17:49 -04:00
def glob1(dirname, pattern):
if not dirname:
dirname = os.curdir
2001-01-14 19:47:14 -04:00
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
def glob0(dirname, basename):
if basename == '':
# `os.path.split()` returns an empty basename for paths ending with a
# directory separator. 'q*x/' should match only directories.
if os.path.isdir(dirname):
return [basename]
else:
if os.path.lexists(os.path.join(dirname, basename)):
return [basename]
return []
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