当前位置: 首页>>代码示例>>Python>>正文


Python ntpath.dirname方法代码示例

本文整理汇总了Python中ntpath.dirname方法的典型用法代码示例。如果您正苦于以下问题:Python ntpath.dirname方法的具体用法?Python ntpath.dirname怎么用?Python ntpath.dirname使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ntpath的用法示例。


在下文中一共展示了ntpath.dirname方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: removedirs

# 需要导入模块: import ntpath [as 别名]
# 或者: from ntpath import dirname [as 别名]
def removedirs(name, **kwargs):
    """
    Remove directories recursively. Works like rmdir() except that, if the leaf directory is successfully removed,
    removedirs() tries to successively remove every parent directory mentioned in path until an error is raised (which
    is ignored, because it generally means that a parent directory is not empty).

    :param name: The directory to start removing recursively from.
    :param kwargs: Common SMB Session arguments for smbclient.
    """
    remove_dir = ntpath.normpath(name)
    while True:
        try:
            rmdir(remove_dir, **kwargs)
        except (SMBResponseException, OSError):
            return
        else:
            remove_dir = ntpath.dirname(remove_dir) 
开发者ID:jborean93,项目名称:smbprotocol,代码行数:19,代码来源:_os.py

示例2: getValue

# 需要导入模块: import ntpath [as 别名]
# 或者: from ntpath import dirname [as 别名]
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 
开发者ID:joxeankoret,项目名称:CVE-2017-7494,代码行数:22,代码来源:winregistry.py

示例3: runIndexedSearch

# 需要导入模块: import ntpath [as 别名]
# 或者: from ntpath import dirname [as 别名]
def runIndexedSearch(dbfilenameFullPath, search_space, options):
    # todo: Handle duplicate hit supression
    logger.info("Performing indexed search")
    DB = appDB.DBClass(dbfilenameFullPath, True, settings.__version__)
    DB.appInitDB()
    DB.appConnectDB()

    searchTerm = options.searchLiteral[0]
    numHits = 0
    # Run actual indexed query
    data = DB.Query("SELECT RowID FROM Entries_FilePaths WHERE %s == '%s';" % (search_space, searchTerm))
    if data:
        # results = []
        # results.append(('cyan', "FileName,HitCount".split(',')))
        with open(options.outputFile, "w") as text_file:
            with open(os.path.join(ntpath.dirname(options.outputFile), ntpath.splitext(options.outputFile)[0] + ".mmd"), "w") as markdown_file:
                for row in data:
                    # results.append(('white', row))
                    record = retrieveSearchData(row[0], DB, search_space)
                    saveSearchData(record, None, None, text_file, markdown_file)
                    numHits += 1
                # outputcolum(results)

        return (numHits, 0, [])
    else: return(0, 0, []) 
开发者ID:mbevilacqua,项目名称:appcompatprocessor,代码行数:27,代码来源:appSearch.py

示例4: extract_fbank_htk

# 需要导入模块: import ntpath [as 别名]
# 或者: from ntpath import dirname [as 别名]
def extract_fbank_htk(self, scriptfile):
        '''
        :param scriptfile: path to the HCopy's script file
        :return: list of path to feature files
        '''

        with open(scriptfile, 'r') as scpf:
            featfiles = scpf.readlines()
        featfiles = [f.split(' ')[1].replace('\n', '') for f in featfiles]

        for f in featfiles:
            if not os.path.exists(ntpath.dirname(f)):
                os.makedirs(ntpath.dirname(f))

        cmd = self.HCopyExe + ' -C ' + self.HConfigFile + ' -S ' + scriptfile
        os.system(cmd)

        return featfiles 
开发者ID:znaoya,项目名称:aenet,代码行数:20,代码来源:__init__.py

示例5: get_path_filename

# 需要导入模块: import ntpath [as 别名]
# 或者: from ntpath import dirname [as 别名]
def get_path_filename(self, obj):

        ''' Get the path and build it into protocol://path
        '''
        if self.direct_path:

            if '\\' in obj['Path']:
                obj['Path'] = "%s\\" % obj['Path']
                obj['TopLevel'] = "%s\\" % dirname(dirname(obj['Path']))
            else:
                obj['Path'] = "%s/" % obj['Path']
                obj['TopLevel'] = "plugin://plugin.video.jellyfin/"

            if not validate(obj['Path']):
                raise Exception("Failed to validate path. User stopped.")
        else:
            obj['TopLevel'] = "plugin://plugin.video.jellyfin/%s/" % obj['LibraryId']
            obj['Path'] = "%s%s/" % (obj['TopLevel'], obj['Id']) 
开发者ID:jellyfin,项目名称:jellyfin-kodi,代码行数:20,代码来源:tvshows.py

示例6: check_proc_susp_path

