Python OS run Command

The OS library comes with features particular to the operating system and facilitates communication with it. The library has the writing and reading methods, and the library is simple to use. Python enables the OS to run different commands by performing different operations on the operating system as the features of the OS module enable communication with the Python operating system. In this Python document, several “OS” methods are utilized to run the shell and interact with the operating system.

Example 1

The Python os.system() method enables us to run a terminal command stored in a string instantly. Let’s accomplish this os.system() method in the following examples to execute with the Python compiler. The initial step we have provided below is to import the OS module through which we can access the os.system() method. After that, we invoked the os.system() method, where the echo command is passed. Here, the echo command executed the specified string on the prompt command.

import os
os.system('echo "Python Os run command Example"')

The provided string is echoed by executing the shell’s os.system() method.

Example 2

Here, we have accessed the path of the working directory by using the os.system() method. The os.system() takes the parameter “pwd”, the abbreviation of the path working directory. The pwd, by default, prints the symbolic path of the working directory. We have given the following program that prints the pwd to the shell screen from the os.system() method of Python. The first line of the program is imported with the OS module. Then, we have the os.system() method call, where the pwd is provided as an argument.

Import os

As we are executing this Python file in the home directory, the pwd also gives us a home directory with the username, which is a symbolic form of the path. The os.system() executes the pwd shell script.

Example 3

The OS command can also be used to execute the Linux commands. We have a program where we have listed all the files inside our current directory. For this, we have defined an import statement of the OS module. Then, we declared the object cmd that will interpret the command line. Then, we used the Linux command “ls -l”, which gives the details regarding files and directories in the file system. Then, we executed this cmd command by utilizing the os.system() method.

import os
cmd = 'ls -l'

The shell script of Python displayed the listed files and the file system’s directory by running the following OS command:

Example 4

Although, we can open any application with the Python os run commands. Here, we have a program that enables us to open any application of the system. We have again used the run command of the OS that is os.system() method. The os.system() takes the name of the “firefox” application and opens it while running this source file of the Python in the BASH.

import os

We have an open Firefox application image form running the following OS command:

Example 5

The OS module is interactive with the operating system. We can make the directory in the operating system by using the OS commands. The Python os.mkdir() method is used to create a directory with the name path and the provided numeric mode. If the specified directory already exists, this method throws a FileExistsError. Let’s begin with the source code. We have declared the variable “Dir”, where the directory name to be created is given in the string format.

After this, we have declared the variable “parentDir”, where the path of the given directory is provided to store it. With the os.path.join() method set in the variable “path”, we have joined the path and directory name. Then, we deployed the os.mkdir() method, where the variable “path” is passed as a parameter to create the directory. Next, we created another directory using the same step as the previous directory. But, we have created this directory with the mode, which is then assigned to the mkdir() method along with the given path. When the directories are created, they will be displayed on the shell.

import os
Dir = "PythonPrograms"
ParentDir = "/home/aqsayasin"
path = os.path.join(ParentDir, Dir)

print("Directory '% s' created" % Dir)

Dir = "NewPythonProgram"
ParentDir = "/home/aqsayasin"
mode = 0o666
path = os.path.join(ParentDir, Dir)
os.mkdir(path, mode)
print("Directory '% s' created" % Dir)

The OS command runs in the previous Python shell script with the mkdir() method to create the directory.

Example 6

Although, we can run the OS command to get the current working directory of our operating system. The os.getcwd() method is built in Python for this purpose. The os.getcwd() method gets the current location of the operating system’s working directory. The following Python shell script is implemented with the os.getcwd() method in the variable “System_CWD”. Then, we called this “System_CWD” in the print method because it holds the current working directory path of the operating system we are using.

import os
System_CWD = os.getcwd()
print("Current Working Directory:", System_CWD)

The current working directory of our operating system is fetched by running the following OS command:

Example 7

Next, we have the built-in Python method os.walk(), which produces the file names in the file index tree by traversing either with its top-down or bottom-up parameters. So, after inserting the OS module in the program, we have invoked the os.walk() method, which takes the root of the file system and the parameter top down. The top-down parameter is set with the True value, which means the root directories will be scanned from top to down. Else it will be scanned from the bottom up.

Import os
for root,  irs., files in os.walk(“.”, topdown=True):
   for name in files:
      print(os.path.join(root, name))
   for name in  irs.:
      print(os.path.join(root, name))

As seen from the path, it returns the path, directories list, and files starting from the top-down.

Example 8

Now, we have run the os.listdir() method to execute the following Python script, which will also get the files and directories with the provided path. We first set the absolute path of the file system and then called the os.listdir() method, where the path is given. Then, the files and directories will be obtained when the OS command is run on the terminal.

Import os

SysPath = “/”
directory_list = os.listdir(SysPath)

print(“Files and Directories in ‘”, SysPath, “’ :”)


The os.listdir() command returns the current directories and file of our absolute path, as shown below:

Example 9

We have executed all the OS commands successfully, but the OS command also generates errors. The OS errors are defined through the os.error() method. When file names, paths, etc., are incorrect or unavailable, it raises an OSError. Inside the program, we have a try statement where we first set the filename in the object “File”. Then, we deployed the open() method to open the specified file in write “w” mode. After that, we read that file via the read() method, and after reading the file, the file will be closed via the close() method. If any of the code lines throws an error, it will get straight to the IOError class and print the os.error message.

import os  
    File = 'MyPython.txt'  
    OpenFile = open(File, 'w')  
    FileText =  
except IOError:  
    print('Problem while reading the file ' + File)

The os.error() generates the error of the class OSError in the output.

Example 10

The last program is to examine whether the user of the operating system has access to the path, which is obtained through the deployment of the os.access() method. By running this, we will get to know the user authorization of the path. So, we have used the following os.access() method with its different parameters. First, the access() method takes the os.F_ok mode to determine the path’s existence.

Then, we test the path accession with the readability of the path by specifying the os.R_OK mode to the os.access() method. After this, we examined the writability of the path bypassing the os.W_OK mode to the access() method. In the end, we tested whether the given path can be executed with the os.X_OK mode in the os.access() method.

import os    
import sys      
FilePath1 = os.access("MyPython.txt", os.F_OK)    
print("Exist path:", FilePath1)    
FilePath1 = os.access("MyPython.txt", os.R_OK)    
print("File can be accessed to read:", FilePath1)    
FilePath1 = os.access("MyPython.txt", os.W_OK)    
print("File can be access to write:", FilePath1)    
FilePath1 = os.access("MyPython.txt", os.X_OK)    
print("Check if path can be executed:", FilePath1)

The previous os.access() method displayed the Boolean results against each specifying testing with the different modes.


Python supports the execution of shell commands, which can be used to launch additional applications or more efficiently control shell programs employed for scripting. We have run several OS methods to run the commands in Bash of the operating system for creating the directories, fetching the files, and raising the errors. All these OS methods are very useful for getting the OS-based task and get the details about the operating system.

About the author

Aqsa Yasin

I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.