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


Python path.expanduser方法代码示例

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


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

示例1: execute_from_file

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import expanduser [as 别名]
def execute_from_file(self, pattern, **_):
        if not pattern:
            message = "\\i: missing required argument"
            return [(None, None, None, message, "", False, True)]
        try:
            with open(os.path.expanduser(pattern), encoding="utf-8") as f:
                query = f.read()
        except IOError as e:
            return [(None, None, None, str(e), "", False, True)]

        if self.destructive_warning and confirm_destructive_query(query) is False:
            message = "Wise choice. Command execution stopped."
            return [(None, None, None, message)]

        on_error_resume = self.on_error == "RESUME"
        return self.pgexecute.run(
            query, self.pgspecial, on_error_resume=on_error_resume
        ) 
开发者ID:dbcli,项目名称:pgcli,代码行数:20,代码来源:main.py

示例2: write_to_file

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import expanduser [as 别名]
def write_to_file(self, pattern, **_):
        if not pattern:
            self.output_file = None
            message = "File output disabled"
            return [(None, None, None, message, "", True, True)]
        filename = os.path.abspath(os.path.expanduser(pattern))
        if not os.path.isfile(filename):
            try:
                open(filename, "w").close()
            except IOError as e:
                self.output_file = None
                message = str(e) + "\nFile output disabled"
                return [(None, None, None, message, "", False, True)]
        self.output_file = filename
        message = 'Writing to file "%s"' % self.output_file
        return [(None, None, None, message, "", True, True)] 
开发者ID:dbcli,项目名称:pgcli,代码行数:18,代码来源:main.py

示例3: parse_service_info

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import expanduser [as 别名]
def parse_service_info(service):
    service = service or os.getenv("PGSERVICE")
    service_file = os.getenv("PGSERVICEFILE")
    if not service_file:
        # try ~/.pg_service.conf (if that exists)
        if platform.system() == "Windows":
            service_file = os.getenv("PGSYSCONFDIR") + "\\pg_service.conf"
        elif os.getenv("PGSYSCONFDIR"):
            service_file = os.path.join(os.getenv("PGSYSCONFDIR"), ".pg_service.conf")
        else:
            service_file = expanduser("~/.pg_service.conf")
    if not service:
        # nothing to do
        return None, service_file
    service_file_config = ConfigObj(service_file)
    if service not in service_file_config:
        return None, service_file
    service_conf = service_file_config.get(service)
    return service_conf, service_file 
开发者ID:dbcli,项目名称:pgcli,代码行数:21,代码来源:main.py

示例4: reset_cache_dir

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import expanduser [as 别名]
def reset_cache_dir():
        # Cache directory
        OCSPCache.CACHE_DIR = os.getenv('SF_OCSP_RESPONSE_CACHE_DIR')
        if OCSPCache.CACHE_DIR is None:
            cache_root_dir = expanduser("~") or tempfile.gettempdir()
            if platform.system() == 'Windows':
                OCSPCache.CACHE_DIR = path.join(cache_root_dir, 'AppData', 'Local', 'Snowflake',
                                                'Caches')
            elif platform.system() == 'Darwin':
                OCSPCache.CACHE_DIR = path.join(cache_root_dir, 'Library', 'Caches', 'Snowflake')
            else:
                OCSPCache.CACHE_DIR = path.join(cache_root_dir, '.cache', 'snowflake')
        logger.debug("cache directory: %s", OCSPCache.CACHE_DIR)

        if not path.exists(OCSPCache.CACHE_DIR):
            try:
                os.makedirs(OCSPCache.CACHE_DIR, mode=0o700)
            except Exception as ex:
                logger.debug('cannot create a cache directory: [%s], err=[%s]',
                             OCSPCache.CACHE_DIR, ex)
                OCSPCache.CACHE_DIR = None 
开发者ID:snowflakedb,项目名称:snowflake-connector-python,代码行数:23,代码来源:ocsp_snowflake.py

示例5: get_data_dir

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import expanduser [as 别名]
def get_data_dir(data_dir=None):
    """Return the path of the pulse2percept data directory

    This directory is used to store the datasets retrieved by the data fetch
    utility functions to avoid downloading the data several times.

    By default, this is set to a directory called 'pulse2percept_data' in the
    user home directory.
    Alternatively, it can be set by a ``PULSE2PERCEPT_DATA`` environment
    variable or set programmatically by specifying a path.

    If the directory does not already exist, it is automatically created.

    Parameters
    ----------
    data_dir : str | None
        The path to the pulse2percept data directory.
    """
    if data_dir is None:
        data_dir = environ.get('PULSE2PERCEPT_DATA',
                               join('~', 'pulse2percept_data'))
    data_dir = expanduser(data_dir)
    if not exists(data_dir):
        makedirs(data_dir)
    return data_dir 
