Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何获取grep命令(Python)的输出_Python_Grep_Subprocess - Fatal编程技术网

如何获取grep命令(Python)的输出

如何获取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

我有一个输入文件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()
但结果是空字符串

我不知道我遇到了什么问题。你能告诉我怎么解决吗?

试试:

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:是的,你说得对。这个例子充其量是不完整的