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
)
130 head
, tail
= path
.split(head
)
131 if head
and tail
and not path
.exists(head
):
135 def removedirs(name
):
136 """removedirs(path) -> None
138 Super-rmdir; remove a leaf directory and empty all intermediate
139 ones. Works like rmdir except that, if the leaf directory is
140 successfully removed, directories corresponding to rightmost path
141 segments will be pruned way until either the whole path is
142 consumed or an error occurs. Errors during this latter phase are
143 ignored -- they generally mean that a directory was not empty.
147 head
, tail
= path
.split(name
)
149 head
, tail
= path
.split(head
)
155 head
, tail
= path
.split(head
)
157 def renames(old
, new
):
158 """renames(old, new) -> None
160 Super-rename; create directories as necessary and delete any left
161 empty. Works like rename, except creation of any intermediate
162 directories needed to make the new pathname good is attempted
163 first. After the rename, directories corresponding to rightmost
164 path segments of the old name will be pruned way until either the
165 whole path is consumed or a nonempty directory is found.
167 Note: this function can fail with the new directory structure made
168 if you lack permissions needed to unlink the leaf directory or
172 head
, tail
= path
.split(new
)
173 if head
and tail
and not path
.exists(head
):
176 head
, tail
= path
.split(old
)
183 # Make sure os.environ exists, at least
189 def execl(file, *args
):
190 """execl(file, *args)
192 Execute the executable file with argument list args, replacing the
196 def execle(file, *args
):
197 """execle(file, *args, env)
199 Execute the executable file with argument list args and
200 environment env, replacing the current process. """
202 execve(file, args
[:-1], env
)
204 def execlp(file, *args
):
205 """execlp(file, *args)
207 Execute the executable file (which is searched for along $PATH)
208 with argument list args, replacing the current process. """
211 def execlpe(file, *args
):
212 """execlpe(file, *args, env)
214 Execute the executable file (which is searched for along $PATH)
215 with argument list args and environment env, replacing the current
218 execvpe(file, args
[:-1], env
)
220 def execvp(file, args
):
223 Execute the executable file (which is searched for along $PATH)
224 with argument list args, replacing the current process.
225 args may be a list or tuple of strings. """
228 def execvpe(file, args
, env
):
229 """execv(file, args, env)
231 Execute the executable file (which is searched for along $PATH)
232 with argument list args and environment env , replacing the
234 args may be a list or tuple of strings. """
235 _execvpe(file, args
, env
)
238 def _execvpe(file, args
, env
=None):
241 argrest
= (args
, env
)
247 head
, tail
= path
.split(file)
249 apply(func
, (file,) + argrest
)
251 if env
.has_key('PATH'):
252 envpath
= env
['PATH']
255 PATH
= envpath
.split(pathsep
)
258 # Exec a file that is guaranteed not to exist
259 try: execv(tempfile
.mktemp(), ('blah',))
260 except error
, _notfound
: pass
261 exc
, arg
= error
, _notfound
263 fullname
= path
.join(dir, file)
265 apply(func
, (fullname
,) + argrest
)
266 except error
, (errno
, msg
):
268 exc
, arg
= error
, (errno
, msg
)
271 # Change environ to automatically call putenv() if it exists
273 # This will fail if there's no putenv
280 if name
in ('os2', 'nt', 'dos'): # Where Env Var Names Must Be UPPERCASE
281 # But we store them as upper case
282 class _Environ(UserDict
.UserDict
):
283 def __init__(self
, environ
):
284 UserDict
.UserDict
.__init
__(self
)
286 for k
, v
in environ
.items():
288 def __setitem__(self
, key
, item
):
290 self
.data
[key
.upper()] = item
291 def __getitem__(self
, key
):
292 return self
.data
[key
.upper()]
293 def __delitem__(self
, key
):
294 del self
.data
[key
.upper()]
295 def has_key(self
, key
):
296 return self
.data
.has_key(key
.upper())
297 def get(self
, key
, failobj
=None):
298 return self
.data
.get(key
.upper(), failobj
)
299 def update(self
, dict):
300 for k
, v
in dict.items():
303 else: # Where Env Var Names Can Be Mixed Case
304 class _Environ(UserDict
.UserDict
):
305 def __init__(self
, environ
):
306 UserDict
.UserDict
.__init
__(self
)
308 def __setitem__(self
, key
, item
):
310 self
.data
[key
] = item
311 def update(self
, dict):
312 for k
, v
in dict.items():
315 environ
= _Environ(environ
)
317 def getenv(key
, default
=None):
318 """Get an environment variable, return None if it doesn't exist.
320 The optional second argument can specify an alternative default."""
321 return environ
.get(key
, default
)
330 # Supply spawn*() (probably only for Unix)
331 if _exists("fork") and not _exists("spawnv") and _exists("execv"):
334 P_NOWAIT
= P_NOWAITO
= 1
336 # XXX Should we support P_DETACH? I suppose it could fork()**2
337 # and close the std I/O streams. Also, P_OVERLAY is the same
340 def _spawnvef(mode
, file, args
, env
, func
):
341 # Internal helper; func is the exec*() function to use
349 func(file, args
, env
)
355 return pid
# Caller is responsible for waiting!
357 wpid
, sts
= waitpid(pid
, 0)
360 elif WIFSIGNALED(sts
):
361 return -WTERMSIG(sts
)
363 return WEXITSTATUS(sts
)
365 raise error
, "Not stopped, signaled or exited???"
367 def spawnv(mode
, file, args
):
368 """spawnv(mode, file, args) -> integer
370 Execute file with arguments from args in a subprocess.
371 If mode == P_NOWAIT return the pid of the process.
372 If mode == P_WAIT return the process's exit code if it exits normally;
373 otherwise return -SIG, where SIG is the signal that killed it. """
374 return _spawnvef(mode
, file, args
, None, execv
)
376 def spawnve(mode
, file, args
, env
):
377 """spawnve(mode, file, args, env) -> integer
379 Execute file with arguments from args in a subprocess with the
380 specified environment.
381 If mode == P_NOWAIT return the pid of the process.
382 If mode == P_WAIT return the process's exit code if it exits normally;
383 otherwise return -SIG, where SIG is the signal that killed it. """
384 return _spawnvef(mode
, file, args
, env
, execve
)
386 # Note: spawnvp[e] is't currently supported on Windows
388 def spawnvp(mode
, file, args
):
389 """spawnvp(mode, file, args) -> integer
391 Execute file (which is looked for along $PATH) with arguments from
392 args in a subprocess.
393 If mode == P_NOWAIT return the pid of the process.
394 If mode == P_WAIT return the process's exit code if it exits normally;
395 otherwise return -SIG, where SIG is the signal that killed it. """
396 return _spawnvef(mode
, file, args
, None, execvp
)
398 def spawnvpe(mode
, file, args
, env
):
399 """spawnvpe(mode, file, args, env) -> integer
401 Execute file (which is looked for along $PATH) with arguments from
402 args in a subprocess with the supplied environment.
403 If mode == P_NOWAIT return the pid of the process.
404 If mode == P_WAIT return the process's exit code if it exits normally;
405 otherwise return -SIG, where SIG is the signal that killed it. """
406 return _spawnvef(mode
, file, args
, env
, execvpe
)
408 if _exists("spawnv"):
409 # These aren't supplied by the basic Windows code
410 # but can be easily implemented in Python
412 def spawnl(mode
, file, *args
):
413 """spawnl(mode, file, *args) -> integer
415 Execute file with arguments from args in a subprocess.
416 If mode == P_NOWAIT return the pid of the process.
417 If mode == P_WAIT return the process's exit code if it exits normally;
418 otherwise return -SIG, where SIG is the signal that killed it. """
419 return spawnv(mode
, file, args
)
421 def spawnle(mode
, file, *args
):
422 """spawnle(mode, file, *args, env) -> integer
424 Execute file with arguments from args in a subprocess with the
425 supplied environment.
426 If mode == P_NOWAIT return the pid of the process.
427 If mode == P_WAIT return the process's exit code if it exits normally;
428 otherwise return -SIG, where SIG is the signal that killed it. """
430 return spawnve(mode
, file, args
[:-1], env
)
432 if _exists("spawnvp"):
433 # At the moment, Windows doesn't implement spawnvp[e],
434 # so it won't have spawnlp[e] either.
435 def spawnlp(mode
, file, *args
):
436 """spawnlp(mode, file, *args, env) -> integer
438 Execute file (which is looked for along $PATH) with arguments from
439 args in a subprocess with the supplied environment.
440 If mode == P_NOWAIT return the pid of the process.
441 If mode == P_WAIT return the process's exit code if it exits normally;
442 otherwise return -SIG, where SIG is the signal that killed it. """
443 return spawnvp(mode
, file, args
)
445 def spawnlpe(mode
, file, *args
):
446 """spawnlpe(mode, file, *args, env) -> integer
448 Execute file (which is looked for along $PATH) with arguments from
449 args in a subprocess with the supplied environment.
450 If mode == P_NOWAIT return the pid of the process.
451 If mode == P_WAIT return the process's exit code if it exits normally;
452 otherwise return -SIG, where SIG is the signal that killed it. """
454 return spawnvpe(mode
, file, args
[:-1], env
)