Python源码示例:ntpath.basename()

示例1
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) 
示例2
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 
示例3
def main():
  args = parser.parse_args()

  for font_path in args.fonts:
    nametable = nametable_from_filename(font_path)
    font = TTFont(font_path)
    font_filename = ntpath.basename(font_path)

    font['name'] = nametable
    style = font_filename[:-4].split('-')[-1]
    font['OS/2'].usWeightClass = set_usWeightClass(style)
    font['OS/2'].fsSelection = set_fsSelection(font['OS/2'].fsSelection, style)
    win_style = font['name'].getName(2, 3, 1, 1033).string.decode('utf_16_be')
    font['head'].macStyle = set_macStyle(win_style)

    font.save(font_path + '.fix')
    print('font saved %s.fix' % font_path) 
示例4
def main():
  args = parser.parse_args()

  rows = []
  for font_filename in args.fonts:
    font = TTFont(font_filename)
    for field in font['name'].names:
      enc = field.getEncoding()
      rows.append([
        ('Font', ntpath.basename(font_filename)),
        ('platformID', field.platformID),
        ('encodingID', field.platEncID),
        ('languageID', field.langID),
        ('nameID', field.nameID),
        ('nameString', field.toUnicode()),
      ])

  if args.csv:
    printInfo(rows, save=True)
  else:
    printInfo(rows) 
示例5
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) 
示例6
def FetchPDBFile(self):
        # Ensure the pdb filename has the correct extension.
        pdb_filename = self.plugin_args.pdb_filename
        guid = self.plugin_args.guid

        if not pdb_filename.endswith(".pdb"):
            pdb_filename += ".pdb"

        for url in self.SYM_URLS:
            basename = ntpath.splitext(pdb_filename)[0]
            try:
                return self.DownloadUncompressedPDBFile(
                    url, pdb_filename, guid, basename)
            except urllib.error.HTTPError:
                return self.DownloadCompressedPDBFile(
                    url, pdb_filename, guid, basename) 
示例7
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 
示例8
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) 
示例9
def generator(self, data):
        if self._config.DUMP_DIR and not self._config.SAVE_EVT:
            debug.error("Please add --save-evt flag to dump EVT files")
        if self._config.SAVE_EVT and self._config.DUMP_DIR == None:
            debug.error("Please specify a dump directory (--dump-dir)")
        if self._config.SAVE_EVT and not os.path.isdir(self._config.DUMP_DIR):
            debug.error(self._config.DUMP_DIR + " is not a directory")

        for name, buf in data:
            ## Dump the raw event log so it can be parsed with other tools
            if self._config.SAVE_EVT:
                ofname = ntpath.basename(name)
                fh = open(os.path.join(self._config.DUMP_DIR, ofname), 'wb')
                fh.write(buf)
                fh.close()
                print 'Saved raw .evt file to {0}'.format(ofname)
            for fields in self.parse_evt_info(name, buf):
                yield (0, [str(fields[0]), str(fields[1]), str(fields[2]), str(fields[3]), str(fields[4]), str(fields[5]), str(fields[6])]) 
示例10
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)) 
示例11
def generator(self, data):

        for process, module, hook in data:
            procname = "N/A"
            pid = -1
            addr_base = 0

            for n, info in enumerate(hook.disassembled_hops):
                (address, data) = info
                addr_base = vad_ck().get_vad_base(process, address)
                procname = str(process.ImageFileName)
                pid = int(process.UniqueProcessId)

                yield (0, [str(hook.Type),
                    procname,
                    pid,
                    str(module.BaseDllName or '') or ntpath.basename(str(module.FullDllName or '')),
                    Address(module.DllBase),
                    module.DllBase + module.SizeOfImage,
                    str(hook.Detail),
                    Address(hook.hook_address),
                    Address(addr_base),
                    str(hook.HookModule),
                    Address(address),
                    Bytes(data)]) 
示例12
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 
示例13
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.jpg' % (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) 
示例14
def save_images(self, webpage, visuals, image_path):
        image_dir = webpage.get_image_dir()
        short_path = ntpath.basename(image_path[0])
        class_info = image_path[0].split('/')[ len( image_path[0].split('/')) -2 ]
        name = class_info + '_' +  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) 
示例15
def get_cfg(existing_cfg, _log):
    """
    generates
    """
    _sanity_check(existing_cfg, _log)
    import ntpath, os, ruamel.yaml as yaml
    with open(os.path.join(os.path.dirname(__file__), "{}.yml".format(ntpath.basename(__file__).split(".")[0])),
              'r') as stream:
        try:
            ret = yaml.load(stream, Loader=yaml.Loader)
        except yaml.YAMLError as exc:
            assert "Default config yaml for '{}' not found!".format(os.path.splitext(__file__)[0])

    #if ret["coma_critic_use_sampling"] and "coma_critic_sample_size" not in ret and hasattr(ret, "batch_size_run"):
    #    ret["coma_critic_sample_size"] = ret["batch_size_run"] * 50
    return ret 
