Python: SYS module

/ Published in: Python
Save to your folder(s)

Copy this code and paste it in your HTML
  1. # The sys module provides an interface to access the environment of the Python interpreter.
  2. # The following examples illustrate some of the most common uses of the sys module.
  4. # The argv attribute of the sys module is a list. The first item in the argv list is the
  5. # path to the module; the rest of the list is made up of arguments that were passed to the
  6. # module at the beginning of execution. The sample code shows how to use the argv list to
  7. # access command-line parameters passed to a Python module:
  9. >>>print sys.argv
  10. ['C:\\books\\python\\CH1\\code\\',
  11. 'text']
  12. >>>print sys.argv[1]
  13. text
  15. # The stdin attribute of the sys module is a file object that gets created at the start of
  16. # code execution. In the following sample code, text is read from stdin (in this case, the
  17. # keyboard, which is the default) using the readline() function:
  19. >>>text = sys.stdin.readline()
  20. >>>print text
  21. Input Text
  23. # The sys module also has the stdout and stderr attributes that point to files used for
  24. # standard output and standard error output. These files default to writing to the screen.
  25. # The following sample code shows how to redirect the standard output and standard error
  26. # messages to a file rather than to the screen:
  28. >>>sOUT = sys.stdout
  29. >>>sERR = sys.stderr
  30. >>>sys.stdout = open("ouput.txt", "w")
  31. >>>sys.stderr = sys.stdout
  32. >>>sys.stdout = sOUT
  33. >>>sys.stderr = sERR

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.