Use os module to access system level functions

Get to know os module

The os module can access several operating system services.

The following table has some important functions and variables in the os module.

Function/VariableDescription
environMapping with environment variables
system(command) Executes an OS command in a subshell
sep Separator used in paths
pathsepSeparator to separate paths
linesepLine separator ( '\n', '\r', or '\r\n')
urandom(n) Returns n bytes of cryptographically strong random data

Run System command

In UNIX, you can do the following to start the firefox browser.


os.system('/usr/bin/firefox') 

A Windows version would be

 
os.system(r'c:\"Program Files"\"Mozilla Firefox"\firefox.exe')

We can use another function os.startfile on Windows as well.


os.startfile(r' c:\Program Files\Mozilla Firefox\firefox.exe') 

We can use system function to call other system functions.


import os#   w  ww . ja  v a2  s  . c o m
result = os.system('cat /etc/motd')
print result
        
result = os.system('uname -a')
print result
        
result = os.system('dir')
os.system("copy c:\\temp.dat c:\\temp1.dat")

The code above generates the following result.





















Home »
  Python »
    Language Basics »




Python Basics
Operator
Statements
Function Definition
Class
Buildin Functions
Buildin Modules