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:
- Why there is an empty line after each line in the output of the first
cowsay
withos.popen
? - Why there is a zero added at the end of the output of the second cowsay
os.system
?
the lines returned by
p.readline
already have newlines appended to the end of them. Theprint
function adds an additional newline, for a total of two. That's why there's a blank line between each one. try doingprint 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 yourprint
function; they're being sent to stdout by thesystem
call itself. If you don't want the zero, just don't printretvalue
.