def pathlib_properties():
    """通过路径对象的属性来访问其他部分"""
    """
    path:  D:\one\two\target.py
    name:  target.py
    suffix:  .py
    stem:  target
    """
    p = pathlib.WindowsPath(r"D:\one\two\target.py")
    print("path: ", p)
    # 路径的最后一部分
    print("name: ", p.name)
    # 路径最后一部分的后缀
    print("suffix: ", p.suffix)
    # 路径中最后一部分(不包含后缀)
    print("stem: ", p.stem)

    print()
    """
    path:  D:\one\two\target
    name:  target
    suffix:  
    stem:  target
    """
    p = pathlib.WindowsPath(r"D:\one\two\target")
    print("path: ", p)
    # 路径的最后一部分
    print("name: ", p.name)
    # 路径最后一部分的后缀
    print("suffix: ", p.suffix)
    # 路径中最后一部分(不包含后缀)
    print("stem: ", p.stem)
 def test_import_images_output_pairs(self):
     fname = pathlib.Path('files for testing\images for testing')
     mem_det = MembraneDetect(fname)
     mem_det.import_images()
     file1=pathlib.WindowsPath('files for testing\images for testing/e3 hol 1250 1500_z0_ch01.tif')
     file2= pathlib.WindowsPath('files for testing\images for testing/e3 hol 1250 1500_z0_ch02.tif')
     tup= (file1,file2)
     assert mem_det.images_list[0]==tup
Exemple #3
0
    def _cleanWin32Filename(self, fname):
        if not isWin:
            return fname

        # deal with things like con/prn/etc
        p = pathlib.WindowsPath(fname)
        if p.is_reserved():
            fname = "renamed" + fname
            assert not pathlib.WindowsPath(fname).is_reserved()

        return fname
Exemple #4
0
def is_valid_firefox_profile(profile_dir):
    is_valid = False
    validity_indicator = "times.json"

    if pathlib.WindowsPath(profile_dir).is_dir():
        test_path = "%s\\%s" % (profile_dir, validity_indicator)

        if pathlib.WindowsPath(test_path).is_file():
            is_valid = True

    return is_valid
Exemple #5
0
def test_junction_readlink(tmp_path):
    target = tmp_path / 'parent'
    target.mkdir(parents=True, exist_ok=True)
    with target.joinpath("original.txt").open('w') as f:
        f.write("Original")
    junction = tmp_path / "target" / "link"
    junction.parent.mkdir(parents=True, exist_ok=True)
    os.system('mklink /J %s %s' % (str(junction), str(target.resolve())))
    assert not os.path.islink(str(junction))
    assert py7zr.win32compat.is_reparse_point(str(junction))
    assert py7zr.win32compat.readlink(str(junction)) == PATH_PREFIX + str(target.resolve())
    assert py7zr.helpers.readlink(str(junction)) == PATH_PREFIX + str(target.resolve())
    assert py7zr.win32compat.is_reparse_point(junction)
    assert py7zr.win32compat.readlink(junction) == pathlib.WindowsPath(PATH_PREFIX + str(target.resolve()))
    assert py7zr.helpers.readlink(junction) == pathlib.WindowsPath(PATH_PREFIX + str(target.resolve()))
Exemple #6
0
def test_unsupported_flavour():
    if os.name == "nt":
        with pytest.raises(NotImplementedError):
            pathlib.PosixPath()
    else:
        with pytest.raises(NotImplementedError):
            pathlib.WindowsPath()
Exemple #7
0
def gui_setup():
    """ UI for rule checking and adding process """
    check_rule = lambda: netsh_call(
        'netsh advfirewall firewall show rule name="Uplay Invisible Mode" | findstr "no rules"'
    )

    while not check_rule():
        root = Tk()
        root.withdraw()

        messagebox.showinfo(
            "Rule not found",
            "Please select \"upc.exe\" from your Uplay installation folder")
        filename = filedialog.askopenfilename(
            initialdir=
            'C:\\Program Files (x86)\\Ubisoft\\Ubisoft Game Launcher',
            title="Select upc.exe",
            filetypes=(("\"upc.exe\" Executable file", "upc.exe"), ))

        if "upc.exe" not in filename.lower() or filename == "":
            if not messagebox.askretrycancel("Error", "Invalid file!"):
                return
            continue

        add_rule = lambda i: netsh_call(
            f'netsh advfirewall firewall add rule name="Uplay Invisible Mode" dir=out action=block enable=no program="{i}"'
        )
        add_rule(pathlib.WindowsPath(filename))
        messagebox.showinfo(
            "Rule added",
            "Setup is now complete. Please reopen the application")
        return False
    return True
