Python Classroom Series – 08/Dec/2019

subprocess

  • subprocess module helps in calling commands from python.
  • Write a python program which will call ping -c4 google.com in linux machine
#!/usr/env/python
import os
import subprocess


def execute_command(cmd, *args):
    cmdargs = " ".join(args)
    ret_code = subprocess.check_call("{} {}".format(cmd, cmdargs),shell=True)
    print("Return code is {}".format(ret_code))


def get_command_output(cmd, *args):
    cmdargs = " ".join(args)
    output = subprocess.check_output("{} {}".format(cmd, cmdargs),shell=True)
    print(output)

def execute_using_popen(*args):
    p = subprocess.Popen(args, stdout=subprocess.PIPE)
    outerrortuple = p.communicate()
    print("Stdout is {}".format(outerrortuple[0]))
    print("stderr is {}".format(outerrortuple[1]))


if __name__ == '__main__':
    execute_command('ping', '-c', '4', 'google.com')
    get_command_output('ping', '-c', '4', 'google.com')
  • check_call method calls the command and returns the exit code to the program. use this when the output of the command need not be processed.

  • check_output method will execute the command and returns the output to the program. use this when output has to be parsed.

PIP Packages

  • Python reusable libraries hosted can de used on any machine using a packaging mechanism called PIP
  • Installing PIP
# ubuntu
sudo apt-get update 
sudo apt-get install python3-pip

#Mac users
https://evansdianga.com/install-pip-osx/

  • Sample usage of python Package
    • I will be using a pacakage called as wget. Command to install this pip install wget
    • Now i will write a function to download the file from web using wget package

Using boto3 to list all the s3 buckets

  • Install and configure boto3 from here
import boto3

s3resource = boto3.resource('s3')

for bucket in s3resource.buckets.all():
    print(bucket)
  • Using boto3 any aws resource can be created, delted or listed. As the user write a python code to use the available methods/classes

Using Azure SDK for python

Leave a Reply

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

About continuous learner

devops & cloud enthusiastic learner