Python操作系统输出

标签 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

输出是:

 ______________________________________

< 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的输出末尾添加了一个零?

最佳答案

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

os.system 返回一个数字,指示已执行命令的退出状态。 财富 | owsay 退出时没有任何问题,因此其退出代码为零。您的 print 函数没有打印奶牛和语音气球;它们由系统调用本身发送到标准输出。如果您不需要零,则不要打印 retvalue

关于Python操作系统输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26938046/

相关文章:

c - Flex 在 C 中使用管道

python - PyQt:在系统托盘应用程序中显示菜单

linux - 在linux中回显路径有什么作用?

linux - Oracle表单运行表单小程序但没有响应

multithreading - 系统在程序中的哪些点切换线程

c - 我应该使用哪个编译标志 -> Os 或 O2?

python - 导入包时如何说服 Python 从子模块导入类?

python - 如何复制 tensorflow 层?

python - 从 patsy 中的 DesignMatrix 获取名称

linux - 无法访问 apache http 服务器上的 .mov 文件