# 需要导入模块: import ntpath [as 别名]
# 或者: from ntpath import dirname [as 别名]
def check_proc_susp_path(self, process):
		if int(process.UniqueProcessId) == 4:
			return True

		if process.Peb == None or \
           process.Peb.ProcessParameters == None or \
           process.Peb.ProcessParameters.ImagePathName == None:
			return None

		suspicious = False
		for r in list_bad_paths:
			if r.match(ntpath.dirname(str(process.Peb.ProcessParameters.ImagePathName).lower())):
				suspicious = True
		
		return not suspicious

    # Checks the process parent 
开发者ID:csababarta,项目名称:volatility_plugins,代码行数:19,代码来源:malprocfind.py

示例7: getValue

# 需要导入模块: import ntpath [as 别名]
# 或者: from ntpath import dirname [as 别名]
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'] == b(regValue):
                    return value['ValueType'], self.__getValueData(value)
                elif regValue == 'default' and value['Flag'] <=0:
                    return value['ValueType'], self.__getValueData(value)

        return None 
开发者ID:Coalfire-Research,项目名称:Slackor,代码行数:22,代码来源:winregistry.py

示例8: makedirs

# 需要导入模块: import ntpath [as 别名]
# 或者: from ntpath import dirname [as 别名]
def makedirs(path, exist_ok=False, **kwargs):
    """
    Recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain
    the leaf directory.

    If exist_ok is False (the default), an OSError is raised if the target directory already exists.

    :param path: The path to the directory to create.
    :param exist_ok: Set to True to not fail if the target directory already exists.
    :param kwargs: Common SMB Session arguments for smbclient.
    """
    create_queue = [ntpath.normpath(path)]
    present_parent = None
    while create_queue:
        mkdir_path = create_queue[-1]
        try:
            mkdir(mkdir_path, **kwargs)
        except OSError as err:
            if err.errno == errno.EEXIST:
                present_parent = mkdir_path
                create_queue.pop(-1)
                if not create_queue and not exist_ok:
                    raise
            elif err.errno == errno.ENOENT:
                # Check if the parent path has already been created to avoid getting in an endless loop.
                parent_path = ntpath.dirname(mkdir_path)
                if present_parent == parent_path:
                    raise
                else:
                    create_queue.append(parent_path)
            else:
                raise
        else:
            create_queue.pop(-1) 
开发者ID:jborean93,项目名称:smbprotocol,代码行数:36,代码来源:_os.py

示例9: renames

# 需要导入模块: import ntpath [as 别名]
# 或者: from ntpath import dirname [as 别名]
def renames(old, new, **kwargs):
    """
    Recursive directory or file renaming function. Works like rename(), except creation of any intermediate directories
    needed to make the new pathname good is attempted first. After the rename, directories corresponding to rightmost
    path segments of the old name will be pruned away using removedirs().

    :param old: The path to the file or directory to rename.
    :param new: The path to rename the file or directory to.
    :param kwargs: Common SMB Session arguments for smbclient.
    """
    makedirs(ntpath.dirname(new), exist_ok=True, **kwargs)
    rename(old, new, **kwargs)
    removedirs(ntpath.dirname(old), **kwargs) 
开发者ID:jborean93,项目名称:smbprotocol,代码行数:15,代码来源:_os.py

示例10: run

# 需要导入模块: import ntpath [as 别名]
# 或者: from ntpath import dirname [as 别名]
def run(cls, path):
        if path is not None:
            return ntpath.dirname(path) 
开发者ID:endgameinc,项目名称:eqllib,代码行数:5,代码来源:functions.py

示例11: gen_wrap_str

# 需要导入模块: import ntpath [as 别名]
# 或者: from ntpath import dirname [as 别名]
def gen_wrap_str(self):
        dir_path = ntpath.dirname(self.file) + '/'
        wrap_str = '''
sess = None
def tf_score({4}):
    "Output: {5}"
    import tensorflow as tf
    import numpy as np
    global sess
    global score_op
    global input_op
    #If it is called for the first time, restore the model and necessary operations
    if sess is None:
        sess=tf.Session()
        #load meta graph and restore weights
        saver = tf.train.import_meta_graph('{0}')
        saver.restore(sess,tf.train.latest_checkpoint('{1}'))

        graph = tf.get_default_graph()
        #restore the ops. Both ops were pre-defined in the model.
        input_op = graph.get_tensor_by_name("{2}:0") #op to feed input data
        score_op = graph.get_tensor_by_name("{3}:0")    #op to score the input

    #Note that the feed value of x has shape (?,xyz), NOT (,xyz)
    {4}_wrap = np.array([{4}])
    {5} = sess.run(score_op, feed_dict={{input_op: {4}_wrap}})[0]

    if isinstance({5}, np.ndarray):
        {5} = {5}.tolist()
    else:
        {5} = {5}.item()

    return {5}'''.format(self.file, dir_path, self.input_op, self.score_op,
                         self.input_name, self.output_name)

        return wrap_str 
