Introducing 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 tool set. Let’s now take a quick, interactive tour
through some of the tools in these two modules before applying them in
bigger examples. We’ll start with sys
, the smaller of the two; remember that
to see a full list of all the attributes in sys
, you need to pass it to the dir
function (or see where we did so earlier
in this chapter).
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 on which the platform code
is running, the largest possible integer on this machine, and the
version number of the Python interpreter running our code:
C:\...\PP3E\System>python
>>>import sys
>>>sys.platform, sys.maxint, sys.version
('win32', 2147483647, '2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 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 today’s program launch and
low-level console interaction tools vary per platform—simply test
sys.platform
to pick the right tool for the machine on which your script is running. ...
Get Programming Python, 3rd 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.