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()
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.
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."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With