Using pure Python over grep? -


i not familiar grep i've been on windows system when suggested add these lines code, i'm little confused...

grep = 'grep -e \'@import.*{}\' * -l'.format(name) proc = popen(grep, shell=true, cwd=info['path'], stdout=pipe, stderr=pipe) 

from understanding, trying find files in cwd contain @import given_file_name essentially, right?

if how grep works, need write in python me, i'm worried time may take such thing.

the script in sublime text 3 plugin runs sublime_plugin.eventlistener method on_post_save find files containing saved filename , build list of file names compile.

def files_that_import(filename, project_root):     files = []     root, dirnames, files in os.walk(project_root):         fn in files:             if fn.endswith(('.scss', '.sass')):                 open(fn, 'r') f:                     data = f.read()                 if re.search(r'@import.*["\']{}["\'];'.format(fn), data):                     files.append(fn)     return files 

not knowing how grep works, best think of. however, said, i'm worried time take scan through .scss , .sass files. while there shouldn't ton of them, getting contents each seems it's more complicated be.

updated

i updated code using @nneonneo corrections. noticed in code used, checking each file @import statement itself.

def files_that_import(filename, project_root):     pattern = re.compile('''@import.*["']{}["'];'''.format(filename))     found = []     root, dirnames, files in os.walk(project_root):         fn in files:             if fn.endswith(('.scss', '.sass')):                 open(fn, 'r') f:                     if any(pattern.search(line) line in f):                         found.append(fn)     return found 

update if finds useful , wants use code, changed files = [] found = [] since files being defined in loop os.walk() causing error.

you've got it. can make bit more efficient doing following:

import_pattern = re.compile(r'''@import.*["']{}["'];'''.format(fn)) open(fn, 'r') f:     line in f:         if import_pattern.match(line):             files.append(fn)             break 

this scan through each line, , break finds looking for. should faster reading whole file.


Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -

firemonkey - How do I make a beep sound in Android using Delphi and the API? -