Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Context Manager for Popen

Tags:

python-3.x

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

like image 954
Sandip Datta Avatar asked Aug 16 '18 12:08

Sandip Datta


People also ask

Is Popen a context manager?

Popen objects are supported as context managers via the with statement: on exit, standard file descriptors are closed, and the process is waited for.

Does Popen wait for process to finish?

Using Popen MethodThe Popen method does not wait to complete the process to return a value.

Should I use Popen or subprocess?

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.

What is difference between Popen and call?

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.


1 Answers

def run_process(cmd_args):
    with subprocess.Popen(cmd_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) as p:
        out, err = p.communicate()
    return out
like image 69
user10754055 Avatar answered Oct 04 '22 16:10

user10754055