Changing sys.path directly like this is an alternative to setting your PYTHONPATH shell
variable, but not a very permanent one. Changes to sys.path are retained only until the
Python process ends, and they must be remade every time you start a new Python
program or session. However, some types of programs (e.g., scripts that run on a web
server) may not be able to depend on PYTHONPATH settings; such scripts can instead
configure sys.path on startup to include all the directories from which they will need
to import modules. For a more concrete use case, see Example 1-34 in the prior
chapter—there we had to tweak the search path dynamically this way, because the web
server violated our import path assumptions.
Windows Directory Paths
Notice the use of a raw string literal in the sys.path configuration code: because back-
slashes normally introduce escape code sequences in Python strings, Windows users
should be sure to either double up on backslashes when using them in DOS directory
path strings (e.g., in "C:\\dir", \\ is an escape sequence that really means \), or use
raw string constants to retain backslashes literally (e.g., r"C:\dir").
If you inspect directory paths on Windows (as in the sys.path interaction listing), Py-
thon prints double \\ to mean a single \. Technically, you can get away with a
single \ in a string if it is followed by a character Python does not recognize as the rest
of an escape sequence, but doubles and raw strings are usually easier than memorizing
escape code tables.
Also note that most Python library calls accept either forward (/) or backward (\)
slashes as directory path separators, regardless of the underlying platform. That is, /
usually works on Windows too and aids in making scripts portable to Unix. Tools in
the os and os.path modules, described later in this chapter, further aid in script path
portability.
The Loaded Modules Table
The sys module also contains hooks into the interpreter; sys.modules, for example, is
a dictionary containing one name:module entry for every module imported in your
Python session or program (really, in the calling Python process):
>>> sys.modules
{'reprlib': <module 'reprlib' from 'c:\python31\lib\reprlib.py'>, ...more deleted...
>>> list(sys.modules.keys())
['reprlib', 'heapq', '__future__', 'sre_compile', '_collections', 'locale', '_sre',
'functools', 'encodings', 'site', 'operator', 'io', '__main__', ...more deleted... ]
>>> sys
<module 'sys' (built-in)>
>>> sys.modules['sys']
<module 'sys' (built-in)>
88 | Chapter 2: System Tools