blob: e314cb3abfd9108a1f40b951db421615addebb14 [file] [log] [blame]
Guido van Rossumc6360141990-10-13 19:23:40 +00001# Module 'path' -- common operations on POSIX pathnames
2
3import posix
4
5
6# Intelligent pathname concatenation.
7# Inserts a '/' unless the first part is empty or already ends in '/'.
8# Ignores the first part altogether if the second part is absolute
9# (begins with '/').
10#
11def cat(a, b):
12 if b[:1] = '/': return b
13 if a = '' or a[-1:] = '/': return a + b
14 return a + '/' + b
15
16
17# Split a path in head (empty or ending in '/') and tail (no '/').
18# The tail will be empty if the path ends in '/'.
19#
20def split(p):
21 head, tail = '', ''
22 for c in p:
23 tail = tail + c
24 if c = '/':
25 head, tail = head + tail, ''
26 return head, tail
27
28
29# Return the tail (basename) part of a path.
30#
31def basename(p):
32 return split(p)[1]
33
34
35# Return the longest prefix of all list elements.
36#
37def commonprefix(m):
38 if not m: return ''
39 prefix = m[0]
40 for item in m:
41 for i in range(len(prefix)):
42 if prefix[:i+1] <> item[:i+1]:
43 prefix = prefix[:i]
44 if i = 0: return ''
45 break
46 return prefix
47
48
49# Does a file/directory exist?
50#
51def exists(path):
52 try:
53 st = posix.stat(path)
54 except posix.error:
55 return 0
56 return 1
57
58
59# Is a path a posix directory?
60#
61def isdir(path):
62 try:
63 st = posix.stat(path)
64 except posix.error:
65 return 0
66 return st[0] / 4096 = 4 # S_IFDIR
67
68
69# Is a path a symbolic link?
70# This will always return false on systems where posix.lstat doesn't exist.
71#
72def islink(path):
73 try:
74 st = posix.lstat(path)
75 except (posix.error, NameError):
76 return 0
77 return st[0] / 4096 = 10 # S_IFLNK
78
79
80_mounts = []
81
82def _getmounts():
83 import commands, string
84 mounts = []
85 data = commands.getoutput('/etc/mount')
86 lines = string.splitfields(data, '\n')
87 for line in lines:
88 words = string.split(line)
89 if len(words) >= 3 and words[1] = 'on':
90 mounts.append(words[2])
91 return mounts
92
93
94# Is a path a mount point?
95# This only works for normalized, absolute paths,
96# and only if the mount table as printed by /etc/mount is correct.
97# Sorry.
98#
99def ismount(path):
100 if not _mounts:
101 _mounts[:] = _getmounts()
102 return path in _mounts
103
104
105# Directory tree walk.
106# For each directory under top (including top itself),
107# func(arg, dirname, filenames) is called, where dirname
108# is the name of the directory and filenames is the list of
109# files (and subdirectories etc.) in the directory.
110# func may modify the filenames list, to implement a filter,
111# or to impose a different order of visiting.
112#
113def walk(top, func, arg):
114 try:
115 names = posix.listdir(top)
116 except posix.error:
117 return
118 func(arg, top, names)
119 exceptions = ('.', '..')
120 for name in names:
121 if name not in exceptions:
122 name = cat(top, name)
123 if isdir(name):
124 walk(name, func, arg)