Execute shell commands in python

In this blog post, one can learn how to execute shell commands in python. A command-line interface (CLI) called shell is used to communicate with the operating system. It offers a setting for executing text-based commands and frequently includes functionality like piping and redirection that are not present in GUIs.

 

 

Execute shell commands in python

One can execute a shell command in a python programming language using two basic approaches:

  • Use of subprocess module
  • Use of RunShellCommand() function

The library we import while using the subprocess approach is the subprocess library which is mainly responsible in python to handle subprocesses as well as the commands related to them. The code by subprocess module is:

 

import subprocess

# Popen ran this command from the shell.

p = subprocess.Popen("ls -lh", stdout=subprocess.PIPE, shell=True)

print(p.communicate())

 

Output:

 

The first option makes it simpler to execute a single line of code before quitting, but it is less versatile when utilizing parameters or outputting text. The second choice will provide you with more customization options for your script, but it will be harder to code.

There is a list of modules available in python that one can use while handling the subprocesses. These are subprocess modules, command modules, and os modules. In the second code, we will try to run code using the os module which is an operating system module that is a part of RunShellCommand() function. The codes go as:

 

 

import os
# popen function opens a connection between the cmd and operating system through python
stream = os.popen('echo Returned output')
output = stream.read()
output

 

Output

 

The Python standard library contains the subprocess module. It offers tools for running shell commands, collecting their results, and reporting errors.

Another practical method for running Python shell scripts is the Command library. The Popen method of the subprocess module is encapsulated by the Command module.

Access to a number of the operating system’s low-level functionalities is made possible by the os module in Python. One can use it to create files, list information about files (stat), change directories, list directories, and more.

 

 

Also Read: AlphaGo: Program that plays the board game Go

 

Share this post

Leave a Reply

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