2

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 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks @kevin your answer worked perfectly well. new to python and still learning. thanks for help! this is fun!!
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.