1 """
2 A collection of filesystem related commands.
3 """
4 import os, re
5
6 -def find( path,
7 include_dirs = True, include_files = True,
8 name_regex = None, not_name_regex = None,
9 whole_name_regex = None, not_whole_name_regex = None,
10 exclude_root = False ):
11 """
12 Creates an iterator of files matching a variety of conditions.
13
14 @param path: which path to iterate
15 @param include_dirs: include directories in output
16 @param include_files: include files in output
17 @param name_regex: optional regex string compared against basename of file
18 @param not_name_regex: if specificed only produces names not matching this regex
19 @param whole_name_regex: like name_regex but applies to whole path, not just basename
20 @param not_whole_name_regex: like not_name_regex but applies to whole path
21 @param exclude_root: do not include the intput 'path' itself in the output
22 @return: a generator for the matched files
23 """
24 def maybe_regex(arg):
25 return re.compile(arg) if arg != None else None
26 c_name_regex = maybe_regex(name_regex)
27 c_not_name_regex = maybe_regex(not_name_regex)
28 c_whole_name_regex = maybe_regex(whole_name_regex)
29 c_not_whole_name_regex = maybe_regex(not_whole_name_regex)
30
31 def check_name(name, whole_name):
32 if c_name_regex != None and not c_name_regex.match( name ):
33 return False
34 if c_not_name_regex != None and c_not_name_regex.match( name ):
35 return False
36 if c_whole_name_regex != None and not c_whole_name_regex.match( whole_name ):
37 return False
38 if c_not_whole_name_regex != None and c_not_whole_name_regex.match( whole_name ):
39 return False
40 return True
41
42 walker = os.walk( path, followlinks = True )
43 def filter_func():
44 for root, dirs, files in walker:
45 if root == path and exclude_root:
46 pass
47 elif include_dirs and check_name( os.path.basename(root), root ):
48 yield root
49
50 if include_files:
51 for item in files:
52 whole = os.path.join( root, item )
53 if check_name( item, whole ):
54 yield whole
55
56 return filter_func()
57