Displaying console output from subprocess

python, stdout, subprocess

Solution

Use `subprocess.Popen`:

>>> import subprocess
>>> var = subprocess.Popen(['echo', 'hi'], stdout=subprocess.PIPE)
>>> print var.communicate()[0]
hi

>>> 

`myfile.txt`:

Hello there,

This is a test with python

Regards,
Me.

Running:

>>> import subprocess
>>> var = subprocess.Popen(['cat', 'myfile.txt'], stdout=subprocess.PIPE)
>>> print var.communicate()[0]
Hello there,

This is a test with python

Regards,
Me.

>>> 

Also, you have a little bug. You are checking if the target exists, but you probably want to check if the source exists.

Here is your edited code:

from sys import argv
from os.path import exists
import subprocess

script, source, target = argv

print "Copying from %s to %s" % (source, target)

indata = open(source).read()

if exists(source):
    out_file = open(target, 'w')
    out_file.write(indata)
    out_file.close()
    var = subprocess.Popen(["cat", target], stdout=subprocess.PIPE) #how can I get text printed on console by cat?
    out = var.communicate()[0]
    print out
    print "OK."

Problem

I wonder, how can I get the output of subprocess called within Python script? ``` from sys import argv from os.path import exists from subprocess import call script, source, target = argv print "Copying from %s to %s" % (source, target) indata = open(source).read() if exists(target): out_file = open(target, 'w') out_file.write(indata) call(["cat", target]) #how can I get text printed on console by cat? print "OK." out_file.close() ```

Original source

Related problems