当前位置: 首页>>代码示例>>Python>>正文


Python os.sep方法代码示例

本文整理汇总了Python中os.sep方法的典型用法代码示例。如果您正苦于以下问题:Python os.sep方法的具体用法?Python os.sep怎么用?Python os.sep使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在os的用法示例。


在下文中一共展示了os.sep方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: scan

# 需要导入模块: import os [as 别名]
# 或者: from os import sep [as 别名]
def scan(self, path, exclude=[]) -> List[str]:
        """Scan path for matching files.

        :param path: the path to scan
        :param exclude: a list of directories to exclude

        :return: a list of sorted filenames
        """
        res = []
        path = path.rstrip("/").rstrip("\\")
        for pat in self.input_patterns:
            res.extend(glob.glob(path + os.sep + pat, recursive=True))

        res = list(filter(lambda p: os.path.isfile(p), res))

        if exclude:
            def excluded(path):
                for e in exclude:
                    if path.startswith(e):
                        return True
                return False

            res = list(filter(lambda p: not excluded(p), res))

        return sorted(res) 
开发者ID:mme,项目名称:vergeml,代码行数:27,代码来源:io.py

示例2: resource_path

# 需要导入模块: import os [as 别名]
# 或者: from os import sep [as 别名]
def resource_path(relativePath):
    """
    Function to detect the correct path of file when working with sourcecode/install or binary.
    :param relativePath: Path to file/data.
    :return: Modified path to file/data.
    """
    # This is not strictly needed because Windows recognize '/'
    # as a path separator but we follow the discipline here.
    relativePath = relativePath.replace('/', os.sep)
    for dir_ in [
            os.path.abspath('.'),
            os.path.abspath('..'),
            getattr(sys, '_MEIPASS', None),
            os.path.dirname(os.path.dirname( # go up two levels
                os.path.realpath(__file__))),
            '/usr/share/multibootusb'.replace('/', os.sep),
            ]:
        if dir_ is None:
            continue
        fullpath = os.path.join(dir_, relativePath)
        if os.path.exists(fullpath):
            return fullpath
    log("Could not find resource '%s'." % relativePath) 
开发者ID:mbusb,项目名称:multibootusb,代码行数:25,代码来源:osdriver.py

示例3: from_path

# 需要导入模块: import os [as 别名]
# 或者: from os import sep [as 别名]
def from_path(cls, context, path):
        """
        Create a device from a device ``path``.  The ``path`` may or may not
        start with the ``sysfs`` mount point:

        >>> from pyudev import Context, Device
        >>> context = Context()
        >>> Devices.from_path(context, '/devices/platform')
        Device(u'/sys/devices/platform')
        >>> Devices.from_path(context, '/sys/devices/platform')
        Device(u'/sys/devices/platform')

        ``context`` is the :class:`Context` in which to search the device.
        ``path`` is a device path as unicode or byte string.

        Return a :class:`Device` object for the device.  Raise
        :exc:`DeviceNotFoundAtPathError`, if no device was found for ``path``.

        .. versionadded:: 0.18
        """
        if not path.startswith(context.sys_path):
            path = os.path.join(context.sys_path, path.lstrip(os.sep))
        return cls.from_sys_path(context, path) 
开发者ID:mbusb,项目名称:multibootusb,代码行数:25,代码来源:_device.py

示例4: fnCall

# 需要导入模块: import os [as 别名]
# 或者: from os import sep [as 别名]
def fnCall():
    """
    Prints filename:line:function for parent and grandparent.
    """

    if not config.debug:
        return

    print(colors.OKGREEN + colors.BOLD + "=== DEBUG === | %s:%d:%s() called from %s:%d:%s()" % (
        inspect.stack()[1][1].split(os.sep)[-1],
        inspect.stack()[1][2],
        inspect.stack()[1][3],
        inspect.stack()[2][1].split(os.sep)[-1],
        inspect.stack()[2][2],
        inspect.stack()[2][3],
        )+colors.RESET) 
开发者ID:mbusb,项目名称:multibootusb,代码行数:18,代码来源:debug.py

