Python3-执行find xargs grep结果的结果与shell不同

时间:2020-04-11 12:19:10

标签: python-3.x find popen xargs colon

我正在尝试确定文件是否包含特定字符串。为此,我在外壳中使用以下命令:

find ~/my_json_files -iname "*.json" | xargs -d "\n" grep -w "\"_id\": \"asdf-qwer-yxcv-dfgh\"" -l

它输出json文件的路径和名称,其中包含确切的字符串。

如果我使用popen在python中复制完全相同的命令,则返回值为空:

find_result = os.popen('find ~/my_json_files -iname "*.json" | xargs -d "\n" grep -w "\"_id\": \"asdf-qwer-yxcv-dfgh\"" -l').read()

我发现如果删除搜索字符串,直到_id与实际ID之间的冒号,它将返回以下内容:

find_result = os.popen('find ~/my_json_files -iname "*.json" | xargs -d "\n" grep -w "\"_id\"" -l').read()

但是,一旦我将"\"_id\"放在冒号(如"\"_id\":)中,它将不再起作用。

如果我将终端用于同一命令,则可以找到一些东西。

:有什么特别之处,以至于Python3中的popen无法使用?我在这里想念什么吗?

非常感谢您的帮助,因为此问题看起来很特殊。

编辑:

如果仅使用grep,则冒号完全相同:

grep "\"_id\": \"asdf-qwer-yxcv-dfgh\"" ~/my_json_files/*.json -l

解决方案:

如果将使用原始字符串(将r放在字符串前面),这两个命令均有效:

find_result = os.popen(r'find ~/my_json_files -iname "*.json" | xargs -d "\n" grep -w "\"_id\": \"asdf-qwer-yxcv-dfgh\"" -l').read()

但是我仍然不知道为什么结肠会影响它,因为我认为转义的字符会导致错误,这些错误发生在结肠之前?

0 个答案:

没有答案
相关问题