|
Note
Currently, functions available in Unix only are not listed in this document, they will be added later.
>>> name
'nt'
Note
This mapping is captured the first time the os module is imported, typically during Python startup as part of processing site.py. Changes to the environment made after this time are not reflected in os.environ, except for changes made by modifying os.environ directly.
>>> environ["home"]
'e:\\cygwin\\home\\ak'
>>> environ["user"]
'ak'
>>> getcwd()
'e:\\Home\\Projects\\py-by-example\\test'
>>> chdir('..')
>>> getcwd()
'e:\\Home\\Projects\\py-by-example'
getpid() # 484
>>> getenv('home')
'e:\\cygwin\\home\\ak'
putenv('home', 'e:\\cygwin\\home\\ak\\newhome')
>>> strerror(1)
'Operation not permitted'
>>> strerror(0)
'No error'
>>> strerror(2)
'No such file or directory'
>>> strerror(3)
'No such process'
>>> fp = open('test', 'w')
>>> d = fp.fileno()
>>> d
3
>>> os.fdopen(d)
<open file '<fdopen>', mode 'r' at 0x0098A530>
>>> access('.', F_OK) # read access
True
>>> access('.', X_OK) # execute access
True
>>> access('.', X_OK | W_OK) # execute and write
True
chmod("myfile.txt", stat.S_IREAD) # set read-only flag
>>> listdir('.')
['.bashrc', '.bash_history', '.bash_profile', '.build', '.inputrc',
'.static', ' .templates', 'conf.py', 'home.lnk', 'index.rst', 'km.lnk',
'projects.lnk', 'test.txt', 'test2.txt', '_viminfo']
mkdir("mydir")
makedirs("firstdir/seconddir/mydir")
remove("my_file.txt")
removedirs("foo/bar/baz")
# first try to remove dir baz, if successful, remove bar, then foo
rename("myfile.txt", "newfile.txt")
Note
This function can fail with the new directory structure made if you lack permissions needed to remove the leaf directory or file.
renames("myfile.txt", "mydir/newfile.txt")
rmdir("mydir")
Changed in version 2.5: Added st_gen and st_birthtime.
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
(33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732,
1105022732)
# tuple items in order are:
# st_mode (protection bits), st_ino (inode number), st_dev (device),
# st_nlink (number of hard links), st_uid (user id of owner),
# st_gid (group id of owner), st_size (size of file, in bytes),
# st_atime (time of most recent access), st_mtime (time of most recent
# content modification), st_ctime (platform dependent; time of most
# recent metadata change on Unix, or the time of creation on Windows)
statinfo.st_size
# 926L
utime("myfile.txt", None) # similar to Unix 'touch' command
Changed in version 2.6: The followlinks parameter.
# For this example we have dir structure:
# somedir
# dir1
# dir2
# dir3
# file.txt
>>> for (dirpath, dirnames, filenames) in walk('somedir'):
... print dirpath, dirnames, filenames
somedir ['dir1', 'dir2'] ['test.txt']
somedir\dir1 [] []
somedir\dir2 ['dir3'] []
somedir\dir2\dir3 [] ['file.txt']
This example displays the number of bytes taken by non-directory files in each directory under the starting directory, except that it doesn’t look under any CVS subdirectory:
# example taken from LibRef
from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/email'):
print root, "consumes",
print sum(getsize(join(root, name)) for name in files),
print "bytes in", len(files), "non-directory files"
if 'CVS' in dirs:
dirs.remove('CVS') # don't visit CVS directories
In the next example, walking the tree bottom-up is essential: rmdir() doesn’t allow deleting a directory before the directory is empty:
# example taken from LibRef
# Delete everything reachable from the directory named in "top",
# assuming there are no symbolic links.
# CAUTION: This is dangerous! For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files in os.walk(top, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
Example in windows command line interpreter:
>>> abort()
This application has requested the Runtime to terminate it in an
unusual way.
Please contact the application's support team for more information.
>>> execl("e:\python26\python", "python", "-V")
ak@ak-65e460dcbdaf ~/projects/py-by-example/test
$ Python 2.6.1
Note that running python interpreter shell was replaced by given command, which printed out version and exited, dropping us back to shell, in this case Cygwin.
The following example is the same but with environment provided by the last arg:
>>> execle("e:\python26\python", "python", "-V", {"HOME":"e:\\"})
ak@ak-65e460dcbdaf ~/projects/py-by-example/test
$ Python 2.6.1
>>> execlp("python", "python", "-V")
ak@ak-65e460dcbdaf ~/projects/py-by-example/test
$ Python 2.6.1
>>> execv("python", ("python", "-V"))
ak@ak-65e460dcbdaf ~/projects/py-by-example/test
$ Python 2.6.1
Of the exec* functions, the ones that end with an ‘e’ require a dictionary of environment variables, those ending in ‘p’ use PATH variable from environment, the ones ending in ‘l’ take parameters from exec* function and call the command; the ones ending in ‘v’ take parameters from the tuple as shown.
startfile("test.txt")
# test.txt will be opened by associated text editor
>>> system("ls -l")
total 351
-rw-r--r-- 1 ak None 6344 Feb 24 03:32 array-module.rst
...
>>> times()
(0.03125, 0.125, 0.0, 0.0, 0.0)
# user time, system time, children's user time, children's system time,
# and elapsed real time since a fixed point in the past
# (on Windows only first two items are filled)
>>> urandom(10)
'\x8a"\xdc\xdb.\xec\x822k\x8f'