【问题标题】:Python os outputPython 操作系统输出
【发布时间】:2015-01-12 07:40:42
【问题描述】:

我的代码是:

#!/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. 为什么第二个cowsayos.system的输出末尾加了一个零?

【问题讨论】:

    标签: python linux operating-system os.system


    【解决方案1】:

    p.readline 返回的行已经在它们的末尾附加了换行符。 print 函数添加了一个额外的换行符,总共两个。这就是为什么每个人之间有一个空行。试试print line.rstrip("\n")

    os.system 返回一个数字,表示已执行命令的退出状态。 fortune | cowsay 退出时没有任何问题,因此其退出代码为零。 print 函数没有打印奶牛和语音气球; system 调用本身将它们发送到标准输出。如果你不想要零,就不要打印retvalue

    【讨论】:

    • 感谢@kevin,您的回答非常好。 python新手,还在学习。感谢帮助!这很有趣!
    【解决方案2】:

    不要按原样打印行,而是尝试做

    print line.rstrip('\n')
    

    最后的 0 是由于你最后的print retvalue

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-23
      • 2011-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-22
      相关资源
      最近更新 更多