Exemple #8
0
def config_logger():
    # Change root logger level from WARNING (default) to NOTSET in order for all messages to be delegated.
    logpath = pathlib.WindowsPath(pathlib.WindowsPath.home(), "buph_logs",
                                  "buph.log")
    logging.getLogger().setLevel(logging.NOTSET)
    # Add stdout handler, with level INFO
    console = logging.StreamHandler(sys.stdout)
    console.setLevel(logging.INFO)
    formater = logging.Formatter('%(asctime)-13s: %(levelname)-8s %(message)s',
                                 datefmt="%m/%d/%Y %I:%M:%S %p")
    # formater = coloredlogs.ColoredFormatter('%(asctime)s %(levelname)s %(message)s')
    console.setFormatter(formater)
    logging.getLogger().addHandler(console)

    # Add file rotating handler, with level DEBUG
    rotatingHandler = logging.handlers.TimedRotatingFileHandler(
        filename=logpath, when='M', interval=2, backupCount=5)
    rotatingHandler.setLevel(logging.DEBUG)
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        datefmt="%m/%d/%Y %I:%M:%S %p %Z")
    rotatingHandler.setFormatter(formatter)
    logging.getLogger().addHandler(rotatingHandler)

    log = logging.getLogger("app." + __name__)

    # log.debug('Debug message, should only appear in the file.')
    # log.info('Info message, should appear in file and stdout.')
    # log.warning('Warning message, should appear in file and stdout.')
    # log.error('Error message, should appear in file and stdout.')

    return log
Exemple #9
0
    def get_backup_version(self, folder_str):
        path_str = pathlib.WindowsPath(folder_str)

        dirs = [f for f in path_str.iterdir() if f.is_dir()]
        dirList = {}
        latest = 0

        for tmp_dir in dirs:
            dirStr = str(tmp_dir)

            if self.backup_folder in dirStr:
                dirList.update({
                    dirStr:
                    int(
                        dirStr.replace(
                            '{0}\{1}'.format(folder_str, self.backup_folder),
                            ''))
                })

        if len(dirList) > 0:
            listSorted = sorted(dirList, key=dirList.__getitem__, reverse=True)
            latest = int(listSorted[0].replace(
                '{0}\{1}'.format(folder_str, self.backup_folder), ''))

        return '{0:04d}'.format(latest + 1)
def test_basic():
    print("\n# test_basic")
    ts = TAINTED_STRING

    tainted_path = pathlib.Path(ts)

    tainted_pure_path = pathlib.PurePath(ts)
    tainted_pure_posix_path = pathlib.PurePosixPath(ts)
    tainted_pure_windows_path = pathlib.PureWindowsPath(ts)

    ensure_tainted(
        tainted_path,
        tainted_pure_path,
        tainted_pure_posix_path,
        tainted_pure_windows_path,
        pathlib.Path("foo") / ts,
        ts / pathlib.Path("foo"),
        tainted_path.joinpath("foo", "bar"),
        pathlib.Path("foo").joinpath(tainted_path, "bar"),
        pathlib.Path("foo").joinpath("bar", tainted_path),
        str(tainted_path),

        # TODO: Tainted methods and attributes
        # https://docs.python.org/3.8/library/pathlib.html#methods-and-properties
    )

    if os.name == "posix":
        tainted_posix_path = pathlib.PosixPath(ts)

        ensure_tainted(tainted_posix_path, )

    if os.name == "nt":
        tainted_windows_path = pathlib.WindowsPath(ts)
        ensure_tainted(tainted_windows_path, )