开发者ID:pulse2percept,项目名称:pulse2percept,代码行数:27,代码来源:base.py

示例6: __init__

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import expanduser [as 别名]
def __init__(self, outfp=sys.stdout, errfp=sys.stderr, debug=False,
                 printTracebacks=False, loadInitFile=True, shell=None,
                 usePtys=True):
        self.outfp = outfp
        self.errfp = errfp
        self.debug = debug
        self.printTracebacks = printTracebacks
        self.shell = shell or ['/bin/sh', '-c']
        self.usePtys = usePtys
        self.stdin = None
        self.lastStdin = None
        self.stdout = None
        self.pendingText = ''
        self.initFile = join(expanduser('~'), '.daudin.py')
        self.lastResultIsList = False
        self.local = self._getLocal()
        if loadInitFile:
            self.loadInitFile()
        self.inPipeline = False 
开发者ID:terrycojones,项目名称:daudin,代码行数:21,代码来源:pipeline.py

示例7: getSettings

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import expanduser [as 别名]
def getSettings():
    if not getSettings.settings:
        cwd = os.getcwd()
        path = cwd + '/.settings.yaml'

        if not os.path.isfile(path):
            path = cwd + '/.screeps_settings.yaml'

        if not os.path.isfile(path):
            path = expanduser('~') + '/.screeps_settings.yaml'

        if not os.path.isfile(path):
            path = '/vagrant/.screeps_settings.yaml'


        if not os.path.isfile(path):
            print 'no settings file found'
            sys.exit(-1)
            return False

        with open(path, 'r') as f:
            getSettings.settings = yaml.load(f)

    return getSettings.settings 
开发者ID:screepers,项目名称:screeps-stats,代码行数:26,代码来源:settings.py

示例8: extendarduinolist

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import expanduser [as 别名]
def extendarduinolist(self, idnum):
        from os.path import expanduser
        home = expanduser("~")

        martasdir = [path for path, dirs, files in os.walk(home) if path.endswith('MARTAS')][0]
        arduinosensorfile = os.path.join(martasdir,'arduinolist.csv')
        log.msg('Checking Arduinofile: %s' % arduinosensorfile)
        arduinolist = []
        sensorelement = []
        try:
            arduinolist = self.loadarduinolist(arduinosensorfile)
            sensorelement = [elem[0] for elem in arduinolist]
            print("Liste", sensorelement)
        except:
            log.msg('Arduino: No Sensor list so far -or- Error while getting sensor list')
            pass
        if not self.sensordict[idnum] in sensorelement:
            arduinolist.append([self.sensordict[idnum], self.keydict[idnum]])
            self.savearduinolist(arduinosensorfile,arduinolist) 
开发者ID:geomagpy,项目名称:magpy,代码行数:21,代码来源:arduinoprotocol.py

示例9: sc

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import expanduser [as 别名]
def sc():
    """
    Show credentials
    """

    sysuser = getuser()
    home = expanduser('~'+sysuser)
    # previously used expanduser('~') which does not work for root
    credentials = os.path.join(home,'.magpycred')
    print("Credentials: Overview of existing credentials:")
    try:
        dictslist = loadobj(credentials)
    except:
        print("Credentials: Could not load file")
        return

    for d in dictslist:
        print(d)
    return dictslist 
开发者ID:geomagpy,项目名称:magpy,代码行数:21,代码来源:cred.py

示例10: protect

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import expanduser [as 别名]
def protect(protect_args=None):
    global c
    flags = ''
    option_end = False
    if not protect_args:
        protect_args = argv[1:]
    for arg in protect_args:
        if arg == '--':
            option_end = True
        elif (arg.startswith("-") and not option_end):
            flags = flags + arg[arg.rfind('-') + 1:]
        elif arg in c.invalid:
            pprint('"." and ".." may not be protected')
        else:
            path = abspath(expv(expu(arg)))
            evalpath = dirname(path) + "/." + basename(path) + c.suffix
            if not exists(path):
                pprint("Warning: " + path + " does not exist")
            with open(evalpath, "w") as f:
                question = input("Question for " + path + ": ")
                answer = input("Answer: ")
                f.write(question + "\n" + answer + "\n" + flags.upper()) 
开发者ID:alanzchen,项目名称:rm-protection,代码行数:24,代码来源:protect.py