开发者ID:sassoftware,项目名称:python-esppy,代码行数:38,代码来源:generators.py

示例12: init

# 需要导入模块: import ntpath [as 别名]
# 或者: from ntpath import dirname [as 别名]
def init(self, config=None, server='https://pipe.databolt.tech', reset=False):
        """

        Initialize config with content

        Args:
            config (dict): manually pass config object
            server (str): location of REST API server
            reset (bool): force reset of an existing config

        """

        if os.path.exists(self.filecfg) and not reset and self.profile in self._loadall():
            # todo: why does Path(self.filecfg).exists() not work in pytest?
            warnings.warn('Config for profile {} in {} already exists, skipping init. Use reset=True to reset config.'.format(self.profile,self.filecfg))
            return None

        if not config:
            config = {}
        if 'server' not in config:
                config['server'] = server
        if 'filerepo' not in config:
            config['filerepo'] = '~/d6tpipe'
        p = Path(config['filerepo'])
        p2 = p/'files/{}/'.format(self.profile)
        config['filereporoot'] = str(p)
        config['filerepo'] = str(p2)
        if 'filedb' not in config:
            config['filedb'] = str(p2/'.filedb.json')

        # create config file if doesn't exist
        if not os.path.exists(self.filecfg):
            if not os.path.exists(ntpath.dirname(self.filecfg)):
                os.makedirs(ntpath.dirname(self.filecfg))

        self._save(config) 
开发者ID:d6t,项目名称:d6tpipe,代码行数:38,代码来源:api.py

示例13: open_value

# 需要导入模块: import ntpath [as 别名]
# 或者: from ntpath import dirname [as 别名]
def open_value(self, path):
        key = self.open_key(ntpath.dirname(path))

        return key.open_value(ntpath.basename(path)) 
开发者ID:google,项目名称:rekall,代码行数:6,代码来源:registry.py

示例14: listPath

# 需要导入模块: import ntpath [as 别名]
# 或者: from ntpath import dirname [as 别名]
def listPath(self, shareName, path, password = None):
        # ToDo: Handle situations where share is password protected
        path = string.replace(path,'/', '\\')
        path = ntpath.normpath(path)
        if len(path) > 0 and path[0] == '\\':
            path = path[1:]

        treeId = self.connectTree(shareName)

        fileId = None
        try:
            # ToDo, we're assuming it's a directory, we should check what the file type is
            fileId = self.create(treeId, ntpath.dirname(path), FILE_READ_ATTRIBUTES | FILE_READ_DATA ,FILE_SHARE_READ | FILE_SHARE_WRITE |FILE_SHARE_DELETE, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, FILE_OPEN, 0) 
            res = ''
            files = []
            from impacket import smb
            while True:
                try:
                    res = self.queryDirectory( treeId, fileId, ntpath.basename(path), maxBufferSize = 65535, informationClass = FILE_FULL_DIRECTORY_INFORMATION )
                    nextOffset = 1
                    while nextOffset != 0:
                        fileInfo = smb.SMBFindFileFullDirectoryInfo(smb.SMB.FLAGS2_UNICODE)
                        fileInfo.fromString(res)
                        files.append(smb.SharedFile(fileInfo['CreationTime'],fileInfo['LastAccessTime'],fileInfo['LastChangeTime'],fileInfo['EndOfFile'],fileInfo['AllocationSize'],fileInfo['ExtFileAttributes'],fileInfo['FileName'].decode('utf-16le'), fileInfo['FileName'].decode('utf-16le')))
                        nextOffset = fileInfo['NextEntryOffset']
                        res = res[nextOffset:]
                except SessionError, e:
                    if (e.get_error_code()) != STATUS_NO_MORE_FILES:
                        raise
                    break 
        finally:
            if fileId is not None:
                self.close(treeId, fileId)
            self.disconnectTree(treeId) 

        return files 
开发者ID:joxeankoret,项目名称:CVE-2017-7494,代码行数:38,代码来源:smb3.py

示例15: _create_remote_dir

# 需要导入模块: import ntpath [as 别名]
# 或者: from ntpath import dirname [as 别名]
def _create_remote_dir(state, host, remote_filename, user, group):
    # Always use POSIX style path as local might be Windows, remote always *nix
    remote_dirname = ntpath.dirname(remote_filename)
    if remote_dirname:
        yield directory(
            state, host, remote_dirname,
            user=user, group=group,
        ) 
开发者ID:Fizzadar,项目名称:pyinfra,代码行数:10,代码来源:windows_files.py


注:本文中的ntpath.dirname方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。