How do you execute a system command in Python?

In this article we will learn to execute a system command in Python Programming Language.

Table Of Contents

Introduction

Today we will be discussing about different methods using which we can execute system/shell commands in Python. This can be useful to automate things which requires a communication with the system. Mainly there are two modules that can be used to execute a system command in python.

So here we will learn about different modules and methods in Python Programming language through which you can execute system commands. Also we will demonstrate you by creating a directory with the mkdir command in the system.

mkdir is a command used to create folder/directory in OS like windows, LINUX,UNIX.

Execute a system command in Python using the OS Module

We can use OS module of Python programming language, to execute system command in Python. OS module comes bundled with Python. It provides us with many functions, which can be used to interact with the operating system. It has many useful functions which provide direct manipulation with files and folders. But here we will be using os.system() with some system commands. For example,

Advertisements

os.system: This function creates a sub-shell inside the python shell(where the python program runs), and executes the system commands. If returned any string by the sub-shell(where the system commands are running), then it returns the string back to Python interpreter and hence visible to user. This way this module can be used for proper input-output communication with the system command. Whatever is passed in the os.system() as a string, is used as a command in system command. Like if you pass “dir” inside the os.system(), it will work as the same as when you type dir in system command/command prompt.

Let’s see an example,

import os

# echo is used to print string in cmd.
os.system("echo Hello, I am Python. I have created a directory for you.")

# mkdir creates a new folder/directory in the cmd.
os.system("mkdir python")

# dir prints the directories/folders available in the folder.
os.system("dir")

OUTPUT :

Hello, I am Python. I have created a directory for you.

12:49 PM               940 code.py
12:49 PM    <DIR>          python
               1 File(s)            940 bytes
               3 Dir(s)  202,821,668,864 bytes free

In the above code and output, you can see how os module is being used to execute system command in python. The mkdir and dir commands has been used to create a new folder named python in the working directory, and list all the available directories respectively.

Execute a system command in Python using the Subprocess Module

Next we can use the subprocess module of Python Programming Language to execute a system command in Python. This module comes bundled with python. This module is the mostly used and recommended executing system commands. This module is an alternative of OS module because some very useful features like:

  • Connects to input/output/error pipes and obtains their return codes.
  • Allows to spawn new process.

This module offers a lot more, for more detailed study go to the Python SubProcess Module DOCS

CODE :

import subprocess

# creating a folder at current path using mkdir and subprocess.run() function
file = subprocess.run("mkdir subprocess",shell=True)

# returncode prints the status of the process subprocess.run(), 0 means that the program ran successfully.
print(file.returncode)

# shell=True because dir command is built into the shell.
subprocess.run("dir",shell= True)

OUTPUT :

0
575 script.py
<DIR>          subprocess

So, In the code and output above you can see subprocess module has been used to create a new folder in the system using mkdir and subprocess.run() function. Also we have passed shell=True has been passed. It has done to prevent us from getting an error, because the dir command is built into the shell.

Summary

So, In this Python tutorial article we learned to execute a system command in Python. We learned about two most popular and most used and useful modules which are widely used to execute system command in Python. First is OS module which provides some useful functions like os.getcwd(), os.fdopen(fd, args, *kwargs), os.pipe(), os.system, os.run, etc. which are used for interaction with OS and file maipulation. Visit Official Python Docs. Also we used Subprocess module which is the most recommended and mostly used to execute a system command in Python, it provides with vast of functions/methods through which we can do file manipulation, os communication and a lot more with the help of function/methods like: subprocess.run(), subprocess.Popen(), Popen.poll(), subprocess.PIPE, etc. Visit the Official Python Docs.

Make sure to read/write the code samples from this article, to have a better understanding of the solutions. Thanks.

Pandas Tutorials -Learn Data Analysis with Python

   

Are you looking to make a career in Data Science with Python?

Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.

Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.

Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.

Join a LinkedIn Community of Python Developers

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top