Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No output from Python subprocess

I'm using Python 3.5.1 and Windows 10. I can't get subprocess to put output to the screen. So let's start with something simple:

import subprocess
process = subprocess.run('echo hi', shell=True, stdout=subprocess.PIPE)

When I run my python module, I want to it to print 'hi' in the Python Shell. The script runs and does not return an error, but it prints nothing to the screen.

I have also tried many different flavors of subprocess (i.e. Popen), but still no luck. I have a feeling this has something to do with the way my Windows/Python environment is setup, but I don't really know where to start. Thoughts?


Update

So I now understand that my original code sample should not have put anything on the screen; however, when I run

import subprocess
p = subprocess.run('echo hi', shell=True)

I get no output. When I run:

import subprocess
p = subprocess.run('echo hi', shell=True, stdout=subprocess.PIPE)
print(p.stdout)

I do get output. Why did the first example not work?

like image 509
David Avatar asked Oct 21 '25 11:10

David


1 Answers

It's not printing to the screen because you're redirecting the output to a PIPE. Remove the pipe argument and the output will go to the normal stdout

You can use subprocess.call also.

subprocess.call('echo hi', shell=True)

If you want to pipe the output, you should use Popen instead

process = subprocess.Popen('echo hi', shell=True, stdout=subprocess.PIPE)
process.wait()
print process.stdout.read()

If you want to decode the result as UTF-8 format, just add .decode('UTF-8')

process.stdout.read().decode('utf-8')
like image 159
Brendan Abel Avatar answered Oct 22 '25 23:10

Brendan Abel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!