sys module
Get to know sys module
sys
module gives you access to variables and
functions that are closely linked to the Python
interpreter.
The following table has some functions and variables in the sys Module.
Function/Variable | Description |
---|---|
argv | The command-line arguments, including the script name |
exit([arg]) | Exits the current program, optionally with a given return value or error message |
modules | A dictionary mapping module names to loaded modules |
path | A list of directory names where modules can be found |
platform | Contains a platform identifier such as sunos5 or win32 |
stdin | Standard input stream |
stdout | Standard output stream |
stderr | Standard error stream |
Setting the Default Encoding
import sys
print sys.getdefaultencoding()
s = u'La Pe\xf1a'
print s
The code above generates the following result.
sys.path
The list of search path can be found in the path variable in the sys module.
import sys, pprint
pprint.pprint(sys.path)
The code above generates the following result.
sys.exit()
#!/usr/bin/env python
# w w w . j av a2 s . c o m
import sys
def usage():
print 'At least 2 arguments (incl. cmd name).'
print 'usage: args.py arg1 arg2 [arg3... ]'
sys.exit(1)
argc = len(sys.argv)
if argc < 3:
usage()
print "number of args entered:", argc
print "args (incl. cmd name) were:", sys.argv
sys.exitfunc()
import sys# from w ww . j a v a 2 s .c o m
prev_exit_func = getattr(sys, 'exitfunc', None)
def my_exit_func(old_exit = prev_exit_func):
if old_exit is not None and callable(old_exit):
old_exit()
sys.exitfunc = my_exit_func
Append path to system path
import sys
sys.path.append('/home/wesc/py/lib')
Version and platform
import sys
sys.stdout.write('Hello World!\n')
print sys.platform
print sys.version
The code above generates the following result.