Exemple #11
0
    def construct_path(self, *path_elements, path_null=''):
        """
        Parameters
        ----------
        path_elements : str or pathlib.PosixPath or pathlib.WindowsPath
            Directories and file that constitute the output path. They are read in the order as they appear in the
            function call left to right.
        path_null : str
            This is a value representing an empty path.

        Returns
        ----------
        potential_path : pathlib.PosixPath or pathlib.WindowsPath
            This path is not validated existence-wise - may or may not exist.
        """

        # Windows pitfall: may change this to WindowsPath on Windows-based machines.
        # The Windows option has not been tested.
        os_platform = platform.system()
        if os_platform == 'Linux':
            path_blocks = [pathlib.PosixPath(path_null)]
        elif os_platform == 'Windows':
            path_blocks = [pathlib.WindowsPath(path_null)]
        else:
            raise NotImplemented(
                'The path handling for the OS {} is not supported.'.format(
                    os_platform))

        path_blocks.extend(list(path_elements))

        potential_path = functools.reduce(lambda x, y: x.joinpath(y),
                                          path_blocks)
        return potential_path
Exemple #12
0
    def test_serialize_pathlib(self):
        # Pure path objects work in all platforms.
        self.assertSerializedEqual(pathlib.PurePosixPath())
        self.assertSerializedEqual(pathlib.PureWindowsPath())
        path = pathlib.PurePosixPath("/path/file.txt")
        expected = ("pathlib.PurePosixPath('/path/file.txt')", {"import pathlib"})
        self.assertSerializedResultEqual(path, expected)
        path = pathlib.PureWindowsPath("A:\\File.txt")
        expected = ("pathlib.PureWindowsPath('A:/File.txt')", {"import pathlib"})
        self.assertSerializedResultEqual(path, expected)
        # Concrete path objects work on supported platforms.
        if sys.platform == "win32":
            self.assertSerializedEqual(pathlib.WindowsPath.cwd())
            path = pathlib.WindowsPath("A:\\File.txt")
            expected = ("pathlib.PureWindowsPath('A:/File.txt')", {"import pathlib"})
            self.assertSerializedResultEqual(path, expected)
        else:
            self.assertSerializedEqual(pathlib.PosixPath.cwd())
            path = pathlib.PosixPath("/path/file.txt")
            expected = ("pathlib.PurePosixPath('/path/file.txt')", {"import pathlib"})
            self.assertSerializedResultEqual(path, expected)

        field = models.FilePathField(path=pathlib.PurePosixPath("/home/user"))
        string, imports = MigrationWriter.serialize(field)
        self.assertEqual(
            string,
            "models.FilePathField(path=pathlib.PurePosixPath('/home/user'))",
        )
        self.assertIn("import pathlib", imports)
Exemple #13
0
 def __init__(self, path):
     self.path = pathlib.WindowsPath(path)
     self.files = glob.glob(self.path / '*.*')
     if "Thumbs.db" in self.files:
         self.files.remove("Thumbs.db")
     self.oldest = None
     self.newest = None
def test_dbase():

    db = device_dbase.DeviceDatabase(dbase_path)
    assert db.dbasefile == pathlib.WindowsPath(dbase_path)

    db.add('aa:bb:cc:dd:ee:ff', 'testname1', 'testinfo4')
    db.add('11:22:33:44:55:66', 'testname2', 'testinfo5')

    # Show all existing devices in this database
    ret_list = db.get_all_devices()
    print('\nAll devices:', ret_list)

    # Test for a non-existing device
    ret_list = (db.search('*'))
    print(f"{ret_list=}")
    assert db.search('doesnotexist') == []

    # Test if an existing device can be found
    search_str = 'aa:bb:cc:dd:ee:ff'
    ret_list = db.search(search_str)
    ret_str = ','.join(ret_list)
    print(f'search for {search_str} returned "{ret_list}"')
    assert search_str in ret_str

    search_str = 'xx:yy:zz:xx:yy:zz'
    ret_list = db.search(search_str)
    ret_str = ','.join(ret_list)
    print(f'search for {search_str} returned {ret_list}')
    assert search_str not in ret_str

    # Delete the test database after the tests
    db.delete()
