我们从Python开源项目中,提取了以下15个代码示例,用于说明如何使用PyQt4.QtCore.QFile()。
def main(args=[],app=None): ''' Default main program which starts Qt based on the command line arguments `args', sets the stylesheet if present, then creates the window object and shows it. The `args' list of command line arguments is also passed to the window object to pick up on specified directories. The `app' object would be the QApplication object if this was created elsewhere, otherwise it's created here. Returns the value of QApplication.exec_() if this object was created here otherwise 0. ''' if not app: app = QtGui.QApplication(args) app.setAttribute(Qt.AA_DontUseNativeMenuBar) # in OSX, forces menubar to be in window app.setStyle('Plastique') # load the stylesheet included as a Qt resource with closing(QtCore.QFile(':/css/DefaultUIStyle.css')) as f: if f.open(QtCore.QFile.ReadOnly): app.setStyleSheet(bytes(f.readAll()).decode('UTF-8')) else: print('Failed to read %r'%f.fileName()) browser=DicomBrowser(args) browser.show() return app.exec_() if app else 0
def save_file(self, fileName): '''(file open for writing)-> boolean ''' fname = QtCore.QFile(fileName) if not fname.open(QtCore.QFile.WriteOnly | QtCore.QFile.Text): QtGui.QMessageBox.warning(self, "Application", "Cannot write file %s:\n%s." % (fileName, fname.errorString())) return False outf = QtCore.QTextStream(fname) QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor) outf << self.ui.textEdit.toPlainText() QtGui.QApplication.restoreOverrideCursor() # self.setCurrentFile(fileName); # QtGui.QMessageBox.about(self,'Information',"File saved")
def displaylog_totextedit(self): ''' This method displaying Design messages(log messages)to textedit widget. ''' afile = QtCore.QFile('./Connections/Shear/Finplate/fin.log') if not afile.open(QtCore.QIODevice.ReadOnly): # ReadOnly QtGui.QMessageBox.information(None, 'info', afile.errorString()) stream = QtCore.QTextStream(afile) self.ui.textEdit.clear() self.ui.textEdit.setHtml(stream.readAll()) vscrollBar = self.ui.textEdit.verticalScrollBar(); vscrollBar.setValue(vscrollBar.maximum()); afile.close()
def handle_download(reply): print "Download finish time: {}".format(datetime.now()) print "Finished: {}".format(reply.isFinished()) # print "Bytes received: {}".format(len(reply.readAll())) print(type(reply), dir(reply), help(reply.write)) url = reply.url().path() print(url) # with open("C:\Users\julien.moura\Documents\GIS DataBase\youhou.xml", "wb") as fifi: # fifi.write(reply.writeData()) newFile = QFile() newFile.setFileName("C:\Users\julien.moura\Documents\GIS DataBase\youhou_2.htm") newFile.open(QIODevice.WriteOnly) newFile.write(reply.readAll()) newFile.close() print("done") reply.deleteLater()
def startDownload(self, networkreply, filepath): """ Browser starts a new download """ self.download = networkreply self.filepath = unicode(filepath) self.timestamp = str(time.time()) self.updateMetaData() self.file = QtCore.QFile(self.filepath, self) self.loadedsize = 0 if self.support_resume == True and self.file.exists(): confirm = QtGui.QMessageBox.question(QtGui.QApplication.desktop(), "Overwrite File ?", "The file already exists.\nDo you want to Overwrite old file?", "Continue Remaining", "Replace Old", "Rename") if confirm == 0: self.download.abort() self.download.deleteLater() self.resumeDownload() elif confirm == 1: self.file.resize(0) else: self.filepath = os.path.splitext(self.filepath)[0] + '1' + os.path.splitext(self.filepath)[1] self.file = QtCore.QFile(self.filepath) else: self.file.resize(0) self.filename = QtCore.QFileInfo(self.filepath).fileName() if self.download.isFinished(): self.dataReceived() self.downloadStopped() return self.connect_signals()
def resumeDownload(self): self.file = QtCore.QFile(self.filepath, self) request = QtNetwork.QNetworkRequest(QtCore.QUrl(self.url)) if self.support_resume: self.loadedsize = self.file.size() if str(self.loadedsize) == self.totalsize : return request.setRawHeader('Range', 'bytes={}-'.format(self.loadedsize) ) else: self.file.resize(0) self.loadedsize = 0 self.download = self.nam.get(request)
def downloadFile(self, index=0): self.file = QtCore.QFile(self.download_list[index][0], self) if self.file.exists(): self.file.resize(0) req = QtNetwork.QNetworkRequest(QtCore.QUrl.fromUserInput(self.download_list[index][1])) req.setRawHeader('User-Agent', self.useragent) self.startDownload(req)
def save (self): """Save editor contents to file.""" if not self.filename: title = _("Save File As") res = QtGui.QFileDialog.getSaveFileName(self, title, self.basedir) if not res: # user canceled return self.filename = res self.setWindowTitle(self.filename) else: if not os.path.isfile(self.filename): return if not os.access(self.filename, os.W_OK): return fh = None saved = False try: try: fh = QtCore.QFile(self.filename) if not fh.open(QtCore.QIODevice.WriteOnly): raise IOError(fh.errorString()) stream = QtCore.QTextStream(fh) stream.setCodec("UTF-8") stream << self.editor.text() self.editor.setModified(False) saved = True except (IOError, OSError) as e: err = QtGui.QMessageBox(self) err.setText(str(e)) err.exec_() finally: if fh is not None: fh.close() if saved: self.saved.emit(self.filename) return saved
def load (self, filename): """Load editor contents from file.""" if not os.path.isfile(filename): return if not os.access(filename, os.R_OK): return self.filename = filename if not os.access(filename, os.W_OK): title = u"%s (%s)" % (self.filename, _(u"readonly")) else: title = self.filename self.setWindowTitle(title) fh = None loaded = False try: try: fh = QtCore.QFile(self.filename) if not fh.open(QtCore.QIODevice.ReadOnly): raise IOError(fh.errorString()) stream = QtCore.QTextStream(fh) stream.setCodec("UTF-8") self.setText(stream.readAll()) loaded = True except (IOError, OSError) as e: err = QtGui.QMessageBox(self) err.setText(str(e)) err.exec_() finally: if fh is not None: fh.close() if loaded: self.loaded.emit(self.filename)
def read_gpx_file(self): """ Reads the gpx file contents and creates QDomDocument version of it. """ gpx_file_path = QFile(self.gpx_path) self.document = QDomDocument() status, msg, line, col = self.document.setContent(gpx_file_path) if status: self.gpx_element = self.document.documentElement()
def runFile(self, path=None): file=open(path1,'r') conectsinfo = self.mc.parse_file(file) unique_sources = self.mc.get_unique_src_ips(conectsinfo) unique_destinations = self.mc.get_unique_dst_ips(conectsinfo) unique_ports = self.mc.get_unique_ports(conectsinfo) self.view.resetTransform selected_dst = self.lchbox_dst.selectedItems() selected_dst_ips = [] for x in selected_dst: if str(x.text()) in unique_destinations: selected_dst_ips.append(str(x.text())) selected_src = self.lchbox_src.selectedItems() selected_src_ips = [] for x in selected_src: if str(x.text()) in unique_sources: selected_src_ips.append(str(x.text())) selected_ports = self.lchbox_ports.selectedItems() selected_ports_ips = [] for x in selected_ports: if str(x.text()) in unique_ports: selected_ports_ips.append(str(x.text())) self.mc.create_map(selected_dst_ips,'svg','dot',conectsinfo, selected_src_ips,selected_ports_ips) from mapcreator import g svg_file = QtCore.QFile(g) self.view.runFile(svg_file)
def openFile(self, path=None): global path1; if not path: path = QtGui.QFileDialog.getOpenFileName(self, "Open File", self.currentPath, "pcap file (*.pcapng)") if path: cmd="sudo tshark -r "+str(path)+" -T fields -e ip.addr -e tcp.port -e udp.port -e frame.len |sort > ./tempfile" cmd1="sudo chmod 777 tempfile" cmd2="sed -ri '/\S+\s+\S+\s+\S+/!d' tempfile" os.system(cmd) os.system(cmd1) os.system(cmd2) path="./tempfile" ipsvg_file = QtCore.QFile(path) if not ipsvg_file.exists(): QtGui.QMessageBox.critical(self, "Open File", "Could not open file '%s'." % path) return self.lchbox_dst.clear(); self.lchbox_src.clear(); self.lchbox_ports.clear(); connects_info = [] path1=path file=open(path,'r') pf=self.mc.parse_file(file) dst = self.mc.get_unique_dst_ips(pf) self.lchbox_dst.openFile(dst) src = self.mc.get_unique_src_ips(pf) self.lchbox_src.openFile(src) ports = self.mc.get_unique_ports(pf) self.lchbox_ports.openFile(ports) if not path.startswith(':/'): self.currentPath = path self.setWindowTitle("%s - ips-Graph" % self.currentPath)
def save_inputs(self, uiObj): '''(Dictionary)--> None ''' inputFile = QtCore.QFile('saveINPUT.txt') if not inputFile.open(QtCore.QFile.WriteOnly | QtCore.QFile.Text): QtGui.QMessageBox.warning(self, "Application", "Cannot write file %s:\n%s." % (inputFile, file.errorString())) # yaml.dump(uiObj, inputFile,allow_unicode=True, default_flow_style = False) pickle.dump(uiObj, inputFile)
def parse_xml(self): """Parse the xml file. Returns false if there is failure.""" xml_file = QFile(self._xml_path) if not xml_file.open(QIODevice.ReadOnly): return False document = QDomDocument() if not document.setContent(xml_file): return False xml_file.close() document_element = document.documentElement() if document_element.tagName() != 'qgis_style': return False # Get all the symbols self._symbols = [] symbols_element = document_element.firstChildElement('symbols') symbol_element = symbols_element.firstChildElement() while not symbol_element.isNull(): if symbol_element.tagName() == 'symbol': symbol = QgsSymbolLayerV2Utils.loadSymbol(symbol_element) if symbol: self._symbols.append({ 'name': symbol_element.attribute('name'), 'symbol': symbol }) symbol_element = symbol_element.nextSiblingElement() # Get all the colorramps self._colorramps = [] ramps_element = document_element.firstChildElement('colorramps') ramp_element = ramps_element.firstChildElement() while not ramp_element.isNull(): if ramp_element.tagName() == 'colorramp': colorramp = QgsSymbolLayerV2Utils.loadColorRamp(ramp_element) if colorramp: self._colorramps.append({ 'name': ramp_element.attribute('name'), 'colorramp': colorramp }) ramp_element = ramp_element.nextSiblingElement() return True
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