def CheckInputValues(self): if self.textNameSubproject.Text is None or self.textNameSubproject.Text == "": QMessageBox.warning(self, "Warning", "Please input project name!") return False if self.textPathSubproject.Text is None or self.textPathSubproject.Text == "": QMessageBox.warning(self, "Warning", "Please input project path!") return False if self.comboProjectSubproject.SelectedIndex < 0: QMessageBox.warning(self, "Warning", "Please select an project!") return False directory = QDir(self.textPathSubproject.Text) if not directory.exists(): if QMessageBox.question( self, "Question", "Procedure path dose not exist! Do you create the directory?", QMessageBox.Yes | QMessageBox.No) == QMessageBox.Yes: directory.mkpath(self.textPathSubproject.Text) else: return False return True
def config_dir(self): confd = QString2str( QApplication.applicationDirPath()) + os.sep + 'configs' dir = QDir(confd) if not dir.exists(): dir.mkpath(confd) return confd
def CheckInputValues(self): if (self.textNameProcedure.Text == None or self.textNameProcedure.Text == ""): QMessageBox.warning(self, "Warning", "Please input project name!") return False if (self.textPathProcedure.Text == None or self.textPathProcedure.Text == ""): QMessageBox.warning(self, "Warning", "Please input project path!") return False if (self.comboProjectProcedure.SelectedIndex < 0): QMessageBox.warning(self, "Warning", "Please select an Project!") return False if (self.comboSubProjectProcedure.SelectedIndex < 0): QMessageBox.warning(self, "Warning", "Please select an Sub-Project!") return False if (self.comboWorkspaceProcedure.SelectedIndex < 0): QMessageBox.warning(self, "Warning", "Please select an Workspace!") return directory = QDir(self.textPathProcedure.Text) if (not directory.exists()): if (QMessageBox.question( self, "Question", "Procedure path dose not exist! Do you create the directory?", QMessageBox.Yes | QMessageBox.No) == QMessageBox.Yes): directory.mkpath(self.textPathProcedure.Text) else: return False return True
def get_music_storage_folder(): storage_path = "%s%s%s" % (QDesktopServices.storageLocation(QDesktopServices.DataLocation).replace("\\", "/"), Config.DataPrefix, Config.MusicPrefix) dir = QDir(storage_path) if dir.exists() != True: dir.mkpath('.') return storage_path
def on_gen(self): '''生成工程''' if not self.currentConfig: return #获取工程名及有效路径 project_name = self.et_project_name.text() project_location = self.et_project_location.text() qdir = QDir(project_location) if not qdir.exists(): if not qdir.mkpath(project_location): QMessageBox.warning(self, '警告', '路径无效!') return project_location = qdir.absolutePath() if not project_location.endsWith( '/') and not project_location.endsWith('\\'): project_location += os.sep project_location.replace('\\', '/') if project_name.isEmpty() or project_location.isEmpty(): QMessageBox.warning(self, '警告', '项目名称或路径不能为空!') return self.currentConfig.project_name = app.QString2str(project_name) self.currentConfig.project_location = app.QString2str(project_location) content = self.currentConfig.toJson() fileInfo = QFileInfo(self.path) if not self.path.isEmpty(): path = app.QString2str(self.path) with open(path, 'w+') as f: f.write(content) item = self.lw.currentItem() item.setData(QtCore.Qt.UserRole, content) template_name = self.currentConfig.template_source template_dir = app.g_pwd + os.sep + 'templates' + os.sep + template_name.encode( 'utf-8') with open(template_dir + os.sep + 'config.json', 'r') as f: self.currentConfig.config_content = f.read() ret_json = app.render(self.currentConfig.config_content, config=self.currentConfig) self.currentConfig.config = json.loads(ret_json) for file in self.currentConfig.config['files']: sourcepath = template_dir + os.sep + file['source'].encode('utf-8') targetdir = self.currentConfig.project_location + self.currentConfig.project_name targetpath = targetdir + os.sep + file['target'] fi = QFileInfo(targetpath) qdir = fi.absoluteDir() if not qdir.exists(): qdir.mkpath(fi.absolutePath()) with open(sourcepath, 'r') as f: content = f.read() content = app.render(content, config=self.currentConfig) #渲染文件 with open(targetpath, 'w+') as f: f.write(content.encode('utf-8')) QMessageBox.information(self, '提示', '生成成功!')
def CheckInputValues(self): if (self.textNameProject.Value == None or self.textNameProject.Value == ""): raise ("Please input project name!") if (self.textPathProject.Value == None or self.textPathProject.Value == ""): raise ("Please input project path!") d = QDir(self.textPathProject.Value) if (not d.exists()): if (QMessageBox.question(self, "Question", "Procedure path dose not exist! Do you create the directory?", QMessageBox.Yes | QMessageBox.No) == QMessageBox.Yes): d = QDir(self.textPathProject.Value) d.mkpath(self.textPathProject.Value) else: return False return True
def render(self, fileName): if self.m_mainFrame.contentsSize() == '': return False fileInfo = QFileInfo(fileName) path = QDir() path.mkpath(fileInfo.absolutePath()) if fileName.lower().endswith('.pdf'): return self.renderPdf(fileName) image = self.renderImage() return image.save(fileName)
def setup_logger(): from stdm.settings.registryconfig import debug_logging logger = logging.getLogger('stdm') logger.setLevel(logging.ERROR) # Create log directory if it does not exist log_folder = QDir() if not log_folder.exists(LOG_DIR): status = log_folder.mkpath(LOG_DIR) # Log directory could not be created if not status: raise IOError('Log directory for STDM could not be created.') # File handler for logging debug messages file_handler = TimedRotatingFileHandler(LOG_FILE_PATH, when='D', interval=1, backupCount=14) file_handler.setLevel(logging.DEBUG) # Create formatter and add it to the handler formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') file_handler.setFormatter(formatter) # Add handler to the logger logger.addHandler(file_handler) # Enable/disable debugging. Defaults to ERROR level. lvl = debug_logging() if lvl: file_handler.setLevel(logging.DEBUG) else: file_handler.setLevel(logging.ERROR)
def rename (self, songs): # TODO: parametrize the main music colleciton mainColl= self.collaggr.collections[0] base= mainColl.path d= QDir () for song in songs: dstPath= self.songPath (base, song) dstDir= os.path.dirname (dstPath) # TODO: QtDir is not net transp. try to make sub jobs creating the missing path if d.mkpath (dstDir): # HINT: KUrl because KIO.* use KUrl # src= KUrl (song.filepath) src= KUrl (utils.path2qurl (song.filepath)) # BUG: Renamer.rename() # PyQt4.QtCore.QUrl(u'file:///home/mdione/media/music/new/bandidos rurales/05 - uruguay, uruguay.mp3') -> # PyQt4.QtCore.QUrl(u'file:///home/mdione/media/music/Le\xf3n Gieco/2001 - Bandidos rurales/05 - Uruguay, Uruguay.mp3') # ^^^^ dst= KUrl (dstPath) logger.info ("Renamer.rename()", src, "->", dst) # TODO: do not launch them all in parallel job= KIO.file_move (src, dst) # TODO: emit a finished. # print "Renamer.rename()", job job.result.connect (self.jobFinished) # print "Renamer.rename(): connected" self.jobs.append (job) # print "Renamer.rename(): next!" else: logger.info ("Renamer.rename(): failed to create", dstDir, ", skipping", dstPath)
def mkdir(self, path): directory = QDir(path) SCJ.lock.lock() if not directory.exists() : if not directory.mkpath(path) : self.emit(SIGNAL("error(QString)"), QString(self.trUtf8("Cannot create %s" % path))) SCJ.lock.unlock()
def setup_search(): # Create search directory if it does not exist search_folder = QDir() if not search_folder.exists(SEARCH_DIR): status = search_folder.mkpath(SEARCH_DIR) # Log directory could not be created if not status: raise IOError('Search directory for FLTS could not be created.')
def setup_templates_folder(): # Create reports directory and templates sub-directory if it does not # exist reports_folder = QDir() if not reports_folder.exists(TEMPLATES_DIR): status = reports_folder.mkpath(TEMPLATES_DIR) # Log directory could not be created if not status: raise IOError('Reports directory for FLTS could not be created.')
def on_gen(self): '''生成工程''' if not self.currentConfig: return #获取工程名及有效路径 project_name = self.et_project_name.text() project_location = self.et_project_location.text() qdir = QDir(project_location) if not qdir.exists(): if not qdir.mkpath(project_location): QMessageBox.warning(self, '警告', '路径无效!') return project_location = qdir.absolutePath() if not project_location.endsWith('/') and not project_location.endsWith('\\'): project_location += os.sep if project_name.isEmpty() or project_location.isEmpty(): QMessageBox.warning(self, '警告', '项目名称或路径不能为空!') return self.currentConfig.project_name = app.QString2str(project_name) self.currentConfig.project_location = app.QString2str(project_location) template_name = self.currentConfig.template_source template_dir = app.g_pwd + os.sep + 'templates' + os.sep + template_name with open(template_dir + os.sep + 'config.json', 'r') as f: self.currentConfig.config_content = f.read() ret_json = app.render(self.currentConfig.config_content, config=self.currentConfig) self.currentConfig.config = json.loads(ret_json) for file in self.currentConfig.config['files']: sourcepath = template_dir + os.sep + file['source'] targetdir = self.currentConfig.project_location + self.currentConfig.project_name targetpath = targetdir + os.sep + file['target'] fi = QFileInfo(targetpath) qdir = fi.absoluteDir() if not qdir.exists(): qdir.mkpath(fi.absolutePath()) with open(sourcepath, 'r') as f: content = f.read() content = app.render(content, config=self.currentConfig) #渲染文件 with open(targetpath, 'w+') as f: f.write(content.encode('utf-8')) QMessageBox.information(self,'提示','生成成功!')
def uploadDocument(self, entity_source, doc_type, fileinfo): """ Upload document in central repository """ self._entity_source = entity_source self._doc_type = doc_type self.fileID = self.generateFileID() self.sourcePath = fileinfo.filePath() profile_name = self.curr_profile.name root_dir = QDir(self.networkPath) doc_dir = QDir('{}/{}/{}/{}'.format( self.networkPath, unicode(profile_name).lower(), self._entity_source, unicode(self._doc_type).lower().replace(' ', '_'))) doc_path_str = u'{}/{}/{}/{}'.format( self.networkPath, profile_name.lower(), self._entity_source, self._doc_type.lower().replace(' ', '_')).lower() if not doc_dir.exists(): res = root_dir.mkpath(doc_path_str) if res: root_doc_type_path = doc_path_str else: root_doc_type_path = self.networkPath else: root_doc_type_path = doc_path_str self.destinationPath = '{}/{}.{}'.format(root_doc_type_path, self.fileID, fileinfo.completeSuffix()) srcFile = open(self.sourcePath, 'rb') destinationFile = open(self.destinationPath, 'wb') #srcLen = self.sourceFile.bytesAvailable() totalRead = 0 while True: inbytes = srcFile.read(4096) if not inbytes: break destinationFile.write(inbytes) totalRead += len(inbytes) #Raise signal on each block written self.emit(SIGNAL("blockWritten(int)"), totalRead) self.emit(SIGNAL("completed(QString)"), self.fileID) srcFile.close() destinationFile.close() return self.fileID
def userResourcePath(cls) -> str: configDir = QFileInfo(cls.settings(QSettings.UserScope).fileName()).path() urp = configDir + "/medux" # TODO: make this more pythonic fi = QFileInfo(urp + "/") if not fi.exists(): dir = QDir() if not dir.mkpath(urp): warnings.warn("could not create {}".format(urp)) return urp
def render(self, fileName): fileInfo = QFileInfo(fileName) path = QDir() path.mkpath(fileInfo.absolutePath()) if fileName.lower().endswith('.pdf'): return self.renderPdf(fileName) viewportSize = QSize(self.m_page.viewportSize()) pageSize = QSize(self.m_page.mainFrame().contentsSize()) bufferSize = QSize() if not self.m_clipRect.isEmpty(): bufferSize = self.m_clipRect.size() else: bufferSize = self.m_page.mainFrame().contentsSize() if pageSize == '': return False image = QImage(bufferSize, QImage.Format_ARGB32) image.fill(qRgba(255, 255, 255, 0)) p = QPainter(image) p.setRenderHint(QPainter.Antialiasing, True) p.setRenderHint(QPainter.TextAntialiasing, True) p.setRenderHint(QPainter.SmoothPixmapTransform, True) self.m_page.setViewportSize(pageSize) if not self.m_clipRect.isEmpty(): p.translate(-self.m_clipRect.left(), -self.m_clipRect.top()) self.m_page.mainFrame().render(p, QRegion(self.m_clipRect)) else: self.m_page.mainFrame().render(p) p.end() self.m_page.setViewportSize(viewportSize) return image.save(fileName)
def checkTempDir(): tempDir = QDir(WorkerPopulateGroup.TEMP_DIR) if not tempDir.exists(): msgtrans1 = QCoreApplication.translate( "CatalogOTF", "Created temporary directory '%s' for GDAL_WMS") msgtrans2 = QCoreApplication.translate( "CatalogOTF", "Not possible create temporary directory '%s' for GDAL_WMS" ) isOk = tempDir.mkpath(WorkerPopulateGroup.TEMP_DIR) msgtrans = msgtrans1 if isOk else msgtrans2 tempDir.setPath(WorkerPopulateGroup.TEMP_DIR) msg = msgtrans % tempDir.absolutePath() msgBar.pushMessage(NAME_PLUGIN, msg, QpluginNamegsMessageBar.CRITICAL, 5)
def readFile(path, default=None, encoding=None): if not os.path.supports_unicode_filenames: path = path.encode("utf-8") if QFile.exists(path): f = QFile(path,parent) if f.open(QIODevice.ReadOnly): data=f.readAll().__str__() else: raise ErrorRead(u'Couldn\'t open file %s with code error %d'%path,f.error()) f.close() if encoding: data = data.decode(encoding) return data else: dir = QDir(os.path.dirname(path)) if not dir.exists(): if not dir.mkpath(dir.path()): raise ErrorCreatePath(u'impossible to create a path!') writeFile(path, default) return default
def setup_logger(): logger = logging.getLogger('stdm') logger.setLevel(logging.DEBUG) #Create log directory if it does not exist log_folder = QDir() if not log_folder.exists(LOG_DIR): status = log_folder.mkpath(LOG_DIR) #Log directory could not be created if not status: raise IOError('Log directory for STDM could not be created.') #File handler for logging debug messages file_handler = TimedRotatingFileHandler(LOG_FILE_PATH, when='D', interval=1, backupCount=14) file_handler.setLevel(logging.DEBUG) #Create formatter and add it to the handler formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') file_handler.setFormatter(formatter) #Add handler to the logger logger.addHandler(file_handler)
def setup_logger(): from stdm.settings.registryconfig import debug_logging logger = logging.getLogger('stdm') logger.setLevel(logging.ERROR) # Create log directory if it does not exist log_folder = QDir() if not log_folder.exists(LOG_DIR): status = log_folder.mkpath(LOG_DIR) # Log directory could not be created if not status: raise IOError('Log directory for STDM could not be created.') # File handler for logging debug messages file_handler = TimedRotatingFileHandler(LOG_FILE_PATH, when='D', interval=1, backupCount=14) file_handler.setLevel(logging.DEBUG) # Create formatter and add it to the handler formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s') file_handler.setFormatter(formatter) # Add handler to the logger logger.addHandler(file_handler) # Enable/disable debugging. Defaults to ERROR level. lvl = debug_logging() if lvl: file_handler.setLevel(logging.DEBUG) else: file_handler.setLevel(logging.ERROR)
def uploadDocument(self, entity_source, doc_type, fileinfo): """ Upload document in central repository """ self._entity_source = entity_source self._doc_type = doc_type self.fileID = self.generateFileID() self.sourcePath = unicode(fileinfo.filePath()) profile_name = self.curr_profile.name root_dir = QDir(self.networkPath) doc_dir = QDir(u'{}/{}/{}/{}'.format( self.networkPath, profile_name.lower(), self._entity_source, self._doc_type.lower().replace(' ', '_') ) ) doc_path_str = u'{}/{}/{}/{}'.format( self.networkPath, profile_name.lower(), self._entity_source, self._doc_type.lower().replace(' ', '_') ).lower() if not doc_dir.exists(): res = root_dir.mkpath(doc_path_str) if res: root_doc_type_path = doc_path_str else: root_doc_type_path = self.networkPath else: root_doc_type_path = doc_path_str self.destinationPath = u'{}/{}.{}'.format( root_doc_type_path, self.fileID, fileinfo.completeSuffix() ) srcFile = open(self.sourcePath,'rb') destinationFile = open(self.destinationPath,'wb') #srcLen = self.sourceFile.bytesAvailable() totalRead = 0 while True: inbytes = srcFile.read(4096) if not inbytes: break destinationFile.write(inbytes) totalRead += len(inbytes) #Raise signal on each block written self.emit(SIGNAL("blockWritten(int)"),totalRead) self.emit(SIGNAL("completed(QString)"),self.fileID) srcFile.close() destinationFile.close() return self.fileID