The sys Module
On to module details. As mentioned earlier, the
sys
and os
modules form the
core of much of Python’s system-related toolset. Let’s
now take a quick, interactive tour through some of the tools in these
two modules, before applying them in bigger examples.
Platforms and Versions
Like most modules, sys
includes both informational
names and functions that take action. For instance, its attributes
give us the name of the underlying operating system the platform code
is running on, the largest possible integer on this machine, and the
version number of the Python interpreter running our code:
C:\...\PP2E\System>python
>>>import sys
>>>sys.platform, sys.maxint, sys.version
('win32', 2147483647, '1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)]') >>> >>>if sys.platform[:3] == 'win': print 'hello windows'
... hello windows
If you have code that must act differently on different machines,
simply test the sys.platform
string as done here;
although most of Python is cross-platform, nonportable tools are
usually wrapped in if
tests like the one here. For
instance, we’ll see later that program launch and low-level
console interaction tools vary per platform today -- simply test
sys.platform
to pick the right tool for the
machine your script is running on.
The Module Search Path
The sys
module also lets us inspect the module
search path both interactively and within a Python program.
sys.path
is a list of strings representing the true search path in a running Python interpreter. ...
Get Programming Python, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.