示例16
def get_cfg(existing_cfg, _log):
    """
    generates
    """
    _sanity_check(existing_cfg, _log)
    import ntpath, os, ruamel.yaml as yaml
    with open(os.path.join(os.path.dirname(__file__), "{}.yml".format(ntpath.basename(__file__).split(".")[0])),
              'r') as stream:
        try:
            ret = yaml.load(stream, Loader=yaml.Loader)
        except yaml.YAMLError as exc:
            assert "Default config yaml for '{}' not found!".format(os.path.splitext(__file__)[0])

    if ret["coma_critic_use_sampling"] and "coma_critic_sample_size" not in ret and hasattr(ret, "batch_size_run"):
        ret["coma_critic_sample_size"] = ret["batch_size_run"] * 50
    return ret 
示例17
def get_cfg(existing_cfg, _log):
    """

    """
    _sanity_check(existing_cfg, _log)
    import ntpath, os, ruamel.yaml as yaml
    with open(os.path.join(os.path.dirname(__file__), "{}.yml".format(ntpath.basename(__file__).split(".")[0])), 'r') as stream:
        try:
            ret = yaml.load(stream, Loader=yaml.Loader)
        except yaml.YAMLError as exc:
            assert False, "Default config yaml for '{}' not found!".format(os.path.splitext(__file__)[0])

    if not "batch_size_run" in ret:
        ret["batch_size_run"] = ret["batch_size"]

    if not "runner_test_batch_size" in ret:
        ret["runner_test_batch_size"] = ret["batch_size_run"]

    if not "name" in ret:
        ret["name"] = ntpath.basename(__file__).split(".")[0]

    return ret 
示例18
def get_cfg(existing_cfg, _log):
    """

    """
    _sanity_check(existing_cfg, _log)
    import ntpath, os, ruamel.yaml as yaml
    with open(os.path.join(os.path.dirname(__file__), "{}.yml".format(ntpath.basename(__file__).split(".")[0])), 'r') as stream:
        try:
            ret = yaml.load(stream, Loader=yaml.Loader)
        except yaml.YAMLError as exc:
            assert False, "Default config yaml for '{}' not found!".format(os.path.splitext(__file__)[0])

    if not "batch_size_run" in ret:
        ret["batch_size_run"] = ret["batch_size"]

    if not "runner_test_batch_size" in ret:
        ret["runner_test_batch_size"] = ret["batch_size_run"]

    if not "name" in ret:
        ret["name"] = ntpath.basename(__file__).split(".")[0]

    return ret 
示例19
def get_cfg(existing_cfg, _log):
    """

    """
    _sanity_check(existing_cfg, _log)
    import ntpath, os, ruamel.yaml as yaml
    with open(os.path.join(os.path.dirname(__file__), "{}.yml".format(ntpath.basename(__file__).split(".")[0])), 'r') as stream:
        try:
            ret = yaml.load(stream, Loader=yaml.Loader)
        except yaml.YAMLError as exc:
            assert False, "Default config yaml for '{}' not found!".format(os.path.splitext(__file__)[0])

    if not "batch_size_run" in ret:
        ret["batch_size_run"] = ret["batch_size"]

    if not "runner_test_batch_size" in ret:
        ret["runner_test_batch_size"] = ret["batch_size_run"]

    if not "name" in ret:
        ret["name"] = ntpath.basename(__file__).split(".")[0]

    return ret 
示例20
def get_cfg(existing_cfg, _log):
    """

    """
    _sanity_check(existing_cfg, _log)
    import ntpath, os, yaml
    with open(os.path.join(os.path.dirname(__file__), "{}.yml".format(ntpath.basename(__file__).split(".")[0])), 'r') as stream:
        try:
            ret = yaml.load(stream)
        except yaml.YAMLError as exc:
            assert False, "Default config yaml for '{}' not found!".format(os.path.splitext(__file__)[0])

    if not "batch_size_run" in ret:
        ret["batch_size_run"] = ret["batch_size"]

    if not "runner_test_batch_size" in ret:
        ret["runner_test_batch_size"] = ret["batch_size_run"]

    if not "name" in ret:
        ret["name"] = ntpath.basename(os.path.dirname(__file__))

    return ret 
示例21
def get_cfg(existing_cfg, _log):
    """

    """
    _sanity_check(existing_cfg, _log)
    import ntpath, os, yaml
    with open(os.path.join(os.path.dirname(__file__), "{}.yml".format(ntpath.basename(__file__).split(".")[0])), 'r') as stream:
        try:
            ret = yaml.load(stream)
        except yaml.YAMLError as exc:
            assert False, "Default config yaml for '{}' not found!".format(os.path.splitext(__file__)[0])

    if not "batch_size_run" in ret:
        ret["batch_size_run"] = ret["batch_size"]

    if not "runner_test_batch_size" in ret:
        ret["runner_test_batch_size"] = ret["batch_size_run"]

    if not "name" in ret:
        ret["name"] = ntpath.basename(os.path.dirname(__file__))

    return ret 
