Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store output of subprocess.Popen call in a string [duplicate]

I'm trying to make a system call in Python and store the output to a string that I can manipulate in the Python program.

#!/usr/bin/python import subprocess p2 = subprocess.Popen("ntpq -p") 

I've tried a few things including some of the suggestions here:

Retrieving the output of subprocess.call()

but without any luck.

like image 875
Mark Avatar asked Mar 23 '10 19:03

Mark


People also ask

How do you store output of subprocess call?

Popen(args,stdout = subprocess. PIPE). stdout ber = raw_input("search complete, display results?") print output #... and on to the selection process ... You now have the output of the command stored in the variable "output".

What does Python subprocess Popen return?

The Python subprocess call() function returns the executed code of the program. If there is no program output, the function will return the code that it executed successfully. It may also raise a CalledProcessError exception.

What is the difference between subprocess call and Popen?

Popen is more general than subprocess. 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.

What is the output of subprocess Check_output?

The subprocess. check_output() is used to get the output of the calling program in python. It has 5 arguments; args, stdin, stderr, shell, universal_newlines. The args argument holds the commands that are to be passed as a string.


Video Answer


2 Answers

In Python 2.7 or Python 3

Instead of making a Popen object directly, you can use the subprocess.check_output() function to store output of a command in a string:

from subprocess import check_output out = check_output(["ntpq", "-p"]) 

In Python 2.4-2.6

Use the communicate method.

import subprocess p = subprocess.Popen(["ntpq", "-p"], stdout=subprocess.PIPE) out, err = p.communicate() 

out is what you want.

Important note about the other answers

Note how I passed in the command. The "ntpq -p" example brings up another matter. Since Popen does not invoke the shell, you would use a list of the command and options—["ntpq", "-p"].

like image 183
Mike Graham Avatar answered Oct 12 '22 23:10

Mike Graham


This worked for me for redirecting stdout (stderr can be handled similarly):

from subprocess import Popen, PIPE pipe = Popen(path, stdout=PIPE) text = pipe.communicate()[0] 

If it doesn't work for you, please specify exactly the problem you're having.

like image 29
Eli Bendersky Avatar answered Oct 12 '22 21:10

Eli Bendersky