def _prepare_code(self, specification): """Prepare the code turning templates into python. :param specification: Specification instance containing template replacement keys/values. :type specification: PluginSpecification """ # process the user entries if specification.gen_makefile: self.populate_template(specification, self.shared_dir, 'Makefile.tmpl', 'Makefile') if specification.gen_pb_tool: self.populate_template(specification, self.shared_dir, 'pb_tool.tmpl', 'pb_tool.cfg') self.populate_template(specification, self.template_dir, '__init__.tmpl', '__init__.py') self.populate_template(specification, self.template_dir, 'module_name.tmpl', '%s.py' % specification.module_name) if specification.gen_scripts: release_script = QFile(os.path.join(self.shared_dir, 'release.sh')) release_script.copy(os.path.join(self.plugin_path, 'release.sh')) plugin_upload = QFile( os.path.join(self.shared_dir, 'plugin_upload.py')) plugin_upload.copy( os.path.join(self.plugin_path, 'plugin_upload.py')) # noinspection PyCallByClass,PyTypeChecker QFile.setPermissions( os.path.join(self.plugin_path, 'plugin_upload.py'), QFile.ReadOwner | QFile.WriteOwner | QFile.ExeOwner | QFile.ReadUser | QFile.WriteUser | QFile.ExeUser | QFile.ReadGroup | QFile.ExeGroup | QFile.ReadOther | QFile.ExeOther)
def method_0(self, iwin32Window_0): if QFile.exists(RunwayList.fileName): fl = QFile.remove(RunwayList.fileName) file0 = QFile(RunwayList.fileName) file0.open(QIODevice.WriteOnly) # f = open(RunwayList.fileName, 'w') # file0.flush() # file0.close() else: file0 = QFile(RunwayList.fileName) file0.open(QIODevice.WriteOnly) # f = open(RunwayList.fileName, 'w') # file0.flush() # file0.close() # file0 = QFile(RunwayList.fileName) # file0.open(QIODevice.WriteOnly) dataStream = QDataStream(file0) dataStream.writeQString(QString("PHXASA")) dataStream.writeInt(3) dataStream.writeInt(len(self)) for runway in self: runway.method_8(dataStream)
def __init__(self, platform, msiFileName, productName, manufacturer, productVersion, language): self.platform = platform self.msiFile = FileObject(msiFileName) self.tempDir = tempfile.mkdtemp() self.productCode = msilib.gen_uuid() self.upgradeCode = msilib.gen_uuid() self.productVersion = productVersion self.manufacturer = manufacturer self.language = language self.productName = productName self.RegsitryComponent = "RegistryComponent" self.registryRecords = [] self.template = QFile(":/files/pyMagicTemplateMSI2.msi") self.template.open(QFile.ReadOnly) data = self.template.readAll() self.templatePath = msiFileName x = QFile(self.templatePath) if x.open(QFile.WriteOnly): print "opened file for write" x.write(data) else: print "could not open file for writing" x.close() self.template.close()
def resolve_path(path, collection_path, search_paths): """Try to resolve the SVG and image path. This is the procedure to check it by order: * It might be a full local path, check if it exists * It might be a url (either local file system or http(s)) * Check in the 'svg' collection path * Check in the 'image' collection path * Check in the search_paths :param path: The original path. :type path: str :param collection_path: The downloaded collection path in local. :type collection_path: str :param search_paths: List of paths to search the image/svg path :type search_paths: str """ # It might be a full path if QFile(path).exists(): return QFileInfo(path).canonicalFilePath() # It might be a url if '://' in path: url = QUrl(path) if url.isValid() and url.scheme() != '': if url.scheme().lower() == 'file': # It's a url to local file path = url.toLocalFile() if QFile(path).exists(): return QFileInfo(path).canonicalFilePath() else: # URL to pointing to online resource return path # Check in the svg collection path file_name = path_leaf(path) svg_collection_path = os.path.join(collection_path, 'svg', file_name) if QFile(svg_collection_path).exists(): return QFileInfo(svg_collection_path).canonicalFilePath() # Check in the image collection path image_collection_path = os.path.join(collection_path, 'image', file_name) if QFile(image_collection_path).exists(): return QFileInfo(image_collection_path).canonicalFilePath() # Still not found, check in the search_paths for search_path in search_paths: local_path = os.path.join(search_path, path) if QFile(local_path).exists(): return QFileInfo(local_path).canonicalFilePath() # Can't find any, just return the original path return path
def load_stylesheet_pyqt5(**kwargs): """ Loads the stylesheet for use in a pyqt5 application. :param pyside: True to load the pyside rc file, False to load the PyQt rc file :return the stylesheet string """ # Smart import of the rc file if kwargs["style"] == "style_Dark": import eslearn.stylesheets.PyQt5_stylesheets.pyqt5_style_Dark_rc if kwargs["style"] == "style_DarkOrange": import eslearn.stylesheets.PyQt5_stylesheets.pyqt5_style_DarkOrange_rc if kwargs["style"] == "style_Classic": import eslearn.stylesheets.PyQt5_stylesheets.pyqt5_style_Classic_rc if kwargs["style"] == "style_navy": import eslearn.stylesheets.PyQt5_stylesheets.pyqt5_style_navy_rc if kwargs["style"] == "style_gray": import eslearn.stylesheets.PyQt5_stylesheets.pyqt5_style_gray_rc if kwargs["style"] == "style_blue": import eslearn.stylesheets.PyQt5_stylesheets.pyqt5_style_blue_rc if kwargs["style"] == "style_black": import eslearn.stylesheets.PyQt5_stylesheets.pyqt5_style_black_rc # Load the stylesheet content from resources from PyQt5.QtCore import QFile, QTextStream f = QFile(":PyQt5_stylesheets/%s.qss" % kwargs["style"]) if not f.exists(): f = QFile(":PyQt5_stylesheets/%s.css" % kwargs["style"]) if not f.exists(): _logger().error("Unable to load stylesheet, file not found in " "resources") return "" else: f.open(QFile.ReadOnly | QFile.Text) ts = QTextStream(f) stylesheet = ts.readAll() if platform.system().lower() == 'darwin': # see issue #12 on github mac_fix = ''' QDockWidget::title { background-color: #31363b; text-align: center; height: 12px; } ''' stylesheet += mac_fix return stylesheet
def _editTemplate(self, templatePath, newName): """ Updates the template document to use the new name. """ templateFile = QFile(templatePath) if not templateFile.open(QIODevice.ReadOnly): QMessageBox.critical(self, QApplication.translate("TemplateDocumentSelector", "Open Operation Error"), \ "{0}\n{1}".format( QApplication.translate("TemplateDocumentSelector", "Cannot read template file."), \ templateFile.errorString() )) return (False, "") templateDoc = QDomDocument() if templateDoc.setContent(templateFile): composerElement = templateDoc.documentElement() titleAttr = composerElement.attributeNode("_title") if not titleAttr.isNull(): titleAttr.setValue(newName) # Try remove file status = templateFile.remove() if not status: return (False, "") # Create new file newTemplatePath = self._composerTemplatesPath() + "/" + newName + ".sdt" newTemplateFile = QFile(newTemplatePath) if not newTemplateFile.open(QIODevice.WriteOnly): QMessageBox.critical(self, QApplication.translate("TemplateDocumentSelector", "Save Operation Error"), \ "{0}\n{1}".format(QApplication.translate("TemplateDocumentSelector", "Could not save template file."), \ newTemplateFile.errorString() )) return (False, "") if newTemplateFile.write(templateDoc.toByteArray()) == -1: QMessageBox.critical(self, QApplication.translate("TemplateDocumentSelector", "Save Error"), \ QApplication.translate("TemplateDocumentSelector", "Could not save template file.")) return (False, "") newTemplateFile.close() return (True, newTemplatePath)
def finished(self): outFn = self.getOutputFileName() if self.needOverwrite: oldFile = QFile(outFn) newFile = QFile(self.tempFile) if oldFile.remove(): newFile.rename(outFn) fileInfo = QFileInfo(outFn) if fileInfo.exists(): if self.base.loadCheckBox.isChecked(): self.addLayerIntoCanvas(fileInfo) QMessageBox.information(self, self.tr("Finished"), self.tr("Processing completed.")) else: QMessageBox.warning(self, self.tr("Warning"), self.tr("{0} not created.").format(outFn))
def writeGcpFile(gc, path): outFile = QFile(path) if (not outFile.open(QIODevice.WriteOnly | QIODevice.Text)): return 'Unable to open GCP file for writing' outStream = QTextStream(outFile) outStream << gc.asCsv() outFile.close()
def load(self): exception = None fh = None try: if self.filename.isEmpty(): raise IOError, "no filename specified for loading" fh = QFile(self.filename) if not fh.open(QIODevice.ReadOnly): raise IOError, unicode(fh.errorString()) stream = QDataStream(fh) magic = stream.readInt32() if magic != MAGIC_NUMBER: raise IOError, "unrecognized file type" fileVersion = stream.readInt16() if fileVersion != FILE_VERSION: raise IOError, "unrecognized file type version" self.ships = [] while not stream.atEnd(): name = QString() owner = QString() country = QString() description = QString() stream >> name >> owner >> country >> description teu = stream.readInt32() self.ships.append(Ship(name, owner, country, teu, description)) self.owners.add(unicode(owner)) self.countries.add(unicode(country)) self.dirty = False except IOError, err: exception = err
def on_pushButton_5_clicked(self): self.listWidget.clear() # 先清空显示 file = QFile("my.xml") if (not file.open(QIODevice.ReadOnly)): raise Exception("open my.xml Err") doc = QDomDocument() status, rrorMsg, errorLine, errorColumn = doc.setContent(file) if (not status): file.close() raise Exception(str(rrorMsg)) file.close() docElem = doc.documentElement() # 返回根元素 n = docElem.firstChild() while (not n.isNull()): if (n.isElement()): e = n.toElement() self.listWidget.addItem(e.tagName() + e.attribute(QString("编号"))) list = e.childNodes() for i in range(list.count()): node = list.at(i) if (node.isElement()): self.listWidget.addItem(" " + node.toElement().tagName() + " : " + node.toElement().text()) n = n.nextSibling()
def open_recent_file(self, action): """ This function opens a recently opened pattern.""" # make sure we ignore menu clicks on non-filename # items (like the clear button) isFile = action.data() if not isFile: return # the actual filename is in the data *not* the # text of the item readFilePath = action.data() if not QFile(readFilePath).exists(): logger.error(msg.patternFileDoesNotExistText % readFilePath) QMessageBox.critical( self, msg.patternFileDoesNotExistTitle, msg.patternFileDoesNotExistText % readFilePath, QMessageBox.Close) return if not self._ok_to_continue_without_saving(): return if self._read_project(readFilePath): self.set_project_save_file(readFilePath) self.mark_project_clean()
def importDOM(self, fname): dom = QDomDocument() error = None fh = None try: fh = QFile(fname) if not fh.open(QIODevice.ReadOnly): raise IOError(str(fh.errorString())) if not dom.setContent(fh): raise ValueError("could not parse XML") except (IOError, OSError, ValueError) as e: error = "Failed to import: {0}".format(e) finally: if fh is not None: fh.close() if error is not None: return False, error try: self.populateFromDOM(dom) except ValueError as e: return False, "Failed to import: {0}".format(e) self.__fname = QString() self.__dirty = True return True, "Imported {0} movie records from {1}".format( len(self.__movies), QFileInfo(fname).fileName())
def get_cdrom_drives(): drives = list(DEFAULT_DRIVES) cdinfo = QFile(LINUX_CDROM_INFO) if cdinfo.open(QIODevice.ReadOnly | QIODevice.Text): drive_names = [] drive_audio_caps = [] line = cdinfo.readLine() while not line.isEmpty(): if line.indexOf(':') != -1: key, values = line.split(':') if key == 'drive name': drive_names = QString(values).trimmed().split(QRegExp("\\s+"), QString.SkipEmptyParts) elif key == 'Can play audio': drive_audio_caps = [v == '1' for v in QString(values).trimmed().split(QRegExp("\\s+"), QString.SkipEmptyParts)] line = cdinfo.readLine() # Show only drives that are capable of playing audio for drive in drive_names: if drive_audio_caps[drive_names.indexOf(drive)]: device = u'/dev/%s' % drive symlink_target = QFile.symLinkTarget(device) if symlink_target != '': device = symlink_target drives.append(device) return sorted(uniqify(drives))
def template_document(self, path): """ Reads the document template file and returns the corresponding QDomDocument. :param path: Absolute path to template file. :type path: str :return: A tuple containing the template document and error message where applicable :rtype: tuple """ if not path: return None, QApplication.translate( "DocumentGenerator", "Empty path to document template") if not QFile.exists(path): return None, QApplication.translate( "DocumentGenerator", "Path to document template " "does not exist") template_file = QFile(path) if not template_file.open(QIODevice.ReadOnly): return None, QApplication.translate("DocumentGenerator", "Cannot read template file") template_doc = QDomDocument() if template_doc.setContent(template_file): return template_doc, "" return None, QApplication.translate( "DocumentGenerator", "Cannot read document template contents")
def go_to_definition(self): self.dirty = True self.results = [] locations = self.get_locations() if self._isVariable: preResults = [ [file_manager.get_basename(x.path), x.path, x.lineno, ''] for x in locations if (x.type == FILTERS['attribs']) and (x.name == self._search) ] else: preResults = [[ file_manager.get_basename(x.path), x.path, x.lineno, '' ] for x in locations if ((x.type == FILTERS['functions']) or (x.type == FILTERS['classes'])) and ( x.name.startswith(self._search))] for data in preResults: file_object = QFile(data[1]) if not file_object.open(QFile.ReadOnly): return stream = QTextStream(file_object) line_index = 0 line = stream.readLine() while not self._cancel and not stream.atEnd(): if line_index == data[2]: data[3] = line self.results.append(data) break #take the next line! line = stream.readLine() line_index += 1 self._search = None self._isVariable = None
def write_file(filename, content): _file = QFile(filename) if not _file.open(QIODevice.WriteOnly | QIODevice.Truncate): raise EdisIOError outfile = QTextStream(_file) outfile << content return filename
def composer_data_source(template_file): """ Creates a ComposerDataSource object from the specified template file. If the file cannot be opened due to file permissions or if it does not exist then the function will return None. :param template_file: Absolute template file path. :type template_file: str :return: Composer data source object. :rtype: ComposerDataSource """ t_file = QFile(template_file) #Check if the file exists if not t_file.exists(): return None #Check if the file can be opened if not t_file.open(QIODevice.ReadOnly): return None template_doc = QDomDocument() #Populate dom document if template_doc.setContent(t_file): return ComposerDataSource.create(template_doc) return None
def accept(self): if self.inputFiles is None: workDir = QDir(self.leInputDir.text()) workDir.setFilter(QDir.Files | QDir.NoSymLinks | QDir.NoDotAndDotDot) nameFilter = ["*.shp", "*.SHP"] workDir.setNameFilters(nameFilter) self.inputFiles = workDir.entryList() if len(self.inputFiles) == 0: QMessageBox.warning( self, self.tr("No shapefiles found"), self.tr("There are no shapefiles in this directory. Please select another one.")) self.inputFiles = None return if self.outFileName is None: QMessageBox.warning( self, self.tr("No output file"), self.tr("Please specify output file.")) return if self.chkListMode.isChecked(): files = self.leInputDir.text().split(";") baseDir = QFileInfo(files[0]).absolutePath() else: baseDir = self.leInputDir.text() # look for shapes with specified geometry type self.inputFiles = ftools_utils.getShapesByGeometryType(baseDir, self.inputFiles, self.cmbGeometry.currentIndex()) if self.inputFiles is None: QMessageBox.warning( self, self.tr("No shapefiles found"), self.tr("There are no shapefiles with the given geometry type. Please select an available geometry type.")) return self.progressFiles.setRange(0, len(self.inputFiles)) outFile = QFile(self.outFileName) if outFile.exists(): if not QgsVectorFileWriter.deleteShapeFile(self.outFileName): QMessageBox.warning(self, self.tr("Delete error"), self.tr("Can't delete file %s") % (self.outFileName)) return if self.inEncoding is None: self.inEncoding = "System" self.btnOk.setEnabled(False) self.mergeThread = ShapeMergeThread(baseDir, self.inputFiles, self.inEncoding, self.outFileName, self.encoding) QObject.connect(self.mergeThread, SIGNAL("rangeChanged( PyQt_PyObject )"), self.setFeatureProgressRange) QObject.connect(self.mergeThread, SIGNAL("checkStarted()"), self.setFeatureProgressFormat) QObject.connect(self.mergeThread, SIGNAL("checkFinished()"), self.resetFeatureProgressFormat) QObject.connect(self.mergeThread, SIGNAL("fileNameChanged( PyQt_PyObject )"), self.setShapeProgressFormat) QObject.connect(self.mergeThread, SIGNAL("featureProcessed()"), self.featureProcessed) QObject.connect(self.mergeThread, SIGNAL("shapeProcessed()"), self.shapeProcessed) QObject.connect(self.mergeThread, SIGNAL("processingFinished()"), self.processingFinished) QObject.connect(self.mergeThread, SIGNAL("processingInterrupted()"), self.processingInterrupted) self.btnClose.setText(self.tr("Cancel")) QObject.disconnect(self.buttonBox, SIGNAL("rejected()"), self.reject) QObject.connect(self.btnClose, SIGNAL("clicked()"), self.stopProcessing) self.mergeThread.start()
def load_stylesheet_pyqt5(): """ Loads the stylesheet for use in a pyqt5 application. :return the stylesheet string """ # Validate that rc files is updated compile_qrc.compile_all() # Smart import of the rc file import qdarkgraystyle.pyqt5_style_rc # Load the stylesheet content from resources from PyQt5.QtCore import QFile, QTextStream f = QFile(':qdarkgraystyle/style.qss') if not f.exists(): _logger().error('Unable to load stylesheet, file not found in ' 'resources') return '' else: f.open(QFile.ReadOnly | QFile.Text) ts = QTextStream(f) stylesheet = ts.readAll() if platform.system().lower() == 'darwin': # see issue #12 on github mac_fix = ''' QDockWidget::title { background-color: #31363b; text-align: center; height: 12px; } ''' stylesheet += mac_fix return stylesheet
def importSAX(self, fname): error = None fh = None try: handler = SaxMovieHandler(self) parser = QXmlSimpleReader() parser.setContentHandler(handler) parser.setErrorHandler(handler) fh = QFile(fname) input = QXmlInputSource(fh) self.clear(False) if not parser.parse(input): raise ValueError(handler.error) except (IOError, OSError, ValueError) as e: error = "Failed to import: {0}".format(e) finally: if fh is not None: fh.close() if error is not None: return False, error self.__fname = QString() self.__dirty = True return True, "Imported {0} movie records from {1}".format( len(self.__movies), QFileInfo(fname).fileName())
def saveCompleteHtml(self, htmlFile): html = QFile(htmlFile) html.open(QIODevice.WriteOnly) savestream = QTextStream(html) css = QFile(self.settings.cssfile) css.open(QIODevice.ReadOnly) # Use a html lib may be a better idea? savestream << "<html><head><meta charset='utf-8'></head>" # Css is inlined. savestream << "<style>" savestream << QTextStream(css).readAll() savestream << "</style>" # Note content savestream << self.toHtml() savestream << "</html>" html.close()
def _replace_results(self): result = QMessageBox.question( self, self.tr("Replace Files Contents"), self.tr("Are you sure you want to replace the content in " "this files?\n(The change is not reversible)"), buttons=QMessageBox.Yes | QMessageBox.No) if result == QMessageBox.Yes: for index in range(self._result_widget.topLevelItemCount()): parent = self._result_widget.topLevelItem(index) root_dir_name = parent.dir_name_root file_name = parent.text(0) file_path = file_manager.create_path(root_dir_name, file_name) file_object = QFile(file_path) if not file_object.open(QFile.ReadOnly): return stream = QTextStream(file_object) content = stream.readAll() file_object.close() pattern = self._find_widget.pattern_line_edit.text() case_sensitive = self._find_widget.case_checkbox.isChecked() type_ = QRegExp.RegExp if \ self._find_widget.type_checkbox.isChecked() else \ QRegExp.FixedString target = QRegExp(pattern, case_sensitive, type_) content.replace(target, self._find_widget.replace_line.text()) file_manager.store_file_content(file_path, content, False)
def WriteUserInfoFile(self): if QFile.exists(self.m_strUserInfoFullName): fl = QFile.remove(self.m_strUserInfoFullName) f = open(self.m_strUserInfoFullName, 'w') f.flush() f.close() else: f = open(self.m_strUserInfoFullName, 'w') # f = open("D:/xml/phxasar.txt") f.flush() f.close() file0 = QFile(self.m_strUserInfoFullName) file0.open(QIODevice.WriteOnly) dataStream = QDataStream(file0) dataStream.writeQString(QString("UserList")) dataStream.writeQString(QString(self.m_strUserInfoFullName)) dataStream.writeQString(QString(self.m_Key)) dataStream.writeQString(QString(self.m_IV)) dataStream.writeInt(len(self.ListUserInfo)) for userInfo in self.ListUserInfo: userInfo.writeData(dataStream) file0.flush() file0.close() return True
def testQgsSVGFillSymbolLayer(self): ''' Create a new style from a .sld file and match test ''' mTestName = 'QgsSVGFillSymbolLayer' mFilePath = QDir.toNativeSeparators('%s/symbol_layer/%s.sld' % (unitTestDataPath(), mTestName)) mDoc = QDomDocument(mTestName) mFile = QFile(mFilePath) mFile.open(QIODevice.ReadOnly) mDoc.setContent(mFile, True) mFile.close() mSymbolLayer = QgsSVGFillSymbolLayer.createFromSld( mDoc.elementsByTagName('PolygonSymbolizer').item(0).toElement()) mExpectedValue = type(QgsSVGFillSymbolLayer()) mValue = type(mSymbolLayer) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 'accommodation_camping.svg' mValue = os.path.basename(mSymbolLayer.svgFilePath()) mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage mExpectedValue = 6 mValue = mSymbolLayer.patternWidth() mMessage = 'Expected "%s" got "%s"' % (mExpectedValue, mValue) assert mExpectedValue == mValue, mMessage
def load_stylesheet_pyqt5(): """ Loads the stylesheet for use in a pyqt5 application. :param pyside: True to load the pyside rc file, False to load the PyQt rc file :return the stylesheet string """ # Smart import of the rc file import vnTrader.qdarkstyle.pyqt5_style_rc # Load the stylesheet content from resources from PyQt5.QtCore import QFile, QTextStream f = QFile(":qdarkstyle/style.qss") if not f.exists(): _logger().error("Unable to load stylesheet, file not found in " "resources") return "" else: f.open(QFile.ReadOnly | QFile.Text) ts = QTextStream(f) stylesheet = ts.readAll() if platform.system().lower() == 'darwin': # see issue #12 on github mac_fix = ''' QDockWidget::title { background-color: #31363b; text-align: center; height: 12px; } ''' stylesheet += mac_fix return stylesheet
def saveQDataStream(self): error = None fh = None try: fh = QFile(self.__fname) if not fh.open(QIODevice.WriteOnly): raise IOError(str(fh.errorString())) stream = QDataStream(fh) stream.writeInt32(MovieContainer.MAGIC_NUMBER) stream.writeInt32(MovieContainer.FILE_VERSION) stream.setVersion(QDataStream.Qt_4_2) for key, movie in self.__movies: stream << movie.title stream.writeInt16(movie.year) stream.writeInt16(movie.minutes) stream << movie.acquired << movie.location \ << movie.notes except EnvironmentError as e: error = "Failed to save: {0}".format(e) finally: if fh is not None: fh.close() if error is not None: return False, error self.__dirty = False return True, "Saved {0} movie records to {1}".format( len(self.__movies), QFileInfo(self.__fname).fileName())
def _deleteDocument(self, templatePath): """ Delete the document template from the file system. """ docFile = QFile(templatePath) return docFile.remove()
def get_searchable_content(self): """ Pulls out tags from the object and returns them in order to be used by the filtered() method. """ f = QFile(self.fileinfo.absoluteFilePath()) f.open(QIODevice.ReadOnly) #stream = QTextStream(f) #stream.setCodec("UTF-8") try: doc = QDomDocument() doc.setContent( f.readAll() ) docelt = doc.documentElement() texts = [] for tagName in FileSystemItem.xmlSearchableTags: nodes = docelt.elementsByTagName(tagName) for i in range(nodes.count()): node = nodes.at(i) value = node.firstChild().toText().data() #print value texts.append( value ) # Add keywords nodes = docelt.elementsByTagName("keywordList") for i in range(nodes.count()): kwnode = nodes.at(i) valnodes = kwnode.toElement().elementsByTagName("value") for j in range(valnodes.count()): value = valnodes.at(j).firstChild().toText().data() texts.append(value) return u' '.join(texts) finally: f.close()
def _grep_file(self, file_path, file_name): """Search for each line inside the file.""" if not self.by_phrase: with open(file_path, 'r') as f: content = f.read() words = [word for word in self.search_pattern.pattern().split('|')] words.insert(0, True) def check_whole_words(result, word): return result and content.find(word) != -1 if not reduce(check_whole_words, words): return file_object = QFile(file_path) if not file_object.open(QFile.ReadOnly): return stream = QTextStream(file_object) lines = [] line_index = 0 line = stream.readLine() while not self._cancel and not (stream.atEnd() and not line): column = self.search_pattern.indexIn(line) if column != -1: lines.append((line_index, line)) #take the next line! line = stream.readLine() line_index += 1 #emit a signal! relative_file_name = file_manager.convert_to_relative( self.root_dir, file_path) self.emit(SIGNAL("found_pattern(PyQt_PyObject)"), (relative_file_name, lines))
def copy_core_configuration(): """ Copies the basic STDM configuration to the user directory if there is none. """ #check network config exist core_config_path = read_network_path() if not QFile.exists(core_config_path): return else: # if not core_config_path: # core_config_path = u'{0}/templates/configuration.stc'.format( # os.path.dirname(__file__) # ) # # #Exit if the core configuration does not exist # if not QFile.exists(core_config_path): # return #File name of previous configuration v1_1_config_path = u'{0}/stdmConfig.xml'.format(USER_PLUGIN_DIR) #Only copy the new one if there is no copy of the previous version # since the version updater will automatically handle the upgrade. if QFile.exists(v1_1_config_path): #Version update will handle the migration return #Copy config assuming that the plugin user folder has no previous # configuration. conf_file = QFile(core_config_path) conf_dest = u'{0}/configuration.stc'.format(USER_PLUGIN_DIR) copy_status = conf_file.copy(conf_dest)