I am very new in Python. I was trying a solution on Context Manager as below: Problem Statement: Define a function run_process which accepts a system command, runs the command in background and returns the result
Solution I tried:
def run_process:
with subprocess.Popen(cmd_args) as proc:
proc.communicate()
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);
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()
Expected 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
Popen objects are supported as context managers via the with statement: on exit, standard file descriptors are closed, and the process is waited for.
Using Popen MethodThe Popen method does not wait to complete the process to return a value.
The main difference is that subprocess. run() executes a command and waits for it to finish, while with subprocess. Popen you can continue doing your stuff while the process finishes and then just repeatedly call Popen. communicate() yourself to pass and receive data to your process.
Popen doesn't block, allowing you to interact with the process while it's running, or continue with other things in your Python program. The call to Popen returns a Popen object. call does block.
def run_process(cmd_args):
with subprocess.Popen(cmd_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as p:
out, err = p.communicate()
return out
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With