def readDir(self, dir, readSubs, tiefe, feedback): #fileList = [ QFileInfo ] #Schleife für alle Einträge des Verzeichnises listOfFiles = os.listdir(dir) total = 100 if len(listOfFiles) > 0: total = 100.0 / len(listOfFiles) #for n,file in enumerate( os.listdir( dir ) ): for n, file in enumerate(listOfFiles): filePath = (os.path.join(dir, file)) info = QFileInfo(filePath) #print( dir, info.isFile(), info.isDir( )) if info.exists() and info.isFile(): self.fileList.append(info) #print (info.fileName(), info.size(), info.birthTime(), info.lastModified()) elif info.exists() and info.isDir() and readSubs == True: # rekursive if Sub Dir self.readDir(filePath, True, tiefe + 1, feedback) else: pass #next if tiefe == 1: # Update the progress bar in level 1 feedback.setProgress(int(n + 1 * total)) else: feedback.setProgress(int(100)) feedback.pushInfo("No files in directory! " + dir) return #fileList
def _file_change_handler(self, path): """ https://stackoverflow.com/a/30076119 Some text editors delete and re-write the file when they save. When the file is deleted, Qt will stop watching it. To get around this, we can wait a short time to see if the file returns. :param str path: The path of the changed file. """ self.logger.debug('File changed (%s)', path) file_info = QFileInfo(path) time_slept = 0.0 sleep_for = 0.1 # Sleep up to 1 second while waiting for the file to be re-created while not file_info.exists() and time_slept < 1.0: self.logger.debug('File deleted... waiting (%s)', path) time_slept += sleep_for sleep(sleep_for) if file_info.exists(): self.logger.debug('File exists (%s)', path) self.watcher.addPath(path) self.update_viewer() else: # File deleted ? self.logger.debug('File deleted, not re-adding watcher (%s)', path)
def check_create_button_active_state(): quizz_name_empty = bool(quizz_name_edit.text()) csv_file_path_empty = bool(csv_file_path_edit.text()) ffmpeg_path_edit_empty = bool(ffmpeg_path_edit.text()) csv_file_exits = QFileInfo.exists(csv_file_path_edit.text()) output_folder_edit_empty = bool(output_folder_edit.text()) output_folder_exists = QFileInfo.exists(output_folder_edit.text()) create_btn.setEnabled( quizz_name_empty and csv_file_path_empty and csv_file_exits and ffmpeg_path_edit_empty and output_folder_edit_empty and output_folder_exists)
def restoreDir(self): "用户点击了“默认运行目录”按钮。" path = self.txtPath.text().strip() fi = QFileInfo(path) if path == "" or not fi.exists(): return self.txtDir.setText(fi.dir().absolutePath())
def __setFileName(self, fileName): """ Private method to set the file name to save the download into. @param fileName name of the file to save into @type str """ fileInfo = QFileInfo(fileName) WebBrowserWindow.downloadManager().setDownloadDirectory( fileInfo.absoluteDir().absolutePath()) self.filenameLabel.setText(fileInfo.fileName()) self.__fileName = fileName # check file path for saving saveDirPath = QFileInfo(self.__fileName).dir() if not saveDirPath.exists(): if not saveDirPath.mkpath(saveDirPath.absolutePath()): self.progressBar.setVisible(False) self.on_stopButton_clicked() self.infoLabel.setText( self.tr("Download directory ({0}) couldn't be created."). format(saveDirPath.absolutePath())) self.__setDateTime() return self.filenameLabel.setText(QFileInfo(self.__fileName).fileName())
def on_btnInfo_exists2_clicked(self): self.__showBtnInfo(self.sender()) fileInfo = QFileInfo(self.ui.editFile.text()) if fileInfo.exists(): self.ui.textEdit.appendPlainText("True \n") else: self.ui.textEdit.appendPlainText("False \n")
def on_new_wallet(self): # TODO: Было бы круто использовать стандартные методы dialog = NewWalletDialog(self.__current_path) if dialog.exec() == QDialog.Accepted: directory = dialog.directory() wallet_name = dialog.wallet_name() if not wallet_name: return file_name = '%s/%s' % (directory, wallet_name) if QFileInfo.exists(file_name): result = QMessageBox.question(self, tr('MyWallet', 'Create new wallet'), tr('MyWallet', 'Wallet \'%s\' already exists. Rewrite?') % wallet_name) if result == QMessageBox.No: return if not wallet_name.endswith('.db'): file_name = '%s.db' % file_name try: WalletModel.create_new_wallet(file_name) except WalletModelException as e: QMessageBox.critical(self, tr('MyWallet', 'Create new wallet'), str(e)) else: QMessageBox.information(self, tr('MyWallet', 'Create new wallet'), tr('MyWallet', 'Wallet \'%s\' was created') % wallet_name)
def open(self, file_name): """Open the file at the given path for reading. Args: file_name (str): File path of the file to open. Only .wav files permitted. Raises: FileNotFoundError: If the filename given cannot be opened. """ if file_name is not None: file_info = QFileInfo(file_name) if file_info.exists(): self.file_name = file_name # Update the waveform data wave_read = wave.open(file_name, 'r') self.waveform_info = wave_read.getparams() step = int(self.waveform_info.framerate / self.stored_fps) self.waveform_data = list(bytesToInts( data=wave_read.readframes(-1), channelWidth=self.waveform_info.sampwidth, numChannels=self.waveform_info.nchannels, signed=True, step=step)) # Update the media player url = QUrl.fromLocalFile(file_info.absoluteFilePath()) self.media_player.setMedia(QMediaContent(url)) # Send out appropriate event self.signalFileChanged.emit() wave_read.close() else: raise FileNotFoundError('No file exists at given file path')
def generate_pj_info(self): """ triggered by button add 1. create new project info dict every time 2. extract project name and address from LineEdit; check if exist and if it is cas and msh file 3. when second step done, get journal path from get_journal function :return: signal_add_pj(dict) """ self.pj_dict = { "project_name": '', "project_address": '', "journal": '' } if self.checkbox_journal.isChecked(): case_path = QFileInfo(self.edit_journal_address.text()) else: case_path = QFileInfo(self.edit_project_address.text() ) # QFileInfo can deeply analyze path info accepted_file_type = ['cas', 'msh', 'h5', 'jou'] if (case_path.exists()) and (case_path.suffix() in accepted_file_type): self.pj_dict["project_name"] = case_path.baseName() self.pj_dict["project_address"] = case_path.absolutePath() self.pj_dict['journal'] = self.get_journal(case_path, case_path.fileName()) self.signal_add_pj.emit(self.pj_dict) self.close() print('generate new project:', self.pj_dict) else: QMessageBox.warning(self, self.make_trans('warning'), self.make_trans('no_case_mesh'), QMessageBox.Yes, QMessageBox.Yes) print('file not exists')
def restoreDir(self): "用户点击了“默认运行目录”按钮。" path = self.txtPath.text().strip() fi = QFileInfo(path) if path == "" or not fi.exists(): return self.txtDir.setText(fi.dir().absolutePath())
def _getFileName(self) -> str: #Get base file name from a absolute path fileInfo = QFileInfo(self._path) if not fileInfo.exists(): return "" else: return fileInfo.fileName()
def executables(self): path = QFileInfo(self.gameDirectory(), "_windows/darkest.exe") if not path.exists(): path = QFileInfo(self.gameDirectory(), "_windowsnosteam/darkest.exe") return [ mobase.ExecutableInfo("Darkest Dungeon", path), ]
def setFileIcon(self, path): "每当txtPath的值改变时,就设置快捷方式的图标" fi = QFileInfo(path) if not fi.exists(): self.shortcutIcon = QIcon(":/images/unknown.png") else: ip = QFileIconProvider() self.shortcutIcon = ip.icon(fi) self.btnFace.setIcon(self.shortcutIcon)
def setFileIcon(self, path): "每当txtPath的值改变时,就设置快捷方式的图标" fi = QFileInfo(path) if not fi.exists(): self.shortcutIcon = QIcon(":/images/unknown.png") else: ip = QFileIconProvider() self.shortcutIcon = ip.icon(fi) self.btnFace.setIcon(self.shortcutIcon)
def resolveAnySymlink(file_name: str) -> str: """ Some OSs have different extensions for linked files (for example, one possibility is .lnk-files on Windows). In such cases, the literal .lnk file will be attempted to open, not the file this resolves: """ info = QFileInfo(file_name) if info.exists() and info.isSymLink( ): # Use 'exists': Not certain to be a literal file, depending on subclass. file_name = info.symLinkTarget() return file_name
def handle_file_changed(self, path): """Handle when a watched file gets changed Crazy stuff ahead. If a file is modified, some editors (systems?) will first remove the file and then write it back to the disk. And for that split second, the watcher will drop the file from being watched. But then again, maybe that file really got deleted? Who knows?! Anyway, when a file gets modified, we sleep a short while to see if that file will "get back" and if so, add it back to the watcher. If not, we'll assume the file got deleted. """ if not self.__is_path_watched(path): fileinfo = QFileInfo(path) total_slept = 0 file_exists = fileinfo.exists() while not file_exists: sleep_for = 0.1 total_slept += sleep_for if total_slept > 1: break time.sleep(sleep_for) file_exists = fileinfo.exists() if file_exists: self.watcher.addPath(path) self.refresh_document(path) else: # file got deleted? path_key = self.get_path_key(path) document = self.open_documents[path_key] self.document_removed.emit(document) elif self.__is_path_watched(path): self.refresh_document(path)
def restore(settings): finfo = QFileInfo(settings.fileName()) if finfo.exists() and finfo.isFile(): for w in qApp.allWidgets(): mo = w.metaObject() if w.objectName() in ['username_text_box', 'password_text_box', 'forget_password']: for i in range(mo.propertyCount()): name = mo.property(i).name() val = settings.value("{}/{}".format(w.objectName(), name), w.property(name)) w.setProperty(name, val)
def add_song(self, song_path): if song_path.split(".")[-1] not in ["mp3", "flac", "ogg"]: raise AssertionError song = self.path_to_song(song_path) filepath = song.path fileInfo = QFileInfo(filepath) if fileInfo.exists(): url = QUrl.fromLocalFile(fileInfo.absoluteFilePath()) if fileInfo.suffix().lower() == "mp3" or "flac" or "ogg": self.playlist.addMedia(QMediaContent(url)) self.songs.append(song)
def addShapeToCanvas( shapefile_path ): file_info = QFileInfo( shapefile_path ) if file_info.exists(): layer_name = file_info.completeBaseName() else: return False vlayer_new = QgsVectorLayer( shapefile_path, layer_name, "ogr" ) if vlayer_new.isValid(): QgsProject.instance().addMapLayers( [vlayer_new] ) return True else: return False
def checkDiskSpace(self, path: str): # noinspection PyCallByClass if self.spaceWarningDelivered or not QFileInfo.exists(path): return info = QStorageInfo(path) available = info.bytesAvailable() / 1000 / 1000 if available < VideoService.spaceWarningThreshold: warnmsg = 'There is less than {0}MB of disk space available at the target folder selected to save ' + \ 'your media. VidCutter WILL FAIL to produce your media if you run out of space during ' + \ 'operations.' QMessageBox.warning(self.parent, 'Disk space is low!', warnmsg.format(VideoService.spaceWarningThreshold)) self.spaceWarningDelivered = True
def Output(filename, output_dir, mod, suffix, rewrite=True, index=-1): """ Take input filename, output dir path, and make a new filename using mod and suffix. Rewrite a file by default. Can be used with Blister.Threading(). """ METHOD_NAME = f"Blister.Output" thread_id = Blister.ThreadID(index) if mod != "": mod = "_" + mod if (suffix != ""): suffix = "." + suffix fileinfo_old = QFileInfo(filename) fileinfo = QFileInfo(QDir(output_dir), fileinfo_old.baseName() + mod + suffix) if (fileinfo.exists() and (not fileinfo.isFile())): print(f"{thread_id}{METHOD_NAME}: This path is a dir:\n{thread_id}\t{fileinfo.absoluteFilePath()}", end='\n') return False if ((fileinfo.exists() and (not fileinfo.isWritable())) or ((not fileinfo.exists()) and (not QFileInfo(fileinfo.absolutePath()).permission(QFile.WriteUser)))): print(f"{thread_id}{METHOD_NAME}: Writing this file is not permitted:\n{thread_id}\t{fileinfo.absoluteFilePath()}", end='\n') return False if (fileinfo.exists() and (rewrite == False)): fileinfo = QFileInfo(QDir(output_dir), fileinfo_old.baseName()+ "_" + str(int(time.time()) % 100000) + suffix) print(f"{thread_id}{METHOD_NAME}: File to write already exists [rewriting is forbidden]. It will be renamed:\n{thread_id}\t{fileinfo_old.absoluteFilePath()} --> {fileinfo.absoluteFilePath()}", end='\n') return fileinfo.absoluteFilePath()
def openPrevImage(self): # print("openPrevImage") fi = QFileInfo(self.filepath) if not fi.exists() : return filename = fi.fileName() basedir = fi.absolutePath() # This does not include filename file_filter = ["*.jpg", "*.jpeg", "*.png", "*.gif", "*.svg", "*.bmp", "*.tiff"] image_list = fi.dir().entryList(file_filter) index = image_list.index(filename) prevfile = image_list[index-1] self.openFile(basedir + '/' + prevfile)
def create_wallet(database): target_dir = QFileInfo(database).absoluteDir() if not target_dir.exists(): QDir().mkdir(target_dir.absolutePath()) db = sqlite3.connect(database) cursor = db.cursor() try: for cq in WalletDatabase.__WALLET_INIT_WALLET_QUERY: cursor.execute(cq) except sqlite3.Error as e: raise WalletDatabaseException(tr('WalletDatabase', 'Failed to create wallet: %s') % e) db.commit() db.close()
def openOnStart(self, name): fileInfo = QFileInfo(name) if fileInfo.exists(): url = QUrl.fromLocalFile(fileInfo.absoluteFilePath()) if fileInfo.suffix().lower() == 'm3u': self.playlist.load(url) else: self.playlist.addMedia(QMediaContent(url)) else: url = QUrl(name) if url.isValid(): self.playlist.addMedia(QMediaContent(url)) print("added Files to playlist")
def check_result(self): """ check if fluent produced result :return: str(describe result) """ case_path = self.running_project[0]["project_address"] case_name = self.running_project[0]["project_name"] result_txt = case_path + "\\%s_result\\totalresult.txt" % case_name result_file = QFileInfo(result_txt) if result_file.exists(): return 'result produced' else: return 'no result'
def addToPlaylist(self, fileNames): for name in fileNames: fileInfo = QFileInfo(name) if fileInfo.exists(): url = QUrl.fromLocalFile(fileInfo.absoluteFilePath()) if fileInfo.suffix().lower() == 'm3u': self.playlist.load(url) else: self.playlist.addMedia(QMediaContent(url)) else: url = QUrl(name) if url.isValid(): self.playlist.addMedia(QMediaContent(url))
def _load_audio(self): filename = os.path.join(self.audio_path, "{:03}.mp3".format(self._song_number)) self.playlist.clear() fileInfo = QFileInfo(filename) if fileInfo.exists(): url = QUrl.fromLocalFile(fileInfo.absoluteFilePath()) if fileInfo.suffix().lower() == 'm3u': self.playlist.load(url) else: self.playlist.addMedia(QMediaContent(url)) self._loading_audio = True self.player.play()
def addToPlaylist(self, fileNames): for name in fileNames: fileInfo = QFileInfo(name) if fileInfo.exists(): url = QUrl.fromLocalFile(fileInfo.absoluteFilePath()) if fileInfo.suffix().lower() == 'm3u': self.playlist.load(url) else: self.playlist.addMedia(QMediaContent(url)) else: url = QUrl(name) if url.isValid(): self.playlist.addMedia(QMediaContent(url))
def handle_file_changed(self, path): """Handle when a watched file gets changed Crazy stuff ahead. If a file is modified, some editors (systems?) will first remove the file and then write it back to the disk. And for that split second, the watcher will drop the file from being watched. But then again, maybe that file really got deleted? Who knows?! Anyway, when a file gets modified, we sleep a short while to see if that file will "get back" and if so, add it back to the watcher. If not, we'll assume the file got deleted. """ if not self.__is_path_watched(path): fileinfo = QFileInfo(path) total_slept = 0 file_exists = fileinfo.exists() while not file_exists: sleep_for = 0.1 total_slept += sleep_for if total_slept > 1: break time.sleep(sleep_for) file_exists = fileinfo.exists() if file_exists: self.watcher.addPath(path) self.refresh_document(path) else: # file got deleted? pass
def checkDiskSpace(self, path: str) -> None: # noinspection PyCallByClass if self.spaceWarningDelivered or not QFileInfo.exists(path): return info = QStorageInfo(path) available = info.bytesAvailable() / 1000 / 1000 if available < VideoService.spaceWarningThreshold: warnmsg = 'There is less than {}MB of free disk space in the '.format(VideoService.spaceWarningThreshold) warnmsg += 'folder selected to save your media. ' warnmsg += 'VidCutter will fail if space runs out before processing completes.' spacewarn = VCMessageBox('Warning', 'Disk space alert', warnmsg, self.parentWidget()) spacewarn.addButton(VCMessageBox.Ok) spacewarn.exec_() self.spaceWarningDelivered = True
def openNextImage(self): fi = QFileInfo(self.filepath) if not fi.exists(): return filename = fi.fileName() basedir = fi.absolutePath() # This does not include filename file_filter = [ "*.jpg", "*.jpeg", "*.png", "*.gif", "*.svg", "*.bmp", "*.tiff" ] image_list = fi.dir().entryList(file_filter) index = image_list.index(filename) if index == len(image_list) - 1: index = -1 nextfile = image_list[index + 1] self.openFile(basedir + '/' + nextfile)
def Dir(dir_path, create=True): """ Take dir path, return absolute path, or False if error. Create new folder by default. """ METHOD_NAME = f"Blister.Dir" if type(dir_path) != type(str()): print(f"{METHOD_NAME}: Invalid input type {type(dir_path)}. String only.", end='\n') return False dir_info = QFileInfo(dir_path) if (dir_info.exists() and (not dir_info.permission(QFile.WriteUser))): print(f"{METHOD_NAME}: Writing in this dir is not permitted:\n\t{dir_info.absoluteFilePath()}", end='\n') return False if ((not dir_info.exists()) and (not create)): print(f"{METHOD_NAME}: This dir does not exist [creating new is forbidden]:\n\t{dir_info.absoluteFilePath()}", end='\n') return False if ((not dir_info.exists()) and create): result = QDir.mkpath(QDir(), dir_info.absoluteFilePath()) if not result: print(f"{METHOD_NAME}: Creating new dir was failed:\n\t{dir_info.absoluteFilePath()}", end='\n') return False else: print(f"{METHOD_NAME}: New dir was created:\n\t{dir_info.absoluteFilePath()}", end='\n') return dir_info.absoluteFilePath()
def open(self, t_filename=None): settings = QSettings(QSettings.IniFormat, QSettings.UserScope, "pySPM", "pySPM") if t_filename is None: home = QDir.cleanPath(os.getenv("HOMEPATH")) path = settings.value("lastPath", home) self.filename = QFileDialog.getOpenFileName( None, "Choose measurement file", path, "*.ita") else: self.filename = t_filename check_file = QFileInfo(self.filename) self.setWindowTitle(check_file.fileName()) if not check_file.exists() or not check_file.isFile(): return settings.setValue("lastPath", check_file.path()) self.ita = pySPM.ITA(self.filename) self.t, self.S = self.ita.getSpectrum(time=True) self.sf, self.k0 = self.ita.get_mass_cal() self.mass = pySPM.utils.time2mass(self.t, self.sf, self.k0) self.spec = self.ax.plot(self.mass, self.S)[0] SatLevel = self.ita.size['pixels']['x'] * self.ita.size['pixels'][ 'y'] * self.ita.Nscan self.sat_level = self.ax.axhline(SatLevel, color='r') if 'pySPM' in self.ita.root.goto("MassScale"): self.MassCal = [] N = self.ita.root.goto("MassScale/pySPM/N").get_ulong() for i in range(N): elt = self.ita.root.goto("MassScale/pySPM/" + str(i) + "/elt").value.decode('utf8') mass = self.ita.root.goto("MassScale/pySPM/" + str(i) + "/mass").get_double() time = self.ita.root.goto("MassScale/pySPM/" + str(i) + "/time").get_double() self.MassCal.append(dict(elt=elt, mass=mass, time=time)) else: self.MassCal = [] for x in self.ita.root.goto("MassScale/calib"): if x.name == 'assign': self.MassCal.append({'elt': x.get_string()}) if x.name == 'mcp': mcp = struct.unpack("<10d", x.value) self.MassCal[-1]['time'] = mcp[0] self.MassCal[-1]['mass'] = mcp[1] self.DoMassCal()
def prepareAPIs(self, ondemand=False, rawList=None): """ Public method to prepare the APIs if necessary. @keyparam ondemand flag indicating a requested preparation (boolean) @keyparam rawList list of raw API files (list of strings) """ if self.__apis is None or self.__inPreparation: return needsPreparation = False if ondemand: needsPreparation = True else: # check, if a new preparation is necessary preparedAPIs = self.__preparedName() if preparedAPIs: preparedAPIsInfo = QFileInfo(preparedAPIs) if not preparedAPIsInfo.exists(): needsPreparation = True else: preparedAPIsTime = preparedAPIsInfo.lastModified() apifiles = sorted( Preferences.getEditorAPI(self.__language, self.__projectType)) if self.__apifiles != apifiles: needsPreparation = True for apifile in apifiles: if (QFileInfo(apifile).lastModified() > preparedAPIsTime): needsPreparation = True break if needsPreparation: # do the preparation self.__apis.clear() if rawList: apifiles = rawList else: apifiles = Preferences.getEditorAPI(self.__language, self.__projectType) for apifile in apifiles: self.__apis.load(apifile) self.__apis.prepare() self.__apifiles = apifiles
def get_journal(self, case_path, file_type): """ if checbox checked, it will use own journal which fill in the LineEdit_journal if not checked, it will use default_journal func to get default journal :param case_path: :return: journal file path """ if self.checkbox_journal.isChecked(): jou_path = QFileInfo(self.edit_journal_address.text()) if (jou_path.exists()) and (jou_path.suffix() == "jou"): return jou_path.filePath() else: QMessageBox.warning(self, self.make_trans('warning'), self.make_trans('no_journal'), QMessageBox.Yes, QMessageBox.Yes) else: jou_file = self.default_journal(case_path, file_type) return jou_file
def on_main_window_start(main_window): main_window.theme_menu = main_window.menuBar().addMenu( main_window.tr('Themes')) themes_directory = QFileInfo('themes') if themes_directory.exists(): active_theme = ThemeManager.get_active_theme() path = themes_directory.absoluteFilePath() group_action = QActionGroup(main_window) group_action.setExclusive(True) for theme in os.listdir(path): action = QAction(theme, main_window) action.setData(theme) action.setCheckable(True) if theme == active_theme: action.setChecked(True) action.changed.connect(ThemeManager.wrapper(main_window)) group_action.addAction(action) group_action.addAction(action) main_window.theme_menu.addAction(action)
def on_main_window_start(main_window): main_window.theme_menu = main_window.menuBar().addMenu( main_window.tr('Themes')) themes_directory = QFileInfo('themes') if themes_directory.exists(): active_theme = ThemeManager.get_active_theme() path = themes_directory.absoluteFilePath() group_action = QActionGroup(main_window) group_action.setExclusive(True) for theme in os.listdir(path): action = QAction(theme, main_window) action.setData(theme) action.setCheckable(True) if theme == active_theme: action.setChecked(True) action.changed.connect(ThemeManager.wrapper(main_window)) group_action.addAction(action) group_action.addAction(action) main_window.theme_menu.addAction(action)
def prepareAPIs(self, ondemand=False, rawList=None): """ Public method to prepare the APIs if necessary. @keyparam ondemand flag indicating a requested preparation (boolean) @keyparam rawList list of raw API files (list of strings) """ if self.__apis is None or self.__inPreparation: return needsPreparation = False if ondemand: needsPreparation = True else: # check, if a new preparation is necessary preparedAPIs = self.__defaultPreparedName() if preparedAPIs: preparedAPIsInfo = QFileInfo(preparedAPIs) if not preparedAPIsInfo.exists(): needsPreparation = True else: preparedAPIsTime = preparedAPIsInfo.lastModified() apifiles = sorted( Preferences.getEditorAPI(self.__language)) if self.__apifiles != apifiles: needsPreparation = True for apifile in apifiles: if QFileInfo(apifile).lastModified() > \ preparedAPIsTime: needsPreparation = True break if needsPreparation: # do the preparation self.__apis.clear() if rawList: apifiles = rawList else: apifiles = Preferences.getEditorAPI(self.__language) for apifile in apifiles: self.__apis.load(apifile) self.__apis.prepare() self.__apifiles = apifiles
def loadRasterfileToCanvas(prjpath, layerName): """Loads a raste to canvas.""" if isLayerLoaded(layerName): return True pathFilename=os.path.join(prjpath, layerName+".tif") file_info = QFileInfo(pathFilename) if file_info.exists(): layer_name = file_info.completeBaseName() else: message="Error loading raster"+pathFilename QMessageBox.critical(None, 'Error', message, QMessageBox.Ok) return False layeropts=QgsRasterLayer.LayerOptions(True) rlayer_new = QgsRasterLayer( pathFilename, layer_name, 'gdal', layeropts ) if rlayer_new.isValid(): QgsProject.instance().addMapLayer(rlayer_new) return True else: return False
def open(self, filename): """Open the file at the given path for reading. Args: filename (str): File path of the file to open. Only .wav files permitted. """ if filename is not None: fileInfo = QFileInfo(filename) if fileInfo.exists(): wave_read = wave.open(filename, 'r') waveform = list(bytesToInts( wave_read.readframes(-1), wave_read.getsampwidth(), wave_read.getnchannels())) self.filename = filename self.waveform = waveform self.signalFileChanged.emit() else: raise FileNotFoundError('No file exists at given file path')
def init_config(self): """ Restore if possible all the widgets to their state saved into a given configuration """ # If a configuration has already been saved in a file, get its path if self.settings.contains("latest_config"): self.config_file_path = self.settings.value("latest_config") # Create a Qt info file required to save the state of each widget info_file = QFileInfo(self.config_file_path) # Initialize the Qt settings file self.latest_config = QSettings(self.config_file_path, QSettings.IniFormat) # Introspect all the children widgets and call their restore_config() function if info_file.exists() and info_file.isFile(): widget_names = self.latest_config.childGroups() for widget_name in widget_names: widget = self.findChild( self.str_to_class(widget_name + "/type"), widget_name) widget.restore_config(self.latest_config)
def createRequest(self, op, request, outgoingData=None): """ Public method to create a request. @param op the operation to be performed (QNetworkAccessManager.Operation) @param request reference to the request object (QNetworkRequest) @param outgoingData reference to an IODevice containing data to be sent (QIODevice) @return reference to the created reply object (QNetworkReply) """ if op == QNetworkAccessManager.GetOperation: fileInfo = QFileInfo(request.url().toLocalFile()) if not fileInfo.isDir() or \ not fileInfo.isReadable() or \ not fileInfo.exists(): return None from .FileReply import FileReply return FileReply(request.url(), self.parent()) else: return None
def fromPath(cls, path): # type: (str) -> ImportItem """ Create a `ImportItem` from a local file system path. """ iconprovider = QFileIconProvider() basename = os.path.basename(path) item = cls() item.setText(basename) item.setToolTip(path) finfo = QFileInfo(path) if finfo.exists(): item.setIcon(iconprovider.icon(finfo)) else: item.setIcon(iconprovider.icon(QFileIconProvider.File)) item.setData(path, ImportItem.PathRole) if not os.path.isfile(path): item.setEnabled(False) item.setToolTip(item.toolTip() + " (missing from filesystem)") return item
def createRequest(self, op, request, outgoingData=None): """ Public method to create a request. @param op the operation to be performed (QNetworkAccessManager.Operation) @param request reference to the request object (QNetworkRequest) @param outgoingData reference to an IODevice containing data to be sent (QIODevice) @return reference to the created reply object (QNetworkReply) """ if op == QNetworkAccessManager.GetOperation: fileInfo = QFileInfo(request.url().toLocalFile()) if not fileInfo.isDir() or \ not fileInfo.isReadable() or \ not fileInfo.exists(): return None from .FileReply import FileReply return FileReply(request.url(), self.parent()) else: return None
def fromPath(cls, path): # type: (str) -> ImportItem """ Create a `ImportItem` from a local file system path. """ iconprovider = QFileIconProvider() basename = os.path.basename(path) item = cls() item.setText(basename) item.setToolTip(path) finfo = QFileInfo(path) if finfo.exists(): item.setIcon(iconprovider.icon(finfo)) else: item.setIcon(iconprovider.icon(QFileIconProvider.File)) item.setData(path, ImportItem.PathRole) if not os.path.isfile(path): item.setEnabled(False) item.setToolTip(item.toolTip() + " (missing from filesystem)") return item
def open(self, t_filename=None): settings = QSettings(QSettings.IniFormat, QSettings.UserScope, "pySPM", "pySPM") if t_filename is None: home = QDir.cleanPath(os.getenv("HOMEPATH")) path = settings.value("lastPath", home) self.filename = QFileDialog.getOpenFileName(None, "Choose measurement file", path, "*.ita") else: self.filename = t_filename check_file = QFileInfo(self.filename) self.setWindowTitle(check_file.fileName()) if not check_file.exists() or not check_file.isFile(): return settings.setValue("lastPath", check_file.path()) self.ita = pySPM.ITA(self.filename) self.t, self.S = self.ita.getSpectrum(time=True) self.sf, self.k0 = self.ita.get_mass_cal() self.mass = pySPM.utils.time2mass(self.t, self.sf, self.k0) self.spec = self.ax.plot(self.mass, self.S)[0] SatLevel = self.ita.size['pixels']['x']*self.ita.size['pixels']['y']*self.ita.Nscan self.sat_level = self.ax.axhline(SatLevel, color='r') if 'pySPM' in self.ita.root.goto("MassScale"): self.MassCal = [] N = self.ita.root.goto("MassScale/pySPM/N").get_ulong() for i in range(N): elt = self.ita.root.goto("MassScale/pySPM/"+str(i)+"/elt").value.decode('utf8') mass = self.ita.root.goto("MassScale/pySPM/"+str(i)+"/mass").get_double() time = self.ita.root.goto("MassScale/pySPM/"+str(i)+"/time").get_double() self.MassCal.append(dict(elt=elt, mass=mass, time=time)) else: self.MassCal = [] for x in self.ita.root.goto("MassScale/calib"): if x.name == 'assign': self.MassCal.append({'elt':x.get_string()}) if x.name == 'mcp': mcp = struct.unpack("<10d", x.value) self.MassCal[-1]['time'] = mcp[0] self.MassCal[-1]['mass'] = mcp[1] self.DoMassCal()
def _getChannelInfo(self) -> [[object]]: #Get channel's informations from tdms file #load units from units.json file f = open("units.json", 'r') units = json.load(f) f.close() fileInfo = QFileInfo(self._path) if not fileInfo.exists(): return [[]] tdms = TdmsFile(self._path) group = tdms.groups()[0] #There is only one data group in TdmsFile chnObjs = tdms.group_channels(group) chnInfos = [] for chnObj in chnObjs: properties = chnObj.properties chnName = chnObj.channel try: chnUnit = properties['NI_UnitDescription'] except KeyError: chnUnit = "unknown" try: chnType = units[chnUnit]["number"] chnUnitDesc = units[chnUnit]["unit_desc"] except KeyError: chnType = 0 chnUnitDesc = "unknown" chnInfo = [chnName, chnType, chnUnit, chnUnitDesc] chnInfos.append(chnInfo) return chnInfos
def open(self): fileName = QFileDialog.getOpenFileName(self, "Open File")[0] fileInfo = QFileInfo(fileName) if fileInfo.exists(): url = QUrl.fromLocalFile(fileInfo.absoluteFilePath()) self.changeMedia(QMediaContent(url))
def main(): # Initialise. defaultContext = "@default" fetchedTor = MetaTranslator() codecForTr = '' codecForSource = '' tsFileNames = [] uiFileNames = [] verbose = False noObsolete = False metSomething = False numFiles = 0 standardSyntax = True metTsFlag = False tr_func = None translate_func = None # Parse the command line. for arg in sys.argv[1:]: if arg == "-ts": standardSyntax = False argc = len(sys.argv) i = 1 while i < argc: arg = sys.argv[i] i += 1 if arg == "-help": printUsage() sys.exit(0) if arg == "-version": sys.stderr.write("pylupdate5 v%s\n" % PYQT_VERSION_STR) sys.exit(0) if arg == "-noobsolete": noObsolete = True continue if arg == "-verbose": verbose = True continue if arg == "-ts": metTsFlag = True continue if arg == "-tr-function": if i >= argc: sys.stderr.write( "pylupdate5 error: missing -tr-function name\n") sys.exit(2) tr_func = sys.argv[i] i += 1 continue if arg == "-translate-function": if i >= argc: sys.stderr.write( "pylupdate5 error: missing -translate-function name\n") sys.exit(2) translate_func = sys.argv[i] i += 1 continue numFiles += 1 fullText = "" if not metTsFlag: f = QFile(arg) if not f.open(QIODevice.ReadOnly): sys.stderr.write( "pylupdate5 error: Cannot open file '%s'\n" % arg) sys.exit(1) t = QTextStream(f) fullText = t.readAll() f.close() if standardSyntax: oldDir = QDir.currentPath() QDir.setCurrent(QFileInfo(arg).path()) fetchedTor = MetaTranslator() codecForTr = '' codecForSource = '' tsFileNames = [] uiFileNames = [] for key, value in proFileTagMap(fullText).items(): for t in value.split(' '): if key == "SOURCES": fetchtr_py(QDir.current().absoluteFilePath(t), fetchedTor, defaultContext, True, codecForSource, tr_func, translate_func) metSomething = True elif key == "TRANSLATIONS": tsFileNames.append(QDir.current().absoluteFilePath(t)) metSomething = True elif key in ("CODEC", "DEFAULTCODEC", "CODECFORTR"): codecForTr = t fetchedTor.setCodec(codecForTr) elif key == "CODECFORSRC": codecForSource = t elif key == "FORMS": fetchtr_ui(QDir.current().absoluteFilePath(t), fetchedTor, defaultContext, True) updateTsFiles(fetchedTor, tsFileNames, codecForTr, noObsolete, verbose) if not metSomething: sys.stderr.write( "pylupdate5 warning: File '%s' does not look like a " "project file\n" % arg) elif len(tsFileNames) == 0: sys.stderr.write( "pylupdate5 warning: Met no 'TRANSLATIONS' entry in " "project file '%s'\n" % arg) QDir.setCurrent(oldDir) else: if metTsFlag: if arg.lower().endswith(".ts"): fi = QFileInfo(arg) if not fi.exists() or fi.isWritable(): tsFileNames.append(arg) else: sys.stderr.write( "pylupdate5 warning: For some reason, I " "cannot save '%s'\n" % arg) else: sys.stderr.write( "pylupdate5 error: File '%s' lacks .ts extension\n" % arg) else: fi = QFileInfo(arg) if fi.suffix() in ("py", "pyw"): fetchtr_py(fi.absoluteFilePath(), fetchedTor, defaultContext, True, codecForSource, tr_func, translate_func) else: fetchtr_ui(fi.absoluteFilePath(), fetchedTor, defaultContext, True) if not standardSyntax: updateTsFiles(fetchedTor, tsFileNames, codecForTr, noObsolete, verbose) if numFiles == 0: printUsage() sys.exit(1)
def __getFileName(self): """ Private method to get the file name to save to from the user. """ if self.__gettingFileName: return import Helpviewer.HelpWindow downloadDirectory = Helpviewer.HelpWindow.HelpWindow\ .downloadManager().downloadDirectory() if self.__fileName: fileName = self.__fileName originalFileName = self.__originalFileName self.__toDownload = True ask = False else: defaultFileName, originalFileName = \ self.__saveFileName(downloadDirectory) fileName = defaultFileName self.__originalFileName = originalFileName ask = True self.__autoOpen = False if not self.__toDownload: from .DownloadAskActionDialog import DownloadAskActionDialog url = self.__reply.url() dlg = DownloadAskActionDialog( QFileInfo(originalFileName).fileName(), self.__reply.header(QNetworkRequest.ContentTypeHeader), "{0}://{1}".format(url.scheme(), url.authority()), self) if dlg.exec_() == QDialog.Rejected or dlg.getAction() == "cancel": self.progressBar.setVisible(False) self.__reply.close() self.on_stopButton_clicked() self.filenameLabel.setText( self.tr("Download canceled: {0}").format( QFileInfo(defaultFileName).fileName())) self.__canceledFileSelect = True return if dlg.getAction() == "scan": self.__mainWindow.requestVirusTotalScan(url) self.progressBar.setVisible(False) self.__reply.close() self.on_stopButton_clicked() self.filenameLabel.setText( self.tr("VirusTotal scan scheduled: {0}").format( QFileInfo(defaultFileName).fileName())) self.__canceledFileSelect = True return self.__autoOpen = dlg.getAction() == "open" if PYQT_VERSION_STR >= "5.0.0": from PyQt5.QtCore import QStandardPaths tempLocation = QStandardPaths.standardLocations( QStandardPaths.TempLocation)[0] else: from PyQt5.QtGui import QDesktopServices tempLocation = QDesktopServices.storageLocation( QDesktopServices.TempLocation) fileName = tempLocation + '/' + \ QFileInfo(fileName).completeBaseName() if ask and not self.__autoOpen and self.__requestFilename: self.__gettingFileName = True fileName = E5FileDialog.getSaveFileName( None, self.tr("Save File"), defaultFileName, "") self.__gettingFileName = False if not fileName: self.progressBar.setVisible(False) self.__reply.close() self.on_stopButton_clicked() self.filenameLabel.setText( self.tr("Download canceled: {0}") .format(QFileInfo(defaultFileName).fileName())) self.__canceledFileSelect = True return fileInfo = QFileInfo(fileName) Helpviewer.HelpWindow.HelpWindow.downloadManager()\ .setDownloadDirectory(fileInfo.absoluteDir().absolutePath()) self.filenameLabel.setText(fileInfo.fileName()) self.__output.setFileName(fileName + ".part") self.__fileName = fileName # check file path for saving saveDirPath = QFileInfo(self.__fileName).dir() if not saveDirPath.exists(): if not saveDirPath.mkpath(saveDirPath.absolutePath()): self.progressBar.setVisible(False) self.on_stopButton_clicked() self.infoLabel.setText(self.tr( "Download directory ({0}) couldn't be created.") .format(saveDirPath.absolutePath())) return self.filenameLabel.setText(QFileInfo(self.__fileName).fileName()) if self.__requestFilename: self.__readyRead()