Exemple #15
0
def _which_dotnet():
    _dotnet_root = None
    if 'DOTNET_ROOT' in os.environ:
        _dotnet_root = pathlib.Path(os.environ['DOTNET_ROOT'])
        if not _dotnet_root.exists():
            _no_dotnet(_dotnet_root)
    if 'DOTNET_LIB_PATH' in os.environ:
        ctypes.cdll.LoadLibrary(os.environ['DOTNET_LIB_PATH'])
        return
    if platform.system() == "Darwin":
        if not _dotnet_root:
            _dotnet_root = pathlib.Path('/usr/local/share/dotnet/')
            if not _dotnet_root.exists():
                _no_dotnet(_dotnet_root)
        lib_path = list(
            _dotnet_root.glob(
                'shared/Microsoft.NETCore.App*/5.0.*/libclrjit.dylib'))
        if len(lib_path) > 0:
            clrjitlib = str(lib_path[0])
            ctypes.cdll.LoadLibrary(clrjitlib)
        else:
            _no_dotnet(_dotnet_root)
    elif platform.system() == "Linux":
        if not _dotnet_root:
            search_paths = [
                pathlib.Path('/usr/local/share/dotnet/'),
                pathlib.Path('/usr/share/dotnet/')
            ]
            for path in search_paths:
                if not path.exists():
                    continue
                else:
                    _dotnet_root = path
        if not _dotnet_root:
            _no_dotnet(_dotnet_root)
        lib_path = list(
            _dotnet_root.glob(
                'shared/Microsoft.NETCore.App*/5.0.*/libclrjit.so'))
        if len(lib_path) > 0:
            clrjitlib = str(lib_path[0])
            ctypes.cdll.LoadLibrary(clrjitlib)
        else:
            _no_dotnet(_dotnet_root)
    elif platform.system() == "Windows":
        if not _dotnet_root:
            _dotnet_root = pathlib.WindowsPath(
                os.path.expandvars(r'%ProgramFiles%\dotnet'))
            if not _dotnet_root.exists():
                _no_dotnet(_dotnet_root)
        lib_path = list(
            _dotnet_root.glob(
                'shared/Microsoft.NETCore.App*/5.0.*/clrjit.dll'))
        if len(lib_path) > 0:
            clrjitlib = str(lib_path[0])
            ctypes.cdll.LoadLibrary(clrjitlib)
        else:
            _no_dotnet(_dotnet_root)
    else:
        raise ValueError("Operating System not Supported")
def test_dbase_path():

    print("hello henk")
    dbase_path = device_dbase.get_dbasefile_path()
    assert dbase_path == pathlib.WindowsPath(dbase_path)

    # The folder has to exist...
    assert dbase_path.parent.is_dir()
def pathlib_existing():
    """根据现有路径创建相似的路径"""
    path = pathlib.WindowsPath(r"D:\lcoder\a.py")
    print(path)
    path = path.with_name("a.go")
    print(path)
    path = path.with_suffix(".conf")
    print(path)
Exemple #18
0
def _check_filename(value) -> Union[pathlib.Path, pathlib.WindowsPath]:
    if not isinstance(value, (pathlib.Path, pathlib.WindowsPath)):
        try:
            return pathlib.Path(value)
        except NotImplementedError:
            return pathlib.WindowsPath(value)
        except:
            raise Exception("File error")
def pathlib_resove():
    """规范化路径"""
    usr = pathlib.WindowsPath(r"D:")
    path = usr / ".." / "lcoder"
    path = path.resolve()
    print(path)
    print((usr / "\lcoder").resolve())
    # 如果是link则会显示目标的路径
    print((usr / "\MySQL.lnk").resolve())
Exemple #20
0
    def __init__(self):
        super(Config, self).__init__()
        self.generated = False
        self.load()

        # Self now should be prepared by now
        img_dir = pathlib.WindowsPath(self['img_dir'])
        if not img_dir.exists():
            img_dir.mkdir()
