Python subprocess调用Unix命令,关于输出存储的问题
我正在写一个Python脚本,这个脚本的功能是读取一行文字,然后调用Unix系统,使用grep命令在一个查询文件中搜索包含这行文字的内容,最后把结果打印出来。
from subprocess import call
for line in infilelines:
output = call(["grep", line, "path/to/query/file"])
print output
print line`
当我查看打印到屏幕上的结果时,我会看到从查询文件中匹配的字符串列表,但同时也会看到“1”和“0”这两个数字,而line
这个内容却从来没有打印出来。我原本期待的是能看到查询文件中与我搜索的字符串匹配的行,后面还应该跟着我用来搜索的字符串。
3 个回答
-2
为什么你要在Python中调用外部的grep
命令呢?其实Python自己也能做到这件事。这样做会增加额外的负担,而且你的代码还得依赖于grep
这个工具必须安装在你的电脑上。下面是用Python的“in”操作符来实现简单的grep
功能的方法。
query=open("/path/to/query/file").readlines()
query=[ i.rstrip() for i in query ]
f=open("file")
for line in f:
if "line" in query:
print line.rstrip()
f.close()
4
以下代码适用于 Python 版本 2.5 及以上:
from commands import getoutput
output = getoutput('grep %s path/to/query/file' % line)
output_list = output.splitlines()
6
调用会返回进程的返回代码。
如果你使用的是 Python 2.7,建议使用 check_output。
from subprocess import check_output
output = check_output(["grep", line, "path/to/query/file"])
如果你使用的是更早的版本,那就用 communicate。
import subprocess
process = subprocess.Popen(["grep", line, "path/to/query/file"], stdout=subprocess.PIPE)
output = process.communicate()[0]
这会为标准输出(stdout)打开一个管道,你可以通过 communicate 来读取。如果你还想获取错误输出(stderr),需要加上 "stderr=subprocess.PIPE"。
这样会返回完整的输出。如果你想把输出分成多行,可以使用 split。
output.split('\n')
我相信 Python 会帮你处理换行符的问题,但因为你在用 grep,我猜你是在 Unix 系统上,那里换行符是 \n。
http://docs.python.org/library/subprocess.html#subprocess.check_output