我尝试构建在我的日志中执行一些 grep 搜索并打印结果的脚本。我尝试使用 Envoy,因为它比 subprocess 更容易,但是当我执行 grep 命令时,它会返回一个错误,即 no such file o directory。
目录结构很简单:
- . # 脚本的根
- test.py # 脚本文件
- web_logs/log/ # 包含要搜索的日志的目录
我的 test.py 很简单:
import envoy
def test(value):
search = "grep 'cv="+str(value)+"' ./web_logs/log/log_*"
print(search) #check of the search string
r = envoy.run(search)
print(r.status_code, r.std_out, r.std_err)#check of the command
response = r.std_out
if __name__ == "__main__":
test(2)
输出是:
grep 'cv=2' ./web_logs/log/log_*
(2, '', 'grep: ./web_logs/log/log_*: No such file or directory\n')
如果我运行相同的命令:
grep 'cv=2' ./web_logs/log/log_*
我可以在日志文件中找到字符串“cv=2”的出现。
错误在哪里?
答案后更新 问题是在使用 * 时,如果不使用 glob 模块,envoy 无法爆炸,所以我按原样使用子流程,并尝试更好地研究使用 glob 模块来改进 envoy。
我使用的新代码是:
import subprocess
def test(value):
search = "grep 'cv="+str(value)+"' ./web_logs/log/log_*"
print(search) #check of the search string
proc = subprocess.check_output(search, shell=True)
print proc.split('\n')
if __name__ == "__main__":
test(2)