System programming with Python is made a lot easy with the help of the os module, it serves as an abstract layer between the python program and the operating system, thus the main advantage of using python for system programming is that most commands are independent of the OS i.e, it is platform independent. All functions we discuss here require us to import the os module first,you can do it by using 'import os'.

Let us go in detail into some functions of the os module. We are using Ubuntu 14.04 in the examples.

os.environ

Environ returns a copy of strings representing the environment. It is returned in the form of a key value pair.

eg. here os.environ['HOME'] gives me my home folder location.

>>> os.environ['HOME']
'/home/jibin'

os.getcwd

It returns the current working directory. Here in the picture it's showing that my working directory is '/bin'

>>> os.getcwd()
'/bin'

os.chdir

It is used to change the current directory.

>>> os.chdir("/home/jibin/projects/")
>>> os.getcwd()
'/home/jibin/projects'

os.mkdir

It's used to make a directory

>>> os.mkdir("/home/jibin/temp")

os.rmdir

It's used to delete a directory.

>>> os.rmdir("/home/jibin/testing")

os.rename

It's used to rename a file or directory. The syntax is as follows,
os.rename(source, destination)

>>> os.rename("/home/jibin/testing/test.txt", "/home/jibin/testing/test_new.txt")

os.chown

It is used to change the owner and group id of a path to the provided owner and group id. To leave a parameter unchanged you can use -1. The syntax is as follows,

os.chown(path,userId,groupId)

In the example I change the ownership of the file to user with id 1001 and leave the group id unchanged.

>>> os.chown("/home/jibin/testing/test.txt",1001,-1)

os.system

The system function allows Python programs to run and execute system commands.

>>> os.system("date")
Thu Feb 23 11:23:32 IST 2017
0

os.kill

It allows us to kill a process. The syntax is as follows:

import signal
os.kill(pid, signal.SIGTERM)

In the example below notice that the process with id 7833 has been killed.

jibin@vinesh:~/testing$ ps -p 7833
  PID TTY       TIME CMD
 7833 ?      00:06:34 chrome
jibin@vinesh:~/testing$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os,signal
>>> os.kill(7833, signal.SIGQUIT)
>>>
>>>
jibin@vinesh:~/testing$ ps -p 7833
  PID TTY       TIME CMD

 

That's it! Now that you have a basic knowledge feel free to dive into the official documentation right here.

Subscribe to our newsletter. Get updates on awesome happenings in the technology world!
Newsletter subscription successfull! Something went wrong! Email is already registered!

TAGS