3

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()
Bach
  • 6,145
  • 7
  • 36
  • 61

1 Answers1

3

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."
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
  • Thanks! There is additional problem with my code, I haven't seen it then. subprocess.Popen(["cat", target], stdout=subprocess.PIPE).communicate()[0] will return empty string, because file wasn't closed. – honkingForMoreSleeptime May 12 '14 at 22:42
  • Ok, yes, just add the `close` before the `Popen`... will edit :) thanks for catching that! – A.J. Uppal May 12 '14 at 22:44