Python pathlib.Path.home() Examples
The following are 30
code examples of pathlib.Path.home().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
pathlib.Path
, or try the search function
.
Example #1
Source File: mdbt.py From ConvLab with MIT License | 6 votes |
def cached_path(file_path, cached_dir=None): if not cached_dir: cached_dir = str(Path(Path.home() / '.tatk') / "cache") return allennlp_cached_path(file_path, cached_dir) # DATA_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))), 'data/mdbt') # VALIDATION_URL = os.path.join(DATA_PATH, "data/validate.json") # WORD_VECTORS_URL = os.path.join(DATA_PATH, "word-vectors/paragram_300_sl999.txt") # TRAINING_URL = os.path.join(DATA_PATH, "data/train.json") # ONTOLOGY_URL = os.path.join(DATA_PATH, "data/ontology.json") # TESTING_URL = os.path.join(DATA_PATH, "data/test.json") # MODEL_URL = os.path.join(DATA_PATH, "models/model-1") # GRAPH_URL = os.path.join(DATA_PATH, "graphs/graph-1") # RESULTS_URL = os.path.join(DATA_PATH, "results/log-1.txt") # KB_URL = os.path.join(DATA_PATH, "data/") # TODO: yaoqin # TRAIN_MODEL_URL = os.path.join(DATA_PATH, "train_models/model-1") # TRAIN_GRAPH_URL = os.path.join(DATA_PATH, "train_graph/graph-1")
Example #2
Source File: hg_helpers.py From funfuzz with Mozilla Public License 2.0 | 6 votes |
def ensure_mq_enabled(): """Ensure that mq is enabled in the ~/.hgrc file. Raises: NoOptionError: Raises if an mq entry is not found in [extensions] """ user_hgrc = Path.home() / ".hgrc" assert user_hgrc.is_file() user_hgrc_cfg = configparser.ConfigParser() user_hgrc_cfg.read(str(user_hgrc)) try: user_hgrc_cfg.get("extensions", "mq") except configparser.NoOptionError: print('Please first enable mq in ~/.hgrc by having "mq =" in [extensions].') raise
Example #3
Source File: install.py From dephell with MIT License | 6 votes |
def bin_dir(self) -> Path: """Global directory from PATH to simlink dephell's binary """ path = Path.home() / '.local' / 'bin' if path.exists(): return path paths = [Path(path) for path in environ.get('PATH', '').split(pathsep)] for path in paths: if path.exists() and '.local' in path.parts: return path for path in paths: if path.exists(): return path raise LookupError('cannot find place to install binary', paths) # actions
Example #4
Source File: app_dirs.py From dephell with MIT License | 6 votes |
def get_data_dir(app: str = 'dephell') -> Path: # unix if 'XDG_DATA_HOME' in os.environ: path = Path(os.environ['XDG_DATA_HOME']) if path.exists(): return path / app # unix default path = Path.home() / '.local' / 'share' if path.exists(): return path / app # mac os x path = Path.home() / 'Library' / 'Application Support' if path.exists(): return path / app return Path(appdirs.user_data_dir(app))
Example #5
Source File: leanproject.py From mathlib-tools with Apache License 2.0 | 6 votes |
def check() -> None: """Check mathlib oleans are more recent than their sources""" project = proj() core_ok, mathlib_ok = project.check_timestamps() toolchain = project.toolchain toolchain_path = Path.home()/'.elan'/'toolchains'/toolchain if not core_ok: print('Some core oleans files in toolchain {} seem older than ' 'their source.'.format(toolchain)) touch = input('Do you want to set their modification time to now (y/n) ? ') if touch.lower() in ['y', 'yes']: touch_oleans(toolchain_path) if not mathlib_ok: print('Some mathlib oleans files seem older than their source.') touch = input('Do you want to set their modification time to now (y/n) ? ') if touch.lower() in ['y', 'yes']: touch_oleans(project.mathlib_folder/'src') if core_ok and mathlib_ok: log.info('Everything looks fine.')
Example #6
Source File: base.py From briefcase with BSD 3-Clause "New" or "Revised" License | 6 votes |
def __init__(self, base_path, home_path=Path.home(), apps=None, input_enabled=True): self.base_path = base_path self.home_path = home_path self.dot_briefcase_path = home_path / ".briefcase" self.global_config = None self.apps = {} if apps is None else apps # Some details about the host machine self.host_arch = platform.machine() self.host_os = platform.system() # External service APIs. # These are abstracted to enable testing without patching. self.cookiecutter = cookiecutter self.requests = requests self.input = Console(enabled=input_enabled) self.os = os self.sys = sys self.shutil = shutil self.subprocess = Subprocess(self) # The internal Briefcase integrations API. self.integrations = integrations
Example #7
Source File: app_dirs.py From dephell with MIT License | 6 votes |
def get_cache_dir(app: str = 'dephell') -> Path: # unix if 'XDG_CACHE_HOME' in os.environ: path = Path(os.environ['XDG_CACHE_HOME']) if path.exists(): return path / app # unix default path = Path.home() / '.cache' if path.exists(): return path / app # mac os x path = Path.home() / 'Library' / 'Caches' if path.exists(): return path / app return get_data_dir(app=app) / 'cache'
Example #8
Source File: autobisectjs.py From funfuzz with Mozilla Public License 2.0 | 6 votes |
def main(): """Prevent running two instances of autobisectjs concurrently - we don't want to confuse hg.""" options = parseOpts() repo_dir = None if options.build_options: repo_dir = options.build_options.repo_dir with LockDir(sm_compile_helpers.get_lock_dir_path(Path.home(), options.nameOfTreeherderBranch, tbox_id="Tbox") if options.useTreeherderBinaries else sm_compile_helpers.get_lock_dir_path(Path.home(), repo_dir)): if options.useTreeherderBinaries: print("TBD: We need to switch to the autobisect repository.", flush=True) sys.exit(0) else: # Bisect using local builds findBlamedCset(options, repo_dir, compile_shell.makeTestRev(options)) # Last thing we do while we have a lock. # Note that this only clears old *local* cached directories, not remote ones. rm_old_local_cached_dirs(sm_compile_helpers.ensure_cache_dir(Path.home()))
Example #9
Source File: s3recon.py From s3recon with MIT License | 6 votes |
def read_config(): config = {} config_hierarchy = [ Path(Path(__file__).parent, "s3recon.yml"), # default Path(Path.home(), "s3recon.yaml"), Path(Path.home(), "s3recon.yml"), Path(Path.cwd(), "s3recon.yaml"), Path(Path.cwd(), "s3recon.yml"), Path(environ.get("S3RECON_CONFIG") or ""), ] for c in config_hierarchy: try: c = load(open(c, "r")) or {} merge(config, c) except (IOError, TypeError): pass return config
Example #10
Source File: gen.py From insightocr with MIT License | 6 votes |
def addNoiseAndGray(surf): # https://stackoverflow.com/questions/34673424/how-to-get-numpy-array-of-rgb-colors-from-pygame-surface imgdata = pygame.surfarray.array3d(surf) imgdata = imgdata.swapaxes(0, 1) # print('imgdata shape %s' % imgdata.shape) # shall be IMG_HEIGHT * IMG_WIDTH imgdata2 = noise_generator('s&p', imgdata) img2 = Image.fromarray(np.uint8(imgdata2)) # img2.save('/home/zhichyu/Downloads/2sp.jpg') grayscale2 = ImageOps.grayscale(img2) # grayscale2.save('/home/zhichyu/Downloads/2bw2.jpg') # return grayscale2 array = np.asarray(np.uint8(grayscale2)) # print('array.shape %s' % array.shape) selem = disk(random.randint(0, 1)) eroded = erosion(array, selem) return eroded
Example #11
Source File: args.py From botbuilder-python with MIT License | 6 votes |
def for_flight_booking( cls, training_data_dir: str = os.path.abspath( os.path.join(os.path.dirname(os.path.abspath(__file__)), "../training_data") ), task_name: str = "flight_booking", ): """Return the flight booking args.""" args = cls() args.training_data_dir = training_data_dir args.task_name = task_name home_dir = str(Path.home()) args.model_dir = os.path.abspath(os.path.join(home_dir, "models/bert")) args.bert_model = "bert-base-uncased" args.do_lower_case = True print( f"Bert Model training_data_dir is set to {args.training_data_dir}", file=sys.stderr, ) print(f"Bert Model model_dir is set to {args.model_dir}", file=sys.stderr) return args
Example #12
Source File: assertions.py From pipelinewise with Apache License 2.0 | 6 votes |
def assert_state_file_valid(target_name, tap_name, log_path=None): """Assert helper function to check if state file exists for a certain tap for a certain target""" state_file = Path(f'{Path.home()}/.pipelinewise/{target_name}/{tap_name}/state.json').resolve() assert os.path.isfile(state_file) # Check if state file content equals to last emitted state in log if log_path: success_log_path = f'{log_path}.success' state_in_log = None with open(success_log_path, 'r') as log_f: state_log_pattern = re.search(r'\nINFO STATE emitted from target: (.+\n)', '\n'.join(log_f.readlines())) if state_log_pattern: state_in_log = state_log_pattern.groups()[-1] # If the emitted state message exists in the log then compare it to the actual state file if state_in_log: with open(state_file, 'r') as state_f: assert state_in_log == ''.join(state_f.readlines())
Example #13
Source File: console.py From libmelee with GNU Lesser General Public License v3.0 | 6 votes |
def _get_dolphin_home_path(self): """Return the path to dolphin's home directory""" if self.dolphin_executable_path: return self.dolphin_executable_path + "/User/" home_path = str(Path.home()) legacy_config_path = home_path + "/.dolphin-emu/" #Are we using a legacy Linux home path directory? if os.path.isdir(legacy_config_path): return legacy_config_path #Are we on OSX? osx_path = home_path + "/Library/Application Support/Dolphin/" if os.path.isdir(osx_path): return osx_path #Are we on a new Linux distro? linux_path = home_path + "/.local/share/dolphin-emu/" if os.path.isdir(linux_path): return linux_path print("ERROR: Are you sure Dolphin is installed? Make sure it is, and then run again.") return ""
Example #14
Source File: mpv.py From trakt-scrobbler with GNU General Public License v2.0 | 6 votes |
def read_player_cfg(cls, auto_keys=None): if sys.platform == "darwin": conf_path = Path.home() / ".config" / "mpv" / "mpv.conf" else: conf_path = ( Path(appdirs.user_config_dir("mpv", roaming=True, appauthor=False)) / "mpv.conf" ) mpv_conf = ConfigParser( allow_no_value=True, strict=False, inline_comment_prefixes="#" ) mpv_conf.optionxform = lambda option: option mpv_conf.read_string("[root]\n" + conf_path.read_text()) return { "ipc_path": lambda: mpv_conf.get("root", "input-ipc-server") }
Example #15
Source File: riposte.py From riposte with MIT License | 6 votes |
def __init__( self, prompt: str = "riposte:~ $ ", banner: Optional[str] = None, history_file: Path = Path.home() / ".riposte", history_length: int = 100, ): self.banner = banner self.print_banner = True self.parser = None self.arguments = None self.input_stream = input_streams.prompt_input(lambda: self.prompt) self._prompt = prompt self._commands: Dict[str, Command] = {} self.setup_cli() self._printer_thread = PrinterThread() self._setup_history(history_file, history_length) self._setup_completer()
Example #16
Source File: multi_stage_training.py From zoo with Apache License 2.0 | 6 votes |
def parent_output_dir(self) -> str: """Top level experiment directory shared by all sub-experiments. This directory will have the following structure: ``` parent_output_dir/models/ # dir shared among all experiments in the sequence to store trained models parent_output_dir/stage_0/ # dir with artifacts (checkpoints, logs, tensorboards, ...) of stage 0 ... parent_output_dir/stage_n/ # dir with artifacts (checkpoints, logs, tensorboards, ...) of stage n ``` """ return str( Path.home() / "zookeeper-logs" / "knowledge_distillation" / self.__class__.__name__ / datetime.now().strftime("%Y%m%d_%H%M") )
Example #17
Source File: multi_stage_training.py From zoo with Apache License 2.0 | 6 votes |
def output_dir(self) -> Path: """Main experiment output directory. In this directory, the training checkpoints, logs, and tensorboard files will be stored for this (sub-)experiment. """ # When running as part of an `MultiStageExperiment` the outputs of this `stage` of the experiment will be # stored in a sub directory of the `MultiStageExperiment` which is named after the current stage index. if hasattr(self, "parent_output_dir"): return Path(self.parent_output_dir) / f"stage_{self.stage}" return ( Path.home() / "zookeeper-logs" / self.dataset.__class__.__name__ / self.__class__.__name__ / datetime.now().strftime("%Y%m%d_%H%M") )
Example #18
Source File: model.py From at16k with MIT License | 5 votes |
def _get_model_dir(name): if 'AT16K_RESOURCES_DIR' in os.environ: base_dir = os.environ['AT16K_RESOURCES_DIR'] else: sys_home_dir = str(Path.home()) base_dir = os.path.join(sys_home_dir, '.at16k') model_dir = os.path.join(base_dir, name) assert os.path.exists(model_dir), ('%s model does not exist at %s' % (name, model_dir)) return model_dir
Example #19
Source File: conf.py From weibospider with MIT License | 5 votes |
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
Example #20
Source File: __init__.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def get_home(): """ Return the user's home directory. If the user's home directory cannot be found, return None. """ try: return str(Path.home()) except Exception: return None
Example #21
Source File: alphavantage.py From AlphaVantageAPI with MIT License | 5 votes |
def export_path(self, value:str) -> None: # If using <Path home> /User, then set absolute path to the __export_path variable # Then set __export_path = value if value is not None and isinstance(value, str): path = Path(value) if is_home(path): # ~/ab/cd -> /ab/cd user_subdir = '/'.join(path.parts[1:]) self.__export_path = Path.home().joinpath(user_subdir) else: self.__export_path = path # Initialize the export_path self._init_export_path()
Example #22
Source File: test_sm_compile_helpers.py From funfuzz with Mozilla Public License 2.0 | 5 votes |
def test_ensure_cache_dir(): """Test the shell-cache dir is created properly if it does not exist, and things work even though it does.""" assert util.sm_compile_helpers.ensure_cache_dir(None).is_dir() assert util.sm_compile_helpers.ensure_cache_dir(Path.home()).is_dir() # pylint: disable=no-member
Example #23
Source File: create_collector.py From funfuzz with Mozilla Public License 2.0 | 5 votes |
def make_collector(): """Creates a jsfunfuzz collector specifying ~/sigcache as the signature cache dir Returns: Collector: jsfunfuzz collector object """ sigcache_path = Path.home() / "sigcache" sigcache_path.mkdir(exist_ok=True) return Collector(sigCacheDir=str(sigcache_path), tool="jsfunfuzz")
Example #24
Source File: sm_compile_helpers.py From funfuzz with Mozilla Public License 2.0 | 5 votes |
def ensure_cache_dir(base_dir): """Retrieve a cache directory for compiled shells to live in, and create one if needed. Args: base_dir (Path): Base directory to create the cache directory in Returns: Path: Returns the full shell-cache path """ if not base_dir: base_dir = Path.home() cache_dir = base_dir / "shell-cache" cache_dir.mkdir(exist_ok=True) return cache_dir
Example #25
Source File: compile_shell.py From funfuzz with Mozilla Public License 2.0 | 5 votes |
def get_shell_cache_js_bin_path(self): """Retrieve the full path to the js binary located in the shell cache. Returns: Path: Full path to the js binary in the shell cache """ return (sm_compile_helpers.ensure_cache_dir(Path.home()) / self.get_shell_name_without_ext() / self.get_shell_name_with_ext())
Example #26
Source File: compile_shell.py From funfuzz with Mozilla Public License 2.0 | 5 votes |
def get_s3_tar_with_ext_full_path(self): """Retrieve the path to the tarball downloaded from S3. Returns: Path: Full path to the tarball in the local shell cache directory """ return sm_compile_helpers.ensure_cache_dir(Path.home()) / self.get_s3_tar_name_with_ext()
Example #27
Source File: compile_shell.py From funfuzz with Mozilla Public License 2.0 | 5 votes |
def run(argv=None): """Build a shell and place it in the autobisectjs cache. Args: argv (object): Additional parameters Returns: int: 0, to denote a successful compile """ usage = "Usage: %prog [options]" parser = OptionParser(usage) parser.disable_interspersed_args() parser.set_defaults( build_opts="", ) # Specify how the shell will be built. parser.add_option("-b", "--build", dest="build_opts", help='Specify build options, e.g. -b "--disable-debug --enable-optimize" ' "(python3 -m funfuzz.js.build_options --help)") parser.add_option("-r", "--rev", dest="revision", help="Specify revision to build") options = parser.parse_args(argv)[0] options.build_opts = build_options.parse_shell_opts(options.build_opts) with LockDir(sm_compile_helpers.get_lock_dir_path(Path.home(), options.build_opts.repo_dir)): if options.revision: shell = CompiledShell(options.build_opts, options.revision) else: local_orig_hg_hash = hg_helpers.get_repo_hash_and_id(options.build_opts.repo_dir)[0] shell = CompiledShell(options.build_opts, local_orig_hg_hash) obtainShell(shell, updateToRev=options.revision) print(shell.get_shell_cache_js_bin_path()) return 0
Example #28
Source File: console.py From libmelee with GNU Lesser General Public License v3.0 | 5 votes |
def _get_dolphin_config_path(self): """ Return the path to dolphin's config directory (which is not necessarily the same as the home path)""" if self.dolphin_executable_path: return self.dolphin_executable_path + "/User/Config/" home_path = str(Path.home()) if platform.system() == "Windows": return home_path + "\\Dolphin Emulator\\Config\\" legacy_config_path = home_path + "/.dolphin-emu/" #Are we using a legacy Linux home path directory? if os.path.isdir(legacy_config_path): return legacy_config_path #Are we on a new Linux distro? linux_path = home_path + "/.config/dolphin-emu/" if os.path.isdir(linux_path): return linux_path #Are we on OSX? osx_path = home_path + "/Library/Application Support/Dolphin/Config/" if os.path.isdir(osx_path): return osx_path print("ERROR: Are you sure Dolphin is installed? Make sure it is, and then run again.") return ""
Example #29
Source File: programs.py From i3-resurrect with GNU General Public License v3.0 | 5 votes |
def restore(workspace_name, saved_programs): """ Restore the running programs from an i3 workspace. """ # Remove already running programs from the list of program to restore. running_programs = get_programs(workspace_name, False) for program in running_programs: if program in saved_programs: saved_programs.remove(program) i3 = i3ipc.Connection() for entry in saved_programs: cmdline = entry['command'] working_directory = entry['working_directory'] # If the working directory does not exist, set working directory to # user's home directory. if not Path(working_directory).exists(): working_directory = Path.home() # If cmdline is array, join it into one string for use with i3's exec # command. if isinstance(cmdline, list): # Quote each argument of the command in case some of # them contain spaces. Also protect quotes contained in the # arguments and those to be added from i3's command parser. cmdline = [ '\\"' + arg.replace('"', '\\\\\\"') + '\\"' for arg in cmdline if arg != "" ] command = ' '.join(cmdline) else: command = cmdline # Execute command via i3 exec. i3.command(f'exec "cd \\"{working_directory}\\" && {command}"')
Example #30
Source File: train.py From zoo with Apache License 2.0 | 5 votes |
def output_dir(self) -> Union[str, os.PathLike]: return ( Path.home() / "zookeeper-logs" / self.dataset.__class__.__name__ / self.__class__.__name__ / datetime.now().strftime("%Y%m%d_%H%M") )