The system module

The sys module will allow us to interact with the interpreter and it contains most of the information related to the execution in progress, updated by the interpreter, as well as a series of functions and low-level objects.

sys.argv contains the list of parameters for executing a script. The first item in the list is the name of the script followed by the list of parameters.

We may, for example, want to parse command-line arguments at runtime. The sys.argv list contains all the command-line arguments. The first sys.argv[0] index contains the name of the Python interpreter script. The remaining items in argv array contain the next command-line arguments. Thus, if we are passing three additional arguments, sys.argv should contain four items.

You can find the following code in the sys_arguments.py file in :

import sys
print "This is the name of the script:",sys.argv[0]
print "The number of arguments is: ",len(sys.argv)
print "The arguments are:",str(sys.argv)
print "The first argument is ",sys.argv[1]

The previous script can be executed with some parameters, such as the following:

$ python sys_arguments.py one two three

If we execute the previous script with three parameters, we can see the following result:

In this example, we obtain many system variables:

These are the main attributes and methods to recover that information:

  • sys.platform: Returns the current operating system
  • sys.stdin,sys,stdout,sys.stderr: File objects that point respectively to the standard input, standard output, and standard error output
  • sys.version: Returns the interpreter version
  • sys.getfilesystemencoding(): Returns the encoding used by the filesystem
  • sys.getdefaultencoding(): Returns the default encoding
  • sys.path: Returns a list of all the directories in which the interpreter searches for the modules when the import directive is used or when the names of the files are used without their full path

You can find more information on the Python online module documents at http://docs.python.org/library/sys.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.251.206