示例5: get_header_guard_dmlc

# 需要导入模块: import os [as 别名]
# 或者: from os import sep [as 别名]
def get_header_guard_dmlc(filename):
    """Get Header Guard Convention for DMLC Projects.

    For headers in include, directly use the path
    For headers in src, use project name plus path

    Examples: with project-name = dmlc
        include/dmlc/timer.h -> DMLC_TIMTER_H_
        src/io/libsvm_parser.h -> DMLC_IO_LIBSVM_PARSER_H_
    """
    fileinfo = cpplint.FileInfo(filename)
    file_path_from_root = fileinfo.RepositoryName()
    inc_list = ['include', 'api', 'wrapper']

    if file_path_from_root.find('src/') != -1 and _HELPER.project_name is not None:
        idx = file_path_from_root.find('src/')
        file_path_from_root = _HELPER.project_name +  file_path_from_root[idx + 3:]
    else:
        for spath in inc_list:
            prefix = spath + os.sep
            if file_path_from_root.startswith(prefix):
                file_path_from_root = re.sub('^' + prefix, '', file_path_from_root)
                break
    return re.sub(r'[-./\s]', '_', file_path_from_root).upper() + '_' 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:26,代码来源:lint.py

示例6: get_header_guard_dmlc

# 需要导入模块: import os [as 别名]
# 或者: from os import sep [as 别名]
def get_header_guard_dmlc(filename):
    """Get Header Guard Convention for DMLC Projects.
    For headers in include, directly use the path
    For headers in src, use project name plus path
    Examples: with project-name = dmlc
        include/dmlc/timer.h -> DMLC_TIMTER_H_
        src/io/libsvm_parser.h -> DMLC_IO_LIBSVM_PARSER_H_
    """
    fileinfo = cpplint.FileInfo(filename)
    file_path_from_root = fileinfo.RepositoryName()
    inc_list = ['include', 'api', 'wrapper']

    if file_path_from_root.find('src/') != -1 and _HELPER.project_name is not None:
        idx = file_path_from_root.find('src/')
        file_path_from_root = _HELPER.project_name +  file_path_from_root[idx + 3:]
    else:
        for spath in inc_list:
            prefix = spath + os.sep
            if file_path_from_root.startswith(prefix):
                file_path_from_root = re.sub('^' + prefix, '', file_path_from_root)
                break
    return re.sub(r'[-./\s]', '_', file_path_from_root).upper() + '_' 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:24,代码来源:lint.py

示例7: convert_images2bmp

# 需要导入模块: import os [as 别名]
# 或者: from os import sep [as 别名]
def convert_images2bmp():
    # cv2.imread() jpg at 230 img/s, *.bmp at 400 img/s
    for path in ['../coco/images/val2014/', '../coco/images/train2014/']:
        folder = os.sep + Path(path).name
        output = path.replace(folder, folder + 'bmp')
        if os.path.exists(output):
            shutil.rmtree(output)  # delete output folder
        os.makedirs(output)  # make new output folder

        for f in tqdm(glob.glob('%s*.jpg' % path)):
            save_name = f.replace('.jpg', '.bmp').replace(folder, folder + 'bmp')
            cv2.imwrite(save_name, cv2.imread(f))

    for label_path in ['../coco/trainvalno5k.txt', '../coco/5k.txt']:
        with open(label_path, 'r') as file:
            lines = file.read()
        lines = lines.replace('2014/', '2014bmp/').replace('.jpg', '.bmp').replace(
            '/Users/glennjocher/PycharmProjects/', '../')
        with open(label_path.replace('5k', '5k_bmp'), 'w') as file:
            file.write(lines) 
开发者ID:zbyuan,项目名称:pruning_yolov3,代码行数:22,代码来源:datasets.py

示例8: get_eclipse_project_rel_locationURI

