def interpolation(self, layer, attribute_for_interpolation, attribute_name, output_dir, resolution): #create interpolation-object layer_data = QgsInterpolator.LayerData() layer_data.source=layer layer_data.interpolationAttribute=attribute_for_interpolation layer_data.valueSource=0 layer_data.sourceType=0 # #add the given layer to the interpolation-object # layer_data.vectorLayer = layer # # #use the given attribute instead of the z coordinate for interpolation # layer_data.zCoordInterpolation=False # layer_data.interpolationAttribute = attribute_for_interpolation # layer_data.mInputType = 1 #interpolate the layer interpolator = QgsIDWInterpolator([layer_data]) #create the resulting raster rect = layer.extent() ncol = int((rect.xMaximum() - rect.xMinimum()) / resolution) nrows = int((rect.yMaximum() - rect.yMinimum()) / resolution) #create outut directory export_folder = QDir.toNativeSeparators(output_dir + "/batch_interpolation/") if not os.path.exists(export_folder): os.makedirs(export_folder) #write raster to file system export_path = QDir.toNativeSeparators(export_folder + layer.name() + "_" + attribute_name + ".tif") #QMessageBox.about(None,"sss","4") output = QgsGridFileWriter(interpolator, export_path, rect, ncol, nrows) #QMessageBox.about(None,"sss","5") a=output.writeFile()
def update_output(self): src_filename = self._model.src_filename src_path_dir = self._model.src_path_dir src_path = QDir.toNativeSeparators( os.path.join(src_path_dir, src_filename) ) dst_path_dir = QDir.toNativeSeparators(self._model.dst_path_dir) dst_prefix, dst_suffix = os.path.splitext(src_filename) cmd = 'ffmpeg -ss %02d:%02d:%02d -t %02d:%02d:%02d ' \ '-i %s ' \ '-vcodec copy -acodec copy ' \ '%s' self.txtbrw_output.clear() for index, interval in enumerate(self._model.iter_intervals()): begin, end = interval begin = Moment(begin[0], begin[1], begin[2]) end = Moment(end[0], end[1], end[2]) delta = end - begin self.txtbrw_output.append(cmd % ( begin.hour, begin.mins, begin.secs, delta.hour, delta.mins, delta.secs, src_path, os.path.join( dst_path_dir, '%s_%d%s' % (dst_prefix, index, dst_suffix) ) ))
def __installPip(self): """ Private slot to install pip. """ python = E5FileDialog.getOpenFileName( None, self.tr("Select Python Executable")) if python: python = QDir.toNativeSeparators(python) dia = PipDialog(self.tr('Install PIP')) res = dia.startProcesses([ (python, ["-m", "ensurepip"]), (python, ["-m", "pip", "install", "--upgrade", "pip"]), ]) if res: dia.exec_() pip = E5FileDialog.getOpenFileName( None, self.tr("Select PIP Executable"), os.path.dirname(python)) if pip: pip = QDir.toNativeSeparators(pip) pipExecutables = \ self.__plugin.getPreferences("PipExecutables") if pip not in pipExecutables: pipExecutables.append(pip) self.__plugin.setPreferences("PipExecutables", pipExecutables)
def get_raw_images_folder(self, MDLA, statusBar): # TODO Remove the hardcoded path separator log_folder = MDLA.outputFolderPath if MDLA.outputFolderPath else expanduser("~") + "/Documents" folder_name = QFileDialog.getExistingDirectory(self, 'Select raw images folder', log_folder,) if folder_name: self.rawImagesField.setText(QDir.toNativeSeparators(folder_name) + sep) MDLA.rawImagesFolder = QDir.toNativeSeparators(folder_name) + sep statusBar.showMessage("Raw images folder set", 2000)
def _write_package_contents(self, contents, dst_dir, src_dir, dir_stack, job_writer, resource_contents): """ Write the contents of a single package directory. """ self._create_directory(dst_dir) for content in contents: if not content.included: continue if isinstance(content, QrcDirectory): dir_stack.append(content.name) self._write_package_contents(content.contents, dst_dir + '/' + content.name, src_dir + '/' + content.name, dir_stack, job_writer, resource_contents) dir_stack.pop() else: freeze_file = True src_file = content.name src_path = src_dir + '/' + src_file if src_file.endswith('.py'): dst_file = src_file[:-3] + '.pyo' elif src_file.endswith('.pyw'): dst_file = src_file[:-4] + '.pyo' else: # Just copy the file. dst_file = src_file freeze_file = False dst_path = dst_dir + '/' + dst_file file_path = list(dir_stack) file_path.append(dst_file) file_path = '/'.join(file_path) if freeze_file: self._freeze(job_writer, dst_path, src_path, file_path[:-1]) else: src_path = QDir.toNativeSeparators(src_path) dst_path = QDir.toNativeSeparators(dst_path) try: shutil.copyfile(src_path, dst_path) except FileNotFoundError: raise UserException( "{0} does not seem to exist".format(src_path)) resource_contents.append(file_path)
def dirSelectionDialog(self): if self.sender().objectName() == 'sourceDirSelectBtn': _dir = QDir.toNativeSeparators( QtWidgets.QFileDialog.getExistingDirectory( directory=self.ui.sourceDirectoryInput.text())) self.ui.sourceDirectoryInput.setText(_dir) self.sourceDirProvided() elif self.sender().objectName() == 'targetDirSelectBtn': _dir = QDir.toNativeSeparators( QtWidgets.QFileDialog.getExistingDirectory( directory=self.ui.targetDirectoryInput.text())) self.ui.targetDirectoryInput.setText(_dir)
def _write_package_contents(self, contents, dst_dir, src_dir, dir_stack, job_writer, resource_contents): """ Write the contents of a single package directory. """ self._create_directory(dst_dir) for content in contents: if not content.included: continue if isinstance(content, QrcDirectory): dir_stack.append(content.name) self._write_package_contents(content.contents, dst_dir + '/' + content.name, src_dir + '/' + content.name, dir_stack, job_writer, resource_contents) dir_stack.pop() else: freeze_file = True src_file = content.name src_path = src_dir + '/' + src_file if src_file.endswith('.py'): dst_file = src_file[:-3] + '.pyo' elif src_file.endswith('.pyw'): dst_file = src_file[:-4] + '.pyo' else: # Just copy the file. dst_file = src_file freeze_file = False dst_path = dst_dir + '/' + dst_file file_path = list(dir_stack) file_path.append(dst_file) file_path = '/'.join(file_path) if freeze_file: self._freeze(job_writer, dst_path, src_path, file_path[:-1]) else: src_path = QDir.toNativeSeparators(src_path) dst_path = QDir.toNativeSeparators(dst_path) try: shutil.copyfile(src_path, dst_path) except FileNotFoundError: raise UserException( "{0} does not seem to exist".format(src_path)) resource_contents.append(file_path)
def _freeze(job_writer, out_file, in_file, name, as_c=False): """ Freeze a Python source file to a C header file or a data file. """ out_file = QDir.toNativeSeparators(out_file) in_file = QDir.toNativeSeparators(in_file) if as_c: conversion = 'C' else: name = ':/' + name conversion = 'data' job_writer.writerow([out_file, in_file, name, conversion])
def get_log_file(self, MDLA, statusBar): file_name = QFileDialog.getOpenFileName( self, 'Select log file', expanduser("~") + "/Documents", # TODO Remove the hardcoded path separator "Log files (*.log)" ) if file_name[0]: self.logFileField.setText(QDir.toNativeSeparators(file_name[0])) MDLA.inputFilePath = QDir.toNativeSeparators(file_name[0]) MDLA.outputFolderPath = QDir.toNativeSeparators(dirname(MDLA.inputFilePath)) + sep statusBar.showMessage("Input log file path set", 2000)
def _freeze(job_writer, out_file, in_file, name, as_c=False): """ Freeze a Python source file to a C header file or a data file. """ out_file = QDir.toNativeSeparators(out_file) in_file = QDir.toNativeSeparators(in_file) if as_c: conversion = 'C' else: name = ':/' + name conversion = 'data' job_writer.writerow([out_file, in_file, name, conversion])
def loadFromFile(): """ Loads settings from the appropiate config file. :return: """ if not Settings.rcFile: # If no file was specified we try to read it from environment # variable o standard path Settings.rcFile = os.environ.get('TERPRC') or os.path.join( str(QDir.toNativeSeparators(QDir.homePath())), '.koorc') try: if not os.path.isfile(Settings.rcFile): Settings.save() return False p = configparser.ConfigParser() p.read([Settings.rcFile]) for section in p.sections(): for (name, value) in p.items(section): if value == 'True' or value == 'true': value = True if value == 'False' or value == 'false': value = False if value == 'None' or value == 'none': value = None Settings.options[section + '.' + name] = value except Exception as e: Debug.warning('Unable to read config file %s !' % Settings.rcFile) return True
def __init__(self, previewImage, fileName,audioFile): super(ImageView, self).__init__() self.fileName = fileName mainLayout = QVBoxLayout(self) self.imageLabel = QLabel() self.imageLabel.setPixmap(QPixmap.fromImage(previewImage)) mainLayout.addWidget(self.imageLabel) topLayout = QHBoxLayout() self.fileNameLabel = QLabel(QDir.toNativeSeparators(fileName)) self.fileNameLabel.setTextInteractionFlags(Qt.TextBrowserInteraction) topLayout.addWidget(self.fileNameLabel) topLayout.addStretch() copyButton = QPushButton("Copy") copyButton.setToolTip("Copy file name to clipboard") topLayout.addWidget(copyButton) copyButton.clicked.connect(self.copy) launchButton = QPushButton("Launch") launchButton.setToolTip("Launch image viewer") topLayout.addWidget(launchButton) launchButton.clicked.connect(self.launch) mainLayout.addLayout(topLayout) self.playSound(audioFile)
def open_about(self): # Open an about window path = __directory__ + \ QDir.toNativeSeparators('/resources/texts/about.txt') title, text = self.model.get_about_text(path) QMessageBox.about(self, title, text)
def _open_file_browser(self): """Gets location to store new file from user""" new_location = QFileDialog.getExistingDirectory( self.parent(), "Select Base Directory", self.location.text(), QFileDialog.ShowDirsOnly) self.location.setText(QDir.toNativeSeparators(new_location)) self.location.setFocus()
def image_show_gview(self, index): self.overlay.show() prevImgPath = os.path.join(self.file_dir, 'prev', self.prev_image_list[index]) self.prevImgPath = QDir.toNativeSeparators(prevImgPath) currImgPath = os.path.join(self.file_dir, 'curr', self.curr_image_list[index]) self.currImgPath = QDir.toNativeSeparators(currImgPath) self.prevGraphicsView.setStyleSheet("border-image: url(%s);" % self.prevImgPath) self.currGraphicsView.setStyleSheet("border-image: url(%s);" % self.currImgPath) self.fileNameLineEdit.setText(self.curr_image_list[index]) self.timer_flag = 1
def browse_file1(self): dlg = QFileDialog() dlg.setFileMode(QFileDialog.Directory) if dlg.exec_(): filenames = dlg.selectedFiles() self.lineEdit.setText(QDir.toNativeSeparators(str(filenames[0])))
def showInFolder(path, open_file_as_fallback=False): ''' Show a file or folder in explorer/finder, highlighting it where possible. Source: https://stackoverflow.com/a/46019091/3388962 ''' path = os.path.abspath(path) dirPath = path if os.path.isdir(path) else os.path.dirname(path) if sys.platform == 'win32': args = [] args.append('/select,') args.append(QDir.toNativeSeparators(path)) if QProcess.startDetached('explorer', args): return True elif sys.platform == 'darwin': args = [] args.append('-e') args.append('tell application "Finder"') args.append('-e') args.append('activate') args.append('-e') args.append('select POSIX file "%s"' % path) args.append('-e') args.append('end tell') args.append('-e') args.append('return') if not QProcess.execute('/usr/bin/osascript', args): return True #if not QtCore.QProcess.execute('/usr/bin/open', [dirPath]): # return # TODO: Linux is not implemented. It has many file managers (nautilus, xdg-open, etc.) # each of which needs special ways to highlight a file in a file manager window. # Fallback. return QDesktopServices.openUrl( QUrl(path if open_file_as_fallback else dirPath))
def display_downloaded_content(self): """Open downloaded non-html content in a separate application. Called when an unsupported content type is finished downloading. """ file_path = ( QDir.toNativeSeparators( QDir.tempPath() + "/XXXXXX_" + self.content_filename ) ) myfile = QTemporaryFile(file_path) myfile.setAutoRemove(False) if myfile.open(): myfile.write(self.reply.readAll()) myfile.close() subprocess.Popen([ (self.config.get("content_handlers") .get(str(self.content_type))), myfile.fileName() ]) # Sometimes downloading files opens an empty window. # So if the current window has no URL, close it. if(str(self.url().toString()) in ('', 'about:blank')): self.close()
def __init__(self, defaultClassName, defaultFile, defaultPath, parent=None): """ Constructor @param defaultClassName proposed name for the new class (string) @param defaultFile proposed name for the source file (string) @param defaultPath default path for the new file (string) @param parent parent widget if the dialog (QWidget) """ super(NewDialogClassDialog, self).__init__(parent) self.setupUi(self) self.pathButton.setIcon(UI.PixmapCache.getIcon("open.png")) self.okButton = self.buttonBox.button(QDialogButtonBox.Ok) self.okButton.setEnabled(False) self.pathnameCompleter = E5DirCompleter(self.pathnameEdit) self.classnameEdit.setText(defaultClassName) self.filenameEdit.setText(defaultFile) self.pathnameEdit.setText(QDir.toNativeSeparators(defaultPath)) msh = self.minimumSizeHint() self.resize(max(self.width(), msh.width()), msh.height())
def detect_python_path(): if (IS_WINDOWS and PYTHON_EXEC_CONFIGURED_BY_USER) or not IS_WINDOWS: return [] suggested = [] dirs = [] try: drives = [ QDir.toNativeSeparators(d.absolutePath()) for d in QDir.drives() ] for drive in drives: info = QFileInfo(drive) if info.isReadable(): dirs += [ os.path.join(drive, folder) for folder in os.listdir(drive) ] for folder in dirs: file_path = os.path.join(folder, "python.exe") if ("python" in folder.lower()) and os.path.exists(file_path): suggested.append(file_path) except: print("Detection couldnt be executed") finally: return suggested
def display_downloaded_content(self): """Open downloaded non-html content in a separate application. Called when an unsupported content type is finished downloading. """ debug("displaying downloaded content from {}".format(self.reply.url())) file_path = ( QDir.toNativeSeparators( QDir.tempPath() + "/XXXXXX_" + self.content_filename ) ) myfile = QTemporaryFile(file_path) myfile.setAutoRemove(False) if myfile.open(): myfile.write(self.reply.readAll()) myfile.close() subprocess.Popen([ (self.config.get("content_handlers") .get(str(self.content_type))), myfile.fileName() ]) # Sometimes downloading files opens an empty window. # So if the current window has no URL, close it. if(str(self.url().toString()) in ('', 'about:blank')): self.close()
def fileSelectionDialog(self): if self.sender().objectName() == 'fileSelectBtn': _file = QDir.toNativeSeparators( QtWidgets.QFileDialog.getOpenFileName( directory=self.ui.filePathInput.text())[0]) self.ui.filePathInput.setText(_file) self.sourceFileProvided()
def selectFile(self, path=None): """Select a file and start a worker thread to compute its digests.""" # pylint: disable=invalid-name # Interrupt any currently running thread self.stopThread() # Get file to process if path is None: (path, _) = QFileDialog.getOpenFileName( self) # getOpenFileName() returns a tuple if path == '': return self.fileedit.setText(QDir.toNativeSeparators(path)) for edit in self.edits.values(): edit.setText('') edit.setPalette(QApplication.palette(edit)) # Create worker and run it in a separate thread # A note on signals: # * the worker receives its signals in the new thread's event loop # * the thread receives its signals in the *main* thread's event loop thread = QThread() worker = FileDigestWorker(ALGORITHMS_AVAILABLE, path) worker.progress.connect(self.setProgress) worker.digested.connect(self.setDigest) worker.error.connect(self.error) worker.moveToThread(thread) thread.started.connect(worker.process) worker.finished.connect(thread.quit) thread.finished.connect(self.stopThread) thread.start(QThread.HighPriority) self.worker = worker self.thread = thread
def importDsmButton(self): self.dsm_folder = QFileDialog.getExistingDirectory() self.dsm_path_folder = QDir.toNativeSeparators(self.dsm_folder) print(self.dsm_folder) dsm_txt_folder = self.dlg.ImportDsm.setText( self.dsm_path_folder ) #scrive semplicemente la url nel form della gui
def __init__(self, defaultClassName, defaultFile, defaultPath, parent=None): """ Constructor @param defaultClassName proposed name for the new class (string) @param defaultFile proposed name for the source file (string) @param defaultPath default path for the new file (string) @param parent parent widget if the dialog (QWidget) """ super(NewDialogClassDialog, self).__init__(parent) self.setupUi(self) self.pathButton.setIcon(UI.PixmapCache.getIcon("open.png")) self.okButton = self.buttonBox.button(QDialogButtonBox.Ok) self.okButton.setEnabled(False) self.pathnameCompleter = E5DirCompleter(self.pathnameEdit) self.classnameEdit.setText(defaultClassName) self.filenameEdit.setText(defaultFile) self.pathnameEdit.setText(QDir.toNativeSeparators(defaultPath)) msh = self.minimumSizeHint() self.resize(max(self.width(), msh.width()), msh.height())
def setMedia(self, source: str) -> None: try: self.source = QDir.toNativeSeparators(source) self.media = self.probe(source) if self.media is not None: if getattr(self.parent, 'verboseLogs', False): self.logger.info(self.media) for codec_type in Streams.__members__: setattr(self.streams, codec_type.lower(), [ stream for stream in self.media.streams if stream.codec_type == codec_type.lower() ]) if len(self.streams.video): self.streams.video = self.streams.video[ 0] # we always assume one video stream per media file else: raise InvalidMediaException( 'Could not load video stream for {}'.format(source)) self.mappings.clear() # noinspection PyUnusedLocal [ self.mappings.append(True) for i in range(int(self.media.format.nb_streams)) ] except OSError as e: if e.errno == errno.ENOENT: errormsg = '{0}: {1}'.format(os.strerror(errno.ENOENT), source) self.logger.error(errormsg) raise FileNotFoundError(errormsg)
def get_save_file_name(*args, **kwargs): filename, _selected_filter = QFileDialog.getSaveFileName(*args, **kwargs) if len(filename) > 0: filename = QDir.toNativeSeparators(filename) return filename
def getQtBinariesPath(): """ Module function to get the path of the Qt binaries. @return path of the Qt binaries (string) """ import Preferences path = "" # step 1: check, if the user has configured a tools path path = Preferences.getQt("QtToolsDir") if not path and isWindowsPlatform(): # step 2.1: check for PyQt5 Windows installer (designer is test object) modDir = getPyQt5ModulesDirectory() if os.path.exists(os.path.join(modDir, "bin", "designer.exe")): path = os.path.join(modDir, "bin") elif os.path.exists(os.path.join(modDir, "designer.exe")): path = modDir if not path: # step 2.2: get the path from Qt # Note: no Qt tools are to found there for PyQt 5.7.0 path = QLibraryInfo.location(QLibraryInfo.BinariesPath) if not os.path.exists(path): path = "" return QDir.toNativeSeparators(path)
def data(self, index, role=Qt.DisplayRole): if (role == Qt.DisplayRole and index.column() == 0): path = QDir.toNativeSeparators(self.filePath(index)) if path.endsWith(QDir.separator()): path.chop(1) return path return QDirModel.data(self, index, role)
def _run_freeze(self, freeze, job_filename, opt): """ Run the accumlated freeze jobs. """ # Note that we assume a relative filename is on PATH rather than being # relative to the project file. interp = os.path.expandvars(self._project.python_host_interpreter) # On Windows the interpreter name is simply 'python'. So in order to # make the .pdy file more portable we strip any trailing version # number. if sys.platform == 'win32': for i in range(len(interp) - 1, -1, -1): if interp[i] not in '.0123456789': interp = interp[:i + 1] break argv = [QDir.toNativeSeparators(interp)] if opt == 2: argv.append('-OO') elif opt == 1: argv.append('-O') argv.append(freeze) argv.append(job_filename) self.run(argv, "Unable to freeze files")
def get_save_file_name(*args, **kwargs): filename, _selected_filter = QFileDialog.getSaveFileName(*args, **kwargs) if len(filename) > 0: filename = QDir.toNativeSeparators(filename) return filename
def exportTileButton(self): self.tile_folder = QFileDialog.getExistingDirectory() self.tile_path_folder = QDir.toNativeSeparators(self.tile_folder) print(self.tile_folder) print(self.tile_path_folder) tile_txt_folder = self.dlg.outFolder.setText( self.tile_path_folder ) #scrive semplicemente la url nel form della gui
def removeTempFiles(self, directory, prefix, suffix): '''This function removes all temporary files from the given directory.''' for entry in os.listdir(directory): absolute_path = QDir.toNativeSeparators(directory + '/' + entry) if os.path.isfile(absolute_path): if os.path.basename(entry).startswith( prefix) and os.path.basename(entry).endswith(suffix): os.remove(absolute_path)
def on_file_click(self): i = self.combo_box.currentIndex() d = self.get_device_from_index(i) path, _ = QFileDialog.getOpenFileName() path = QDir.toNativeSeparators(path) if path: self.textbox.setText(path) self.play(d, path)
def toNativeSeparators(path): """ Function returning a path, that is using native separator characters. @param path path to be converted (QString) @return path with converted separator characters (QString) """ return QDir.toNativeSeparators(path)
def __setPath(self): path = QDir.toNativeSeparators( QFileDialog.getExistingDirectory(self.MainWindow, str("Path"), QDir.currentPath())) if (self.pathText.findText(path) == -1): self.pathText.addItem(path) self.pathText.setCurrentIndex(self.pathText.findText(path))
def toNativeSeparators(path): """ Function returning a path, that is using native separator characters. @param path path to be converted (QString) @return path with converted separator characters (QString) """ return QDir.toNativeSeparators(path)
def on_pathButton_clicked(self): """ Private slot called to open a directory selection dialog. """ path = E5FileDialog.getExistingDirectory( self, self.tr("Select source directory"), QDir.fromNativeSeparators(self.pathnameEdit.text()) ) if path: self.pathnameEdit.setText(QDir.toNativeSeparators(path))
def get_open_file_names(*args, **kwargs): filenames = [] names, _selected_filter = QFileDialog.getOpenFileNames(*args, **kwargs) for filename in names: filenames.append(QDir.toNativeSeparators(filename)) return filenames
def expand(name_item): item_type = name_item.data(USER_ROLE_ITEM_TYPE) if item_type == ITEM_TYPE_DIRECTORY: for i in range(name_item.rowCount()): expand(name_item.child(i, 0)) elif item_type == ITEM_TYPE_FILE: filename = get_full_item_path(name_item) downloads.append(Download(filename, QDir.toNativeSeparators(filename)))
def getConfigDir(): """ Global function to get the name of the directory storing the config data. @return directory name of the config dir (string) """ if sys.platform.startswith("win"): cdn = "_eric6" else: cdn = ".eric6" hp = QDir.homePath() dn = QDir(hp) dn.mkdir(cdn) hp += "/" + cdn try: return QDir.toNativeSeparators(hp) except AttributeError: return QDir.toNativeSeparators(hp)
def browse_timestamp_handler(self): """ Handler when the timestamp browser button is clicked """ tmp_name, _ = QFileDialog.getOpenFileName( self, "Choose Timestamp file", None, "Timestamp File (*.tmsp);;All Files (*)" ) if not tmp_name: return self.set_timestamp_filename(QDir.toNativeSeparators(tmp_name))
def browse_video_handler(self): """ Handler when the video browse button is clicked """ tmp_name, _ = QFileDialog.getOpenFileName( self, "Choose Video file", None, "All Files (*)" ) if not tmp_name: return self.set_video_filename(QDir.toNativeSeparators(tmp_name))
def path_to_user(self, path): """ Convert a file name to one that is relative to the project name if possible and uses native separators. """ if self._name is not None: rel = self._name.dir().relativeFilePath(path) if not rel.startswith('..'): path = rel return QDir.toNativeSeparators(path)
def changeFolder(self, button): fname = QFileDialog.getExistingDirectory( self, 'Select a directory', download_path) if fname: # Returns pathName with the '/' separators converted to separators that are appropriate for the underlying operating system. # On Windows, toNativeSeparators("c:/winnt/system32") returns # "c:\winnt\system32". fname = QDir.toNativeSeparators(fname) if os.path.isdir(fname): self.download_folder_lineEdit.setText(fname)
def get_existing_directory(*args, **kwargs): directory = QFileDialog.getExistingDirectory(*args, **kwargs) if len(directory) > 0: directory = QDir.toNativeSeparators(directory) # FIXME: on macOS the getExistingDirectory() might return the directory with # the last part being invalid, try to find the valid part of the directory if sys.platform == 'darwin': while len(directory) > 0 and not os.path.isdir(directory): directory = os.path.split(directory)[0] return directory
def downloadFolderPushButtonClicked(self, button): download_path = str( self.persepolis_setting.value('settings/download_path')) fname = QFileDialog.getExistingDirectory( self, 'Select a directory', download_path) if fname: # Returns pathName with the '/' separators converted to separators that are appropriate for the underlying operating system. # On Windows, toNativeSeparators("c:/winnt/system32") returns # "c:\winnt\system32". fname = QDir.toNativeSeparators(fname) self.download_folder_lineEdit.setText(fname) self.persepolis_setting.setValue( 'settings/download_path', str(fname))
def _create_directory(self, dir_name): """ Create a directory which may already exist. """ dir_name = QDir.toNativeSeparators(dir_name) self._message_handler.verbose_message( "Creating directory {0}".format(dir_name)) try: os.makedirs(dir_name, exist_ok=True) except Exception as e: raise UserException( "Unable to create the '{0}' directory".format(dir_name), str(e))
def dropEvent(self, ev): if not ev.source() and ev.mimeData().hasUrls(): ev.accept() lyurls = [] impurls = [] for url in ev.mimeData().urls(): imp = file_import.FileImport.instance(self) if imp.isImportable(url.toLocalFile()): impurls.append(QDir.toNativeSeparators(url.toLocalFile())) else: lyurls.append(url) docs = self.openUrls(lyurls) if docs: self.setCurrentDocument(docs[-1]) for i in impurls: imp.openDialog(i)
def run(self, argv, error_message, in_build_dir=False): """ Execute a command and capture the output. """ if in_build_dir: project = self._project saved_cwd = os.getcwd() build_dir = project.path_from_user(project.build_dir) build_dir = QDir.toNativeSeparators(build_dir) os.chdir(build_dir) self._message_handler.verbose_message( "{0} is now the current directory".format(build_dir)) else: saved_cwd = None self._message_handler.verbose_message( "Running '{0}'".format(' '.join(argv))) QCoreApplication.processEvents() process = QProcess() process.readyReadStandardOutput.connect( lambda: self._message_handler.progress_message( QTextCodec.codecForLocale().toUnicode( process.readAllStandardOutput()).strip())) stderr_output = QByteArray() process.readyReadStandardError.connect( lambda: stderr_output.append(process.readAllStandardError())) process.start(argv[0], argv[1:]) finished = process.waitForFinished() if saved_cwd is not None: os.chdir(saved_cwd) self._message_handler.verbose_message( "{0} is now the current directory".format(saved_cwd)) if not finished: raise UserException(error_message, process.errorString()) if process.exitStatus() != QProcess.NormalExit or process.exitCode() != 0: raise UserException(error_message, QTextCodec.codecForLocale().toUnicode(stderr_output).strip())
def getConfigDir(): """ Module function to get the name of the directory storing the config data. @return directory name of the config dir (string) """ if configDir is not None and os.path.exists(configDir): hp = configDir else: if isWindowsPlatform(): cdn = "_eric6" else: cdn = ".eric6" hp = QDir.homePath() dn = QDir(hp) dn.mkdir(cdn) hp += "/" + cdn return QDir.toNativeSeparators(hp)
def _scan(self, _): """ Invoked when the user clicks on the scan button. """ project = self.project package = self.package # Get the root directory to scan. root = self.get_root_dir() if root == '': return # Save the included state of any existing contents so that they can be # restored after the scan. old_state = {} for itm in self._get_items(): rel_path = [itm.data(0, Qt.DisplayRole)] parent = itm.parent() while parent is not None: rel_path.append(parent.data(0, Qt.DisplayRole)) parent = parent.parent() rel_path.reverse() if self._show_root: rel_path = rel_path[1:] old_state['/'.join(rel_path)] = (itm.checkState(0) == Qt.Checked) # Walk the package. root_dir = QDir(root) if not root_dir.exists(): QMessageBox.warning(self.parentWidget(), "Scan Directory", "{0} is not a valid directory.".format( QDir.toNativeSeparators(root))) return self._add_to_container(package, root_dir, [], old_state) self._visualise() self.package_changed.emit()
def getQtBinariesPath(): """ Module function to get the path of the Qt binaries. @return path of the Qt binaries (string) """ path = "" if isWindowsPlatform(): # check for PyQt5 installer first (designer is test object) modDir = getPyQt5ModulesDirectory() if os.path.exists(os.path.join(modDir, "bin", "designer.exe")): path = os.path.join(modDir, "bin") elif os.path.exists(os.path.join(modDir, "designer.exe")): path = modDir if not path: path = QLibraryInfo.location(QLibraryInfo.BinariesPath) if not os.path.exists(path): path = "" return QDir.toNativeSeparators(path)
def detect_python_path(): if (IS_WINDOWS and PYTHON_PATH_CONFIGURED_BY_USER) or not IS_WINDOWS: return [] suggested = [] try: drives = [QDir.toNativeSeparators(d.absolutePath()) for d in QDir.drives()] dirs = [] for drive in drives: info = QFileInfo(drive) if info.isReadable(): dirs += [os.path.join(drive, folder) for folder in os.listdir(drive)] for folder in dirs: file_path = os.path.join(folder, "python.exe") if ("Python" in folder) and os.path.exists(file_path): suggested.append(file_path) except: print("Detection couldnt be executed") return suggested
def add_editor(self, fileName="", project=None, tabIndex=None, syntax=None, use_open_highlight=False): print("add_editor_2.3", fileName) project_obj = self._parent.explorer.get_project_given_filename( fileName) editorWidget = editor.create_editor(fileName=fileName, project=project, syntax=syntax, use_open_highlight=use_open_highlight, project_obj=project_obj) if not fileName: tabName = "New Document" else: tabName = file_manager.get_basename(fileName) #add the tab inserted_index = self.add_tab(editorWidget, tabName, tabIndex=tabIndex) self.actualTab.setTabToolTip(inserted_index, QDir.toNativeSeparators(fileName)) #Connect signals editorWidget.modificationChanged[bool].connect(self._editor_tab_was_modified) editorWidget.fileSaved['QPlainTextEdit*'].connect(self._editor_tab_was_saved) editorWidget.openDropFile[str].connect(self.open_file) editorWidget.addBackItemNavigation.connect(self.addBackItemNavigation.emit) editorWidget.locateFunction[str, str, bool].connect(self._editor_locate_function) editorWidget.warningsFound['QPlainTextEdit*'].connect(self._show_warning_tab_indicator) editorWidget.errorsFound['QPlainTextEdit*'].connect(self._show_error_tab_indicator) editorWidget.cleanDocument['QPlainTextEdit*'].connect(self._hide_icon_tab_indicator) editorWidget.findOcurrences[str].connect(self._find_occurrences) editorWidget.migrationAnalyzed.connect(self.migrationAnalyzed.emit) #Cursor position changed editorWidget.cursorPositionChange[int, int].connect(self._cursor_position_changed) #keyPressEventSignal for plugins editorWidget.keyPressSignal['QEvent*'].connect(self._editor_keyPressEvent) #emit a signal about the file open self.fileOpened.emit(fileName) return editorWidget
def _run_freeze(self, freeze, interpreter, job_filename, opt): """ Run the accumlated freeze jobs. """ # On Windows the interpreter name is simply 'python'. So in order to # make the .pdy file more portable we strip any trailing version # number. if sys.platform == 'win32': for i in range(len(interpreter) - 1, -1, -1): if interpreter[i] not in '.0123456789': interpreter = interpreter[:i + 1] break argv = [QDir.toNativeSeparators(interpreter)] if opt == 2: argv.append('-OO') elif opt == 1: argv.append('-O') argv.append(freeze) argv.append(job_filename) self.run(argv, "Unable to freeze files")
from PyQt5.QtCore import QDir from PyQt5.QtCore import QSettings from PyQt5.QtCore import Qt ############################################################################### # CHECK PYTHON VERSION ############################################################################### IS_PYTHON3 = sys.version_info.major == 3 ############################################################################### # PATHS ############################################################################### HOME_PATH = QDir.toNativeSeparators(QDir.homePath()) NINJA_EXECUTABLE = os.path.realpath(sys.argv[0]) PRJ_PATH = os.path.abspath(os.path.dirname(__file__)) if not IS_PYTHON3: PRJ_PATH = PRJ_PATH.decode('utf-8') #Only for py2exe frozen = getattr(sys, 'frozen', '') if frozen in ('dll', 'console_exe', 'windows_exe'): # py2exe: PRJ_PATH = os.path.abspath(os.path.dirname(sys.executable)) HOME_NINJA_PATH = os.path.join(HOME_PATH, ".ninja_ide") NINJA_KNOWLEDGE_PATH = os.path.join(HOME_NINJA_PATH, 'knowledge')
def build(self, opt, nr_resources, build_dir=None, clean=False): """ Build the project in a given directory. Raise a UserException if there is an error. """ project = self._project # Create a temporary directory which will be removed automatically when # this function's objects are garbage collected. temp_dir = QTemporaryDir() if not temp_dir.isValid(): raise UserException( "There was an error creating a temporary directory") # Get the names of the required Python modules, extension modules and # libraries. metadata = get_python_metadata(project.python_target_version) required_modules, required_libraries = project.get_stdlib_requirements( include_hidden=True) required_py = {} required_ext = {} for name in required_modules.keys(): module = metadata[name] if module.source is None: required_py[name] = module elif not module.core: required_ext[name] = module # Initialise and check we have the information we need. if len(required_py) != 0 or len(required_ext) != 0: if project.python_source_dir == '': raise UserException( "The name of the Python source directory has not been " "specified") if project.get_executable_basename() == '': raise UserException("The name of the application has not been " "specified and cannot be inferred") if project.application_script == '': if project.application_entry_point == '': raise UserException("Either the application script name or " "the entry point must be specified") elif len(project.application_entry_point.split(':')) != 2: raise UserException("An entry point must be a module name and " "a callable separated by a colon.") elif project.application_entry_point != '': raise UserException("Either the application script name or the " "entry point must be specified but not both") # Get the name of the build directory. if build_dir is None: build_dir = project.build_dir if build_dir == '': build_dir = '.' build_dir = project.path_from_user(build_dir) # Remove any build directory if required. if clean: native_build_dir = QDir.toNativeSeparators(build_dir) self._message_handler.progress_message( "Cleaning {0}".format(native_build_dir)) shutil.rmtree(native_build_dir, ignore_errors=True) # Now start the build. self._create_directory(build_dir) # Create the job file and writer. job_filename = QDir.toNativeSeparators(temp_dir.path() + '/jobs.csv') job_file = open(job_filename, 'w', newline='') job_writer = csv.writer(job_file) # Freeze the bootstrap. py_major, py_minor, py_patch = project.python_target_version py_version = (py_major << 16) + (py_minor << 8) + py_patch bootstrap_src = get_embedded_file_for_version(py_version, __file__, 'lib', 'bootstrap') bootstrap = self._copy_lib_file(bootstrap_src, temp_dir.path(), dst_file_name='bootstrap.py') self._freeze(job_writer, build_dir + '/frozen_bootstrap.h', bootstrap, 'pyqtdeploy_bootstrap', as_c=True) # Freeze any main application script. if project.application_script != '': self._freeze(job_writer, build_dir + '/frozen_main.h', project.path_from_user(project.application_script), 'pyqtdeploy_main', as_c=True) # Create the pyqtdeploy module version file. version_f = self._create_file(build_dir + '/pyqtdeploy_version.h') version_f.write( '#define PYQTDEPLOY_HEXVERSION %s\n' % hex( PYQTDEPLOY_HEXVERSION)) version_f.close() # Generate the application resource. resource_names = self._generate_resource(build_dir + '/resources', required_py, job_writer, nr_resources) # Write the .pro file. self._write_qmake(build_dir, required_ext, required_libraries, job_writer, opt, resource_names) # Run the freeze jobs. job_file.close() # The odd naming of Python source files is to prevent them from being # frozen if we deploy ourself. freeze = self._copy_lib_file(self._get_lib_file_name('freeze.python'), temp_dir.path(), dst_file_name='freeze.py') self._run_freeze(freeze, job_filename, opt) # Remove the contents of the temporary directory. QFile.remove(freeze) QFile.remove(bootstrap) QFile.remove(job_filename)
def _generate_resource(self, resources_dir, required_py, job_writer, nr_resources): """ Generate the application resource. """ project = self._project self._create_directory(resources_dir) resource_contents = [] # Handle any application package. if project.application_package.name is not None: fi = QFileInfo(project.path_from_user( project.application_package.name)) package_src_dir = fi.canonicalFilePath() package_name = project.application_package.name if package_name != '': package_name = fi.completeBaseName() self._write_package(resource_contents, resources_dir, package_name, project.application_package, package_src_dir, job_writer) # Handle the Python standard library. self._write_stdlib_py(resource_contents, resources_dir, required_py, job_writer) # Handle any additional packages. for package in project.other_packages: self._write_package(resource_contents, resources_dir, '', package, project.path_from_user(package.name), job_writer) # Handle the PyQt package. if len(project.pyqt_modules) != 0: pyqt_subdir = 'PyQt5' if project.application_is_pyqt5 else 'PyQt4' pyqt_dst_dir = resources_dir + '/' + pyqt_subdir pyqt_src_dir = project.path_from_user(project.python_target_stdlib_dir) + '/site-packages/' + pyqt_subdir self._create_directory(pyqt_dst_dir) self._freeze(job_writer, pyqt_dst_dir + '/__init__.pyo', pyqt_src_dir + '/__init__.py', pyqt_subdir + '/__init__.pyo') resource_contents.append(pyqt_subdir + '/__init__.pyo') # Handle the PyQt.uic package. if 'uic' in project.pyqt_modules: skip_dirs = ['__pycache__'] if project.python_target_version[0] == 3: skip_dirs.append('port_v2') else: skip_dirs.append('port_v3') def copy_freeze(src, dst): for skip in skip_dirs: if skip in src: break else: if dst.endswith('.py'): dst += 'o' src = QDir.fromNativeSeparators(src) dst = QDir.fromNativeSeparators(dst) rel_dst = dst[len(resources_dir) + 1:] self._freeze(job_writer, dst, src, rel_dst) resource_contents.append(rel_dst) shutil.copytree(QDir.toNativeSeparators(pyqt_src_dir + '/uic'), QDir.toNativeSeparators(pyqt_dst_dir + '/uic'), copy_function=copy_freeze) # Write the .qrc files. if nr_resources == 1: resource_names = [self._write_resource(resources_dir, resource_contents)] else: resource_names = [] nr_files = len(resource_contents) if nr_resources > nr_files: nr_resources = nr_files per_resource = (nr_files + nr_resources - 1) // nr_resources start = 0 for r in range(nr_resources): end = start + per_resource if end > nr_files: end = nr_files resource_names.append( self._write_resource(resources_dir, resource_contents[start:end], r)) start += per_resource return resource_names
def _create_file(file_name): """ Create a text file in the build directory. """ return create_file(QDir.toNativeSeparators(file_name))