how do i test subprocess's stdout, stderr in python on windows - python

>>> import subprocess
>>> f = open('txt', 'w+')
>>> p = subprocess.Popen(['dir'],stdout=f,stderr=f, shell=True)
>>> p.communicate()
(None, None) # stdout, stderr are empty. Same happens if I open a win32 gui app instead of python (don't think win32 gui apps set a stdout/stderr)
I want to retrieve the stdout or stderr of a subprocess to test a few characteristics of them (not the current sys.__stdout__). How can I do this from the python interpreter?

I think you are looking for subprocess.PIPE
Example
>>> from subprocess import Popen, PIPE
>>> process = subprocess.Popen(['ls'], stdout = PIPE, stderr = PIPE, shell = True )
>>> process.communicate()
('file\nfile1\nfile2, '')
As it can be seen,
process.communicate()[0]
is the stdout of the command and
process.communicate()[1]
is the stderr

You can use check_output and catch a CalledProcessError:
from subprocess import check_output, CalledProcessError
try:
out = check_output(["dir"]) # windows out = check_output(["cmd", "/c", "dir"])
except CalledProcessError as e:
out = e.output
print(out)

Related

Python subprocess returning output as stderr

I've been working on a Python script to interact with ffmpeg; however, I've noticed that even though everything runs fine, stdout is empty and stderr returns what I should expect from stdout. How do I fix it so that the output will be returned by stdout?
Here's the simplest example that reproduces the phenomenon:
from subprocess import Popen, PIPE
p = Popen(['python', '-V'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
out, err = p.communicate()
if out:
print("Output. ", out.decode())
else:
print("Error. ", err.decode())
Here's the output:
Error. Python 3.6.1 :: Anaconda 4.4.0 (64-bit)
I should note that I'm using Windows 10.
You can redirect the stderr of your process to its stdoutby doing so:
from subprocess import PIPE, STDOUT
p = subprocess.Popen(["python", "-V"], stdout=PIPE, stderr=STDOUT)
Then you can retrieve the output produced by the process like so:
out = p.stdout.read()
This will return the content of the stdout after your process has terminated.

How to print output of Subprocess Python?

`import subprocess
subprocess.check_call(
['/home/kadia/tensorflow/bazelbin/tensorflow/examples/label_image/label_image',
'--graph=/home/kadia/Desktop/TrainedShadowModel-1/output_graph.pb',
'--labels=/home/kadia/Desktop/TrainedShadowModel-1/output_labels.txt',
'--output_layer=final_result',
'--input_layer=Mul',
'--image=/home/kadia/Desktop/2.jpg']`
How can I print the output from this? Output right now going in console. I want to save the output in file
You can use popen:
from subprocess import Popen, PIPE
p = Popen(['/home/kadia/tensorflow/bazelbin/tensorflow/examples/label_image/label_image',
'--graph=/home/kadia/Desktop/TrainedShadowModel-1/output_graph.pb',
'--labels=/home/kadia/Desktop/TrainedShadowModel-1/output_labels.txt',
'--output_layer=final_result',
'--input_layer=Mul',
'--image=/home/kadia/Desktop/2.jpg'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
output, err = p.communicate(b"input data that is passed to subprocess' stdin")
rc = p.returncode

I want to check the DNS value from my system

I want to check the DNS value from my system.
If the command goes wrong, the error should be stored in a different variable.
This is what I have so far:
proc = subprocess.Popen(['echo', '"to stdout"'], stdout=subprocess.PIPE,)
stdout_value = proc.communicate()
print '\tstdout:', repr(stdout_value)
subprocess.call('echo #user', shell=True)
#subprocess.check_call('echo #HOME', shell=True)
You should try this :
It captures errorcode, stdout and stderr from a command you passed as an argument :
import shlex
from subprocess import Popen, PIPE
def get_exitcode_stdout_stderr(cmd):
"""
Execute the external command and get its exitcode, stdout and stderr.
"""
args = shlex.split(cmd)
proc = Popen(args, stdout=PIPE, stderr=PIPE)
out, err = proc.communicate()
exitcode = proc.returncode
#
return exitcode, out, err
cmd = "..." # arbitrary external command, e.g. "python mytest.py"
exitcode, out, err = get_exitcode_stdout_stderr(cmd)
For your need, I think you can use a python module to get what you want instead of using the bash cmd line. For example, to get your fully qualified domain name you can use :
socket.getfqdn()

subprocess.Popen process stdout returning empty?

I have this python code
input()
print('spam')
saved as ex1.py
in interactive shell
>>>from subprocess import Popen ,PIPE
>>>a=Popen(['python.exe','ex1.py'],stdout=PIPE,stdin=PIPE)
>>> a.communicate()
(b'', None)
>>>
why it is not printing the spam
Input expects a whole line, but your input is empty. So there is only an exception written to stderr and nothing to stdout. At least provide a newline as input:
>>> a = Popen(['python3', 'ex1.py'], stdout=PIPE, stdin=PIPE)
>>> a.communicate(b'\n')
(b'spam\n', None)
>>>
You are missing stderr piping:
from subprocess import Popen ,PIPE
proc = Popen(['python.exe','ex1.py'], stdout=PIPE, stderr=PIPE)
out, err = proc.communicate()
print(out, err)
What you're looking for is subprocess.check_output

Not able to fetch log files from shell using python

I am trying to use subprocess module with Popen to fetch log from a specified URL, However, I am not able to fetch the log and the program returns me a blank.
I have been using the below mentioned code:
import subprocess
url = r'C:\project\dummy\pro'
mycmd = ['svn', 'log', url]
log = subprocess.Popen(mycmd, shell=True,
stdin = subprocess.PIPE, stdout = subprocess.PIPE,
stderr = subprocess.PIPE)
result = log.wait()
out1, err = log.communicate()
print out1
I need the output string to use as next part of the program. Any help would be appreciated.
Try without shell=True:
log = subprocess.Popen(mycmd,
stdin = subprocess.PIPE, stdout = subprocess.PIPE,
stderr = subprocess.PIPE)

Categories