0

I have this part of following code:

p = subprocess.Popen(['C:/Python27/python.exe', '-m', 'robot', '-d', logs_directory, input_file], stdout=subprocess.PIPE)
for line in iter(p.stdout.readline, ''):
    output = sys.stdout.write(line)
    #sys.stdout.write(line)
print "\n\n"
print "************************************************"
print  output
print "\n\n"
print "************************************************"
print "\n\n"

But 'output' variable in console shows 'none'

************************************************
None



************************************************

What i am doing wrong here?

user2678074
  • 768
  • 3
  • 9
  • 22
  • related: [Python subprocess get children's output to file and terminal?](http://stackoverflow.com/q/4984428/4279) – jfs Apr 22 '16 at 19:21

3 Answers3

3

sys.stdout.write(line) returns the number of characters written on stdout.

You could write your loop like this:

output = ""
for line in iter(p.stdout.readline, ''):
    output += line
    sys.stdout.write(line)

imho you can also remove the sys.stdout.write(line) part. But I don't know what you are meant to do with it so...

bashrc
  • 4,725
  • 1
  • 22
  • 49
salomonderossi
  • 2,180
  • 14
  • 20
  • sys.stdout.write(line) does return a value. It returns the number of characters written on stdout. – bashrc Apr 22 '16 at 10:10
  • 1- `sys.stdout.write()` returns `None` on Python 2 by default. 2- `output += line` may produce quadratic behavior on some Python implementations. You could use `lines = []; ... lines.append(line) ... output = ''.join(lines)` instead (linear behavior). – jfs Apr 22 '16 at 19:26
1

Try output += line instead of output = sys.stdout.write(line)

pelya
  • 4,326
  • 2
  • 24
  • 23
0

You can also try function check_output.

Here is an example:

>>> subprocess.check_output(["echo", "Hello World!"])
'Hello World!\n'

You can try:

cmd = ['C:/Python27/python.exe', '-m', 'robot', '-d', logs_directory, input_file]
output = subprocess.check_output(cmd)
print output

In most of the cases, it can do the job simply.

For details, you may want to reference to subprocess.check_output

dokelung
  • 206
  • 1
  • 5