我的代码是:
#!/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
我的问题是:
- 为什么在第一个
cowsay
和os.popen
的输出中,每行后面都有一个空行? - 为什么第二个cowsay
os.system
的输出末尾添加了一个零?
最佳答案
p.readline 返回的行已经在其末尾附加了换行符。 print
函数添加了一个额外的换行符,总共有两个换行符。这就是为什么每个之间有一个空行。尝试执行 print line.rstrip("\n")
。
os.system
返回一个数字,指示已执行命令的退出状态。 财富 | owsay
退出时没有任何问题,因此其退出代码为零。您的 print
函数没有打印奶牛和语音气球;它们由系统调用本身发送到标准输出。如果您不需要零,则不要打印 retvalue
。
关于Python操作系统输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26938046/