Python: OS module


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



Copy this code and paste it in your HTML
  1. # The os module provides a portable platform-independent interface to access common operating services,
  2. # allowing you to add OS-level support to your programs.
  3.  
  4. # The os.path.abspath(path) function of the os module returns a string version of the absolute path of the
  5. # path specified. Because abspath takes into account the current working directory, the . and .. directory
  6. # options will work as shown next:
  7.  
  8. >>>print os.path.abspath(".")
  9. >>>C:\books\python\ch1\ print os.path.abspath("..") C:\books\python\
  10.  
  11. ## The os.path module provides the exists(path), isdir(path), and isfile(path) function to check for the
  12. # existence of files and directories, as shown here:
  13.  
  14. >>>print os.path.exists("/books/python/ch1")
  15. True
  16. >>>print os.path.isdir("/books/python/ch1")
  17. True
  18. >>>print
  19. os.path.isfile("/books/python/ch1/ch1.doc")
  20. True
  21.  
  22. ## The os.chdir(path) function provides a simple way of changing the current working directory for the program,
  23. # as follows:
  24.  
  25. >>>os.chdir("/books/python/ch1/code")
  26. >>>print os.path.abspath(".")
  27. C:\books\python\CH1\code
  28.  
  29. ## The os.environ attribute contains a dictionary of environmental variables. You can use this dictionary as
  30. # shown next to access the environmental variables of the system:
  31.  
  32. >>>print os.environ['PATH']
  33. C:\WINNT\system32;C:\WINNT;C:\Python24
  34.  
  35. ## The os.system(command) function will execute a system function as if it were in a subshell, as shown with
  36. # the following dir command:
  37.  
  38. >>>os.system("dir")
  39. Volume Serial Number is 98F3-A875
  40. Directory of C:\books\python\ch1\code
  41. 08/11/2006 02:10p <DIR> .
  42. 08/11/2006 02:10p <DIR> ..
  43. 08/10/2006 04:00p 405 format.py
  44. 08/10/2006 10:27a 546 function.py
  45. 08/10/2006 03:07p 737 scope.py
  46. 08/11/2006 02:58p 791 sys_tools.py
  47. 4 File(s) 3,717 bytes
  48. 2 Dir(s) 7,880,230,400 bytes free
  49.  
  50. ## Python provides a number of exec type functions to execute applications on the native system. The following
  51. # example illustrates using the os.execvp(path, args) function to execute the application update.exe with a
  52. # command-line parameter of -verbose:
  53.  
  54. >>>os.execvp("update.exe", ["-verbose"])

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.