【问题标题】:Issues with os.popen and scutilos.popen 和 scutil 的问题
【发布时间】:2012-06-17 22:55:58
【问题描述】:

我需要来自scutil 命令的信息。当我在终端上运行scutil -d -r xyz.com 时。我可以看到几行输出。 但是当我执行scutil -d -r xyz.com > file.txt 时,文件中只能看到类似flags = 0x00000002 (Reachable) 的命令输出的最后一行。

我正在从 python 运行这个命令,我需要这个命令的全部内容。 我在python中运行的方式是:

import os

output = os.popen('scutil -r -d yahoo.com').read()
print output

输出是:

标志 = 0x00000002(可达)

但我也需要这里命令的所有输出。请让我知道是否有任何解决此问题的方法。

【问题讨论】:

    标签: python macos shell unix networking


    【解决方案1】:

    scutil 将信息打印到stderr 尝试使用&> file.txt 而不是> file.txt

    在python中尝试使用:

    import commands 
    print commands.getstatusoutput("scutil -d -r xyz.com")
    

    【讨论】:

    • commands 已被弃用......使用它作为答案可能不是一个好主意。你或许可以使用subprocess.check_output("scutil -d -r xyz.com", stderr=subprocess.STDOUT, shell=True) 来达到同样的效果。
    • @Michael:感谢分享。我正在尝试 subprocess.Popen(['scutil','-d',' -r',domain],shell=False,stdout=subprocess.PIPE) 但是你建议的东西就像魅力一样。再次感谢。
    • @user1424975 我把它作为答案,所以除了我们在 cmets 中的线程之外,还有一些东西要指出。
    【解决方案2】:

    os.popenis deprecated since 2.6
    该文档提供了使用 subprocess 模块替换 os.popen 的入门指南:
    http://docs.python.org/library/subprocess.html#replacing-os-popen-os-popen2-os-popen3

    应用于您的代码的示例:

    import subprocess
    my_process = subprocess.Popen('scutil -r -d yahoo.com', 
                                  shell=True,
                                  stdout=subprocess.PIPE, 
                                  stderr=subprocess.PIPE)
    out, err = my_process.communicate()
    print out
    print err
    

    【讨论】:

      【解决方案3】:

      你可能会使用subprocess.check_output("scutil -d -r xyz.com", stderr=subprocess.STDOUT, shell=True)

      import subprocess
      
      output = subprocess.check_output("scutil -d -r xyz.com", stderr=subprocess.STDOUT, shell=True)
      print(output)
      

      您应该注意 check_output 命令发生的两件事:

      1. stderr=subprocess.STDOUT 将错误输出流通过管道传输到标准输出
      2. shell=True 通过 shell 执行命令。这使您可以访问运行 shell 进程的同一环境。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-24
        • 1970-01-01
        • 2015-10-15
        • 2011-03-21
        • 1970-01-01
        • 1970-01-01
        • 2013-07-28
        • 1970-01-01
        相关资源
        最近更新 更多