How to use the pathlib2.Path.home function in pathlib2

To help you get started, we’ve selected a few pathlib2 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github awdeorio / mailmerge / tests / test_template_message.py View on Github external
"""Attachment with home directory tilde notation file path."""
    template_path = Path(tmpdir/"template.txt")
    template_path.write_text(textwrap.dedent(u"""\
        TO: to@test.com
        FROM: from@test.com
        ATTACHMENT: ~/attachment.txt

        Hello world
    """))

    # Render will throw an error because we didn't create a file in the
    # user's home directory.  We'll just check the filename.
    template_message = TemplateMessage(template_path)
    with pytest.raises(MailmergeError) as err:
        template_message.render({})
    correct_path = Path.home() / "attachment.txt"
    assert str(correct_path) in str(err)
github tribe29 / checkmk / omd / license_sources / update_licenses.py View on Github external
def main(args):
    try:
        path_omd = Path("%s/git/check_mk/omd/" % Path.home())
        path_cmk_dir = Path(args.cmk_path + ("/" if args.cmk_path[-1] != "/" else ""))
        fn_csv = str(path_omd / "Licenses.csv")
    except:
        raise OSError

    print "Inspecting CheckMK repository \"%s\"" % path_cmk_dir

    # Find all package paths within the given CheckMK sources repository
    found_paths = find(["*" + ze for ze in ZIP_ENDINGS], path_cmk_dir)
    if not found_paths:
        print "\nFor the given CheckMK repository \"%s\" no package paths were found." \
            % path_cmk_dir
        sys.exit()
    n_found = str(len(found_paths))

    # Exceptional package paths that cannot be matched via package name
github tribe29 / checkmk / omd / license_sources / build_license_texts_pdf.py View on Github external
def main():
    try:
        path_omd = Path("%s/git/check_mk/omd/" % Path.home())
        path_license_texts = path_omd / "license_sources/license_texts/"
        path_pdf = path_omd / "License_texts.pdf"
        path_cover = path_omd / "license_sources/licenses_cover.pdf"
    except:
        raise OSError

    registerFont(TTFont('Calibri', 'Calibri.ttf'))
    doc = SimpleDocTemplate(str(path_pdf),
                            pagesize=letter,
                            bottomMargin=.4 * inch,
                            topMargin=.6 * inch,
                            rightMargin=.8 * inch,
                            leftMargin=.8 * inch)
    toc = TableOfContents()
    toc.levelStyles = [
        PS(fontName='Calibri',
github MultiChain / multichain / depends / v8_data_lib.py View on Github external
def get_options():
    mc_path_default = str(Path.home() / "multichain")
    parser = ArgumentParser(description="Build v8_data.lib from .bin and .dat files")
    parser.add_argument("-v", "--verbose", action="store_true", help="print debug messages to log")
    parser.add_argument("-m", "--multichain", metavar="DIR", default=mc_path_default,
                        help="MultiChain path prefix (default: %(default)s)")
    parser.add_argument("-o", "--platform", default=sys.platform,
                        help="override platform definition (default: %(default)s)")

    options = parser.parse_args()

    if options.verbose:
        logger.setLevel(logging.DEBUG)

    if not Path(options.multichain).exists():
        parser.error("{!r}: MultiChain path does not exist".format(options.multichain))

    logger.info("{} - {}".format(logger.name, parser.description))
github allegroai / trains / trains / utilities / resource_monitor.py View on Github external
:return: machine stats dictionary, all values expressed in megabytes
        """
        cpu_usage = [float(v) for v in psutil.cpu_percent(percpu=True)]
        stats = {
            "cpu_usage": sum(cpu_usage) / float(len(cpu_usage)),
        }

        bytes_per_megabyte = 1024 ** 2

        def bytes_to_megabytes(x):
            return x / bytes_per_megabyte

        virtual_memory = psutil.virtual_memory()
        stats["memory_used_gb"] = bytes_to_megabytes(virtual_memory.used) / 1024
        stats["memory_free_gb"] = bytes_to_megabytes(virtual_memory.available) / 1024
        disk_use_percentage = psutil.disk_usage(Text(Path.home())).percent
        stats["disk_free_percent"] = 100.0-disk_use_percentage
        with warnings.catch_warnings():
            if logging.root.level > logging.DEBUG:  # If the logging level is bigger than debug, ignore
                # psutil.sensors_temperatures warnings
                warnings.simplefilter("ignore", category=RuntimeWarning)
            sensor_stat = (psutil.sensors_temperatures() if hasattr(psutil, "sensors_temperatures") else {})
        if "coretemp" in sensor_stat and len(sensor_stat["coretemp"]):
            stats["cpu_temperature"] = max([float(t.current) for t in sensor_stat["coretemp"]])

        # update cached measurements
        net_stats = psutil.net_io_counters()
        stats["network_tx_mbs"] = bytes_to_megabytes(net_stats.bytes_sent)
        stats["network_rx_mbs"] = bytes_to_megabytes(net_stats.bytes_recv)
        io_stats = psutil.disk_io_counters()
        stats["io_read_mbs"] = bytes_to_megabytes(io_stats.read_bytes)
        stats["io_write_mbs"] = bytes_to_megabytes(io_stats.write_bytes)
github allegroai / trains-agent / trains_agent / helper / base.py View on Github external
def reverse_home_folder_expansion(path):
    path = str(path)
    if is_windows_platform():
        return path
    return re.sub('^{}/'.format(re.escape(str(Path.home()))), '~/', path)