# 需要导入模块: import os [as 别名]
# 或者: from os import sep [as 别名]
def get_eclipse_project_rel_locationURI(path, eclipseProjectDir):
    """
    Gets the URI for a resource relative to an Eclipse project directory (i.e.,
    the directory containing the `.project` file for the project). The URI
    returned is based on the builtin PROJECT_LOC Eclipse variable.
    See http://stackoverflow.com/a/7585095
    """
    relpath = os.path.relpath(path, eclipseProjectDir)
    names = relpath.split(os.sep)
    parents = len([n for n in names if n == '..'])
    sep = '/' # Yes, even on Windows...
    if parents:
        projectLoc = 'PARENT-{}-PROJECT_LOC'.format(parents)
    else:
        projectLoc = 'PROJECT_LOC'
    return sep.join([projectLoc] + [n for n in names if n != '..']) 
开发者ID:graalvm,项目名称:mx,代码行数:18,代码来源:mx_ide_eclipse.py

示例9: gen_dockerfile_path_from_tag

# 需要导入模块: import os [as 别名]
# 或者: from os import sep [as 别名]
def gen_dockerfile_path_from_tag(img_tag):
    """
    sample input: 'tensorflow:1.0.1-gpu-py3'
    sample output: 'dl/tensorflow/1.0.1/Dockerfile-py3.gpu'
    """
    match = docker_tag_re.match(img_tag)
    if not match:
        return None

    path_list = ['dl', match.group('project'), match.group('version')]
    filename = 'Dockerfile-' + match.group('env')
    arch = match.group('arch')
    if arch:
        filename += '.' + arch
    cloud = match.group('cloud')
    if cloud:
        filename += '_' + cloud

    path_list.append(filename)
    return os.path.sep.join(path_list) 
开发者ID:floydhub,项目名称:dockerfiles,代码行数:22,代码来源:utils.py

示例10: __init__

# 需要导入模块: import os [as 别名]
# 或者: from os import sep [as 别名]
def __init__(self, out_dir=None, ckpt_name_fmt='ckpt_{:010d}.pt', tmp_postfix='.tmp'):
        assert len(tmp_postfix)
        assert '.' in tmp_postfix
        m = re.search(r'{:0(\d+?)d}', ckpt_name_fmt)
        assert m, 'Expected ckpt_name_fmt to have an int specifier such as or {:09d} or {:010d}.'
        max_itr = 10 ** int(m.group(1)) - 1
        if max_itr < 10000000:  # ten million, should be enough
            print(f'Maximum iteration supported: {max_itr}')
        assert os.sep not in ckpt_name_fmt
        self.ckpt_name_fmt = ckpt_name_fmt
        self.ckpt_prefix = ckpt_name_fmt.split('{')[0]
        assert len(self.ckpt_prefix), 'Expected ckpt_name_fmt to start with a prefix before the format part!'
        self.tmp_postfix = tmp_postfix

        self._out_dir = None
        if out_dir is not None:
            self.set_out_dir(out_dir) 
开发者ID:fab-jul,项目名称:L3C-PyTorch,代码行数:19,代码来源:saver.py

示例11: __getitem__

# 需要导入模块: import os [as 别名]
# 或者: from os import sep [as 别名]
def __getitem__(self, index):

        img_path = self.files[self.split][index].rstrip()
        lbl_path = os.path.join(self.annotations_base,
                                img_path.split(os.sep)[-2],
                                os.path.basename(img_path)[:-15] + 'gtFine_labelIds.png')

        _img = Image.open(img_path).convert('RGB')
        _tmp = np.array(Image.open(lbl_path), dtype=np.uint8)
        _tmp = self.encode_segmap(_tmp)
        _target = Image.fromarray(_tmp)

        sample = {'image': _img, 'label': _target}

        if self.split == 'train':
            return self.transform_tr(sample)
        elif self.split == 'val':
            return self.transform_val(sample)
        elif self.split == 'test':
            return self.transform_ts(sample) 
开发者ID:clovaai,项目名称:overhaul-distillation,代码行数:22,代码来源:cityscapes.py

示例12: main

