Python子进程调用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
永远不会打印到屏幕上。我希望从查询文件中获取与我的字符串匹配的行,后跟我在搜索中使用的字符串。
I am writing a python script that reads a line/string, calls Unix, uses grep to search a query file for lines that contain the string, and then prints the results.
from subprocess import call
for line in infilelines:
output = call(["grep", line, "path/to/query/file"])
print output
print line`
When I look at my results printed to the screen, I will get a list of matching strings from the query file, but I will also get "1" and "0" integers as output, and line
is never printed to the screen. I expect to get the lines from the query file that match my string, followed by the string that I used in my search.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
调用返回进程返回码。
如果使用 Python 2.7,请使用 check_output。
如果在此之前使用任何内容,请使用通信。
这将打开一个标准输出管道,您可以通过通信来读取它。如果您也想要 stderr,则还需要添加“stderr=subprocess.PIPE”。
这将返回完整的输出。如果您想将其解析为单独的行,请使用 split。
我相信Python会为你处理行结束转换,但由于你使用的是grep,我将假设你在Unix上,行结束无论如何都是\n。
http://docs.python.org/library/subprocess.html#subprocess.check_output
call returns the process return code.
If using Python 2.7, use check_output.
If using anything before that, use communicate.
This will open a pipe for stdout that you can read with communicate. If you want stderr too, you need to add "stderr=subprocess.PIPE" too.
This will return the full output. If you want to parse it into separate lines, use split.
I believe Python takes care of line-ending conversions for you, but since you're using grep I'm going to assume you're on Unix where the line-ending is \n anyway.
http://docs.python.org/library/subprocess.html#subprocess.check_output
以下代码适用于 Python >= 2.5:
The following code works with Python >= 2.5:
当 Python 本身可以执行对外部
grep
的调用时,为什么要执行呢?这是额外的开销,您的代码将依赖于安装的grep
。这就是在 Python 中使用“in”运算符执行简单grep
的方法。Why would you want to execute a call to external
grep
when Python itself can do it? This is extra overhead and your code will then be dependent ongrep
being installed. This is how you do simplegrep
in Python with "in" operator.