Python toml.dump() Examples

The following are 30 code examples of toml.dump(). 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 toml , or try the search function .
Example #1
Source File: oca_towncrier.py    From maintainer-tools with GNU Affero General Public License v3.0 7 votes vote down vote up
def _prepare_pyproject_toml(addon_dir, org, repo):
    """Inject towncrier options in pyproject.toml"""
    pyproject_path = os.path.join(addon_dir, "pyproject.toml")
    with _preserve_file(pyproject_path):
        pyproject = {}
        if os.path.exists(pyproject_path):
            with open(pyproject_path) as f:
                pyproject = toml.load(f)
        if "tool" not in pyproject:
            pyproject["tool"] = {}
        pyproject["tool"]["towncrier"] = {
            "template": _get_towncrier_template(),
            "underlines": ["~"],
            "title_format": "{version} ({project_date})",
            "issue_format": _make_issue_format(org, repo),
            "directory": "readme/newsfragments",
            "filename": "readme/HISTORY.rst",
        }
        with open(pyproject_path, "w") as f:
            toml.dump(pyproject, f)
        yield 
Example #2
Source File: conftest.py    From briefcase with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def bundle_path(myapp, tmp_path):
    # Return the bundle path for the app; however, as a side effect,
    # ensure that the app, app_packages and support target directories
    # exist, and the briefcase index file has been created.
    bundle_path = tmp_path / 'tester' / '{myapp.app_name}.bundle'.format(myapp=myapp)
    (bundle_path / 'path' / 'to' / 'app').mkdir(parents=True, exist_ok=True)
    (bundle_path / 'path' / 'to' / 'app_packages').mkdir(parents=True, exist_ok=True)
    (bundle_path / 'path' / 'to' / 'support').mkdir(parents=True, exist_ok=True)
    with (bundle_path / 'briefcase.toml').open('w') as f:
        index = {
            'paths': {
                'app_path': 'path/to/app',
                'app_packages_path': 'path/to/app_packages',
                'support_path': 'path/to/support',
            }
        }
        toml.dump(index, f)

    return bundle_path 
Example #3
Source File: proc.py    From PyPPL with Apache License 2.0 6 votes vote down vote up
def _save_settings(self):
        def stringify(conf):
            """Convert Path to str, even if it is buried deeply"""
            if isinstance(conf, Path):
                return str(conf)
            if isinstance(conf, Proc):
                return conf.name
            if isinstance(conf, dict):
                return {str(key): stringify(val) for key, val in conf.items()}
            if isinstance(conf, list):
                return [stringify(val) for val in conf]
            return str(conf)

        with open(self.workdir / 'proc.settings.toml', 'w') as fsettings:
            toml.dump({key: stringify(val)
                       for key, val in self.__attrs_property_raw__.items()
                       if key not in ('id', 'jobs', 'runtime_config')},
                      fsettings) 
Example #4
Source File: shaft_element.py    From ross with MIT License 6 votes vote down vote up
def save(self, file):
        signature = inspect.signature(self.__init__)
        args_list = list(signature.parameters)
        args = {arg: getattr(self, arg) for arg in args_list}

        # add material characteristics so that the shaft element can be reconstructed
        # even if the material is not in the available_materials file.
        args["material"] = {
            "name": self.material.name,
            "rho": self.material.rho,
            "E": self.material.E,
            "G_s": self.material.G_s,
            "color": self.material.color,
        }

        try:
            data = toml.load(file)
        except FileNotFoundError:
            data = {}

        data[f"{self.__class__.__name__}_{self.tag}"] = args
        with open(file, "w") as f:
            toml.dump(data, f) 
Example #5
Source File: shaft_element.py    From ross with MIT License 6 votes vote down vote up
def save(self, file):
        signature = inspect.signature(self.__init__)
        args_list = list(signature.parameters)
        args = {arg: getattr(self, arg) for arg in args_list}

        # add material characteristics so that the shaft element can be reconstructed
        # even if the material is not in the available_materials file.
        args["material"] = {
            "name": self.material.name,
            "rho": self.material.rho,
            "E": self.material.E,
            "G_s": self.material.G_s,
            "color": self.material.color,
        }

        try:
            data = toml.load(file)
        except FileNotFoundError:
            data = {}

        data[f"{self.__class__.__name__}_{self.tag}"] = args
        with open(file, "w") as f:
            toml.dump(data, f) 
Example #6
Source File: rotor_assembly.py    From ross with MIT License 6 votes vote down vote up
def save(self, file):
        """Save the rotor to a .toml file.

        Parameters
        ----------
        file : str or pathlib.Path

        Examples
        --------
        >>> from tempfile import tempdir
        >>> from pathlib import Path
        >>> # create path for temporary file
        >>> file = Path(tempdir) / 'rotor.toml'
        >>> rotor = rotor_example()
        >>> rotor.save(file)
        """
        with open(file, "w") as f:
            toml.dump({"parameters": self.parameters}, f)
        for el in self.elements:
            el.save(file) 
Example #7
Source File: lib.py    From mathlib-tools with Apache License 2.0 6 votes vote down vote up
def write_config(self) -> None:
        """Write leanpkg.toml for this project."""
        # Fix leanpkg lean_version bug if needed (the lean_version property
        # setter is working here, hence the weird line).
        self.lean_version = self.lean_version

        # Note we can't blindly use toml.dump because we need dict as values
        # for dependencies.
        with (self.directory/'leanpkg.toml').open('w') as cfg:
            cfg.write('[package]\n')
            cfg.write(toml.dumps(self.pkg_config))
            cfg.write('\n[dependencies]\n')
            for dep, val in self.deps.items():
                nval = str(val).replace("'git':", 'git =').replace(
                        "'rev':", 'rev =').replace("'", '"')
                cfg.write('{} = {}\n'.format(dep, nval)) 
Example #8
Source File: release.py    From rasa-sdk with Apache License 2.0 6 votes vote down vote up
def write_version_to_pyproject(version: Version) -> None:
    """Dump a new version into the pyproject.toml."""

    import toml

    pyproject_file = pyproject_file_path()

    try:
        data = toml.load(pyproject_file)
        data["tool"]["poetry"]["version"] = str(version)
        with pyproject_file.open("w") as f:
            toml.dump(data, f)
    except (FileNotFoundError, TypeError):
        print(f"Unable to update {pyproject_file}: file not found.")
        sys.exit(1)
    except toml.TomlDecodeError:
        print(f"Unable to parse {pyproject_file}: incorrect TOML file.")
        sys.exit(1)

    check_call(["git", "add", str(pyproject_file.absolute())]) 
Example #9
Source File: release.py    From rasa-for-botfront with Apache License 2.0 6 votes vote down vote up
def write_version_to_pyproject(version: Version) -> None:
    """Dump a new version into the pyproject.toml."""
    pyproject_file = pyproject_file_path()

    try:
        data = toml.load(pyproject_file)
        data["tool"]["poetry"]["version"] = str(version)
        with pyproject_file.open("w", encoding="utf8") as f:
            toml.dump(data, f)
    except (FileNotFoundError, TypeError):
        print(f"Unable to update {pyproject_file}: file not found.")
        sys.exit(1)
    except toml.TomlDecodeError:
        print(f"Unable to parse {pyproject_file}: incorrect TOML file.")
        sys.exit(1)

    check_call(["git", "add", str(pyproject_file.absolute())]) 
Example #10
Source File: test_properties.py    From briefcase with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_document_type_single_icon(create_command, myapp):
    "If a doctype icon target is specified as a single string, the document_type_icons list has one unsized entry"
    bundle_path = create_command.bundle_path(myapp)
    bundle_path.mkdir(parents=True)
    with (bundle_path / 'briefcase.toml').open('w') as f:
        index = {
            'paths': {
                'app_path': 'path/to/app',
                'document_type_icon': {
                    'mydoc': 'path/to/mydoc-icon.png',
                    'other': 'path/to/otherdoc-icon.png',
                }
            }
        }
        toml.dump(index, f)

    assert create_command.document_type_icon_targets(myapp) == {
        'mydoc': {
            None: 'path/to/mydoc-icon.png',
        },
        'other': {
            None: 'path/to/otherdoc-icon.png',
        },
    } 
Example #11
Source File: test_properties.py    From briefcase with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_single_splash(create_command, myapp):
    "If the splash target is specified as a single string, the splash list has one unsized entry"
    bundle_path = create_command.bundle_path(myapp)
    bundle_path.mkdir(parents=True)
    with (bundle_path / 'briefcase.toml').open('w') as f:
        index = {
            'paths': {
                'app_path': 'path/to/app',
                'splash': 'path/to/splash.png',
            }
        }
        toml.dump(index, f)

    assert create_command.splash_image_targets(myapp) == {
        None: 'path/to/splash.png'
    } 
Example #12
Source File: test_properties.py    From briefcase with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_multiple_splash(create_command, myapp):
    "If there are multiple splash targets, they're all in the target list"
    bundle_path = create_command.bundle_path(myapp)
    bundle_path.mkdir(parents=True)
    with (bundle_path / 'briefcase.toml').open('w') as f:
        index = {
            'paths': {
                'app_path': 'path/to/app',
                'splash': {
                    '10x20': 'path/to/splash-10.png',
                    '20x30': 'path/to/splash-20.png',
                },
            }
        }
        toml.dump(index, f)

    assert create_command.splash_image_targets(myapp) == {
        '10x20': 'path/to/splash-10.png',
        '20x30': 'path/to/splash-20.png',
    } 
Example #13
Source File: test_properties.py    From briefcase with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_app_path(create_command, myapp):
    bundle_path = create_command.bundle_path(myapp)
    bundle_path.mkdir(parents=True)
    with (bundle_path / 'briefcase.toml').open('w') as f:
        index = {
            'paths': {
                'app_path': 'path/to/app',
                'app_packages_path': 'path/to/app_packages',
                'support_path': 'path/to/support',
            }
        }
        toml.dump(index, f)

    assert create_command.app_path(myapp) == bundle_path / 'path' / 'to' / 'app'

    # Requesting a second time should hit the cache,
    # so the briefcase file won't be needed.
    # Delete it to make sure the cache is used.
    (bundle_path / 'briefcase.toml').unlink()
    assert create_command.app_path(myapp) == bundle_path / 'path' / 'to' / 'app' 
Example #14
Source File: test_properties.py    From briefcase with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_app_packages_path(create_command, myapp):
    bundle_path = create_command.bundle_path(myapp)
    bundle_path.mkdir(parents=True)
    with (bundle_path / 'briefcase.toml').open('w') as f:
        index = {
            'paths': {
                'app_path': 'path/to/app',
                'app_packages_path': 'path/to/app_packages',
                'support_path': 'path/to/support',
            }
        }
        toml.dump(index, f)

    assert create_command.app_packages_path(myapp) == bundle_path / 'path' / 'to' / 'app_packages'

    # Requesting a second time should hit the cache,
    # so the briefcase file won't be needed.
    # Delete it to make sure the cache is used.
    (bundle_path / 'briefcase.toml').unlink()
    assert create_command.app_packages_path(myapp) == bundle_path / 'path' / 'to' / 'app_packages' 
Example #15
Source File: test_properties.py    From briefcase with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_support_path(create_command, myapp):
    bundle_path = create_command.bundle_path(myapp)
    bundle_path.mkdir(parents=True)
    with (bundle_path / 'briefcase.toml').open('w') as f:
        index = {
            'paths': {
                'app_path': 'path/to/app',
                'app_packages_path': 'path/to/app_packages',
                'support_path': 'path/to/support',
            }
        }
        toml.dump(index, f)

    assert create_command.support_path(myapp) == bundle_path / 'path' / 'to' / 'support'

    # Requesting a second time should hit the cache,
    # so the briefcase file won't be needed.
    # Delete it to make sure the cache is used.
    (bundle_path / 'briefcase.toml').unlink()
    assert create_command.support_path(myapp) == bundle_path / 'path' / 'to' / 'support' 
Example #16
Source File: test_properties.py    From briefcase with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_multiple_icon(create_command, myapp):
    "If there are multiple icon targets, they're all in the target list"
    bundle_path = create_command.bundle_path(myapp)
    bundle_path.mkdir(parents=True)
    with (bundle_path / 'briefcase.toml').open('w') as f:
        index = {
            'paths': {
                'app_path': 'path/to/app',
                'icon': {
                    '10': 'path/to/icon-10.png',
                    '20': 'path/to/icon-20.png',
                },
            }
        }
        toml.dump(index, f)

    assert create_command.icon_targets(myapp) == {
        '10': 'path/to/icon-10.png',
        '20': 'path/to/icon-20.png',
    } 
Example #17
Source File: materials.py    From ross with MIT License 5 votes vote down vote up
def dump_data(data):
        """Save material properties.

        This is an auxiliary function to save the materials properties in the save
        method.

        Parameters
        ----------
        data : dict
            Dictionary containing all data needed to instantiate the Object.
        """
        with open(AVAILABLE_MATERIALS_PATH, "w") as f:
            toml.dump(data, f) 
Example #18
Source File: okta_aws.py    From okta_aws with Apache License 2.0 5 votes vote down vote up
def interactive_setup(self, config_file):
        """Performs first-time setup for users who haven't set up a config
        file yet, by asking some simple questions.
        """
        try:
            toml_config = toml.load(os.path.expanduser(config_file))
        except FileNotFoundError:
            toml_config = {}
        toml_config.setdefault('general', {})

        default_username = toml_config['general'].get(
            'username', getpass.getuser())
        default_server = toml_config['general'].get(
            'okta_server', 'example.okta.com')

        print("Okta AWS initial setup")
        print("======================")
        print()
        username = input("Enter your okta username [%s]: " % default_username)
        if username == "":
            username = default_username

        okta_server = input("Enter your okta domain [%s]: " % default_server)
        if okta_server == "":
            okta_server = default_server

        print()
        print("Creating/updating %s" % config_file)
        toml_config['general']['username'] = username
        toml_config['general']['okta_server'] = okta_server
        with open(os.path.expanduser(config_file), "w") as fh:
            toml.dump(toml_config, fh)

        print("Setup complete. You can now log in with okta_aws PROFILENAME.")
        print("Hint: you can use 'okta_aws --list' to see which profiles "
              "you can use.") 
Example #19
Source File: element.py    From ross with MIT License 5 votes vote down vote up
def save(self, file):
        """Save the element in a .toml file.

        This function will save the element to a .toml file.
        The file will have all the argument's names and values that are needed to
        reinstantiate the element.

        Parameters
        ----------
        file : str, pathlib.Path
            The name of the file the element will be saved in.

        Examples
        --------
        >>> # Example using DiskElement
        >>> from tempfile import tempdir
        >>> from pathlib import Path
        >>> from ross.disk_element import disk_example
        >>> # create path for a temporary file 
        >>> file = Path(tempdir) / 'disk.toml'
        >>> disk = disk_example()
        >>> disk.save(file)
        """
        # get __init__ arguments
        signature = inspect.signature(self.__init__)
        args_list = list(signature.parameters)
        args = {arg: getattr(self, arg) for arg in args_list}
        try:
            data = toml.load(file)
        except FileNotFoundError:
            data = {}

        data[f"{self.__class__.__name__}_{self.tag}"] = args
        with open(file, "w") as f:
            toml.dump(data, f) 
Example #20
Source File: bearing_seal_element.py    From ross with MIT License 5 votes vote down vote up
def save(self, file):
        try:
            data = toml.load(file)
        except FileNotFoundError:
            data = {}

        args = {
            "n": self.n,
            "kxx": [float(i) for i in self.kxx.coefficient],
            "cxx": [float(i) for i in self.cxx.coefficient],
            "kyy": [float(i) for i in self.kyy.coefficient],
            "kxy": [float(i) for i in self.kxy.coefficient],
            "kyx": [float(i) for i in self.kyx.coefficient],
            "kzz": [float(i) for i in self.kzz.coefficient],
            "cyy": [float(i) for i in self.cyy.coefficient],
            "cxy": [float(i) for i in self.cxy.coefficient],
            "cyx": [float(i) for i in self.cyx.coefficient],
            "czz": [float(i) for i in self.czz.coefficient],
            "tag": self.tag,
            "n_link": self.n_link,
            "scale_factor": self.scale_factor,
        }
        if self.frequency is not None:
            args["frequency"] = [float(i) for i in self.frequency]
        else:
            args["frequency"] = self.frequency

        data[f"{self.__class__.__name__}_{self.tag}"] = args

        with open(file, "w") as f:
            toml.dump(data, f) 
Example #21
Source File: config.py    From robosat with MIT License 5 votes vote down vote up
def save_config(attrs, path):
    """Saves a configuration dictionary to a file.
    Args:
      path: the path to save the configuration dictionary to.
    """

    toml.dump(attrs, path) 
Example #22
Source File: configuration.py    From pennylane with Apache License 2.0 5 votes vote down vote up
def save(self, filepath):
        """Save a configuration file.

        Args:
            filepath (str): path to the configuration file.
        """
        with open(filepath, "w") as f:
            toml.dump(self._config, f) 
Example #23
Source File: app.py    From aioli with MIT License 5 votes vote down vote up
def appconfig(output_path, core=None, extra=None):
    extra = extra and dict(extra) or {}

    data = {
        "aioli-core": ApplicationConfigSchema().load(core or {}),
        **extra
    }

    with open(output_path, mode="w") as fh:
        return toml.dump(data, fh) 
Example #24
Source File: poetry.py    From aioli with MIT License 5 votes vote down vote up
def poetry_config(output_path, data):
    pyproject = PyprojectSchema().load(data or {})
    with open(output_path, mode="w") as fh:
        # Toml dump doesn't support sorting, so let's iterate and write chunks.
        for name, fields in pyproject.items():
            toml.dump({name: fields}, fh)
            fh.write("\n") 
Example #25
Source File: txt2toml.py    From bili2.0 with MIT License 5 votes vote down vote up
def txt2toml(split_str: str):
    assert len(split_str) == 1
    split_elements = f'{split_str}{whitespace} '
    split_pattern = compile(
        f'([^{split_elements}]+)[{split_elements}]+([^{split_elements}]+)')
    
    list_users = []
    with open(path_txt, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            result = split_pattern.fullmatch(line)
            username = result.group(1)
            password = result.group(2)
            
            print(f'原数据:|{line}|')
            print(f'分割 :|{username}|{password}|', end='\n\n')
            
            dict_user = {
                'username': username,
                'password': password,
                'access_key': '',
                'cookie': '',
                'csrf': '',
                'uid': '',
                'refresh_token': ''
            }
            list_users.append(dict_user)
            
    dict_users = {'users': list_users}
  
    with open(path_toml, 'w', encoding='utf-8') as f:
        toml.dump(dict_users, f) 
Example #26
Source File: conf_loader.py    From bili2.0 with MIT License 5 votes vote down vote up
def toml_dump(object, path):
        with open(path, 'w', encoding="utf-8") as f:
            toml.dump(object, f) 
Example #27
Source File: config.py    From piqueserver with GNU General Public License v3.0 5 votes vote down vote up
def dump_to_file(self, fobj, format_=DEFAULT_FORMAT):
        '''
        Writes the current configuration to a file-like objection,
        with the format specified by `format_`.
        '''
        if format_ == TOML_FORMAT:
            toml.dump(self._raw_config, fobj)
        elif format_ == JSON_FORMAT:
            json.dump(self._raw_config, fobj, indent=2)
        else:
            raise ValueError(
                'Unsupported config file format: {}'.format(format_)) 
Example #28
Source File: main.py    From typed-json-dataclass with MIT License 5 votes vote down vote up
def main(package_json_path: 'path to the package.json file', pyproject_toml_path: ('path'
         ' to the pyproject.toml file to sync version string to')):
  package_json = json.load(open(package_json_path, 'r'))
  pyproject_toml = toml.load(open(pyproject_toml_path, 'r'))
  package_json_version = package_json['version']
  pyproject_toml_version = pyproject_toml['tool']['poetry']['version']
  pyproject_toml['tool']['poetry']['version'] = package_json_version
  toml.dump(pyproject_toml, open(pyproject_toml_path, 'w'))

  print(f'{pyproject_toml_version} -> {package_json_version}') 
Example #29
Source File: rust.py    From pre-commit with MIT License 5 votes vote down vote up
def _add_dependencies(
        cargo_toml_path: str,
        additional_dependencies: Set[str],
) -> None:
    with open(cargo_toml_path, 'r+') as f:
        cargo_toml = toml.load(f)
        cargo_toml.setdefault('dependencies', {})
        for dep in additional_dependencies:
            name, _, spec = dep.partition(':')
            cargo_toml['dependencies'][name] = spec or '*'
        f.seek(0)
        toml.dump(cargo_toml, f)
        f.truncate() 
Example #30
Source File: converters.py    From Box with MIT License 5 votes vote down vote up
def _to_toml(obj, filename=None, encoding="utf-8", errors="strict"):
    if filename:
        _exists(filename, create=True)
        with open(filename, 'w', encoding=encoding, errors=errors) as f:
            toml.dump(obj, f)
    else:
        return toml.dumps(obj)