Exemple #21
0
def get_yaml_loader() -> Any:
    class OmegaConfLoader(yaml.SafeLoader):  # type: ignore
        def construct_mapping(self,
                              node: yaml.Node,
                              deep: bool = False) -> Any:
            keys = set()
            for key_node, value_node in node.value:
                if key_node.tag != yaml.resolver.BaseResolver.DEFAULT_SCALAR_TAG:
                    continue
                if key_node.value in keys:
                    raise yaml.constructor.ConstructorError(
                        "while constructing a mapping",
                        node.start_mark,
                        f"found duplicate key {key_node.value}",
                        key_node.start_mark,
                    )
                keys.add(key_node.value)
            return super().construct_mapping(node, deep=deep)

    loader = OmegaConfLoader
    loader.add_implicit_resolver(
        "tag:yaml.org,2002:float",
        re.compile(
            """^(?:
         [-+]?(?:[0-9][0-9_]*)\\.[0-9_]*(?:[eE][-+]?[0-9]+)?
        |[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+)
        |\\.[0-9_]+(?:[eE][-+][0-9]+)?
        |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*
        |[-+]?\\.(?:inf|Inf|INF)
        |\\.(?:nan|NaN|NAN))$""",
            re.X,
        ),
        list("-+0123456789."),
    )
    loader.yaml_implicit_resolvers = {
        key: [(tag, regexp) for tag, regexp in resolvers
              if tag != "tag:yaml.org,2002:timestamp"]
        for key, resolvers in loader.yaml_implicit_resolvers.items()
    }

    loader.add_constructor(
        "tag:yaml.org,2002:python/object/apply:pathlib.Path",
        lambda loader, node: pathlib.Path(*loader.construct_sequence(node)),
    )
    loader.add_constructor(
        "tag:yaml.org,2002:python/object/apply:pathlib.PosixPath",
        lambda loader, node: pathlib.PosixPath(*loader.construct_sequence(node)
                                               ),
    )
    loader.add_constructor(
        "tag:yaml.org,2002:python/object/apply:pathlib.WindowsPath",
        lambda loader, node: pathlib.WindowsPath(*loader.construct_sequence(
            node)),
    )

    return loader
Exemple #22
0
def main():
    p = pathlib.WindowsPath('.')
    #p = pathlib.Path('.')
    for tune in p.glob("*.musicxml"):
        #for tune in p.glob("NU7-73.musicxml"):
        print(tune)
        chord_seq, key = get_chord_seq(tune)
        print(chord_seq, key)
        chord_seq = transpose(chord_seq, key)
        print(chord_seq)
Exemple #23
0
def set_file_logger(filename: str, level: Union[str, int] = 0) -> None:
    """Set logging level and filename for the file handler."""
    try:
        filename = pathlib.Path(filename)
    except NotImplementedError:
        filename = pathlib.WindowsPath(filename)

    file_handler = logging.FileHandler(filename)
    file_handler.setFormatter(log_formatter)
    file_handler.set_name("FileLogger")
    logger.addHandler(file_handler)
    _setLevel(file_handler, level)
def pathlib_parent():
    """不断向上迭代获取父目录"""
    path = pathlib.WindowsPath(r"D:\one\two\three.py")
    # D:\one\two
    print(path.parent)
    """
    D:\one\two
    D:\one
    D:\
    """
    for p in path.parents:
        print(p)
 def setpath(self, path):
     try:
         self.path = pathlib.WindowsPath(path).resolve()
         self.title.configure(text=self.gettitle())
         self.pics = []
         for child in self.path.iterdir():
             try:
                 if child.is_file() and child.suffix in ('.jpg', '.jpeg',
                                                         '.gif', '.png'):
                     self.pics.append(child)
             except:
                 pass
     except Exception as e:
         pass
     self.populate(self.pics)
Exemple #26
0
    def collect_images(self):
        c = []
        for fn in os.listdir(str(self.assets_dir)):
            asset_path = self.assets_dir / fn
            target_path = pathlib.WindowsPath(
                self.config['img_dir']) / (fn + '.jpg')

            if target_path.exists():
                continue

            if matchResolution(asset_path, self.config['scr_width'],
                               self.config['scr_height']):
                shutil.copy2(asset_path, target_path)
                c.append(fn)
        return c
