2017-04-10 18 views
0

目前,我在使用declare -A的bash中存在限制,以便使用關聯數組並將字符串視爲索引,這是因爲我無法安裝v4.0環境。作爲一種解決方法,我試圖用Python構建我的腳本。這是我想在Python翻譯代碼:如何使用Python中使用包含在字典中的正則表達式使用Python

declare -A regex 
regex[test_one]="line1\|here1" 
regex[test_two]="line2\|here2" 
regex[test_three]="line3\|here3" 
regex[test_four]="line4\|here4" 

echo -n "Enter the path to evaluate...> " 
read path 
for i in "${!regex[@]}" 
do 
     grep -h -r --color=always "${regex["$i"]}" "$path" >> "$i.txt" 
done 

任何幫助,將大大appreciated.Thanks

編輯注:

這是一段代碼,我目前,謝謝到@Harvey

import sys 
import subprocess 

regex = { 
'test_one': r'line1\|here1', 
'test_two': r'line2\|here2', 

} 

sys.stdin.flush() 
path = raw_input("Enter the path to evaluate...> ") 

search = "/bin/sh -c \'grep -h -r'.split()" 
    for name, pattern in regex.items(): 
     with open('{}.txt'.format(name), 'a') as output: 
      cmd = search + [pattern,path] 
     subprocess.call(cmd, stdout=output) 

不過,我已經在Line 18以下錯誤:

Traceback (most recent call last): 
File "./Script.py", line 18, in <module> 
cmd = search + [pattern,path] 
TypeError: cannot concatenate 'str' and 'list' objects 
+0

你有沒有試過用Python寫這個?分享您的代碼並指定問題。 – Harvey

+0

修復此問題:'「/ bin/sh -c \'grep -h -r'.split()」'。 '.split()'在'「字符串之後。擺脫'/ bin/sh'部分。這是沒有必要的。查看我答案中的最新代碼。它已經過測試。 – Harvey

+0

OK !,我改變了你的建議,它只在傳遞命令行參數時起作用,例如:'./script.py/the/path/to/directory',但是如果我不帶參數運行命令,我會得到以下:'path = sys.argv [1]' 'IndexError:列表索引超出範圍' – raver83

回答

1

我認爲這是僅使用標準庫的最佳方法。

這是用於Python 3.對於Python 2,變化:

  • subprocess.run() ==>subprocess.call()
  • input() ==>raw_input()

#!/usr/bin/env python3 

import sys 
import subprocess 

regex = { 
    'test_one': r'line1\|here1', 
    'test_two': r'line2\|here2', 
    'test_three': r'line3\|here2', 
    'test_four': r'line4\|here2', 
} 

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

base_cmd = 'grep -h -r --color=always'.split() 
for name, pattern in regex.items(): 
    with open('{}.txt'.format(name), 'a') as output: 
     cmd = base_cmd + [pattern, path] 
     subprocess.run(cmd, stdout=output) 
+0

我目前正在運行Python 2.7。我根據這個版本做了一些修改:首先,'path = raw_input()'而不是'path = input()',然後是'subprocess.call'而不是'subprocess.run',但是我仍然無法使其工作,因爲shell運行腳本後立即提示以下內容:'usage:grep [-abcDEFGHhIiJLlmnOoqRSsUVvwxZ] [-A num] [-B num] [-C [num]] \t [ - [ - pattern]] - [-f file] [--binary-files = value] [--color = when] \t [--context [= num]] [--directories = action] [--label] [ - 行緩衝] \t [--null] [pattern] [file ...]' – raver83

+0

對於哪個grep的調用?我們告訴shell重定向的那個:「:」?或者我們自己捕獲輸出的那個? – Harvey

+0

我現在有這個: 'sys.stdin.flush() path = raw_input(「Enter the path to evaluate ...>」) search =「/ bin/sh -c \'grep -h -r'.split()「 用於名稱,regex.items()中的模式: with open('{}。txt'.format(name),'a')作爲輸出: cmd = search + [pattern ,路徑]
子流程。調用(cmd,stdout =輸出)' 我也嘗試添加'str(search)',但仍然是: 'Traceback(最近調用最後一個): 文件「./Functional_Check_2.py」,第18行, cmd = str(搜索)+ [模式,路徑] TypeError:無法連接'str'和'list'對象' – raver83

相關問題