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
"""
# subprocess.call(["touch", file_name])
capture_output(["touch", file_name])
print(f"created file {file_name}")
# subprocess.call(["ls"])
capture_output(["ls"])
print("listed the files")
# subprocess.call(["rm", file_name])
capture_output(["rm", file_name])
print(f"removed the file {file_name}")
capture_output(["ls"])
pass
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 = subprocess.run(commands, 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__":
create_check_remove_file()
Python Programs to Read Command line arguments
- Lets try to build a python program which
python sum.py 1 2 3 4 5 6 7 8 9 10
55
-
There are 3 ways to read command line args
- In the sys module we have argv
- 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__":
print(sum_of_numbers())
print(sum_of_squares())
- In Majority of the cases we might have named arguments, but the above command works only for positional args
python calc.py -a 1 2 3 4 5 6 7 8 9 10
55
python calc.py -m 1 2 3
6
- 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:")
print(opts)
print(args)
if __name__ == "__main__":
parse_args()