How to use the pathlib.PureWindowsPath 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 gpoore / codebraid / codebraid / codeprocessors / base.py View on Github external
stdout_lines.append('')
            stdout_lines.append(sentinel_delim)
            stderr_lines.append('')
            stderr_lines.append(sentinel_delim)
            expected_stdstream_delims.append(-1)
            chunk_stdout_dict = {}
            chunk_stderr_dict = {}
            chunk_expr_dict = {}
            chunk_rich_output_dict = {}
            files_list = []
            chunk_runtime_source_error_dict = {}
            # More source patterns may be needed in future to cover the
            # possibility of languages that make paths lowercase on
            # case-insensitive filesystems
            source_pattern_posix = source_path.as_posix()
            source_pattern_win = str(pathlib.PureWindowsPath(source_path))
            source_pattern_final = 'source.{0}'.format(session.lang_def.extension)
            source_pattern_final_inline = ''
            error_patterns = session.lang_def.error_patterns
            warning_patterns = session.lang_def.warning_patterns
            line_number_pattern_re = session.lang_def.line_number_pattern_re
            line_number_regex_re = session.lang_def.line_number_regex_re

            session_output_index = -1
            chunk_start_index = 0
            chunk_end_index = 0
            for index, line in enumerate(stdout_lines):
                if line.startswith(stdstream_delim_start) and line.startswith(stdstream_delim_start_hash):
                    next_session_output_index = int(line.split('output_chunk=', 1)[1].split(',', 1)[0])
                    if index > 0:
                        chunk_end_index = index - 1
                        if stdout_lines[chunk_end_index]:
github Terrabits / rohdeschwarz / rohdeschwarz / instruments / vna / filesystem.py View on Github external
def is_directory(self, path):
        path = pathlib.PureWindowsPath(path)
        location = str(path.parent).replace("/", "\\")
        name = path.name
        original_dir = self.directory()
        if location != ".":
            self.cd(location)
        directories= self.directories()
        for d in directories:
            if d.upper() == name.upper():
                if location != ".":
                    self.cd(original_dir)
                return True
        # Else
        if location != ".":
            self.cd(original_dir)
        return False
github dreamer / boxtron / toolbox.py View on Github external
if not this_line:
                continue
            first_word = this_line[0]
            if first_word.lower() in ('exit', '@exit'):
                continue
            if first_word.lower() in ('echo', '@echo'):
                continue
            if first_word.lower() in ('cd', '@cd'):
                # This works only for a single 'CD', but no game uses more than
                # one (so far).  If we'll ever find one, then it's time to
                # implement more serious batch interpreter instead.
                new_path = winpathlib.to_posix_path(this_line[1])
                assert new_path, 'error processing .bat ' + \
                                 'file: no directory named ' + \
                                 '{}'.format(this_line[1])
            win_path = pathlib.PureWindowsPath(first_word)
            exe = win_path.parts[-1]
            if exe.lower() in ('dosbox', 'dosbox.exe'):
                return new_path, this_line[1:]
    assert False, 'error processing .bat file (line {})'.format(line_num)
    return None, []
