2014-11-14 138 views
2

我的代码是:Python的OS输出

#!/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 

输出是:

______________________________________ 

< 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 

我的问题是:

  1. 为什么在输出每行后一个空行第一个cowsayos.popen
  2. 为什么有被添加在第二cowsay os.system的输出端部的零?

回答

3

p.readline返回的行已经有追加到它们的端部的换行。 print函数会添加一个额外的换行符,总共两个换行符。这就是为什么每个人之间都有一条空白线。尝试做print line.rstrip("\n")

os.system返回一个数字,指示执行的命令的退出状态。 fortune | cowsay没有任何问题退出,所以退出代码为零。牛和语音气球没有被您的print功能打印;他们被system调用本身发送到标准输出。如果你不想要零,只是不要打印retvalue

+0

谢谢@kevin你的回答非常好。新的Python和仍然学习。感谢帮助!这个很有趣!! – 0x2 2014-11-15 01:53:08

2

除了打印线的原样,尝试做

print line.rstrip('\n') 

的0末是由于你print retvalue末。

+0

谢谢@scott它的工作! – 0x2 2014-11-15 01:53:34