當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。