# 需要导入模块: import os [as 别名]
# 或者: from os import sep [as 别名]
def main(opt):
    ann_file = '{}/annotations/instances_{}.json'.format(opt.input, opt.type)
    dataset = json.load(open(ann_file, 'r'))
    image_dict = {}
    invalid_anno = 0

    for image in dataset["images"]:
        if image["id"] not in image_dict.keys():
            image_dict[image["id"]] = {"file_name": image["file_name"], "objects": []}

    for ann in dataset["annotations"]:
        if ann["image_id"] not in image_dict.keys():
            invalid_anno += 1
            continue
        image_dict[ann["image_id"]]["objects"].append(
            [int(ann["bbox"][0]), int(ann["bbox"][1]), int(ann["bbox"][0] + ann["bbox"][2]),
             int(ann["bbox"][1] + ann["bbox"][3]), ann["category_id"]])

    pickle.dump(image_dict, open(opt.output + os.sep + 'COCO_{}.pkl'.format(opt.type), 'wb'))
    print ("There are {} invalid annotation(s)".format(invalid_anno)) 
开发者ID:uvipen,项目名称:Yolo-v2-pytorch,代码行数:22,代码来源:convert_coco_to_pkl.py

示例13: get_wallpaper_directory

# 需要导入模块: import os [as 别名]
# 或者: from os import sep [as 别名]
def get_wallpaper_directory():
    """ check if `default` wallpaper download directory exists or not, create if doesn't exist """
    pictures_dir = ""
    wall_dir_name = "freshpaper"
    os.path.join(os.sep, os.path.expanduser("~"), "a", "freshpaper")
    if sys.platform.startswith("win32"):
        pictures_dir = "My Pictures"
    elif sys.platform.startswith("darwin"):
        pictures_dir = "Pictures"
    elif sys.platform.startswith("linux"):
        pictures_dir = "Pictures"
    wall_dir = os.path.join(
        os.sep, os.path.expanduser("~"), pictures_dir, wall_dir_name
    )

    if not os.path.isdir(wall_dir):
        log.error("wallpaper directory does not exist.")
        os.makedirs(wall_dir)
        log.info("created wallpaper directory at: {}".format(wall_dir))

    return wall_dir 
开发者ID:guptarohit,项目名称:freshpaper,代码行数:23,代码来源:freshpaper.py

示例14: get_resource_path

# 需要导入模块: import os [as 别名]
# 或者: from os import sep [as 别名]
def get_resource_path(*args):
  if is_frozen():
    # MEIPASS explanation:
    # https://pythonhosted.org/PyInstaller/#run-time-operation
    basedir = getattr(sys, '_MEIPASS', None)
    if not basedir:
      basedir = os.path.dirname(sys.executable)
    resource_dir = os.path.join(basedir, 'gooey')
    if not os.path.isdir(resource_dir):
      raise IOError(
        ("Cannot locate Gooey resources. It seems that the program was frozen, "
         "but resource files were not copied into directory of the executable "
         "file. Please copy `languages` and `images` folders from gooey module "
         "directory into `{}{}` directory. Using PyInstaller, a.datas in .spec "
         "file must be specified.".format(resource_dir, os.sep)))
  else:
    resource_dir = os.path.normpath(os.path.join(os.path.dirname(__file__), '..', '..'))
  return os.path.join(resource_dir, *args) 
开发者ID:ME-ICA,项目名称:me-ica,代码行数:20,代码来源:freeze.py

示例15: get_all_classes

# 需要导入模块: import os [as 别名]
# 或者: from os import sep [as 别名]
def get_all_classes(self):
        """Get all classes

        Get the classes of the type we want from all modules found
        in the directory that defines this class.
        """
        classes = []
        for dirpath, dirnames, filenames in os.walk(self.path):
            relpath = os.path.relpath(dirpath, self.path)
            if relpath == '.':
                relpkg = ''
            else:
                relpkg = '.%s' % '.'.join(relpath.split(os.sep))
            for fname in filenames:
                root, ext = os.path.splitext(fname)
                if ext != '.py' or root == '__init__':
                    continue
                module_name = "%s%s.%s" % (self.package, relpkg, root)
                mod_classes = self._get_classes_from_module(module_name)
                classes.extend(mod_classes)
        return classes 
开发者ID:openstack,项目名称:zun,代码行数:23,代码来源:loadables.py


注:本文中的os.sep方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。