04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 10 ■ BATTERIES INCLUDED 217<br />

Table 10-3. Some Important Functions and Variables in the os Module<br />

Function/Variable<br />

environ<br />

system(command)<br />

sep<br />

pathsep<br />

linesep<br />

urandom(n)<br />

Description<br />

Mapping with environment variables<br />

Executes an OS command in a subshell<br />

Separator used in paths<br />

Separator to separate paths<br />

Line separator ('\n', '\r', or '\r\n')<br />

Returns n bytes of cryptographically strong random data<br />

■Tip A useful function for traversing directories is os.walk. Check it out in the Python Library Reference.<br />

The mapping os.environ contains environment variables described earlier in this chapter.<br />

For example, to access the environment variable PYTHONPATH, you would use the expression<br />

os.environ['PYTHONPATH']. This mapping can also be used to change environment variables,<br />

although not all platforms support this.<br />

The function os.system is used to run external programs. There are other functions for<br />

executing external programs, including execv, which exits the Python interpreter, yielding<br />

control to the executed program, and popen, which creates a file-like connection to the program.<br />

For more information about these functions, consult the standard library documentation.<br />

■Tip The subprocess module is a recent addition to Python, which collects the functionality of the<br />

os.system, execv, and popen functions.<br />

The module variable os.sep is a separator used in pathnames. The standard separator in<br />

UNIX is '/', the standard in Windows is '\\' (the Python syntax for a single backslash), and in<br />

Mac OS, it is ':'. (On some platforms, os.altsep contains an alternate path separator, such as<br />

'/' in Windows.)<br />

You use os.pathsep when grouping several paths, as in PYTHONPATH. The pathsep is used to<br />

separate the pathnames: ':' in UNIX, ';' in Windows, and '::' in Mac OS.<br />

The module variable os.linesep is the line separator string used in text files. In UNIX this<br />

is a single newline character ('\n'), in Mac OS it’s a single carriage return character ('\r'), and<br />

in Windows it’s the combination of a carriage return and a newline ('\r\n').<br />

The urandom function uses a system-dependent source of “real” (or, at least, cryptographically<br />

strong) randomness. If your platform doesn’t support it, you’ll get a NotImplementedError.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!