Last Updated:

Python sys module

 

The sys module provides a number of functions and variables that you can use to manage different parts of the Python runtime.

Working with Command-Line Arguments

The argv list contains the arguments that were passed to the script when the interpreter was started, as shown in the example. The first element contains the name of the script itself.

Example#1. Using the sys Module to Get Script Arguments

File: sys-argv-example-1.py
importsys

print"script name", sys.argv[0]

iflen(sys.argv) > 1:
print"yes", len(sys.argv)-1, "arguments:"
forargvsys.argv[1:]:
printargelse
:
print "there are no arguments!"

the name of the script sys-argv-example-1.py
there are no arguments!

If you are reading a script with standard input (for example, "python< sys-argv-example-1.py"), the script name is set to an empty line. If you pass the program as a string (using the -c option), the script name will be set to "-c"."

Working with modules

 

The path list contains a list of the directory names in which Python looks for extension modules (original Python modules, compiled modules, or binary extensions). When you run Python, this list is initialized from a mixture of built-in rules, the contents of the PYTHONPATH environment variable, and the contents of the registry (on Windows). But since this is a regular list, you can also manipulate it from the program, as shown in the example.

Example#2. Using the sys module to manage by searching for the module

File: sys-path-example-1.py

importsys

print»path has», len(sys.path), «members»

# add the sample directory to the path
sys.path.insert(0, "samples")
importexample

sys.path = []
import random # oops!

The following example shows a list of builtin_module_names that contains the names of all the modules built into the Python interpreter.

Example#3. Using the sys module to find built-in modules

File: sys-builtin-module-names-example-1.py

importsys

def dump(module):
print module, "=>",
if module in sys.builtin_module_names:
print"<BUILTIN>"
else:
module= _ _import_ _(module)
print module._ _ file_ _

dump(«os»)
dump(«sys»)
dump(«string»)
dump(«strop»)
dump(«zlib»)

os => C:\python\lib\os.pyc
sys =><BUILTIN>
string=> C:\python\lib\string.pyc
strop =><BUILTIN>
zlib => C:\python\zlib.pyd

The module dictionary contains all loaded modules. The import statement checks this dictionary before it actually loads something from disk. As you can see from the following example, Python loads quite a few modules before passing control to your script.

Example#4. Using the sys module to find imported modules

File: sys-modules-example-1.py

importsys

printsys.modules.keys()

[‘os.path’, ‘os’, ‘exceptions’, ‘_ _main_ _’, ‘ntpath’, ‘strop’, ‘nt’,
‘sys’, ‘_ _builtin_ _’, ‘site’, ‘signal’, ‘UserDict’, ‘string’, ‘stat’]

Work with reference counts

 

The getrefcount function (shown in Example #5) returns a reference count for a given object—that is, the number of places where this variable is used. Python keeps track of this value, and when it drops to 0, the object is destroyed.

Example#5. Using the sys module to find the number of references

File: sys-getrefcount-example-1.py

import sys

variable = 1234

printsys.getrefcount(0)
printsys.getrefcount(variable)
printsys.getrefcount(None)

50
3
192

Note that this value is always greater than the actual count because the function itself hangs on the object when determining the value.

Host Platform Verification

Example No6 . Using the sys module to find the current platform

File: sys-platform-example-1.py

Import sys

#
# emulate "importos.path" (something like)...

ifsys.platform == "win32":
importntpath
pathmodule = ntpath
elifsys.platform == "mac":
importmacpath
pathmodule = macpath else
:
# suppose it is posix platform
importposixpath
pathmodule = posixpath pathmodule = posixpath

printpathmodule

Typical platform names are win32 for Windows 9X/NT and mac for Macintosh. For Unix systems, the platform name is usually inferred from the output of the "uname-r" command, such as irix6, linux2, or sunos5 (Solaris).

Program trace

 

The setprofiler function allows you to install the profiling function. This is called whenever a function or method is called, on every return (explicit or implied), and for every exception. Let's look at example #7.

Example No7. Using the sys Module to Install the Profiler Feature

File: sys-setprofiler-example-1.py

importsys

testdef(n):
j = 0
fori in range (n):
j = j + i
returnn

def profiler(frame, event, arg):
print event, frame.f_code.co_name, frame.f_lineno, «->», arg

# profiler is activated the next time
sys.setprofile(profiler) is called, returned, or excluded

# profile test call this function
test(1)

# disable sys.setprofile(None) profiler


# do not profile this
test(2)

call test 3 ->None
return test 7 -> 1

The profile module provides a complete profiler structure based on this feature. The settrace function in example #8 is similar, but the trace function is called for each new line.

Example No8. Using the sys Module to Set the Trace Feature

File: sys-settrace-example-1.py

importsys

testdef(n):
j = 0
for i in range (n):
j = j + i
returnn

def tracer(frame, event, arg):
print event, frame.f_code.co_name, frame.f_lineno, «->», arg
returntracer

# tracer is activated on the next call, return, or exception of
sys.settrace(tracer)

# trace this function call
test(1)

# disable
sys.settrace(None) tracing

# do not track this
test(2)

call test 3 -> None
line test 3 -> None
line test 4 -> None
line test 5 -> None
line test 5 -> None
line test 6 -> None
line test 5 -> None
line test 7 -> None
return test 7 -> 1

The pdb module provides a complete debugger structure based on the tracing tools offered by this feature.

Working with standard inputs and outputs

 

The variables stdin, stdout, and stderr contain streaming objects that correspond to standard I/O streams. You can access them directly if you want better control over the output than printing can give you. You can also replace them if you want to redirect the output and input to some other device or process them in some non-standard way, as shown in example #9.

Example No9. Using the sys module to redirect output

File: sys-stdout-example-1.py

import sys
import string

class redirection:

def _ _init_ _(self, stdout):
self.stdout = stdout

def write(self, s):
self.stdout.write(string.lower(s))

# standard output redirection (including print statement)
old_stdout = sys.stdout
sys.stdout= Redirect(sys.stdout)

print «HEJA SVERIGE»,
print «FRISKT HUM\303\226R»

# restore the standard output
sys.stdout = old_stdout

print «M\303\205\303\205\303\205\303\205L!»

hejasverigefriskthum\303\266r
M\303\205\303\205\303\205\303\205L!

An object that implements the write method is all that is required to redirect the output.

(Unless it's an instance of type C, that is:Python uses the softspace integer attribute to control the interval and adds it to the object if it's not there. You don't have to worry if you're using Python objects, but if you need to redirect them to type C, you should make sure that this type supports the softspace attribute.)

Exit the program

 

When you reach the end of the main program, the interpreter will automatically terminate. If you need to go out in flight, you can call the sys.exit function, which takes an optional integer value returned by the calling program. This is shown in example #10.

Example No10. Using the sys module to exit a program

File: sys-exit-example-1.py

Import sys

print»hello»

sys.exit(1)

print "there"

Hello

It may not be obvious, but sys.exit does not exit immediately. Instead, it throws a SystemExit exception. This means that you can intercept sys.exit calls in your main program, as shown in example #11.

Example No11. Intercept a sys.exit call

File: sys-exit-example-2.py

Import sys

print»hello»
sys.exit(1)
exceptSystemExit:
pass
print "there"

Hello

If you want to clean things up after yourself, you can set the "output handler", which is a function that is automatically called on the output. This is shown in example #12.

Example No12. Intercept a sys.exit call in another way

File: sys-exitfunc-example-1.py

importsys
defexitfunc():
print"World"
sys.exitfunc = exitfunc
print "hello"
sys.exit(1)
print "there" # never print

world

In Python 2.0, you can use the atexit module to register multiple exit handlers.