github BobBuildTool / bob / pym / bob / generators / VisualStudio.py View on Github external
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
github SteveDoyle2 / pyNastran / pyNastran / bdf / bdf_interface / include_file.py View on Github external
'\0' (NUL)

    Invalid Windows Tokens
    < (less than)
    > (greater than)
    : (colon - sometimes works, but is actually NTFS Alternate Data Streams)
    " (double quote)
    / (forward slash)
    \ (backslash)
    | (vertical bar or pipe)
    ? (question mark)
    * (asterisk)
    All control codes (<= 31)
    """
    if is_windows:
        inc = PureWindowsPath(include_dir)
        pth = PureWindowsPath(filename).parts

        # fails if the comment has stripped out the file (e.g., "INCLUDE '$ENV/model.bdf'")
        pth0 = pth[0]

        # Linux style paths
        # /work/model.bdf
        if len(pth0) == 1 and pth0[0] == '\\':
            # utterly breaks os.path.join
            raise SyntaxError('filename=%r cannot start with / on Windows' % filename)
    else:
        inc = PurePosixPath(include_dir)
        pth = PurePosixPath(filename).parts

        # fails if the comment has stripped out the file (e.g., "INCLUDE '$ENV/model.bdf'")
        pth0 = pth[0]
github SteveDoyle2 / pyNastran / pyNastran / bdf / bdf_interface / include_file.py View on Github external
assert '%' not in stokens[0], token0

                if '%' in token0:
                    assert token0[0] == '%', token0
                    assert token0[-1] == '%', token0
                    token0 = '%' + token0 + '%'
                else:
                    token0 = '$' + token0

                #tokeni = os.path.expandvars('$' + stokens[0])
                tokeni = os.path.expandvars(token0)
                if '$' in tokeni:
                    raise SyntaxError('tokeni=%r has a $ in it after expanding (token0=%r)...\n'
                                      'tokens=%s stokens=%s' % (tokeni, token0, tokens, stokens))

                tokensi = PureWindowsPath(tokeni).parts
            else:
                if '$' in token0:
                    assert token0[0] == '$', token0
                else:
                    token0 = '$' + token0
                assert '%' not in stokens[0], token0
                tokeni = os.path.expandvars(token0)
                tokensi = PurePosixPath(tokeni).parts

            tokens2.extend(tokensi)
            tokens2.append(stokens[1])

        elif ':' in token:
            # Windows

            # this has an environment variable or a drive letter
github SpiderLabs / scavenger / scavenger.py View on Github external
credit_smb = con_db.execute(f"""SELECT ip_address,folder_cc FROM credit_smb_latest ORDER BY ip_address""")
        for r in credit_smb:
            html_list_credit.append(r)

    if len(html_list_credit) > 0:

        cc_file_list = []
        for ip_cc_download, fold_cc_download in html_list_credit:
            cc_match_download = search(r'^(.+)\s{1}[A-Z_]+\s{1}\d+\s?', fold_cc_download)
            if cc_match_download:
                cc_match_download2 = search(r'^(\w{1}:.+)(\/[\w\d\-\.\@]+.\w{3})', cc_match_download.group(1))
                if cc_match_download2:
                    parent = cc_match_download2.group(1)
                    file = cc_match_download2.group(2)
                parent2 = str(PureWindowsPath(cc_match_download.group(1)).parent)
                file2 = str(PureWindowsPath(cc_match_download.group(1)).name)

            size_c = crackmapexec_command_exec(ip_cc_download, f"""-x 'forfiles.exe /P "{parent2}" /m "{file2}" /C "cmd /c echo @fsize"'""")
            if int(size_c[-1]) > 0 and int(size_c[-1 ]) < 314572800:
                if not path.exists(f"downloads/{ip_cc_download}/chdfiles"):
                    mkdir(f"downloads/{ip_cc_download}/chdfiles")
                parent2 = parent2.replace('c:', '')
                command_execute(f"""smbclient //{ip_cc_download}/c$ -c 'lcd downloads/{ip_cc_download}/chdfiles; cd {parent2}; get \"{file2}\"' -U {username_g}%{password_g} -W {domain_g}""")
                cc_file_list.append(f"\033[97m{ip_cc_download} -\033[00m {cc_match_download.group(1)} \033[97m=> local:\033[00m {script_path}/downloads/{ip_cc_download}/chdfiles/{file2}")

        cc_file_list_set = set(cc_file_list)

    laz_browsers_check = False

    with db:
        laz_browser = con_db.execute(f"""SELECT ip_address,laz_browsers FROM laz_b_smb_latest ORDER BY ip_address""")
        for r in laz_browser:
github dreamer / boxtron / toolbox.py View on Github external
def known_bat_cmd(bat_cmd_line):
    """Test if a line qualifies as known batch file command"""
    stripped_line = bat_cmd_line.strip()
    if not stripped_line:  # empty line
        return True
    pseudo_expanded_line = stripped_line.replace('%~dp0', '')
    line = argsplit_windows(pseudo_expanded_line)
    first_word = line[0].lstrip('@').lower()
    if first_word in ('echo', 'cd', 'exit'):
        return True
    win_path = pathlib.PureWindowsPath(first_word)
    exe = win_path.parts[-1]
    return exe in ('dosbox', 'dosbox.exe')
github qbicsoftware / mqrun / mqrun / mqparams.py View on Github external
param_groups = root.find('parameterGroups')

        # maps file names to file paths, belongs to self.extra_data
        paths_dict = {}

        files = []
        for elems in zip(experiments, file_paths, fractions, param_group_inds):
            exp, path, frac, grp_ind = elems

            file = {}

            if exp.text and exp.text.strip():
                file['experiment'] = exp.text.strip()
            if path.text and path.text.strip():
                file['path'] = path.text.strip()
                file['name'] = PureWindowsPath(file['path']).stem
                paths_dict[file['name']] = file['path']
            if frac.text and frac.text.strip():
                file['fraction'] = int(frac.text.strip())
            file['grp_ind'] = int(grp_ind.text.strip())

            files.append(file)

        extra_data = ExtraMQData(paths_dict, None, None, None)
        self.update_data(extra_data=extra_data)

        # data is list of parameter groups
        # each parameter group contains a list of files and a set of parameters
        data = []

        # read schema for group specific parameters
        params_schema = self._schema['items']['properties']['params']
github Terrabits / rohdeschwarz / rohdeschwarz / instruments / vna / vna.py View on Github external
def delete_set(self, name):
        if self.properties.is_zvx() and not name.lower().endswith('.zvx'):
            name += '.zvx'
        elif self.properties.is_znx() and not name.lower().endswith('.znx'):
            name += '.znx'
        current_dir = ''
        if str(PureWindowsPath(name).parent) ==  '.':
            current_dir = self.file.directory()
            self.file.cd(Directory.recall_sets)
        self.file.delete(name)
        if current_dir:
            self.file.cd(current_dir)