【问题标题】:How to implement find command to use input from sys.argv in Python如何在 Python 中实现 find 命令以使用来自 sys.argv 的输入
【发布时间】:2017-09-07 14:07:43
【问题描述】:

我在字典中有一堆用于解析信息的搜索字符串。

my_func_dict = {
    'index_one': r'pattern1'
    'index_two': r'pattern2'
    etc
}

然后我使用以下内容来捕获评估和应用我的搜索字符串的路径,它工作正常。

if len(sys.argv) >= 2:
    location = sys.argv[1]
else:
    location = raw_input("Enter the path to evaluate...>: ")

然后,我迭代字典项以应用搜索命令:

search_cmd = 'grep -h -r'.split()
for name, pattern in my_func_dict.items():
    with open('{}.txt'.format(name), 'a') as output:
        cmd = search_cmd + [pattern, location]
        subprocess.call(cmd, stdout=output)

这适用于少数搜索模式和少数要评估的文件。但在我的情况下,我有许多搜索模式并将它们应用于包含多个文件的文件夹,这些文件包括多种扩展类型:*.txt、*log 等,这需要很长时间。我想先使用find 选项在文件夹路径中仅查找特定文件类型,然后更精确地应用grep 以便更快地获得输出结果。

但以下尝试:

search_cmd = 'find $location -name "*test.txt" -print0 | xargs -0 grep -h -r'.split()
for name, pattern in my_func_dict.items():
    with open('{}.txt'.format(name), 'a') as output:
        cmd = search_cmd + [pattern, location]
        subprocess.call(cmd, stdout=output)

给我一​​个错误:

find: |: unknown primary or operator
find: |: unknown primary or operator
find: |: unknown primary or operator
find: |: unknown primary or operator

如何实现我的search_cmd 以避免此问题?我需要使用-print0xargs -0 作为find 的属性,因为路径中的文件夹名称有空格,例如:/This is the path/for/This Folder。谢谢

【问题讨论】:

  • 这不是我非常了解的东西,但您不应该在 search_cmd = ... 行上遇到语法错误吗?
  • 更改为:search_cmd = 'find $location -name "*test.txt" -print0 | xargs -0 grep -h -r'.split(),这个给出了find: |: unknown primary or operator 错误。
  • 那个有输出重定向而不是管道,但没有什么不同。
  • 在使用 dup 中的建议后仍然无法使其工作:search_cmd = shlex.split("""find $location -name "*test.txt" -print0 | xargs -0 grep -h -r"""),仍然出现以下错误:find: |: unknown primary or operator

标签: python regex grep find associative-array


【解决方案1】:

您可以使用shell=TruePopen 来使用带有完整字符串的子进程。我们还可以使用 Python 在换行符上拆分输出。

import subprocess

mydict = {'.': 'patte', './': '".atty"'}

results = []
for path, pattern in mydict.items():
    cmd = 'find ' + path + ' -type f -name "*.txt" | xargs fgrep -h --basic-regex ' + pattern
    sp = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    response = sp.communicate()
    response = [x.decode('utf-8').strip().split('\n') for x in response if x]
    if response:
        response = response[0] 
        results.append(response)

结果

[['pattern1', 'pattern2'], ['pattycakes', 'patty']]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-16
    • 1970-01-01
    • 2020-12-14
    • 2011-06-13
    • 2021-05-22
    • 1970-01-01
    • 2015-09-07
    相关资源
    最近更新 更多