1 """OS routines for Mac, DOS, NT, or Posix depending on what system we're on.
4 - all functions from posix, nt, dos, os2, mac, or ce, e.g. unlink, stat, etc.
5 - os.path is one of the modules posixpath, ntpath, macpath, or dospath
6 - os.name is 'posix', 'nt', 'dos', 'os2', 'mac', or 'ce'
7 - os.curdir is a string representing the current directory ('.' or ':')
8 - os.pardir is a string representing the parent directory ('..' or '::')
9 - os.sep is the (or a most common) pathname separator ('/' or ':' or '\\')
10 - os.altsep is the alternate pathname separator (None or '/')
11 - os.pathsep is the component separator used in $PATH etc
12 - os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
13 - os.defpath is the default search path for executables
15 Programs that import and use 'os' stand a better chance of being
16 portable between different platforms. Of course, they must then
17 only use functions that are defined by all platforms (e.g., unlink
18 and opendir), and leave all pathname manipulation to os.path
19 (e.g., split and join).
24 _names
= sys
.builtin_module_names
31 curdir
= '.'; pardir
= '..'; sep
= '/'; pathsep
= ':'
32 defpath
= ':/bin:/usr/bin'
35 from posix
import _exit
44 curdir
= '.'; pardir
= '..'; sep
= '\\'; pathsep
= ';'
49 exec "from nt import " + i
58 curdir
= '.'; pardir
= '..'; sep
= '\\'; pathsep
= ';'
71 curdir
= '.'; pardir
= '..'; sep
= '\\'; pathsep
= ';'
84 curdir
= ':'; pardir
= '::'; sep
= ':'; pathsep
= '\n'
97 curdir
= '.'; pardir
= '..'; sep
= '\\'; pathsep
= ';'
102 exec "from ce import " + i
105 # We can use the standard Windows path.
110 raise ImportError, 'no os specific module found'
114 sys
.modules
['os.path'] = path
116 # Super directory utilities.
117 # (Inspired by Eric Raymond; the doc strings are mostly his)
119 def makedirs(name
, mode
=0777):
120 """makedirs(path [, mode=0777]) -> None
122 Super-mkdir; create a leaf directory and all intermediate ones.
123 Works like mkdir, except that any intermediate path segment (not
124 just the rightmost) will be created if it does not exist. This is
128 head
, tail
= path
.split(name
)
129 if head
and tail
and not path
.exists(head
):
133 def removedirs(name
):
134 """removedirs(path) -> None
136 Super-rmdir; remove a leaf directory and empty all intermediate
137 ones. Works like rmdir except that, if the leaf directory is
138 successfully removed, directories corresponding to rightmost path
139 segments will be pruned way until either the whole path is
140 consumed or an error occurs. Errors during this latter phase are
141 ignored -- they generally mean that a directory was not empty.
145 head
, tail
= path
.split(name
)
151 head
, tail
= path
.split(head
)
153 def renames(old
, new
):
154 """renames(old, new) -> None
156 Super-rename; create directories as necessary and delete any left
157 empty. Works like rename, except creation of any intermediate
158 directories needed to make the new pathname good is attempted
159 first. After the rename, directories corresponding to rightmost
160 path segments of the old name will be pruned way until either the
161 whole path is consumed or a nonempty directory is found.
163 Note: this function can fail with the new directory structure made
164 if you lack permissions needed to unlink the leaf directory or
168 head
, tail
= path
.split(new
)
169 if head
and tail
and not path
.exists(head
):
172 head
, tail
= path
.split(old
)
179 # Make sure os.environ exists, at least
185 def execl(file, *args
):
188 def execle(file, *args
):
190 execve(file, args
[:-1], env
)
192 def execlp(file, *args
):
195 def execlpe(file, *args
):
197 execvpe(file, args
[:-1], env
)
199 def execvp(file, args
):
202 def execvpe(file, args
, env
):
203 _execvpe(file, args
, env
)
206 def _execvpe(file, args
, env
=None):
209 argrest
= (args
, env
)
215 head
, tail
= path
.split(file)
217 apply(func
, (file,) + argrest
)
219 if env
.has_key('PATH'):
220 envpath
= env
['PATH']
224 PATH
= string
.splitfields(envpath
, pathsep
)
227 # Exec a file that is guaranteed not to exist
228 try: execv(tempfile
.mktemp(), ())
229 except error
, _notfound
: pass
230 exc
, arg
= error
, _notfound
232 fullname
= path
.join(dir, file)
234 apply(func
, (fullname
,) + argrest
)
235 except error
, (errno
, msg
):
237 exc
, arg
= error
, (errno
, msg
)
240 # Change environ to automatically call putenv() if it exists
242 # This will fail if there's no putenv
249 if name
in ('os2', 'nt', 'dos'): # Where Env Var Names Must Be UPPERCASE
250 # But we store them as upper case
252 class _Environ(UserDict
.UserDict
):
253 def __init__(self
, environ
):
254 UserDict
.UserDict
.__init
__(self
)
257 for k
, v
in environ
.items():
259 def __setitem__(self
, key
, item
):
261 key
= string
.upper(key
)
262 self
.data
[key
] = item
263 def __getitem__(self
, key
):
264 return self
.data
[string
.upper(key
)]
265 def has_key(self
, key
):
266 return self
.data
.has_key(string
.upper(key
))
268 else: # Where Env Var Names Can Be Mixed Case
269 class _Environ(UserDict
.UserDict
):
270 def __init__(self
, environ
):
271 UserDict
.UserDict
.__init
__(self
)
273 def __setitem__(self
, key
, item
):
275 self
.data
[key
] = item
277 environ
= _Environ(environ
)
279 def getenv(key
, default
=None):
280 """Get an environment variable, return None if it doesn't exist.
282 The optional second argument can specify an alternative default."""
283 return environ
.get(key
, default
)
292 # Supply spawn*() (probably only for Unix)
293 if _exists("fork") and not _exists("spawnv") and _exists("execv"):
296 P_NOWAIT
= P_NOWAITO
= 1
298 # XXX Should we support P_DETACH? I suppose it could fork()**2
299 # and close the std I/O streams. Also, P_OVERLAY is the same
302 def _spawnvef(mode
, file, args
, env
, func
):
303 # Internal helper; func is the exec*() function to use
311 func(file, args
, env
)
317 return pid
# Caller is responsible for waiting!
319 wpid
, sts
= waitpid(pid
, 0)
322 elif WIFSIGNALED(sts
):
323 return -WTERMSIG(sts
)
325 return WEXITSTATUS(sts
)
327 raise error
, "Not stopped, signaled or exited???"
329 def spawnv(mode
, file, args
):
330 return _spawnvef(mode
, file, args
, None, execv
)
332 def spawnve(mode
, file, args
, env
):
333 return _spawnvef(mode
, file, args
, env
, execve
)
335 # Note: spawnvp[e] is't currently supported on Windows
337 def spawnvp(mode
, file, args
):
338 return _spawnvef(mode
, file, args
, None, execvp
)
340 def spawnvpe(mode
, file, args
, env
):
341 return _spawnvef(mode
, file, args
, env
, execvpe
)
343 if _exists("spawnv"):
344 # These aren't supplied by the basic Windows code
345 # but can be easily implemented in Python
347 def spawnl(mode
, file, *args
):
348 return spawnv(mode
, file, args
)
350 def spawnle(mode
, file, *args
):
352 return spawnve(mode
, file, args
[:-1], env
)
354 if _exists("spawnvp"):
355 # At the moment, Windows doesn't implement spawnvp[e],
356 # so it won't have spawnlp[e] either.
357 def spawnlp(mode
, file, *args
):
358 return spawnvp(mode
, file, args
)
360 def spawnlpe(mode
, file, *args
):
362 return spawnvpe(mode
, file, args
[:-1], env
)