如何获取grep命令(Python)的输出
我有一个输入文件test.txt,如下所示:如何获取grep命令(Python)的输出,python,grep,subprocess,Python,Grep,Subprocess,我有一个输入文件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.PIP
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()
但结果是空字符串
我不知道我遇到了什么问题。你能告诉我怎么解决吗?试试:
import subprocess
hosts = subprocess.check_output("grep 'host:' /root/test.txt", shell=True)
print hosts
您的代码应该可以工作,您确定用户有权读取该文件吗 另外,您确定文件中有一个主机:?你的意思可能是:
hosts_process = subprocess.Popen(['grep','host:',file_input], stdout= subprocess.PIPE)
hosts_out, hosts_err = hosts_process.communicate()
另一种解决方案,请尝试Plumbum package():
从plumbum.cmd导入grep
打印(grep(“主机:”,“/root/test.txt”))
打印(grep(“-n”,“host:”,“/root/test.txt”)#“-n”选项
如果grep
在文件中没有发现字符串,是否可能check\u output
抛出子进程。调用的进程错误
异常?@Shai:是的,你说得对。这个例子充其量是不完整的