How to use the pathlib.WindowsPath function in pathlib

To help you get started, we’ve selected a few pathlib examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github facebook / buck / third-party / py / pathlib / test_pathlib.py View on Github external
def test_concrete_class(self):
        p = self.cls('a')
        self.assertIs(type(p),
            pathlib.WindowsPath if os.name == 'nt' else pathlib.PosixPath)
github tesseract-ocr / tesseract / src / training / tesstrain_utils.py View on Github external
def run_command(cmd, *args, env=None):
    for d in ("", "api/", "training/"):
        testcmd = shutil.which(f"{d}{cmd}")
        if shutil.which(testcmd):
            cmd = testcmd
            break
    if not shutil.which(cmd):
        err_exit(f"{cmd} not found")

    log.debug(f"Running {cmd}")
    args = list(args)
    for idx, arg in enumerate(args):
        log.debug(arg)
        # Workaround for https://bugs.python.org/issue33617
        # TypeError: argument of type 'WindowsPath' is not iterable
        if isinstance(arg, pathlib.WindowsPath):
            args[idx] = str(arg)

    proc = subprocess.run(
        [cmd, *args], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env
    )
    proclog = logging.getLogger(cmd)
    if proc.returncode == 0:
        proclog.debug(proc.stdout.decode("utf-8", errors="replace"))
    else:
        try:
            proclog.error(proc.stdout.decode("utf-8", errors="replace"))
        except Exception as e:
            proclog.error(e)
        err_exit(f"Program {cmd} failed with return code {proc.returncode}. Abort.")
github pkgw / pwkit / pwkit / io.py View on Github external
a boolean indicating whether the symlink already existed.

    """
    try:
        os.symlink (src, dst)
    except OSError as e:
        if e.errno == 17: # EEXIST
            return True
        raise
    return False


# Extended Path object. pathlib.Path objects have fancy __new__ semantics that
# we need to jump through some hoops for.

_ParentPath = pathlib.WindowsPath if os.name == 'nt' else pathlib.PosixPath

class Path (_ParentPath):
    """This is an extended version of the :class:`pathlib.Path` class.
    (:mod:`pathlib` is built into Python 3.x and is available as a backport to
    Python 2.x.) It represents a path on the filesystem.

    """
    # Manipulations

    def expand (self, user=False, vars=False, glob=False, resolve=False):
        """Return a new :class:`Path` with various expansions performed. All
	expansions are disabled by default but can be enabled by passing in
	true values in the keyword arguments.

	user : bool (default False)
	  Expand ``~`` and ``~user`` home-directory constructs. If a username is
github cool-RR / python_toolbox / source_py3 / python_toolbox / os_tools.py View on Github external
elif sys.platform == 'darwin': # Mac:
        subprocess.check_call(['open', '--', str(path)])
        
    elif sys.platform in ('win32', 'cygwin'): # Windows:
        os.startfile(path)
        
    else:
        raise NotImplementedError(
            "Your operating system `%s` isn't supported by "
            "`start_file`." % sys.platform)
    
    
_is_windows = (os.name == 'nt')
null_path = pathlib.Path(os.path.devnull)
path_type = pathlib.WindowsPath if _is_windows else pathlib.PosixPath
github vatlab / sos / src / sos / targets.py View on Github external
def __new__(cls, *args, **kwargs):
        if cls is Path:
            cls = WindowsPath if os.name == 'nt' else PosixPath
        return cls._from_parts(args).expanduser().expandnamed(host=kwargs.get('host', None))
github microsoft / nodejstools / Nodejs / Product / Nodejs / Theme / make_theme_pkgdef.py View on Github external
#! python3.4 -b

THEME_NAME = 'NodejsTools'
THEME_PKGDEF = 'Microsoft.NodejsTools.theme.v{}.0.pkgdef'

import struct
import xml.etree.ElementTree
from pathlib import WindowsPath
from uuid import UUID

for VS_VERSION in (11, 12, 14, 15, 16):
    print('Writing to {}'.format(THEME_PKGDEF.format(VS_VERSION)))
    output = open(THEME_PKGDEF.format(VS_VERSION), 'w', encoding='ascii')

    for src in WindowsPath(__file__).parent.glob("*.vstheme"):
        print(src)
        tree = xml.etree.ElementTree.parse(str(src))
        root = tree.getroot()
        
        data = []
        
        theme = root.find('Theme')
        theme_guid = UUID(theme.get('GUID'))
        try:
            theme_ver = int(theme.get('MinVSVersion'))
        except (ValueError, TypeError):
            pass
        else:
            if theme_ver > VS_VERSION:
                print('SKIPPED {}'.format(src))
                continue
github GStreamer / cerbero / cerbero / hacks.py View on Github external
def symlink(src, dst, **kwargs):
    src = str(WindowsPath(src))
    os_symlink(src, dst, **kwargs)
github karlicoss / my / my / kython / kompress.py View on Github external
import lz4.frame # type: ignore
        return lz4.frame.open(str(pp), mode, *args, **kwargs)
    elif suf in {'.zstd'}:
        return _zstd_open(pp, mode, *args, **kwargs)
    else:
        return pp.open(mode, *args, **kwargs)


import typing
import os

if typing.TYPE_CHECKING:
    # otherwise mypy can't figure out that BasePath is a type alias..
    BasePath = pathlib.Path
else:
    BasePath = pathlib.WindowsPath if os.name == 'nt' else pathlib.PosixPath


class CPath(BasePath):
    """
    Hacky way to support compressed files.
    If you can think of a better way to do this, please let me know! https://github.com/karlicoss/HPI/issues/20

    Ugh. So, can't override Path because of some _flavour thing.
    Path only has _accessor and _closed slots, so can't directly set .open method
    _accessor.open has to return file descriptor, doesn't work for compressed stuff.
    """
    def open(self, *args, **kwargs):
        # TODO assert read only?
        return kopen(str(self))
github creativeprojects / resticprofile / src / resticprofile / filesearch.py View on Github external
def get_restic_binary() -> str:
    path = Path()
    if isinstance(path, WindowsPath):
        return RESTIC_BINARY_WINDOWS

    return RESTIC_BINARY_POSIX