Exemple #27
0
def convert_path_to_os(path_string):
    """Attempts to convert path_string from format of original OS
    to format of OS running this code. Fails on paths
    that mix forward and backward slashes, which are not
    transferable between Posix and Windows.
    """
    assert_compatibility(path_string)

    path_string = path_string.replace("\\", "/")
    try:
        path = pathlib.PosixPath(path_string)
    except NotImplementedError:
        path = pathlib.WindowsPath(path_string)

    return str(path)
Exemple #28
0
 def __init__(self, path_to_data):
     """ The path to data"""
     self.BATCH_SIZE = 32  #  was 32
     self.IMG_HEIGHT = 224
     self.IMG_WIDTH = 224
     # STEPS_PER_EPOCH = np.ceil(image_count/BATCH_SIZE)
     # training data is in a dir called training_data, each subdir is a class
     self.data_dir = pathlib.WindowsPath(path_to_data, "data")
     self.training_dir = pathlib.Path(self.data_dir, "training")
     self.training_count = len(list(self.training_dir.glob('*/*.jpg')))
     self.validation_dir = pathlib.Path(self.data_dir, "validation")
     self.validation_count = len(list(self.validation_dir.glob('*/*.jpg')))
     self.CLASS_NAMES = np.array([
         item.name for item in self.training_dir.glob('*')
         if item.name != "LICENSE.txt"
     ])
     self.AUTOTUNE = tf.data.experimental.AUTOTUNE
Exemple #29
0
def test_symlink_readlink_absolute(tmp_path):
    origin = tmp_path / 'parent' / 'original.txt'
    origin.parent.mkdir(parents=True, exist_ok=True)
    with origin.open('w') as f:
        f.write("Original")
    slink = tmp_path / "target" / "link"
    slink.parent.mkdir(parents=True, exist_ok=True)
    target = origin.resolve()
    slink.symlink_to(target, False)
    if sys.platform.startswith("win"):
        assert py7zr.win32compat.readlink(str(tmp_path / "target" / "link")) == PATH_PREFIX + str(target)
        assert py7zr.helpers.readlink(str(slink)) == PATH_PREFIX + str(target)
        assert py7zr.helpers.readlink(slink) == pathlib.WindowsPath(PATH_PREFIX + str(target))
    else:
        assert py7zr.helpers.readlink(str(slink)) == str(target)
        assert py7zr.helpers.readlink(slink) == target
    assert slink.open('r').read() == 'Original'
Exemple #30
0
def run(callback, items=None, location=None, *, browser=None):
    if None is items and None is location:
        if None is browser:
            browser = Browser.get()
        location = browser.location()
        if not location:
            raise ValueError
        location = pathlib.WindowsPath(location)
        items = tuple(browser.selected_items())
    elif location:
        location = pathlib.Path.cwd()
    location = pathlib.Path(location)
    if not all(
            location.samefile(location.joinpath(item).resolve().parent)
            for item in items):
        raise ValueError
    items = tuple(map(pathlib.PurePath, items))
    while True:
        forces = tuple(map(Item, items))
        callback(location, forces)
        count = 0
        for before, after in zip(items, (item.rename for item in forces)):
            if None is after:
                continue
            before = str(before)
            after = str(after)
            if before == after:
                continue
            print('{!r} => {!r}'.format(before, after))
            count += 1
        print('@count    {!s}/{!s}'.format(count, len(items)))
        print('@location {!s}'.format(location))
        if 0 >= count:
            input('There is no change.')
            continue
        if input("yes or no? ") in ('y', 'Y', 'yes', 'Yes', 'YES'):
            for before, after in zip(items, (item.rename for item in forces)):
                if None is after:
                    continue
                item = pathlib.Path(location, before)
                item.rename(item.with_name(str(after)))
            break
        if None is not browser:
            browser._webbrowser_.Refresh()
    return None