Python源码示例:pathlib.PureWindowsPath()
示例1
def get_path_from_template(path_template: str, path_type: PathType = PathType.AUTO) -> str:
"""Replace tags in the given path template and return either Windows or Linux formatted path."""
# automatically select path type depending on running OS
if path_type == PathType.AUTO:
if platform.system() == "Windows":
path_type = PathType.WINDOWS
elif platform.system() == "Linux":
path_type = PathType.LINUX
else:
raise RuntimeError("Unknown platform")
path_template = path_template.replace("<USERNAME>", get_user_name())
# return correctly formatted path
if path_type == PathType.WINDOWS:
return str(pathlib.PureWindowsPath(path_template))
elif path_type == PathType.LINUX:
return str(pathlib.PurePosixPath(path_template))
else:
raise RuntimeError("Unknown platform")
示例2
def filter_extension_skip_current(self, event, src_check=False, dest_check=False):
#src_path
if src_check:
if not self.extension_filter is None:
extension = pathlib.PureWindowsPath(event.src_path).suffix.lower().lstrip('.')
if not extension in self.extension_filter:
return True
#dest_path
if dest_check:
if not self.extension_filter is None:
extension = pathlib.PureWindowsPath(event.dest_path).suffix.lower().lstrip('.')
if not extension in self.extension_filter:
return True
return False
示例3
def test_different_flavours_unordered(self):
p = pathlib.PurePosixPath('a')
q = pathlib.PureWindowsPath('a')
with self.assertRaises(TypeError):
p < q
with self.assertRaises(TypeError):
p <= q
with self.assertRaises(TypeError):
p > q
with self.assertRaises(TypeError):
p >= q
#
# Tests for the concrete classes
#
# Make sure any symbolic links in the base test path are resolved
示例4
def test_different_flavours_unordered(self):
p = pathlib.PurePosixPath('a')
q = pathlib.PureWindowsPath('a')
with self.assertRaises(TypeError):
p < q
with self.assertRaises(TypeError):
p <= q
with self.assertRaises(TypeError):
p > q
with self.assertRaises(TypeError):
p >= q
#
# Tests for the concrete classes
#
# Make sure any symbolic links in the base test path are resolved
示例5
def test_different_flavours_unordered(self):
p = pathlib.PurePosixPath('a')
q = pathlib.PureWindowsPath('a')
with self.assertRaises(TypeError):
p < q
with self.assertRaises(TypeError):
p <= q
with self.assertRaises(TypeError):
p > q
with self.assertRaises(TypeError):
p >= q
#
# Tests for the concrete classes
#
# Make sure any symbolic links in the base test path are resolved
示例6
def to_posix_path(code_path):
"""
Change the code_path to be of unix-style if running on windows when supplied with an absolute windows path.
Parameters
----------
code_path : str
Directory in the host operating system that should be mounted within the container.
Returns
-------
str
Posix equivalent of absolute windows style path.
Examples
--------
>>> to_posix_path('/Users/UserName/app')
>>> to_posix_path('C:\\\\Users\\\\UserName\\\\AppData\\\\Local\\\\Temp\\\\mydir')
"""
return re.sub("^([A-Za-z])+:",
lambda match: posixpath.sep + match.group().replace(":", "").lower(),
pathlib.PureWindowsPath(code_path).as_posix()) if os.name == "nt" else code_path
示例7
def get_path_from_template(path_template: str, path_type: PathType = PathType.AUTO) -> str:
"""Replace tags in the given path template and return either Windows or Linux formatted path."""
# automatically select path type depending on running OS
if path_type == PathType.AUTO:
if platform.system() == "Windows":
path_type = PathType.WINDOWS
elif platform.system() == "Linux":
path_type = PathType.LINUX
else:
raise RuntimeError("Unknown platform")
path_template = path_template.replace("<USERNAME>", get_user_name())
# return correctly formatted path
if path_type == PathType.WINDOWS:
return str(pathlib.PureWindowsPath(path_template))
elif path_type == PathType.LINUX:
return str(pathlib.PurePosixPath(path_template))
else:
raise RuntimeError("Unknown platform")
示例8
def get_path_from_template(path_template: str, path_type: PathType = PathType.AUTO) -> str:
"""Replace tags in the given path template and return either Windows or Linux formatted path."""
# automatically select path type depending on running OS
if path_type == PathType.AUTO:
if platform.system() == "Windows":
path_type = PathType.WINDOWS
elif platform.system() == "Linux":
path_type = PathType.LINUX
else:
raise RuntimeError("Unknown platform")
path_template = path_template.replace("<USERNAME>", get_user_name())
# return correctly formatted path
if path_type == PathType.WINDOWS:
return str(pathlib.PureWindowsPath(path_template))
elif path_type == PathType.LINUX:
return str(pathlib.PurePosixPath(path_template))
else:
raise RuntimeError("Unknown platform")
示例9
def check_url(self, url, expected):
url_parts = urlsplit(url)
if urlsplit(expected).scheme not in uses_relative:
expected = add_leading_slash(expected)
expected_parts = urlsplit(expected, scheme='file')
self.assertEqual(url_parts.scheme, expected_parts.scheme,
"%r: Schemes differ." % url)
self.assertEqual(url_parts.netloc, expected_parts.netloc,
"%r: Netloc parts differ." % url)
self.assertEqual(url_parts.query, expected_parts.query,
"%r: Query parts differ." % url)
self.assertEqual(url_parts.fragment, expected_parts.fragment,
"%r: Fragment parts differ." % url)
if is_windows_path(url_parts.path) or is_windows_path(expected_parts.path):
path = PureWindowsPath(filter_windows_path(url_parts.path))
expected_path = PureWindowsPath(filter_windows_path(expected_parts.path))
else:
path = PurePath(url_parts.path)
expected_path = PurePath(expected_parts.path)
self.assertEqual(path, expected_path, "%r: Paths differ." % url)
示例10
def get_path_from_template(path_template: str, path_type: PathType = PathType.AUTO) -> str:
"""Replace tags in the given path template and return either Windows or Linux formatted path."""
# automatically select path type depending on running OS
if path_type == PathType.AUTO:
if platform.system() == "Windows":
path_type = PathType.WINDOWS
elif platform.system() == "Linux":
path_type = PathType.LINUX
else:
raise RuntimeError("Unknown platform")
path_template = path_template.replace("<USERNAME>", get_user_name())
# return correctly formatted path
if path_type == PathType.WINDOWS:
return str(pathlib.PureWindowsPath(path_template))
elif path_type == PathType.LINUX:
return str(pathlib.PurePosixPath(path_template))
else:
raise RuntimeError("Unknown platform")
示例11
def test_different_flavours_unordered(self):
p = pathlib.PurePosixPath('a')
q = pathlib.PureWindowsPath('a')
with self.assertRaises(TypeError):
p < q
with self.assertRaises(TypeError):
p <= q
with self.assertRaises(TypeError):
p > q
with self.assertRaises(TypeError):
p >= q
#
# Tests for the concrete classes
#
# Make sure any symbolic links in the base test path are resolved
示例12
def get_probabilityLeft(session_path, save=False, data=False, settings=False):
if not data:
data = raw.load_data(session_path)
if not settings:
settings = raw.load_settings(session_path)
if settings is None:
settings = {"IBLRIG_VERSION_TAG": "100.0.0"}
elif settings["IBLRIG_VERSION_TAG"] == "":
settings.update({"IBLRIG_VERSION_TAG": "100.0.0"})
num = settings.get("PRELOADED_SESSION_NUM", None)
if num is None:
num = settings.get("PREGENERATED_SESSION_NUM", None)
if num is None:
fn = settings.get('SESSION_LOADED_FILE_PATH', None)
fn = PureWindowsPath(fn).name
num = ''.join([d for d in fn if d.isdigit()])
if num == '':
raise ValueError("Can't extract left probability behaviour.")
# Load the pregenerated file
sessions_folder = Path(raw.__file__).parent.joinpath('extractors', 'ephys_sessions')
fname = f"session_{num}_ephys_pcqs.npy"
pcqsp = np.load(sessions_folder.joinpath(fname))
pLeft = pcqsp[:, 4]
pLeft = pLeft[: len(data)]
if raw.save_bool(save, "_ibl_trials.probabilityLeft.npy"):
lpath = Path(session_path).joinpath("alf", "_ibl_trials.probabilityLeft.npy")
np.save(lpath, pLeft)
return pLeft
示例13
def __init__(self, recipesRoot, uuid, scan):
self.uuid = uuid
self.isRoot = scan.isRoot
self.packagePath = scan.stack
self.workspacePath = recipesRoot.joinpath(PureWindowsPath(scan.workspacePath))
self.headers = [ recipesRoot.joinpath(PureWindowsPath(i)) for i in scan.headers ]
self.sources = [ recipesRoot.joinpath(PureWindowsPath(i)) for i in scan.sources ]
self.resources = [ recipesRoot.joinpath(PureWindowsPath(i)) for i in scan.resources ]
self.incPaths = [ recipesRoot.joinpath(PureWindowsPath(i)) for i in scan.incPaths ]
self.dependencies = scan.dependencies
self.runTargets = [ recipesRoot.joinpath(PureWindowsPath(i)) for i in scan.runTargets ]
示例14
def test_encode_model_with_path(model_with_path):
if isinstance(model_with_path.path, PureWindowsPath):
expected = "\\foo\\bar"
else:
expected = "/foo/bar"
assert jsonable_encoder(model_with_path) == {"path": expected}
示例15
def converted_path(self, path):
if self.props.is_windows():
return str(PureWindowsPath(path))
else:
return str(PosixPath(path))
示例16
def __init__(self, platform: str = sys.platform, *args, **kwargs) -> None:
"""Initialize attributes.
Supported platforms: 'linux', 'darwin', 'win32', 'win64'.
:param platform: Required platform type.
"""
super().__init__(*args, **kwargs)
self.platform = platform
self._pathlib_home = PureWindowsPath() if 'win' in platform \
else PurePosixPath()
self._pathlib_home /= PLATFORMS[platform]['home']
示例17
def test_concrete_class(self):
p = self.cls('a')
self.assertIs(type(p),
pathlib.PureWindowsPath if os.name == 'nt' else pathlib.PurePosixPath)
示例18
def test_different_flavours_unequal(self):
p = pathlib.PurePosixPath('a')
q = pathlib.PureWindowsPath('a')
self.assertNotEqual(p, q)
示例19
def test_concrete_class(self):
p = self.cls('a')
self.assertIs(type(p),
pathlib.PureWindowsPath if os.name == 'nt' else pathlib.PurePosixPath)
示例20
def test_different_flavours_unequal(self):
p = pathlib.PurePosixPath('a')
q = pathlib.PureWindowsPath('a')
self.assertNotEqual(p, q)
示例21
def test_load_from_file():
cfg = config.from_file(Path("test") / Path("data") / Path("config.json"))
# Check unchanged defaults are the same
assert not cfg["app_mode"]
assert not cfg["debug"]
assert cfg["pPort"] == 55851
assert cfg["xPort"] == 55852
assert cfg["gPort"] == 55853
assert len(cfg["dataHashSecret"]) == 64 and not cfg["dataHashSecret"].isspace()
assert PureWindowsPath(cfg["data"]) == PureWindowsPath("C:/User/SCope data")
# Check new values
assert cfg["extra setting"] == "value"
示例22
def test_concrete_class(self):
p = self.cls('a')
self.assertIs(type(p),
pathlib.PureWindowsPath if os.name == 'nt' else pathlib.PurePosixPath)
示例23
def test_different_flavours_unequal(self):
p = pathlib.PurePosixPath('a')
q = pathlib.PureWindowsPath('a')
self.assertNotEqual(p, q)
示例24
def findStimulusWaveformFile(abf, channel=0):
"""
Look for the stimulus waveform file in several places. Return the path
where it can be found. Return None if it cannot be found.
The original path is an absolute windows filename stored in the ABF header.
"""
# first try looking at the path stored in the header
pathInHeader = Path(abf._stringsIndexed.lDACFilePath[channel])
if pathInHeader.is_file():
return str(pathInHeader)
# try the current working directory of the Python interpreter
stimBasename = PureWindowsPath(pathInHeader).name
pathCurrent = Path(stimBasename).resolve().absolute()
if pathCurrent.is_file():
return str(pathCurrent)
# try path defined by the stimulusFileFolder argument of the ABF constructor
pathUserDefined = Path(str(abf.stimulusFileFolder)).joinpath(stimBasename).resolve()
if pathUserDefined.is_file():
return str(pathUserDefined)
# try the same folder that houses the ABF file
pathSameFolderAsABF = Path(abf.abfFilePath).parent.joinpath(stimBasename).resolve()
if pathSameFolderAsABF.is_file():
return str(pathSameFolderAsABF)
# warn if stimulus file was never found
warnings.warn(
f"Could not locate stimulus file for channel {channel}.\n"
f"ABF file path: {abf.abfFilePath}.\n"
f"The following paths were searched:\n"
f"* Path in the ABF header: {pathInHeader}\n"
f"* Current working directory: {pathCurrent}\n"
f"* User-defined stimulus folder: {pathUserDefined}\n"
f"* Same folder as ABF: {(pathSameFolderAsABF)}\n"
)
return None
示例25
def targetPath(self):
"""
Args:
woAnchor (bool): remove the anchor (\\server\path or drive:) from returned path.
Returns:
a libpath PureWindowsPath object for combined workingDir/relative path
or the envTarget
Raises:
ShortCutError when no target path found in Shortcut
"""
target = None
if self.workingDir:
target = PureWindowsPath(self.workingDir)
if self.relativePath:
target = target / PureWindowsPath(self.relativePath)
else: target = None
if not target and self.envTarget:
target = PureWindowsPath(self.envTarget)
if not target:
raise ShortCutError("Unable to retrieve target path from MS Shortcut: shortcut = {}"
.format(str(self.scPath)))
return target
示例26
def test_concrete_class(self):
p = self.cls('a')
self.assertIs(type(p),
pathlib.PureWindowsPath if os.name == 'nt' else pathlib.PurePosixPath)
示例27
def test_different_flavours_unequal(self):
p = pathlib.PurePosixPath('a')
q = pathlib.PureWindowsPath('a')
self.assertNotEqual(p, q)
示例28
def _compress(root_data_folder, command, flag_pattern, dry=False, max_sessions=None):
# runs a command of the form command = "ls -1 {file_name}.avi"
c = 0
for flag_file in Path(root_data_folder).rglob(flag_pattern):
ses_path = flag_file.parent
files2compress = flags.read_flag_file(flag_file)
if isinstance(files2compress, bool):
Path(flag_file).unlink()
continue
for f2c in files2compress:
cfile = ses_path.joinpath(PureWindowsPath(f2c))
c += 1
if max_sessions and c > max_sessions:
return
print(cfile)
if dry:
continue
if not cfile.exists():
_logger.error(f'NON-EXISTING RAW FILE: {cfile}. Skipping...')
continue
if flag_file.exists():
flag_file.unlink()
# run the compression command redirecting output
cfile.parent.joinpath(cfile.stem)
# if the output file already exists, overwrite it
outfile = cfile.parent / (cfile.stem + '.mp4')
if outfile.exists():
outfile.unlink()
command2run = command.format(file_name=cfile.parent.joinpath(cfile.stem))
process = subprocess.Popen(command2run, shell=True, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
info, error = process.communicate()
if process.returncode != 0:
_logger.error('COMPRESSION FAILED FOR ' + str(cfile))
with open(cfile.parent.joinpath('extract.error'), 'w+') as fid:
fid.write(command2run)
fid.write(error.decode())
else:
# if the command was successful delete the original file
cfile.unlink()
# and add the file to register_me.flag
flags.write_flag_file(ses_path.joinpath('register_me.flag'), file_list=cfile.stem)
示例29
def generate(self, extra, bobRoot):
super().generate()
# gather root paths
bobPwd = Path(os.getcwd())
if sys.platform == 'msys':
if os.getenv('WD') is None:
raise BuildError("Cannot create Visual Studio project for Windows! MSYS2 must be started by msys2_shell.cmd script!")
msysRoot = PureWindowsPath(os.getenv('WD')) / '..' / '..'
winPwd = PureWindowsPath(os.popen('pwd -W').read().strip())
winDestination = PureWindowsPath(os.popen('cygpath -w {}'.format(quoteBash(self.destination))).read().strip())
baseBuildMe = str(msysRoot / "msys2_shell.cmd") + \
" -msys2 -defterm -no-start -use-full-path -where " + \
str(winPwd)
buildMe = os.path.join(self.destination, "buildme.sh")
buildMeCmd = baseBuildMe + " " + buildMe
else:
winPwd = bobPwd
winDestination = Path(self.destination).resolve()
buildMe = os.path.join(str(winDestination), "buildme.cmd")
buildMeCmd = buildMe
projects = {
name : Project(winPwd, sha1NsUuid(self.uuid, name), scan)
for name,scan in self.packages.items()
}
if not self.args.update:
self.updateFile(buildMe, self.__generateBuildme(extra, winPwd, bobRoot))
solutionProjectList = []
solutionProjectConfigs = []
for name,project in projects.items():
p = os.path.join(self.destination, name)
os.makedirs(p, exist_ok=True)
self.updateFile(os.path.join(p, name+".vcxproj"), project.generateProject(projects, buildMeCmd),
encoding="utf-8", newline='\r\n')
self.updateFile(os.path.join(p, name+".vcxproj.filters"), project.generateFilters(),
encoding="utf-8", newline='\r\n')
if not self.args.update:
self.updateFile(os.path.join(p, name+".vcxproj.user"), project.generateUser(),
encoding="utf-8", newline='\r\n')
solutionProjectList.append(SOLUTION_PROJECT_TEMPLATE.format(NAME=name, GUID=str(project.uuid).upper()))
solutionProjectConfigs.append("\t\t{{{GUID}}}.Build|x86.ActiveCfg = Build|Win32".format(GUID=str(project.uuid).upper()))
solutionProjectConfigs.append("\t\t{{{GUID}}}.Checkout+Build|x86.ActiveCfg = Checkout+Build|Win32".format(GUID=str(project.uuid).upper()))
if project.isRoot:
solutionProjectConfigs.append("\t\t{{{GUID}}}.Build|x86.Build.0 = Build|Win32".format(GUID=str(project.uuid).upper()))
solutionProjectConfigs.append("\t\t{{{GUID}}}.Checkout+Build|x86.Build.0 = Checkout+Build|Win32".format(GUID=str(project.uuid).upper()))
self.updateFile(os.path.join(self.destination, self.projectName+".sln"),
SOLUTION_TEMPLATE.format(PROJECTS_LIST="\n".join(solutionProjectList),
PROJECTS_CFG="\n".join(solutionProjectConfigs),
SOLUTION_GUID=str(self.uuid)),
encoding="utf-8", newline='\r\n')
示例30
def _location(cfg, topdir=None):
# Making this a function that gets called each time you ask for a
# configuration file makes it respect updated environment
# variables (such as XDG_CONFIG_HOME, PROGRAMDATA) if they're set
# during the program lifetime.
#
# Its existence is also relied on in the test cases, to ensure
# that the WEST_CONFIG_xyz variables are respected and we're not about
# to clobber the user's own configuration files.
env = os.environ
if cfg == ConfigFile.ALL:
raise ValueError('ConfigFile.ALL has no location')
elif cfg == ConfigFile.SYSTEM:
if 'WEST_CONFIG_SYSTEM' in env:
return env['WEST_CONFIG_SYSTEM']
plat = platform.system()
if plat == 'Linux':
return '/etc/westconfig'
elif plat == 'Darwin':
return '/usr/local/etc/westconfig'
elif plat == 'Windows':
return os.path.expandvars('%PROGRAMDATA%\\west\\config')
elif 'BSD' in plat:
return '/etc/westconfig'
elif 'CYGWIN' in plat:
# Cygwin can handle windows style paths, so make sure we
# return one. We don't want to use os.path.join because
# that uses '/' as separator character, and the ProgramData
# variable is likely to be something like r'C:\ProgramData'.
#
# See https://github.com/zephyrproject-rtos/west/issues/300
# for details.
pd = pathlib.PureWindowsPath(os.environ['ProgramData'])
return str(pd / 'west' / 'config')
else:
raise ValueError('unsupported platform ' + plat)
elif cfg == ConfigFile.GLOBAL:
if 'WEST_CONFIG_GLOBAL' in env:
return env['WEST_CONFIG_GLOBAL']
elif platform.system() == 'Linux' and 'XDG_CONFIG_HOME' in env:
return os.path.join(env['XDG_CONFIG_HOME'], 'west', 'config')
else:
return canon_path(
os.path.join(os.path.expanduser('~'), '.westconfig'))
elif cfg == ConfigFile.LOCAL:
if topdir:
return os.path.join(topdir, '.west', 'config')
elif 'WEST_CONFIG_LOCAL' in env:
return env['WEST_CONFIG_LOCAL']
else:
# Might raise WestNotFound!
return os.path.join(west_dir(), 'config')
else:
raise ValueError(f'invalid configuration file {cfg}')