本文整理汇总了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)
示例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
示例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, [])
示例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
示例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'])
示例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
示例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
示例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)
示例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)
示例10: run
# 需要导入模块: import ntpath [as 别名]
# 或者: from ntpath import dirname [as 别名]
def run(cls, path):
if path is not None:
return ntpath.dirname(path)
示例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
示例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)
示例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))
示例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
示例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,
)