Programming Essentials Python - Basic Programming Constructs - Running os commands

In this article, we will explore how to run OS commands using Python with the help of libraries such as os and subprocess. We will learn how to import these libraries and execute various commands to interact with the operating system.

Explanation for the video

[Embedded video placeholder]

Key Concepts Explanation

Importing Libraries

To start using OS commands in Python, we need to import the necessary libraries such as os and subprocess. This allows us to access functions and methods provided by these libraries.

import os
import subprocess

Reading Environment Variables

The os library is commonly used to read environment variables during the runtime of the application. It helps in accessing keys, credentials, and other configuration details without hardcoding them in the source code.


Running Commands

We can use the subprocess library to execute system commands and process their output. This allows us to interact with the operating system and get results from executed commands.

output = subprocess.check_output(['ls', '-ltr'])

Hands-On Tasks

Here are some hands-on tasks for you to practice running OS commands using Python:

  1. Get the current working directory using os.getcwd().
  2. Read environment variables and display their values using os.environ.get('ENV_VARIABLE_NAME').
  3. Execute a system command like ls -ltr using subprocess.check_output(['ls', '-ltr']).


In conclusion, we have discussed how to run OS commands in Python using libraries such as os and subprocess. It is essential to understand these concepts when working with system-level interactions in Python. Practice these commands and explore more functionalities to enhance your skills further.

Running OS Commands

Watch the video tutorial here