我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用ntpath.basename()。
def browse_picture(self): self.image = QtGui.QFileDialog.getOpenFileName(None,'OpenFile','c:\\',"Image file(*.png *.jpg)") #self.progressBar.setValue(0) self.image = str(self.image) self.labeLAnomaly.setStyleSheet("QLabel {background-color:red;color:white;}") self.file_name = ntpath.basename(self.image) self.file_name, ext=os.path.splitext(self.file_name) self.file_path = ntpath.dirname(self.image) self.write_path = ntpath.expanduser('~\\Documents\\Document Analysis') # creating write path if not exists if not os.path.exists(self.write_path): os.makedirs(self.write_path) if self.image: self.imgPreview.setPixmap(QtGui.QPixmap(self.image). scaled(self.imgPreview.width(), self.imgPreview.height()))
def save_images(self, webpage, visuals, image_path): image_dir = webpage.get_image_dir() short_path = ntpath.basename(image_path[0]) name = os.path.splitext(short_path)[0] webpage.add_header(name) ims = [] txts = [] links = [] for label, image_numpy in visuals.items(): image_name = '%s_%s.png' % (name, label) save_path = os.path.join(image_dir, image_name) util.save_image(image_numpy, save_path) ims.append(image_name) txts.append(label) links.append(image_name) webpage.add_images(ims, txts, links, width=self.win_size)
def get_patient_spacing(): cn_patient_id = [] dst_dir = settings.TEST_EXTRACTED_IMAGE_DIR for subject_no in range(settings.TEST_SUBSET_START_INDEX, settings.TEST_SUBSET_TRAIN_NUM): src_dir = settings.RAW_SRC_DIR + "test_subset0" + str(subject_no) + "/" src_paths = glob.glob(src_dir + "*.mhd") for path in src_paths: patient_id = ntpath.basename(path).replace(".mhd", "") print("Patient: ", patient_id) if patient_id=='LKDS-00384': continue if not os.path.exists(dst_dir): os.mkdir(dst_dir) itk_img = SimpleITK.ReadImage(path) img_array = SimpleITK.GetArrayFromImage(itk_img) print("Img array: ", img_array.shape) spacing = numpy.array(itk_img.GetSpacing()) # spacing of voxels in world coor. (mm) print("Spacing (x,y,z): ", spacing) cn_patient_id.append([patient_id,spacing[0],spacing[1],spacing[2]]) cn_patient = pandas.DataFrame(cn_patient_id, columns=["patient_id", "spacing_x", "spacing_y", "spacing_z"]) print(cn_patient.head()) cn_patient.to_csv(dst_dir +"patient_spacing.csv", index=False)
def get_patient_xyz(path_f): candidate_index = 0 only_patient = "197063290812663596858124411210" only_patient = None patient_list=[] for subject_no in range(settings.TEST_SUBSET_START_INDEX, settings.TEST_SUBSET_TRAIN_NUM): src_dir = settings.RAW_SRC_DIR + "test_subset0" + str(subject_no) + "/" for src_path in glob.glob(src_dir + "*.mhd"): if only_patient is not None and only_patient not in src_path: continue patient_id = ntpath.basename(src_path).replace(".mhd", "") print(candidate_index, " patient: ", patient_id) if patient_id=='LKDS-00395' or patient_id == 'LKDS-00434'or patient_id == 'LKDS-00384' or patient_id == 'LKDS-00186': continue pos_annos = get_patient_xyz_do(src_path, patient_id,path_f) patient_list.extend(pos_annos) candidate_index += 1 df_patient_list = pandas.DataFrame(patient_list, columns=["seriesuid", "coordX", "coordY", "coordZ","probability"]) print("len of can:",len(df_patient_list)) df_patient_list.to_csv("./output_val/prediction_submisssion_luna_manal.csv", index=False)
def merge_csv_orign(): df_empty = pandas.DataFrame(columns=['seriesuid','coord_x','coord_y','coord_z','probability',]) src_dir =settings.VAL_NODULE_DETECTION_DIR+'predictions10_luna16_fs/' # src_dir =settings.VAL_NODULE_DETECTION_DIR # for r in glob.glob(src_dir + "*_candidates_1.csv"): for r in glob.glob(src_dir + "*.csv"): csv=pandas.read_csv(r) del csv['diameter'] del csv['diameter_mm'] del csv['anno_index'] file_name = ntpath.basename(r) # patient_id = file_name.replace("_candidates_1.csv", "") patient_id = file_name.replace(".csv", "") csv['seriesuid']=patient_id csv = csv[csv["probability"] >= 0.95] df_empty = df_empty.append(csv) id = df_empty['seriesuid'] df_empty.drop(labels=['seriesuid'], axis=1,inplace = True) df_empty.insert(0, 'seriesuid', id) df_empty.rename(columns={'coord_x':'coordX','coord_y':'coordY','coord_z':'coordZ'}, inplace = True) df_empty.to_csv("./output_val/prediction_can_val3.csv",index=False)
def get_patient_xyz(path_f): candidate_index = 0 only_patient = "197063290812663596858124411210" only_patient = None patient_list=[] for subject_no in range(settings.VAL_SUBSET_START_INDEX, settings.VAL_SUBSET_TRAIN_NUM): src_dir = settings.RAW_SRC_DIR + "val_subset0" + str(subject_no) + "/" for src_path in glob.glob(src_dir + "*.mhd"): if only_patient is not None and only_patient not in src_path: continue patient_id = ntpath.basename(src_path).replace(".mhd", "") print(candidate_index, " patient: ", patient_id) if patient_id == 'LKDS-00557'or patient_id =='LKDS-00978' or patient_id =='LKDS-00881' or patient_id == 'LKDS-00186' or patient_id=='LKDS-00228' or patient_id=='LKDS-00877': continue pos_annos = get_patient_xyz_do(src_path, patient_id,path_f) patient_list.extend(pos_annos) candidate_index += 1 df_patient_list = pandas.DataFrame(patient_list, columns=["seriesuid", "coordX", "coordY", "coordZ","probability"]) df_patient_list.to_csv("./output_val/prediction_submission_val3.csv", index=False)
def do_put(self, s): try: params = s.split(' ') if len(params) > 1: src_path = params[0] dst_path = params[1] elif len(params) == 1: src_path = params[0] dst_path = '' src_file = os.path.basename(src_path) fh = open(src_path, 'rb') dst_path = string.replace(dst_path, '/','\\') import ntpath pathname = ntpath.join(ntpath.join(self.__pwd,dst_path), src_file) drive, tail = ntpath.splitdrive(pathname) logging.info("Uploading %s to %s" % (src_file, pathname)) self.__transferClient.putFile(drive[:-1]+'$', tail, fh.read) fh.close() except Exception, e: logging.critical(str(e)) pass
def do_put(self, s): try: if self.transferClient is None: self.connect_transferClient() params = s.split(' ') if len(params) > 1: src_path = params[0] dst_path = params[1] elif len(params) == 1: src_path = params[0] dst_path = '/' src_file = os.path.basename(src_path) fh = open(src_path, 'rb') f = dst_path + '/' + src_file pathname = string.replace(f,'/','\\') logging.info("Uploading %s to %s\%s" % (src_file, self.share, dst_path)) self.transferClient.putFile(self.share, pathname, fh.read) fh.close() except Exception, e: logging.error(str(e)) pass self.send_data('\r\n')
def do_get(self, src_path): try: if self.transferClient is None: self.connect_transferClient() import ntpath filename = ntpath.basename(src_path) fh = open(filename,'wb') logging.info("Downloading %s\%s" % (self.share, src_path)) self.transferClient.getFile(self.share, src_path, fh.write) fh.close() except Exception, e: logging.error(str(e)) pass self.send_data('\r\n')
def do_get(self, src_path): try: if self.transferClient is None: self.connect_transferClient() import ntpath filename = ntpath.basename(src_path) fh = open(filename,'wb') logging.info("Downloading %s\%s" % (self.share, src_path)) self.transferClient.getFile(self.share, src_path, fh.write) fh.close() except Exception, e: logging.critical(str(e)) pass self.send_data('\r\n')
def do_put(self, s): try: if self.transferClient is None: self.connect_transferClient() params = s.split(' ') if len(params) > 1: src_path = params[0] dst_path = params[1] elif len(params) == 1: src_path = params[0] dst_path = '/' src_file = os.path.basename(src_path) fh = open(src_path, 'rb') f = dst_path + '/' + src_file pathname = string.replace(f,'/','\\') logging.info("Uploading %s to %s\%s" % (src_file, self.share, dst_path)) self.transferClient.putFile(self.share, pathname.decode(sys.stdin.encoding), fh.read) fh.close() except Exception, e: logging.error(str(e)) pass self.send_data('\r\n')
def getValue(self, keyValue): # returns a tuple with (ValueType, ValueData) for the requested keyValue regKey = ntpath.dirname(keyValue) regValue = ntpath.basename(keyValue) key = self.findKey(regKey) if key is None: return None if key['NumValues'] > 0: valueList = self.__getValueBlocks(key['OffsetValueList'], key['NumValues']+1) for value in valueList: if value['Name'] == regValue: return value['ValueType'], self.__getValueData(value) elif regValue == 'default' and value['Flag'] <=0: return value['ValueType'], self.__getValueData(value) return None
def check_and_repair_framework(self, base): name = os.path.basename(base) if ".framework" in name: basename = name[:-len(".framework")] finalHeaders = os.path.join(base, "Headers") finalCurrent = os.path.join(base, "Versions/Current") finalLib = os.path.join(base, basename) srcHeaders = "Versions/A/Headers" srcCurrent = "A" srcLib = "Versions/A/" + basename if not os.path.exists(finalHeaders): os.symlink(srcHeaders, finalHeaders) if not os.path.exists(finalCurrent): os.symlink(srcCurrent, finalCurrent) if not os.path.exists(finalLib): os.symlink(srcLib, finalLib)
def resize_addset(source_folder, target_folder, dsize, pattern=FILE_PATTERN): print('Resizing additional set...') if not os.path.exists(target_folder): os.makedirs(target_folder) for clazz in ClassNames: if clazz not in os.listdir(target_folder): os.makedirs(os.path.join(target_folder, clazz)) total_images = glob.glob(os.path.join(source_folder, clazz, pattern)) total = len(total_images) for i, source in enumerate(total_images): filename = ntpath.basename(source) target = os.path.join(target_folder, clazz, filename.replace('.jpg', '.png')) try: img = cv2.imread(source) img_resized = cv2.resize(img, dsize, interpolation=cv2.INTER_CUBIC) cv2.imwrite(target, img_resized) except: print('-------------------> error in: {}'.format(source)) if i % 20 == 0: print("Resized {}/{} images".format(i, total))
def processFile(self, file_fullpath, hostID, instanceID, rowsData): rowNumber = 0 file_object = loadFile(file_fullpath) rows = _processAmCacheFile_StringIO(file_object) file_object.close() for r in rows: namedrow = settings.EntriesFields(HostID = hostID, EntryType = settings.__AMCACHE__, RowNumber = rowNumber, FilePath = (None if r.path == None else ntpath.dirname(r.path)), FileName = (None if r.path == None else ntpath.basename(r.path)), Size = r.size, ExecFlag = 'True', SHA1 = (None if r.sha1 == None else r.sha1[4:]), FileDescription = r.file_description, FirstRun = r.first_run, Created = r.created_timestamp, Modified1 = r.modified_timestamp, Modified2 = r.modified_timestamp2, LinkerTS = r.linker_timestamp, Product = r.product, Company = r.company, PE_sizeofimage = r.pe_sizeofimage, Version_number = r.version_number, Version = r.version, Language = r.language, Header_hash = r.header_hash, PE_checksum = r.pe_checksum, SwitchBackContext = r.switchbackcontext, InstanceID = instanceID) rowsData.append(namedrow) rowNumber += 1
def download_files_subtitles(user,password,files_array): array_errors = [] open_subs_manager = OpenSubsManager(False) if open_subs_manager.loginServer(user,password) == False: array_errors.append("Cant login into open subtitles server") else: for i, film_path in enumerate(files_array): if os.path.isfile(film_path): return_codes = open_subs_manager.automatically_download_subtitles(film_path,array_languages,"srt") for key, val in enumerate(return_codes): if val == 2: array_errors.append(basename(film_path)+" ( " + array_languages[key] + " ) : Download limit reached") if val == 4: array_errors.append(basename(film_path)+" ( " + array_languages[key] + " ) : Couldnt write subtitle to disk") elif val != 1: array_errors.append(basename(film_path)+" ( " + array_languages[key] + " ) : Not found valid subtitle") # Logout open_subs_manager.logoutServer() return array_errors ######################################################################################################################### # MAIN # ######################################################################################################################### # Get movies array
def parse_ini_file(self, ini_file): self.active_ini = cp.ConfigParser() self.active_ini.read(ini_file) self.active_ini_filename = ini_file self.section_select.delete(0, tk.END) for index, section in enumerate(self.active_ini.sections()): self.section_select.insert(index, section) self.ini_elements[section] = {} if "DEFAULT" in self.active_ini: self.section_select.insert(len(self.active_ini.sections()) + 1, "DEFAULT") self.ini_elements["DEFAULT"] = {} file_name = ": ".join([ntpath.basename(ini_file), ini_file]) self.file_name_var.set(file_name) self.clear_right_frame()
def parse_ini_file(self, ini_file): self.active_ini = cp.ConfigParser() self.active_ini.read(ini_file) self.active_ini_filename = ini_file self.section_select.delete(0, tk.END) for index, section in enumerate(self.active_ini.sections()): self.section_select.insert(index, section) if "DEFAULT" in self.active_ini: self.section_select.insert(len(self.active_ini.sections()) + 1, "DEFAULT") file_name = ": ".join([ntpath.basename(ini_file), ini_file]) self.file_name_var.set(file_name) self.clear_right_frame()
def browse_picture(self): image = QtGui.QFileDialog.getOpenFileName(None,'OpenFile','c:\\',"Image file(*.png *.jpg)") self.progressBar.setValue(0) image = str(image) print(image) self.file_name = ntpath.basename(image) self.file_name, ext=os.path.splitext(self.file_name) self.file_path = ntpath.dirname(image) self.write_path = ntpath.expanduser('~\\Documents\\Document Analysis') # creating write path if not exists if not os.path.exists(self.write_path): os.makedirs(self.write_path) if image: self.labelInputImage.setPixmap(QtGui.QPixmap(image). scaled(self.labelInputImage.width(), self.labelInputImage.height()))
def execute(self, context): scene = context.scene if not scene.sequence_editor: return {"FINISHED"} audiofile = bpy.path.abspath(scene.bz_audiofile) name = ntpath.basename(audiofile) all_strips = list(sorted( bpy.context.scene.sequence_editor.sequences_all, key=lambda x: x.frame_start)) bpy.ops.sequencer.select_all(action="DESELECT") count = 0 for strip in all_strips: if strip.name.startswith("bz_" + name): strip.select = True bpy.ops.sequencer.delete() return {"FINISHED"}
def do_get(self, arg, lpath="", r=True): "Receive file: get <file>" if not arg: arg = raw_input("Remote file: ") if not lpath: lpath = self.basename(arg) path = self.rpath(arg) if r else arg str_recv = self.get(path) if str_recv != c.NONEXISTENT: rsize, data = str_recv lsize = len(data) # fix carriage return chars added by some devices if lsize != rsize and len(conv().nstrip(data)) == rsize: lsize, data = rsize, conv().nstrip(data) # write to local file file().write(lpath, data) if lsize == rsize: print(str(lsize) + " bytes received.") else: self.size_mismatch(rsize, lsize)
def do_put(self, arg, rpath=""): "Send file: put <local file>" if not arg: arg = raw_input("Local file: ") if not rpath: rpath = os.path.basename(arg) rpath = self.rpath(rpath) lpath = os.path.abspath(arg) # read from local file data = file().read(lpath) if data != None: self.put(rpath, data) lsize = len(data) rsize = self.file_exists(rpath) if rsize == lsize: print(str(rsize) + " bytes transferred.") elif rsize == c.NONEXISTENT: print("Permission denied.") else: self.size_mismatch(lsize, rsize) # ------------------------[ append <file> <string> ]------------------
def load_TED(): '''Loads a TED file and returns a TrackObject''' root=tk.Tk() root.withdraw() root.attributes("-topmost", True) file_opt = options = {} options['defaultextension'] = '.ted' options['filetypes'] = [('GT6TED', '.ted')] options['initialdir'] = 'TED' options['parent'] = root options['title'] = 'Open file' path = filedialog.askopenfilename(**file_opt) filename = basename(path) root.destroy() try: with open(path, mode='rb') as file: tedfile = file.read() Track = initFromTedFile(tedfile, filename) return Track except FileNotFoundError: return None
def action_inject_delay(self): stereo = None if (self.var_3d.get()): stereo = "top-bottom" metadata = metadata_utils.Metadata() metadata.video = metadata_utils.generate_spherical_xml(stereo=stereo) if self.var_spatial_audio.get(): metadata.audio = metadata_utils.SPATIAL_AUDIO_DEFAULT_METADATA console = Console() metadata_utils.inject_metadata( self.in_file, self.save_file, metadata, console.append) self.set_message("Successfully saved file to %s\n" % ntpath.basename(self.save_file)) self.button_open.configure(state="normal") self.update_state()
def action_inject(self): """Inject metadata into a new save file.""" split_filename = os.path.splitext(ntpath.basename(self.in_file)) base_filename = split_filename[0] extension = split_filename[1] self.save_options["initialfile"] = (base_filename + "_injected" + extension) self.save_file = tkFileDialog.asksaveasfilename(**self.save_options) if not self.save_file: return self.set_message("Saving file to %s" % ntpath.basename(self.save_file)) # Launch injection on a separate thread after disabling buttons. self.disable_state() self.master.after(100, self.action_inject_delay)
def browse_picture(self): self.image = QtGui.QFileDialog.getOpenFileName(None,'OpenFile','c:\\',"Image file(*.png *.jpg)") self.progressBar.setValue(0) self.image = str(self.image) print(self.image) self.file_name = ntpath.basename(self.image) self.file_name, ext=os.path.splitext(self.file_name) self.file_path = ntpath.dirname(self.image) self.write_path = ntpath.expanduser('~\\Documents\\Document Analysis') # creating write path if not exists if not os.path.exists(self.write_path): os.makedirs(self.write_path) if self.image: pixmap = QtGui.QPixmap(self.image) pixmap = pixmap.scaled(pixmap.width()/5, pixmap.height()/5, QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation) #self.labelInputImage.resize(pixmap.width()/4,pixmap.height()/4) #self.labelInputImage.setPixmap(QtGui.QPixmap(self.image). # scaled(self.labelInputImage.width(), # self.labelInputImage.height())) self.labelInputImage.setPixmap(pixmap) #self.btnImageBrowse.setEnabled(False)
def askopenfilename(self): # define options for opening or saving a file self.file_opt = options = {} #options['defaultextension'] = '' #'.csv' #options['filetypes'] = [('all files', '.*'), ('text files', '.csv')] options['initialdir'] = expanduser(self.filename) if self.filename else expanduser("~") #options['initialfile'] = '' options['parent'] = self options['title'] = 'Choose File to upload' # get filename _filename = tkFileDialog.askopenfilename(**self.file_opt) # open file on your own if _filename: self.filename = _filename self.file_button["text"] = self.filename if (len(self.filename) <= 33) else "...{}".format(self.filename[-30:]) self.s3_name.set(ntpath.basename(self.filename))
def send_file(self, filepath): """ Send a base64 encoded string to the server. :param filepath: string path to file :return: None """ _, tail = os.path.split(filepath) print str(self.username) + " sending out " + str(tail) fh = open(filepath, 'rb') content = base64.b64encode(fh.read()) payload = self.new_payload() payload['content'] = content payload['type'] = constants.FILE payload['filename'] = os.path.basename(filepath) # Send the payload as a binary message by marking binary=True self.send(str(json.dumps(payload)), True) # Avoid feedback time.sleep(0.2) fh.close() # self.close()
def interpreter_path(self): ''' Returns the path for python interpreter, assuming it can be found. Because of various factors (inlcuding ablity to override) this may not be accurate. ''' if not self.__interpreter_path: #first try sys.executable--this is reliable most of the time but doesn't work when python is embedded, ex. using wsgi mod for web server if "python" in os.path.basename(sys.executable): self.__interpreter_path = sys.executable #second try sys.prefix and common executable names else: possible_path = os.path.join(sys.prefix, "python.exe") if os.path.exists(possible_path): self.__interpreter_path = possible_path possible_path = os.path.join(sys.prefix, "bin", "python") if os.path.exists(possible_path): self.__interpreter_path = possible_path #other options to consider: #look at some library paths, such as os.__file__, use system path to find python executable that uses that library #use shell and let it find python. Ex. which python return self.__interpreter_path
def list_parsers(self): ''' Retrieve list of parsers ''' parsers = [] if self.__disablemodulesearch: #We only look for .py files--it is much better to use regualr module search parser_file_postfix = self.__parsernamepostfix + '.py' for fullpath in glob.glob(os.path.join(self.parserdir, '*' + parser_file_postfix)): basefile = os.path.basename(fullpath) parsers.append(basefile[:-len(parser_file_postfix)]) else: for loader, modulename, ispkg in pkgutil.iter_modules(): if not ispkg: if modulename[-len(self.__parsernamepostfix):] == self.__parsernamepostfix and len(modulename) > len(self.__parsernamepostfix): parsers.append(modulename[:-len(self.__parsernamepostfix)]) return sorted(parsers, key=lambda s: s.lower())
def lookup_user_sids(self): regapi = registryapi.RegistryApi(self._config) regapi.set_current("hklm") key = "Microsoft\\Windows NT\\CurrentVersion\\ProfileList" val = "ProfileImagePath" sids = {} for subkey in regapi.reg_get_all_subkeys(None, key = key): sid = str(subkey.Name) path = regapi.reg_get_value(None, key = "", value = val, given_root = subkey) if path: path = str(path).replace("\x00", "") user = ntpath.basename(path) sids[sid] = user return sids
def render_text(self, outfd, data): if self._config.DUMP_DIR == None: debug.error("Please specify a dump directory (--dump-dir)") if not os.path.isdir(self._config.DUMP_DIR): debug.error(self._config.DUMP_DIR + " is not a directory") for name, buf in data: ## We can use the ntpath module instead of manually replacing the slashes ofname = ntpath.basename(name) ## Dump the raw event log so it can be parsed with other tools if self._config.SAVE_EVT: fh = open(os.path.join(self._config.DUMP_DIR, ofname), 'wb') fh.write(buf) fh.close() outfd.write('Saved raw .evt file to {0}\n'.format(ofname)) ## Now dump the parsed, pipe-delimited event records to a file ofname = ofname.replace(".evt", ".txt") fh = open(os.path.join(self._config.DUMP_DIR, ofname), 'wb') for fields in self.parse_evt_info(name, buf): fh.write('|'.join(fields) + "\n") fh.close() outfd.write('Parsed data sent to {0}\n'.format(ofname))
def path_leaf(path): """ Get just the filename from the full path. http://stackoverflow.com/questions/8384737/extract-file-name-from-path-no-matter-what-the-os-path-format """ head, tail = ntpath.split(path) return tail or ntpath.basename(head)
def get_file_name(self): return ntpath.basename(self.checker.path)
def get_file_name(self): return ntpath.basename(self.code.path)
def upload_policy(self, policy_file_path): try: data = {"policy": ""} files = {'file': (ntpath.basename(policy_file_path), open(policy_file_path, 'rb'),)} except IOError as e: return WebInspectResponse(success=False, message="There was an error while handling the request{}.".format(e)) # hack. doing this avoids us later specifying a content-type of application/json. needs a refactor headers = { 'Accept': 'application/json' } return self._request('POST', '/webinspect/securebase/policy', data=data, files=files, headers=headers)
def upload_settings(self, settings_file_path): try: data = {"scanSettings": ""} files = {'file': (ntpath.basename(settings_file_path), open(settings_file_path, 'rb'),)} except IOError as e: return WebInspectResponse(success=False, message="There was an error while handling the request{}.".format(e)) return self._request('PUT', '/webinspect/scanner/settings', data=data, files=files)
def upload_webmacro(self, macro_file_path): try: files = {'macro': (ntpath.basename(macro_file_path), open(macro_file_path, 'rb'))} except IOError as e: return WebInspectResponse(success=False, message="Could not read file to upload {}.".format(e)) return self._request('PUT', '/webinspect/scanner/macro', files=files)
def slice_image(self, source_image, tile_width, tile_height): if not os.path.isfile(source_image): self.logger.error('file {} does not exist'.format(source_image)) exit(1) file = open(source_image, 'rb') with Image.open(file) as image: cwd = os.getcwd() basename = strftime("slice_%Y-%m-%d_%H-%M-%S", gmtime()) directory = os.path.join(cwd, basename) self.logger.info('slicing picture {} into tiles'.format(source_image)) tiles = make_tiles(image, tile_width=tile_width, tile_height=tile_height) store_tiles(tiles, directory) self.logger.info('picture sliced into {} tiles {}'.format(len(tiles), directory))
def _get_filename(self, path): head, tail = ntpath.split(path) return tail or ntpath.basename(head)
def post_localfile(roomId, encoded_photo, text='', html='', markdown='', toPersonId='', toPersonEmail=''): filename='/app/output.jpg' with open(filename, 'wb') as handle: handle.write(encoded_photo.decode('base64')) openfile = open(filename, 'rb') filename = ntpath.basename(filename) payload = {'roomId': roomId, 'files': (filename, openfile, 'image/jpg')} #payload = {'roomId': roomId} if text: payload['text'] = text if html: payload['html'] = html if markdown: payload['markdown'] = markdown if toPersonId: payload['toPersonId'] = toPersonId if toPersonEmail: payload['toPersonEmail'] = toPersonEmail m = MultipartEncoder(fields=payload) headers = {'Authorization': "Bearer " + spark_token, 'Content-Type': m.content_type} page = requests.request("POST",url=spark_host + "v1/messages", data=m, headers = headers ) sys.stderr.write( "page: "+str(page)+"\n" ) message=page.json() file_dict = json.loads(page.text) file_dict['statuscode'] = str(page.status_code) sys.stderr.write( "statuscode: "+str(file_dict['statuscode'])+"\n" ) sys.stderr.write( "file_dict: "+str(file_dict)+"\n" ) handle.close() openfile.close() return message
def post_pdffile(roomId, encoded_file, text='', html='', markdown='', toPersonId='', toPersonEmail=''): filename='/app/output.pdf' with open(filename, 'wb') as handle: handle.write(encoded_file.decode('base64')) openfile = open(filename, 'rb') filename = ntpath.basename(filename) payload = {'roomId': roomId, 'files': (filename, openfile, 'application/pdf')} #payload = {'roomId': roomId} if text: payload['text'] = text if html: payload['html'] = html if markdown: payload['markdown'] = markdown if toPersonId: payload['toPersonId'] = toPersonId if toPersonEmail: payload['toPersonEmail'] = toPersonEmail m = MultipartEncoder(fields=payload) headers = {'Authorization': "Bearer " + spark_token, 'Content-Type': m.content_type} page = requests.request("POST",url=spark_host + "v1/messages", data=m, headers = headers ) sys.stderr.write( "page: "+str(page)+"\n" ) message=page.json() file_dict = json.loads(page.text) file_dict['statuscode'] = str(page.status_code) sys.stderr.write( "statuscode: "+str(file_dict['statuscode'])+"\n" ) sys.stderr.write( "file_dict: "+str(file_dict)+"\n" ) handle.close() openfile.close() return message