Python操作系统输出
我的代码是:Python操作系统输出,python,linux,operating-system,os.system,Python,Linux,Operating System,Os.system,我的代码是: #!/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 输出为: _____
#!/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
______________________________________
<今天远离飞碟。>
--------------------------------------
\ ^__^
\(oo)\_______
(__)\ )\/\
||----w|
|| ||
______________________________________
/问:当四只黄蜂发现它们时会发生什么\
|他们在同一个房间吗?A:A|
\晚宴/
--------------------------------------
\ ^__^
\(oo)\_______
(__)\ )\/\
||----w|
|| ||
0
我的问题是:
os.popen
的第一个cowsay
的输出中,每行后面都有一个空行os.system
的输出末尾添加了零尝试这样做,而不是按原样打印行
print line.rstrip('\n')
结尾处的0是由于结尾处的
print retvalue
造成的。由p.readline
返回的行已在其末尾追加了新行。print
功能添加了一个额外的换行符,总共两行。这就是为什么每一条之间都有一个空白行。尝试执行打印line.rstrip(“\n”)
os.system
返回一个数字,指示已执行命令的退出状态fortune | cowsay
退出时没有出现任何问题,因此其退出代码为零。您的print
功能未打印cow和speech气球;它们被系统
调用本身发送到stdout。如果你不想要零,就不要打印retvalue
谢谢@kevin你的答案非常有效。python新手,仍在学习中。谢谢你的帮助!这很有趣!!