2014-11-14 40 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