首页 > 解决方案 > 从python执行时grep无法找到字符串

问题描述

编辑:我使用 Ubuntu 20.04.2 LTS 和 python 3.8.5

我有一个更大的项目,其中有未使用的翻译键。我编写了一个 shell 脚本来完成这项工作。我将一些代码导出到 2 个测试文件,以缩小奇怪行为的范围。我能够重现该错误,但我不明白为什么会发生。

if sudo grep -r --include=\*.{js,html,json} --exclude-dir={node_modules,locale} 404_custom_error ../myreactproject/
then
    echo 'found'
else
    echo 'not found'
fi

如果我通过终端运行它,它会被找到。

import os
import subprocess

os.system("./testing.sh")
subprocess.call(['sh', 'testing.sh'])

但是当我从 python 文件中执行它时,它会得到一个“未找到”。

os.getcmd() -> /home/{name}/projects/translation-cleaner
echo $PWD   -> /home/{name}/projects/translation-cleaner

注意:python文件和shell脚本在同一个目录下。另一个项目位于 /home/{name}/projects/myreactproject。

在 ../myreactproject/src/views/Pages/Page404/Page404Admin.js 中可以找到该特定键:

标签: pythonbash

解决方案


我有 2 个解决方案,但我之前没有在以前的 Windows 10 机器上测试过它们,因为我现在完全迁移到 linx:

合适的:

subprocess.call(['bash', './testing.sh'])

最脏的:我不得不从我的 shell 脚本中删除所有的括号。所以我的 grep 命令如下所示:

grep -qr --include=*.js --include=*.html --include=*.json --exclude-dir=node_modules --exclude-dir=locale 404_custom_error ../myreactproject/;

推荐阅读