Give a Try - Run a System Command using Popen utility of Subprocess module - Python Context Manager - Hands On
Give a Try - Run a System Command using Popen utility of Subprocess module - Python Context Manager - Hands On
Give a Try - Run a System Command using Popen utility of Subprocess module - Python Context Manager - Hands On
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'
3
python
-c
print("Hello")
'with' used in 'run_process' function definition. 'Popen' used in 'run_process' function definition. Process Output : Hello
#!/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()
'with' used in 'run_process' function definition.
'Popen' used in 'run_process' function definition.
Process Output : Hello
First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.
Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.