How to execute bash commands in python???

 Bash (Bourne Again shell). It is a shell used in Linux and GNU operating systems. Bash is an enhanced version of Bourne shell.

Why bash commands???

Bash commands interact the system. It deals with Datatypes, files, directories and its associated functions.

Some of the bash commands are listed below.

ls – lists the files and directory.

cd- changes the directory.

pwd – displays the present working directory.

touch – creates a new file.

rm -remove files and directory.

cp – copying a file.

mv – move a file to another location.

These are the basic bash commands.

How to execute bash commands in python???

              This can be done by some built in packages in python. Let us use the package “os”.

Print the current working directory: Equivalent to pwd

#first, import the os package

import os

#getcwd() prints the current working directory

os.getcwd()

#the output is given below

To change directory: Equivalent to cd

              It uses a function called “chdir()”. Let us built the code.

#import the os package.

import os

#use the chdir() function to change the directory. Include your URL.

os.chdir(“c:\raji”)

#print the changed directory.

print(os.getcwd())

#output to change directory


To list the files in current directory: Equivalent to ls

              Here, a function listdir() is used. To print the files in the directory, use the below code..

#code to display the files in the directory.

os.listdir()

#here is the output

These are the basic bash commands can be executed in python.

No comments:

Post a Comment