Using BASH commands in PYTHON-Part 1
Let’s start without any gibberish Introduction to what Python or BASH is. It’s mostly obvious that you wouldn’t be here if you didn’t knew them.
In simple words:
Python is a programming language
BASH commands are those that you use on your Linux terminal
For people who would like to know or revise about them can refer to links:
Python: https://www.w3schools.com/python/
BASH: https://www.tutorialspoint.com/unix_commands/bash.htm
Methods to invoke UNIX commands in python
There are two ways in python to invoke or call bash commands:
1) using the os library
2) using the subprocess library
We’l be seeing how to invoke bash commands using the os library in python today. The second method will be covered later.
Using the OS library to invoke UNIX
This is the sinplest method where we can write our commands directly as we write them on the CLI (command line interface). os is an inbuilt library (which means that there is no need to install it since it comes pre installed with python)
Let’s see how to implement it in two steps with an example:
Step 1: Import the library
import os
Step 2: Execute the bash command using the system function
os.system('your commad here')
Example:
Suppose for example’s sake you want to create a directory named mydir using the bash command (although there are os.mkdir() or os.makedirs() inbuilt functions to do the same) we write:
import os
os.system('mkdir mydir')
That’s it.
Easy enough right !
Click here to see a list of simple BASH commands and try to implement them yourself.
For any suggestions or corrections please comment. It will help me a lot in the future, since this is my first Meduim blog.
Se you in the next Part !!!
Adios !!!