Python os output

344 views Asked by At

My code is:

#!/usr/bin/python

## print linux os command output

import os

p = os.popen ('fortune | cowsay',"r")
while 1:
    line = p.readline()
    if not line: break
    print line

retvalue = os.system ("fortune | cowsay")
print retvalue

Output is:

 ______________________________________

< Stay away from flying saucers today. >

 --------------------------------------

        \   ^__^

         \  (oo)\_______

            (__)\       )\/\

                ||----w |

                ||     ||

 ______________________________________
/ Q: What happens when four WASPs find \
| themselves in the same room? A: A    |
\ dinner party.                        /
 --------------------------------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||
0

My questions are:

  1. Why there is an empty line after each line in the output of the first cowsay with os.popen?
  2. Why there is a zero added at the end of the output of the second cowsay os.system?
2

There are 2 answers

1
Kevin On BEST ANSWER

the lines returned by p.readline already have newlines appended to the end of them. The print function adds an additional newline, for a total of two. That's why there's a blank line between each one. try doing print line.rstrip("\n").

os.system returns a number indicating the exit status of the executed command. fortune | cowsay exited without any problems, so its exit code was zero. The cow and speech balloon isn't being printed by your print function; they're being sent to stdout by the system call itself. If you don't want the zero, just don't print retvalue.

0
Scott On

Instead of printing line as is, try doing

print line.rstrip('\n')

The 0 at the end is due to your print retvalue at the end.