Python Classroom Series – 14/Sept/2020

Writing a Python program to execute external commands

  • In python standard library we have a module name subprocess Refer Here
  • Lets write a simple program to create, list and remove the file using external linux commands
#!/usr/bin/env python3
import subprocess

def create_check_remove_file(file_name="frompython.txt"):
    This function will create a file called as frompython.txt
    equivalent linux commands
    1. touch frompython.txt
    2. ls
    3. rm frompython.txt
    #["touch", file_name])
    capture_output(["touch", file_name])
    print(f"created file {file_name}")
    print("listed the files")
    #["rm", file_name])
    capture_output(["rm", file_name])
    print(f"removed the file {file_name}")

def capture_output(commands):
    This command will capture the return code of the commands executed
    and the stdout
    :param commands: commands to be executed
    result =, stdout=subprocess.PIPE)
    print(f"return code: {result.returncode}")
    command = " ".join(commands)
    print(f"output from the {command} executed are {result.stdout.decode('utf-8')}")

if __name__ == "__main__":


Python Programs to Read Command line arguments

  • Lets try to build a python program which
python 1 2 3 4 5 6 7 8 9 10
  • There are 3 ways to read command line args

    1. In the sys module we have argv
    2. Using the getopt module which has getopt method (getopt.getopt)
  • Argv Example to calculate squares

#!/usr/bin/env python3

import sys

def sum_of_numbers():
    This method will print the sum of arguments passed from command line
    :return: sum of numbers from cmdline
    # naive method
    # result = 0
    # for argument in sys.argv[1:]:
    #     result = result + int(argument)
    # return  result

    # list comprehension
    arguments = [int(argument) for argument in sys.argv[1:]]
    return sum(arguments)

def sum_of_squares():
    This method will print the sum of arguments passed from command line
    :return: sum of squares numbers passed from cmdline
    # list comprehension
    arguments = [int(argument) * int(argument) for argument in sys.argv[1:]]
    return sum(arguments)

if __name__ == "__main__":

  • In Majority of the cases we might have named arguments, but the above command works only for positional args
python -a 1 2 3 4 5 6 7 8 9 10

python -m 1 2 3
  • Lets explore getopts Refer Here
  • Exercise: Debug this program.
#!/usr/bin/env python3

import getopt
import sys

def parse_args():
    This method will parse arguments
    opts, args = getopt.getopt(sys.argv, "a:m:")

if __name__ == "__main__":

Leave a Comment

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

About learningthoughtsadmin