【问题标题】:how to get output of grep command (Python)如何获取 grep 命令的输出(Python)
【发布时间】:2012-10-09 22:43:58
【问题描述】:

我有一个输入文件 test.txt:

host:dc2000
host:192.168.178.2

我想通过以下方式获取这些机器的所有地址:

grep "host:" /root/test.txt 

等等,我通过python得到命令输出:

import subprocess
file_input='/root/test.txt'
hosts=subprocess.Popen(['grep','"host:"',file_input], stdout= subprocess.PIPE)
print hosts.stdout.read()

但结果是空字符串。

我不知道我遇到了什么问题。你能建议我如何解决吗?

【问题讨论】:

    标签: python grep subprocess


    【解决方案1】:

    试试看:

    import subprocess
    hosts = subprocess.check_output("grep 'host:' /root/test.txt", shell=True)
    print hosts
    

    【讨论】:

    • 如果grep在文件中没有找到字符串,check_output是否有可能抛出subprocess.CalledProcessError异常?
    【解决方案2】:

    你的代码应该可以工作,你确定用户有读取文件的权限吗?

    另外,您确定文件中有"host:" 吗?你可能是这个意思:

    hosts_process = subprocess.Popen(['grep','host:',file_input], stdout= subprocess.PIPE)
    hosts_out, hosts_err = hosts_process.communicate()
    

    【讨论】:

    • @Shai:是的,你是对的。该示例充其量是不完整的
    【解决方案3】:

    另一种解决方案,试试 Plumbum 包(https://plumbum.readthedocs.io/):

    from plumbum.cmd import grep print(grep("host:", "/root/test.txt")) print(grep("-n", "host:", "/root/test.txt")) #'-n' option

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-31
      相关资源
      最近更新 更多