Give a Try - Run a System Command using Popen utility of Subprocess module - Python Context Manager - Hands On

Python Python Classes and Objects (Article) Python Classes and Objects (Program)

457

3. Give a Try - Run a System Command using Popen utility of Subprocess module

• Define a function 'run_process', which accepts a system command, runs the command at the background, and returns the results.

• Hint: Use 'Popen' utility in 'subprocess' module to run a system command.

Hint: Use 'with' along with 'Popen'

Given Input:

3
python
-c
print("Hello")

Expected Output:

'with' used in 'run_process' function definition.
'Popen' used in 'run_process' function definition.
Process Output : Hello

Program:

#!/bin/python3

import sys
import os
import subprocess
import inspect

# Complete the function below.
def run_process(cmd_args):

    with subprocess.Popen(cmd_args,stdout=subprocess.PIPE) as proc:

        return proc.communicate()[0]




if __name__ == "__main__":
    f = open(os.environ['OUTPUT_PATH'], 'w')

    cmd_args_cnt = 0
    cmd_args_cnt = int(input())
    cmd_args_i = 0
    cmd_args = []
    while cmd_args_i < cmd_args_cnt:
        try:
            cmd_args_item = str(input())
        except:
            cmd_args_item = None
        cmd_args.append(cmd_args_item)
        cmd_args_i += 1


    res = run_process(cmd_args);
    #f.write(res.decode("utf-8") + "\n")
    
   
    
    if 'with' in inspect.getsource(run_process):
        f.write("'with' used in 'run_process' function definition.\n")
    
    if 'Popen' in inspect.getsource(run_process):
        f.write("'Popen' used in 'run_process' function definition.\n")
        f.write('Process Output : %s\n' % (res.decode("utf-8")))

    f.close()

    

Output:

'with' used in 'run_process' function definition.
'Popen' used in 'run_process' function definition.
Process Output : Hello

This Particular section is dedicated to Programs only. If you want learn more about Python. Then you can visit below links to get more depth on this subject.