示例11: __init__

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import expanduser [as 别名]
def __init__(self, root=None, transform=None, pre_transform=None,
                 pre_filter=None):
        super(Dataset, self).__init__()

        if isinstance(root, str):
            root = osp.expanduser(osp.normpath(root))

        self.root = root
        self.transform = transform
        self.pre_transform = pre_transform
        self.pre_filter = pre_filter
        self.__indices__ = None

        if 'download' in self.__class__.__dict__.keys():
            self._download()

        if 'process' in self.__class__.__dict__.keys():
            self._process() 
开发者ID:rusty1s,项目名称:pytorch_geometric,代码行数:20,代码来源:dataset.py

示例12: loadMetadata

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import expanduser [as 别名]
def loadMetadata(self, zip):
        # Load the turtle metadata.
        aff4cache = os.path.join(expanduser("~"), ".aff4")
        if not os.path.exists(aff4cache):
            try:
                os.makedirs(aff4cache)
            except OSError as exc:  # Guard against race condition
                if exc.errno != errno.EEXIST:
                    raise
        cached_turtle = os.path.join(aff4cache, "%s.hdt" % str(zip.urn)[7:])
        if not os.path.exists(cached_turtle):
            self.createHDTviaLib(zip, cached_turtle)

        if os.path.exists(cached_turtle):
            # assume we have a HDT cache of turtle at this point
            self.hdt = HDTDocument(cached_turtle)


    # this implementation currently not tested
    # and it is super ugly. We are materializing all triples just to
    # list all the subjects.
    # TODO: Implement subject iterator in pyHDT 
开发者ID:aff4,项目名称:pyaff4,代码行数:24,代码来源:data_store.py

示例13: connect_key

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import expanduser [as 别名]
def connect_key(self, params={}):
        home_dir = (path.expanduser('~'))
        key_file = "{}/.ssh".format(home_dir)
        f = params.get('key').get('privateKey')
        fb = f.get('content')
        fb64 = base64.b64decode(fb)
        fb64 = fb64.decode("utf-8")
        if not path.exists(key_file):
            os.makedirs(key_file)
            os.chmod(key_file, 0o700)
        key_file_path = path.join(key_file, "id_rsa")
        with open(key_file_path, 'w+') as f:
            f.write(fb64)
        os.chmod(key_file_path, 0o600)
        self.logger.info("Establishing connection")
        device = {'device_type': params.get('device_type'), 'ip': params.get('host'),
                  'username': params.get('credentials').get('username'), 'use_keys': True, 'key_file': key_file_path,
                  'password': params.get('credentials').get('password'), 'port': params.get('port'),
                  'secret': params.get('secret').get('secretKey'), 'allow_agent': True, 'global_delay_factor': 4}
        self.device_connect = ConnectHandler(**device)
        return self.device_connect 
开发者ID:rapid7,项目名称:insightconnect-plugins,代码行数:23,代码来源:connection.py

示例14: __get_data_home__

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import expanduser [as 别名]
def __get_data_home__(data_home=None):
    """
    Return the path of the rankeval data dir.
    This folder is used by some large dataset loaders to avoid
    downloading the data several times.
    By default the data dir is set to a folder named 'rankeval_data'
    in the user home folder.
    Alternatively, it can be set by the 'RANKEVAL_DATA' environment
    variable or programmatically by giving an explicit folder path. The
    '~' symbol is expanded to the user home folder.
    If the folder does not already exist, it is automatically created.
    """
    if data_home is None:
        data_home = environ.get('RANKEVAL_DATA', join('~', 'rankeval_data'))
    data_home = expanduser(data_home)
    if not exists(data_home):
        makedirs(data_home)
    return data_home 
开发者ID:hpclab,项目名称:rankeval,代码行数:20,代码来源:datasets_fetcher.py

示例15: handle_template

# 需要导入模块: from os import path [as 别名]
# 或者: from os.path import expanduser [as 别名]
def handle_template(self, template, subdir):
        """
        Determines where the app or project templates are.
        Use django.__path__[0] as the default because we don't
        know into which directory Django has been installed.
        """
        if template is None:
            return path.join(django.__path__[0], 'conf', subdir)
        else:
            if template.startswith('file://'):
                template = template[7:]
            expanded_template = path.expanduser(template)
            expanded_template = path.normpath(expanded_template)
            if path.isdir(expanded_template):
                return expanded_template
            if self.is_url(template):
                # downloads the file and returns the path
                absolute_path = self.download(template)
            else:
                absolute_path = path.abspath(expanded_template)
            if path.exists(absolute_path):
                return self.extract(absolute_path)

        raise CommandError("couldn't handle %s template %s." %
                           (self.app_or_project, template)) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:27,代码来源:templates.py


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