Created
March 15, 2012 14:14
-
-
Save D3f0/2044392 to your computer and use it in GitHub Desktop.
Grep files using Qt with grep
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# encoding: utf-8 | |
import sys | |
import os | |
import sip | |
import re | |
from operator import itemgetter | |
# Qt | |
sip.setapi('QString', 2) | |
from PyQt4.Qt import * | |
_ = lambda s:s | |
GREP_OUTPUT_RE = re.compile(r'^(?P<path>[\//\w\.]+)[\s:](?P<lineno>\d+)[\s:](?P<line>.+)?') | |
class FileGrepModel(QStandardItemModel): | |
recordFound = pyqtSignal(object) | |
procs = [] | |
__searchLocations = [] | |
COLUMNS = ( | |
('path', _(u'Archivo')), | |
('lineno', _(u'#')), | |
('line', _(u'Coincidencia')), | |
) | |
def __init__(self, parent = None): | |
super(FileGrepModel, self).__init__(parent) | |
self.setColumnCount(len(self.COLUMNS)) | |
for n, (re_group, title) in enumerate(self.COLUMNS): | |
self.setHeaderData(n, Qt.Horizontal, title) | |
self.recordFound.connect(self.appendRecord) | |
@property | |
def searchLocations(self): | |
return self.__searchLocations | |
@searchLocations.setter | |
def searchLocations(self, locations): | |
if isinstance(locations, basestring): | |
locations = [ locations ] | |
for loc in locations: | |
if os.path.exists(loc): | |
self.__searchLocations.append(os.path.dirname(loc)) | |
def _launchSearchProcess(self, term, location): | |
proc = QProcess(self) | |
proc.finished.connect(self.searchProcessFinished) | |
proc.readyReadStandardOutput.connect(self.readStandardOutput) | |
proc.start('grep', ['-R', '-n', '-e', '%s' % term, location]) | |
return proc | |
def searchProcessFinished(self, exitCode, exitStatus): | |
print "Terminando %s" % self.sender() | |
index = self.procs.index(self.sender()) | |
self.procs.pop(index) | |
def search(self, term): | |
''' Buscar una cadena con Grep''' | |
if not self.searchLocations: | |
QMessageBox.critical(None, "Error", "No se definieron ubicaciones donde buscar") | |
return | |
if self.procs: | |
for proc in procs: | |
proc.kill() | |
self.removeRows(0, self.rowCount()) | |
for loc in self.searchLocations: | |
searchProc = self._launchSearchProcess(term, loc) | |
self.procs.append( searchProc ) | |
print searchProc | |
def readStandardOutput(self): | |
print "read" | |
proc = self.sender() | |
count, matches = 0, 0 | |
while proc.canReadLine(): | |
line = str(proc.readLine()).strip() | |
count += 1 | |
match = GREP_OUTPUT_RE.search(line) | |
if not match: | |
matches += 1 | |
print "ERROR: ### %s ###" % line | |
continue | |
d = match.groupdict() | |
self.appendRecord(d) | |
print d | |
def appendRecord(self, matchdict): | |
items = [ | |
QStandardItem(os.path.basename(matchdict['path'])), | |
QStandardItem(matchdict['lineno']), | |
QStandardItem(matchdict['line'][:100]) | |
] | |
self.appendRow(items) | |
QApplication.processEvents() | |
class Tabla(QWidget): | |
def __init__(self, parent = None): | |
super(Tabla, self).__init__(parent) | |
self.setupUi(self) | |
# Model | |
model = FileGrepModel(self) | |
model.searchLocations = [os.getcwd(), ] | |
self.tableView.setModel(model) | |
model.rowsInserted.connect(lambda *foo: self.adjust) | |
model.rowsRemoved.connect(lambda *foo: self.adjust) | |
self.lineEdit.returnPressed.connect(self.searchModel) | |
def adjust(self): | |
print "Adjust" | |
self.tableView.resizeRowsToContents() | |
self.tableView.resizeColumnsToContents() | |
def searchModel(self): | |
text = self.lineEdit.text() | |
#print "Vamos a buscar", text | |
if not text: | |
return | |
self.tableView.model().search(text) | |
def setupUi(self, widget): | |
layout = QVBoxLayout() | |
self.lineEdit = QLineEdit() | |
layout.addWidget(self.lineEdit) | |
self.tableView = QTableView() | |
layout.addWidget(self.tableView) | |
self.tableView.verticalHeader().hide() | |
self.setLayout(layout) | |
def main(): | |
app = QApplication(sys.argv) | |
win = Tabla() | |
win.show() | |
return app.exec_() | |
if __name__ == "__main__": | |
sys.exit(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment