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
cowsaywithos.popen? - Why there is a zero added at the end of the output of the second cowsay
os.system?
the lines returned by
p.readlinealready have newlines appended to the end of them. Theprintfunction 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.systemreturns a number indicating the exit status of the executed command.fortune | cowsayexited without any problems, so its exit code was zero. The cow and speech balloon isn't being printed by yourprintfunction; they're being sent to stdout by thesystemcall itself. If you don't want the zero, just don't printretvalue.