如何在 Python 中实现 find 命令以使用 sys.argv 的输入



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

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的属性,因为 path 中的文件夹名称有空格,例如:/This is the path/for/This Folder. 谢谢

您可以使用带有完整字符串的子进程,使用shell=True与 Popen一起使用。我们还可以使用 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']]

最新更新