我们从Python开源项目中,提取了以下29个代码示例,用于说明如何使用pathlib.Path.home()。
def call_scout(kubectl_version, kube_cluster_version, operation, method): config_root = Path.home() / ".config" / "telepresence" config_root.mkdir(parents=True, exist_ok=True) id_file = config_root / 'id' scout_kwargs = dict( kubectl_version=kubectl_version, kubernetes_version=kube_cluster_version, operation=operation, method=method ) try: with id_file.open('x') as f: install_id = str(uuid4()) f.write(install_id) scout_kwargs["new_install"] = True except FileExistsError: with id_file.open('r') as f: install_id = f.read() scout_kwargs["new_install"] = False scout = Scout("telepresence", __version__, install_id) return scout.report(**scout_kwargs)
def main(): config_path = Path(sys.argv[1]) if len(sys.argv) > 1 else Path.home() / '.config' / 'whereisit.toml' with open(config_path) as f: config = toml.load(f) import logging logging.getLogger('aiohttp.client').setLevel(logging.ERROR) db_path = Path.home() / '.local' / 'share' / config['database']['path'] orm.sql_debug(config['database'].get('debug', False)) database.bind("sqlite", str(db_path), create_db=True) database.generate_mapping(create_tables=True) with orm.db_session(): orm.select(t for t in database.Tracking if t.id not in list(config['trackings'].keys())).delete(bulk=True) asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) with contextlib.closing(asyncio.get_event_loop()) as loop: tracker = Tracker(loop=loop, db=database, config=config) loop.create_task(tracker.run()) loop.run_forever()
def __init__(self, config_path=None): try: # using this env var should be considered unofficial, we need this temporarily for backwards compatibility. # support for it may be removed without notice, do not use it! if 'APP_HOME' in os.environ: config_path = os.path.join(os.environ['APP_HOME'], 'config.yml') # this case is only meant for using gitlabform as a library elif not config_path: config_path = os.path.join(str(Path.home()), '.gitlabform', 'config.yml') elif config_path in [os.path.join('.', 'config.yml'), 'config.yml']: config_path = os.path.join(os.getcwd(), 'config.yml') logging.info("Reading config from: {}".format(config_path)) with open(config_path, 'r') as ymlfile: self.config_from_file = yaml.safe_load(ymlfile) # we need config path for accessing files for relative paths self.config_dir = os.path.dirname(config_path) except Exception as e: raise ConfigFileNotFoundException(config_path)
def complete_config(config: Config) -> Config: """ Complete configuration with complete paths and parameters. Parameters ---------- config Input configuration. Returns ------- The completed configuration. """ # Allow changing home path through environment variable (for testing) home = Path(os.environ.get('MARKDOWNREVEAL_HOME', str(Path.home()))) config['local_path'] = home / config['local_path'] config['output_path'] = config['local_path'] / 'out' config['reveal_extra']['theme'] = config['theme'] return config
def do_activate(self): self.ui.activate() if Settings.get().first_start: Settings.update(first_start=False).execute() path = str(Path.home()) + "/Audiobooks" Settings.update(path=str(Path.home()) + "/Audiobooks").execute() if not os.path.exists(path): os.makedirs(path) else: self.ui.scan(None, True) self.ui.refresh_content() self.add_window(self.ui.window) MPRIS(self, self.ui)
def save_cookies(cls, requests_cookiejar, file_name=COOKIE_FILE_NAME): """ ?????????????????????????????????? :param cookies.RequestsCookieJar requests_cookiejar: :param str file_name: :rtype: dict """ # Python 3.5?????????????? # file_path = make_dir(Path.home() / file_name) # file_path.write_text("\n".join([k + "\t" + v for k, v in cook.items()])) file_path = join(expanduser("~"), file_name) cook = {key: val for key, val in requests_cookiejar.items()} with open(file_path, "w") as fd: fd.write("\n".join([k + "\t" + v for k, v in cook.items()])) return cook
def load_cookies(cls, file_name=COOKIE_FILE_NAME): """ ????????????????????????????????? :param str file_name: :rtype: dict | None """ # Python 3.5?????????????? # file_path = make_dir(Path.home() / file_name) # return {line.split("\t")[0]: line.split("\t")[1] # for line in file_path.read_text().split("\n")} try: file_path = join(expanduser("~"), file_name) with open(file_path, "r") as fd: return {line.split("\t")[0]: line.split("\t")[1].strip() for line in fd.readlines()} except (FileNotFoundError, EOFError): return None
def load(file_name, folder='', home_path=Path.home()): # Check home_path fp = Path(home_path, folder, file_name + _EXTENSION) if fp.exists() and fp.is_file(): # load fp = fp.open('r') data_loaded = json.load(fp) fp.close() print(file_name, 'loaded successfully') else: fp_dir = Path(home_path, folder, file_name) if fp.exists(): print('Invalid path') elif fp_dir.is_dir(): print("It's a folder, not a file") else: print("This file doesn't exist") data_loaded = {} print('Empty data is loaded') return data_loaded
def check_folder(folder_to_check: str=Path.home().as_posix(), check_space: int=1) -> bool: """Check working folder,from argument,for everything that can go wrong.""" folder = Path(str(folder_to_check)) m = "Folder {0} ({0!r}) free space {1} ({2} Bytes) of Minimum {3} GigaByte" log.debug("Checking Working Folder: {0} ({0!r}).".format(folder)) if not folder.is_dir(): # What if folder not a folder. log.critical("Folder does not exist: {0} ({0!r}).".format(folder)) return False elif not os.access(folder.as_posix(), os.R_OK): # What if not Readable. log.critical("Folder not readable: {0} ({0!r}).".format(folder)) return False elif not os.access(folder.as_posix(), os.W_OK): # What if not Writable. log.critical("Folder not writable: {0} ({0!r}).".format(folder)) return False elif disk_usage and folder.exists() and bool(check_space): hdd = int(disk_usage(folder.as_posix()).free) if int(hdd / 1_024 / 1_024 / 1_024) >= int(check_space): # Check_space log.info(m.format(folder, bytes2human(hdd), hdd, check_space)) return True else: # < check_space Gb. log.critical(m.format(folder, bytes2human(hdd), hdd, check_space)) return False return False
def _read_ssh_key(): ''' Inner function for read_ssh_key, suitable for passing to our Executor. ''' default_data_dir = Path(Path.home(), ".local", "share", "juju") juju_data = os.environ.get("JUJU_DATA", default_data_dir) ssh_key_path = Path(juju_data, 'ssh', 'juju_id_rsa.pub') with ssh_key_path.open('r') as ssh_key_file: ssh_key = ssh_key_file.readlines()[0].strip() return ssh_key
def load_from_home(cls, relative_conf_path, **kwargs): """ loads workspace relative to the user directory :param relative_conf_path: path to configuration relative to the user directory :return: initialized workspace """ return cls(Path.home() / relative_conf_path, override_configuration=None, **kwargs)
def home_dir(*paths): """ Create a path to dirs/file in OS home dir Ex: home_dir('temp', 'ex.txt') is: ~/temp/ex.txt """ home = str(Path.home()) return os.path.join(home,*paths)
def home_directory() -> Path: """ Not Path.home() for compatibility with Python 3.4. """ return Path(path.expanduser('~'))
def _create_local_storage(): """Adds local storage option for data storage of spykeball statistics.""" storage_target = Path.home().joinpath(LOCAL_STORAGE) storage_target.mkdir(exist_ok=True) storage_target.joinpath(LOCAL_PLAYER_STORAGE).mkdir(exist_ok=True) storage_target.joinpath(LOCAL_GAME_STORAGE).mkdir(exist_ok=True) return storage_target
def test_all(absolute_path=None): """Run on multiple Python versions with tox.""" from pathlib import Path # This happens to be where I have Python 3.5 installed; may well be different for others. Edit as necessary. py35_path = Path(Path.home(), '.pyenv/versions/3.5.2/bin') if absolute_path is None else Path(absolute_path) with path(str(py35_path.absolute())): local('tox')
def getHomeDir(): try: from pathlib import Path return str(Path.home()) except: from os.path import expanduser return expanduser("~user")
def home(relative_path=None): if relative_path is None: return Path.home() else: if relative_path.startswith(os.sep): log.exit( "Requested abspath '%s' in relative context" % relative_path) return build('~' + os.sep + relative_path).expanduser()
def get_files_dir(): """Get directory for config and remote files.""" try: home = Path.home() except AttributeError: # Fix for older Python version were Path has no 'home' attribute home = os.getenv('HOME', '/tmp/') # Ignore B108 files_dir = os.path.join(home, '.fabric8-analytics-tagger') if not os.path.exists(files_dir): os.makedirs(files_dir) return files_dir
def test_all(absolute_path=None): """Run on multiple Python versions with tox.""" from pathlib import Path py35_path = Path(Path.home(), '.pyenv/versions/3.5.2/bin') if absolute_path is None else Path(absolute_path) with path(str(py35_path.absolute())): local('tox')
def __init__(self, *args): super().__init__(*args) self.log = self.setup_logging() # Experimental: Add a logger that sets the label_error text error_handler = ConsoleHandler(self.write_error) error_handler.setFormatter(logging.Formatter('%(levelname)s: %(message)s')) error_handler.setLevel(logging.DEBUG) self.log.addHandler(error_handler) self.setupUi(self) self.settings_dir = Path.home().joinpath('AppData\Local\DynamicGravitySystems\DGP') self.recent_file = self.settings_dir.joinpath('recent.json') if not self.settings_dir.exists(): self.log.info("Settings Directory doesn't exist, creating.") self.settings_dir.mkdir(parents=True) # self.dialog_buttons.accepted.connect(self.accept) self.btn_newproject.clicked.connect(self.new_project) self.btn_browse.clicked.connect(self.browse_project) self.list_projects.currentItemChanged.connect(self.set_selection) self.project_path = None # type: Path self.set_recent_list() self.show()
def get_config_file(): home = str(Path.home()) return os.path.join(home, CONFIG_PATH, CONFIG_FILE)
def load_configuration(section='Server'): """ The GNS3 Server (/Controller) is configured through the gns3_server.conf file. GNS3 searches various locations depending on the platform. These locations are listed in the documentation. DOCUMENTATION / GNS3 SERVER CONFIGURATION FILE http://docs.gns3.com/1f6uXq05vukccKdMCHhdki5MXFhV8vcwuGwiRvXMQvM0/ """ platform_file_locations = { # TODO add Linux/Windows file locations and test. 'Darwin': [ f'{str(Path.home())}/.config/GNS3/gns3_server.conf', './gns3_server.conf', ] } system_platform = platform.system() if system_platform not in platform_file_locations.keys(): # TODO manual input option? Perhaps additional argument in staticmethod? raise OSError('Operating system {} not supported') # TODO verify behaviour ConfigParser vs GNS3 (i.e. does it merge or is there precedence?) parser = ConfigParser() found = parser.read(platform_file_locations[system_platform]) if found and section in parser.sections(): for k, v in dict(parser.items(section)).items(): setattr(GNS3API, k, v) GNS3API.cred = HTTPBasicAuth(GNS3API.user, GNS3API.password) GNS3API.base = f'{GNS3API.protocol}://{GNS3API.host}:{str(GNS3API.port)}/v2' else: print(f'Platform: {system_platform}\n' 'Looked for configuration files at these locations:\n') for candidate in platform_file_locations[system_platform]: print(f' {candidate}') print('\n') raise FileNotFoundError('No Valid Configuration File Found')
def find_config(): '''Find the i3 config file in either ${HOME}/.i3/config or ${HOME}/.config/i3 Exit if not found. ''' if args.verbose: print('Searching for i3 config file....') print('Looking in .i3 ...') homedir = str(Path.home()) doti3 = homedir + '/.i3/config' dotconfig = homedir + '/.config/i3/config' config = Path(doti3) if (config.is_file()): if args.verbose: print('Found .i3/config!') return config else: if args.verbose: print('File not found. Trying another directory.') config = Path(dotconfig) if (config.is_file()): if args.verbose: print('Found .config/i3/config!') return config else: print('No config files found.') print('Please make sure the file is in ~/.i3 or ~/.config') sys.exit(1)
def test_cache_use_input(): """Use existing dir when specified?""" INPUT = Path.home() EXPECT = INPUT assert util.default_cache_dir(INPUT) == EXPECT
def test_data_use_input(): """Use existing dir when specified?""" INPUT = Path.home() EXPECT = INPUT assert util.default_data_dir(INPUT) == EXPECT
def cell_renderer(quadkey, solution): retVal = "" retVal = "Quadkey: <a href=\"{}\" target=\"_blank\">{}</a><br>".format(quadkey_to_url(quadkey), quadkey) if solution is not None: retVal += "Officially: {}<br>".format(solution.ground_truth[quadkey]) retVal += "Predicted class: " + solution.predicted_class(quadkey) + "<br>" retVal += "<img align=\"center\" src=\"mapswipe_working_dir/{}\"/>".format(os.path.relpath(mapswipe.get_tile_path(quadkey), os.path.join(str(Path.home()),'.mapswipe'))) if solution is not None: retVal += "PV:" + str(solution.prediction_vectors[quadkey]) return retVal
def get_images_path(): img_dir = cf.get('images_path') if cf.get('images_path') else os.path.join(str(Path.home()), 'weibospider', 'images') if not os.path.exists(img_dir): os.makedirs(img_dir) return img_dir
def save(data, file_name, folder='', home_path=Path.home()): fp = Path(home_path, folder) while True: if fp.exists(): break else: user_input = input("This folder doesn't exist. Do you want create it? [yes]/no: ") if _user_decision(user_input): fp.mkdir() break else: folder = input('Write new name: ') fp = Path(home_path, folder) fp = Path(home_path, folder, file_name + _EXTENSION) while True: if fp.exists(): if fp.is_dir(): print("It's a folder, not a file") _user_decision('yes') else: user_input = input('This file already exists. Do you want rename it? [yes]/no: ') if _user_decision(user_input): name = input('Write new file name: ') fp = Path(home_path, folder, name) else: break else: break print('File saved in: ', fp) # Save fp = fp.open('w') json.dump(data, fp, indent=4, ensure_ascii=False, sort_keys=True) fp.close() print('Save successfully!')
def set_desktop_launcher(app: str, desktop_file_content: str, autostart: bool=False) -> namedtuple: """Add to autostart or launcher icon on the Desktop.""" if not sys.platform.startswith("linux"): return # .desktop files are Linux only AFAIK. if not isinstance(app, str) or not isinstance(desktop_file_content, str): raise TypeError("app or desktop_file_content are not String Types.") app, desktop_file_txt = app.strip().lower(), desktop_file_content.strip() if not len(app) or not len(desktop_file_txt): raise ValueError("app or desktop_file_content can not be Empty value.") # Auto-Start file below. config_dir = Path.home() / ".config" / "autostart" config_dir.mkdir(parents=True, exist_ok=True) fyle = config_dir / (app + ".desktop") if config_dir.is_dir() and not fyle.is_file(): if bool(autostart): log.info(f"Writing 1 Auto-Start desktop file: {fyle} ({fyle!r}).") fyle.write_text(desktop_file_txt, encoding="utf-8") fyle.chmod(0o776) if fyle.is_file() else log.debug("chmod: NO.") # Desktop Launcher file below. apps_dir = Path.home() / ".local" / "share" / "applications" # paths XDG. apps_dir.mkdir(parents=True, exist_ok=True) desktop_file = apps_dir / (app + ".desktop") if apps_dir.is_dir() and not desktop_file.is_file(): log.info(f"Writing 1 Launcher file: {desktop_file} ({desktop_file!r})") desktop_file.write_text(desktop_file_txt, encoding="utf-8") fyle.chmod(0o776) if fyle.is_file() else log.debug("chmod: NO.") return namedtuple("DesktopFiles", "launcher autostart")(desktop_file, fyle)