示例22
def _copy(src, dst, follow_symlinks, copy_meta_func, **kwargs):
    # Need to check if dst is a UNC path before checking if it's a dir in smbclient.path before checking to see if it's
    # a local directory. If either one is a dir, join the filename of src onto dst.
    if ntpath.normpath(dst).startswith('\\\\') and isdir(dst, **kwargs):
        dst = ntpath.join(dst, ntpath.basename(src))
    elif os.path.isdir(dst):
        dst = os.path.join(dst, os.path.basename(src))

    copyfile(src, dst, follow_symlinks=follow_symlinks)
    copy_meta_func(src, dst, follow_symlinks=follow_symlinks)
    return dst 
示例23
def prep(fil3):
    matches = re.match('^(.*)\..*?$', ntpath.basename(fil3)).groups(0)
    convert(fil3, 'osm/%s.osm' % matches[0]) 
示例24
def run(cls, path):
        if path is not None:
            return ntpath.basename(path) 
示例25
def __init__(self, opt, save_dir, filename='loss_log.txt'):
        self.display_id = opt.display_id
        self.use_html = not opt.no_html
        self.win_size = opt.display_winsize
        self.save_dir = save_dir
        self.name = os.path.basename(self.save_dir)
        self.saved = False
        self.display_single_pane_ncols = opt.display_single_pane_ncols

        # Error plots
        self.error_plots = dict()
        self.error_wins = dict()

        if self.display_id > 0:
            import visdom
            self.vis = visdom.Visdom(port=opt.display_port)

        if self.use_html:
            self.web_dir = os.path.join(self.save_dir, 'web')
            self.img_dir = os.path.join(self.web_dir, 'images')
            print('create web directory %s...' % self.web_dir)
            util.mkdirs([self.web_dir, self.img_dir])
        self.log_name = os.path.join(self.save_dir, filename)
        with open(self.log_name, "a") as log_file:
            now = time.strftime("%c")
            log_file.write('================ Training Loss (%s) ================\n' % now) 
示例26
def get_module_by_name(self, module_name):
		for mod in self.modules:
			if ntpath.basename(mod.name).find(module_name) != -1:
				return mod
		return None 
示例27
def listOfPathsToDir(lst, target_Dir):
    for i in lst:
        parentfolder = ntpath.basename(os.path.dirname(i))
        filename = ntpath.basename(i)
        # Ensure the Dir is There
        forcedir(target_Dir + "/" + parentfolder)
        dstBuilder = target_Dir + "/" + parentfolder + filename
        shutil.copyfile(i, dstBuilder)


# [synth pack 1, synth pack 2, synth pack 3, synth pack 4... ], op1/synth 
示例28
def copyListOfDirs(lst, target_Dir):
    for i in lst:
        foldername = ntpath.basename(i)
        forcedir(target_Dir + "/" + foldername)
        copytree(i, target_Dir + "/" + foldername)


# =======================List Files====================== 
示例29
def fileTransferHelper(srclist, dest):
    """
    Pass in list of paths to file, and copy to root destination
    It will create patch's parent folder if not already exist in the destination folder
    For example:
        fileTransferHelper(["..../OP1_File_Organizer/NotUsed/..../patch.aif"], dest = "/..../synth")

    :param srclist: ["pwd/1.aif", "pwd/2.aif", "pwd/3.aif",....., "pwd/n.aif"]
    :param dest: Root of the synth and drum destination folder
    :return: NA
    """

    for i in srclist:
        srcParentFolderName = abspath(join(i, pardir)).split("/")[-1:][0]
        srcBaseName = basename(i)
        distParentFolderName = dest + "/" + str(srcParentFolderName)
        print(distParentFolderName)
        forcedir(distParentFolderName)
        image = Image.new('1', (128, 64))

        if workDir in srclist[0]:
            # Local to OP1
            image.paste(Image.open(workDir + "/Assets/Img/UploadPatches.png").convert("1"))
        else:
            # OP1 to Local
            image.paste(Image.open(workDir + "/Assets/Img/DownloadPatches.png").convert("1"))
        draw = ImageDraw.Draw(image)
        draw.text((20, 63), srcBaseName, font=GPIO_Init.getFont(), fill="white")
        GPIO_Init.displayImage(image)
        print(i, distParentFolderName + "/" + srcBaseName)
        shutil.copy2(i, distParentFolderName + "/" + srcBaseName)

    GPIO_Init.displayPng(workDir + "/Assets/Img/Done.png")
    GPIO_Init.getAnyKeyEvent()  # Press any key to proceed
    return 
示例30
def moveFilesToFolder(lst, destFolderPath):
    for f in lst:
        base = basename(f)
        dest = os.path.join(destFolderPath, base)
        print("Moving: ", f, "      To: ", dest)
        shutil.move(f, dest)