id stringlengths 15 54 | text stringlengths 3 133k | title stringclasses 1
value |
|---|---|---|
ros_yaml/pythonyaml_383.txt | Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!
Keep Learning | |
ros_yaml/pythonyaml_186.txt | >>> user = yaml.unsafe_load("""
... !!python/object:models.User
... name: Wbua Qbr
... """) | |
ros_yaml/pythonyaml_102.txt | First, make a sample Python script to print out JSON on the standard output: | |
ros_yaml/UsingParametersInACl_8.txt | * [ ](../../index.html)
* [ Tutorials ](../../Tutorials.html)
* [ Beginner: Client libraries ](../Beginner-Client-Libraries.html)
* Using parameters in a class (Python)
* [ Edit on GitHub ](https://github.com/ros2/ros2_documentation/blob/foxy/source/Tutorials/Beginner-Client-Libraries/Using-Parameters-In-A-C... | |
ros_yaml/pythonyaml_154.txt | !!python/object
!!python/object/new
!!python/object/apply
They all must be followed by a fully qualified name of the class to instantiate, which includes the package and module names. The first tag expects a mapping of key-value pairs, in either the flow or block style. Here’s an example: | |
ros_yaml/pythonyaml_303.txt | from yaml import (
ScalarEvent,
SequenceStartEvent,
SequenceEndEvent,
MappingStartEvent,
MappingEndEvent,
) | |
ros_yaml/yamlinpython_30.txt | {
'apiVersion': 'v1',
'kind':'persistentVolume',
'metadata': {'name':'mysql-pv', 'labels':{'type':'local'}},
'spec':{'storageClassName':'hostpath'},
'capacity':{'storage':'2Gi'},
'accessModes':['ReadWriteOnce'],
'hostpath':{'path':'/mnt/data'}
}
]
Now call the dump_all() function to ... | |
ros_yaml/rclpyparamstutorialg_87.txt |
$ ros2 param get /test_params_rclpy my_str
String value is: Set from code | |
ros_yaml/pythonyaml_266.txt | Color Font Weight Escape Sequence
Blue Bold ESC[34;1m
Cyan Regular ESC[36m
Red Regular ESC[31m
For example, keys could become blue, values might be cyan, and YAML tags could turn red. Remember that you can’t modify a sequence of elements while iterating over them, because that would shift their indices. What you can do... | |
ros_yaml/pythonyaml_234.txt | %TAG !model! tag:yaml.org,2002:python/object:models.
---
- !model!Person
first_name: John
last_name: Doe | |
ros_yaml/UsingParametersInACl_35.txt | Your terminal will return a message verifying the creation of your package `
python_parameters ` and all its necessary files and folders. | |
ros_yaml/pythonyaml_49.txt | The three fundamental data structures in YAML are essentially the same as in Perl, which was once a popular scripting language. They’re the following: | |
ros_yaml/pythonyaml_305.txt | class HTMLBuilder:
# ... | |
ros_yaml/rclpyparamstutorialg_74.txt | ### Again, if you forget to declare a parameter | |
ros_yaml/pythonyaml_59.txt | Remove ads
Unique Features
In this section, you’ll check out some of YAML’s most unique features, including: | |
ros_yaml/pythonyaml_284.txt | When you parse a document with PyYAML, the library yields a sequence of events: | |
ros_yaml/pythonyaml_61.txt | YAML Python
2022-01-16 23:59:59 datetime.datetime(2022, 1, 16, 23, 59, 59)
2022-01-16 datetime.date(2022, 1, 16)
23:59:59 86399
59:59 3599
YAML understands various date and time formats, including the ISO 8601 standard, and can work with optional time zones. Timestamps such as 23:59:59 get deserialized into the number ... | |
ros_yaml/UsingParametersInACl_25.txt | When making your own [ nodes ](../Beginner-CLI-Tools/Understanding-
ROS2-Nodes/Understanding-ROS2-Nodes.html) you will sometimes need to add
parameters that can be set from the launch file. | |
ros_yaml/pythonyaml_212.txt | Again, remember to import the corresponding dumper class prefixed with the letter C for the best serialization performance, and keep in mind that there might be slight differences between the Python and C implementations: | |
ros_yaml/UsingParametersInACl_45.txt | The ` import ` statements at the top are used to import the package
dependencies. | |
ros_yaml/pythonyaml_184.txt | def __setstate__(self, state):
self.name = codecs.decode(state["name"], "rot13")
You decode the persisted username using a primitive ROT-13 cipher, which rotates characters by thirteen places in the alphabet. For serious encryption, though, you’ll have to look beyond the standard library. Note that you coul... | |
ros_yaml/pythonyaml_274.txt | The final piece of the puzzle is taking YAML from the standard input and presenting it onto the standard output stream: | |
ros_yaml/pythonyaml_379.txt | Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas: | |
ros_yaml/UsingParametersInACl_104.txt | The terminal should return the following message every second: | |
ros_yaml/UsingParametersInACl_9.txt | * * * | |
ros_yaml/pythonyaml_334.txt | >>> from tree import visit
>>> visit(root)
['42', {'pi': '3.14', 'e': '2.72'}]
You get a Python list as a result, but the individual scalar values contained in it are all strings. PyYAML detects the data type associated with a scalar value and stores it in the node’s .tag attribute, but you have to do the typecasting y... | |
ros_yaml/pythonyaml_248.txt | >>> class Person(yaml.YAMLObject):
... yaml_tag = "!Person"
... yaml_loader = yaml.SafeLoader
... def __init__(self, first_name, last_name):
... self.first_name = first_name
... self.last_name = last_name
First, let the class inherit from yaml.YAMLObject. Then specify two class attributes. O... | |
ros_yaml/UsingParametersInACl_63.txt | Itâs good practice to run ` rosdep ` in the root of your workspace ( `
ros2_ws ` ) to check for missing dependencies before building: | |
ros_yaml/pythonyaml_346.txt | # ... | |
ros_yaml/pythonyaml_19.txt | As the first kid on the block, XML dominated the scene for many years. It became a mature and trusted data interchange format and helped shape new concepts like building interactive web applications. After all, the letter X in AJAX, a technique for getting data from the server without reloading the page, stands for non... | |
ros_yaml/rclpyparamstutorialg_61.txt |
$ ros2 run ros2_tutorials test_params_rclpy --ros-args -p my_str:="Hello world" -p my_int:=5 -p my_double_array:="[4.4, 5.5, 6.6]"
[INFO] [test_params_rclpy]: str: Hello world, int: 5, double[]: [4.4, 5.5, 6.6] | |
ros_yaml/pythonyaml_310.txt | Here’s a quick line-by-line rundown of the snippet above: | |
ros_yaml/pythonyaml_240.txt | (venv) $ python -m pip install fastapi uvicorn
(venv) $ uvicorn server:app
To run the server, you must provide the module name followed by a colon and the name of the ASGI-compatible callable in that module. The details of implementing such a server and a client are far beyond the scope of this tutorial, but feel free ... | |
ros_yaml/rclpyparamstutorialg_113.txt | In this tutorial you have learned how to get and set parameters from a Python
node, using rclpy. You saw the importance of declaring parameters. | |
ros_yaml/yamlinpython_80.txt | Products
Earthly
Earthly Cloud
Earthly Satellites
Check Status
Content
Blog
Newsletter
Videos & Webinars
Resources
Docs
Pricing
Customer Stories
Solutions
FAQ
About Earthly
Newsroom
Download
Made with 🩵 on Planet Earth | We're hiring!
Terms of Service | Privacy Policy | Security | |
ros_yaml/yamlinpython_31.txt | script.py
Copyyaml_output2 = yaml.dump_all(data2, sort_keys=False)
print(yaml_output2)
Once you execute this code, you should have the following output. The output below shows that the data2 list has been dumped into a single stream—as multiple blocks of YAML separated by - - -. | |
ros_yaml/pythonyaml_166.txt | Sometimes, these tags bypass the normal object creation path, which is typical of object serialization mechanisms in general. Say you wanted to load a user object from YAML and make it an instance of the following class: | |
ros_yaml/yamlinpython_14.txt | In your working directory, run the command below to install PyYAML via pip3: | |
ros_yaml/pythonyaml_246.txt | >>> class Person:
... def __init__(self, first_name, last_name):
... self.first_name = first_name
... self.last_name = last_name
...
>>> yaml.safe_dump(Person("John", "Doe"))
Traceback (most recent call last):
...
yaml.representer.RepresenterError: ('cannot represent an object',
<__main__.Person... | |
ros_yaml/rclpyparamstutorialg_103.txt | 2 things here: | |
ros_yaml/yamlinpython_47.txt | Output<generator object load_all at 0x7f9e0e0b6880>
If you’d like to learn more about generators in Python and how they work, you can check out the docs on Python generator expressions
Similarly, you can also write the loaded data into another file: | |
ros_yaml/pythonyaml_75.txt | Other powerful features of YAML are anchors and aliases, which let you define an element once and then refer to it many times within the same document. Potential use cases include: | |
ros_yaml/pythonyaml_37.txt | When it comes to document size, JSON is a clear winner again. While the extra quotation marks, commas, and curly brackets take up valuable space, you can remove all the whitespace between the individual elements. You can do the same with XML documents, but it won’t overcome the overhead of the opening and closing tags.... | |
ros_yaml/rclpyparamstutorialg_83.txt | However, if you want to impose a parameter’s value from your code, you can use
the ` set_parameters(List[Parameters]) ` method. If the parameter’s value was
already set before, it will be overridden. | |
ros_yaml/UsingParametersInACl_71.txt | Open a new terminal, navigate to ` ros2_ws ` , and source the setup files: | |
ros_yaml/UsingParametersInACl_109.txt | Now that you have some packages and ROS 2 systems of your own, the [ next
tutorial ](Getting-Started-With-Ros2doctor.html) will show you how to examine
issues in your environment and systems in case you have problems. | |
ros_yaml/pythonyaml_24.txt | Comparison With XML and JSON
If you’re familiar with XML or JSON, then you might be wondering what YAML brings to the table. All three are major data interchange formats, which share some overlapping features. For example, they’re all text based and more or less human readable. At the same time, they differ in many res... | |
ros_yaml/rclpyparamstutorialg_70.txt | When you start your node: | |
ros_yaml/pythonyaml_275.txt | # colorize.py | |
ros_yaml/rclpyparamstutorialg_95.txt | Here’s how to do. | |
ros_yaml/rclpyparamstutorialg_28.txt | Note: you also need to provide either a default value (more on that later), or
the type for each parameter. If you have autocompletion, you can easily find
the available types by writing first “rclpy.Parameter.Type”. | |
ros_yaml/pythonyaml_277.txt | # ... | |
ros_yaml/rclpyparamstutorialg_86.txt | If you start this node, and get each parameter in another window with ` ros2
param get ` , you’ll see the values set in the code. | |
ros_yaml/UsingParametersInACl_115.txt | Releases | |
ros_yaml/rclpyparamstutorialg_112.txt | ## Going further with ROS2 params | |
ros_yaml/UsingParametersInACl_80.txt | This part will use the knowledge you have gained from the [ tutoral about
parameters ](../Beginner-CLI-Tools/Understanding-
ROS2-Parameters/Understanding-ROS2-Parameters.html) and apply it to the node
you have just created. | |
ros_yaml/yamlinpython_41.txt | script.py
Copydef read_one_block_of_yaml_data(filename):
with open(f'{filename}.yaml','r') as f:
output = yaml.safe_load(f)
print(output)
read_one_block_of_yaml_data('output')
Output{'Name': 'John Doe', 'Position': 'DevOps Engineer', \
'Location': 'England', 'Age': '30', 'Experience': \
{'GitHub':... | |
ros_yaml/rclpyparamstutorialg_139.txt | Performance | |
ros_yaml/pythonyaml_219.txt | >>> stream.getvalue()
'name: John\n'
When called with a single argument, the function returns a string representing the serialized object. However, you can optionally pass a second argument to specify the target stream to write to. It can be a file or any file-like object. When you pass this optional argument, the func... | |
ros_yaml/pythonyaml_236.txt | - !<tag:yaml.org,2002:python/object:models.Person>
first_name: John
last_name: Doe
By using a %TAG directive above the YAML document, you declare a custom tag handle called !model!, which gets expanded into the following prefix. The double exclamation point (!!) is a built-in shortcut for the default namespace ... | |
ros_yaml/UsingParametersInACl_64.txt | Linux macOS Windows | |
ros_yaml/pythonyaml_105.txt | person = {
"firstName": "John",
"dateOfBirth": datetime.date(1969, 12, 31),
"married": False,
"spouse": None,
"children": ["Bobby", "Molly"],
} | |
ros_yaml/rclpyparamstutorialg_27.txt |
import rclpy
from rclpy.node import Node
class TestParams(Node):
def __init__(self):
super().__init__('test_params_rclpy')
self.declare_parameter('my_str', rclpy.Parameter.Type.STRING)
self.declare_parameter('my_int', rclpy.Parameter.Type.... | |
ros_yaml/pythonyaml_135.txt | Loading YAML Documents in Python
Loading YAML boils down to reading a piece of text and parsing it according to the data format’s grammar. PyYAML can make this confusing due to the plethora of functions and classes to choose from. Plus, the library’s documentation doesn’t reliably clearly explain their differences and ... | |
ros_yaml/pythonyaml_175.txt | You can fix this by adding a __slots__ declaration to your class, which forbids adding or removing attributes dynamically once the object exists in memory: | |
ros_yaml/rclpyparamstutorialg_137.txt | Functional cookies help to perform certain functionalities like sharing the
content of the website on social media platforms, collect feedbacks, and other
third-party features. | |
ros_yaml/yamlinpython_27.txt | The dump_all() Function
💡 The dump_all() function is used to serialize Python objects—in order—into a single stream. It only accepts Python objects represented as lists, such as a list of dictionaries. If you pass in a dictionary object instead of a Python object represented as lists, the dump_all() function will outp... | |
ros_yaml/rclpyparamstutorialg_23.txt | It’s important: **if you don’t declare a parameter in your node’s code, you
will get an error when you try to get or set it**
(ParameterNotDeclaredException exception). | |
ros_yaml/pythonyaml_183.txt | def __init__(self, name):
self.name = name | |
ros_yaml/pythonyaml_225.txt | >>> print(yaml.dump_all([
... {"title": "Document #1"},
... {"title": "Document #2"},
... {"title": "Document #3"},
... ]))
title: 'Document #1'
---
title: 'Document #2'
---
title: 'Document #3'
Now you get a string containing more than one YAML document separated with the triple dash (---). | |
ros_yaml/pythonyaml_353.txt | def cast(value, tag):
match tag.split(":")[-1]:
case "binary":
return f'<img src="data:image/png;base64, {value}" />'
case _:
if "\n" in value:
return f'<div class="multiline">{value}</div>'
else:
return f"<span>{value}</span>"
The ... | |
ros_yaml/pythonyaml_160.txt | !!python/object/apply:models.Person
args: [John]
kwds: {last_name: Doe}
This would still call .__init__() on your class, but one of the arguments would be passed as a keyword argument. In any case, you could define the Person class manually or by taking advantage of data classes in Python: | |
ros_yaml/pythonyaml_151.txt | Suppose you’d like to deserialize a custom class from YAML, make a function call in your Python code, or even execute a shell command while parsing YAML. In that case, your only option is the UnsafeLoader, which accepts a few special library tags. The other loaders either raise an exception or ignore those tags. You’ll... | |
ros_yaml/rclpyparamstutorialg_32.txt | ### Run your node without params | |
ros_yaml/pythonyaml_18.txt | Even though XML was initially designed to be a metalanguage for creating markup languages for documents, people quickly adopted it as the standard data serialization format. The HTML-like syntax of angle brackets made XML look familiar. Suddenly, everyone wanted to use XML as their configuration, persistence, or messag... | |
ros_yaml/pythonyaml_97.txt | Remove ads
Getting Started With YAML in Python
As you learned in the introduction, working with YAML in Python requires a few extra steps because the language doesn’t support this data format out of the box. You’re going to need a third-party library to serialize Python objects into YAML and the other way around. | |
ros_yaml/rclpyparamstutorialg_76.txt |
def __init__(self):
super().__init__('test_params_rclpy')
# self.declare_parameter('my_str') --> not declared!
param_str = self.get_parameter('my_str') | |
ros_yaml/pythonyaml_10.txt | In this tutorial, you’ll learn how to: | |
ros_yaml/pythonyaml_302.txt | import yaml | |
ros_yaml/rclpyparamstutorialg_148.txt | Others | |
ros_yaml/rclpyparamstutorialg_69.txt |
...
self.declare_parameters(
namespace='',
parameters=[
('my_str', "default value"),
('my_int', 7),
('my_double_array', [1.1, 2.2])
]
)
... | |
ros_yaml/pythonyaml_178.txt | def __init__(self, name):
self.name = name
Now, your user objects won’t have the .__dict__ attribute at all. Because there’s no inherent .__dict__, the library falls back to calling setattr() for each key-value pair on the blank object. This ensures that only attributes listed in __slots__ will pass through... | |
ros_yaml/rclpyparamstutorialg_77.txt | As soon as you start your node – even if you specify a parameter value for
“my_str”, you’ll get an ParameterNotDeclaredException error. | |
ros_yaml/yamlinpython_51.txt | Reading and writing multiple blocks of yaml data
Modifying YAML in Python
Modifying YAML in Python
You can modify the contents of a YAML file using the yaml module with PyYAML. All you have to do is ensure the function takes in the following arguments: a YAML file to read and the key with the new value. | |
ros_yaml/UsingParametersInACl_57.txt | Open the ` setup.py ` file. Again, match the ` maintainer ` , `
maintainer_email ` , ` description ` and ` license ` fields to your `
package.xml ` : | |
ros_yaml/rclpyparamstutorialg_81.txt | ## Set params with rclpy | |
ros_yaml/UsingParametersInACl_15.txt | Contents | |
ros_yaml/yamlinpython_0.txt | Introducing Earthly Cloud. Consistent, repeatable builds. Advanced caching for speed. Works with any CI. Get 6,000 build min/mth free! Learn more.
Join us on
Slack
Products
Docs
Pricing
Blog
Get Started Free
How to Work with YAML in Python
Blog / Tutorials
Table of contents
The Need for Data Serialization and Why You S... | |
ros_yaml/pythonyaml_269.txt | import yaml | |
ros_yaml/pythonyaml_79.txt | schedule:
monday:
- *push-up
- *squat
tuesday:
- *plank
wednesday:
- *push-up
- *plank
Here, you’ve created a workout plan from the exercises that you defined earlier, repeating them across various daily routines. Additionally, the recursive property demonstrates an example of a circular refer... | |
ros_yaml/UsingParametersInACl_112.txt | © Copyright 2024, Open Robotics. | |
ros_yaml/UsingParametersInACl_10.txt | **You're reading the documentation for a version of ROS 2 that has reached its
EOL (end-of-life), and is no longer officially supported. If you want up-to-
date information, please have a look at[ Iron
](../../../iron/Tutorials/Beginner-Client-Libraries/Using-Parameters-In-A-
Class-Python.html) . ** | |
ros_yaml/rclpyparamstutorialg_19.txt | * * * | |
ros_yaml/pythonyaml_92.txt | if __name__ == "__main__":
main()
The YAML document above defines a property named script, which holds a short Python script consisting of a few lines of code. Without the pipe indicator, a YAML parser would’ve treated the following lines as nested elements rather than as a whole. Ansible is a notable example... | |
ros_yaml/pythonyaml_172.txt | >>> user
<models.User object at 0x7fe8adb12050> | |
ros_yaml/pythonyaml_131.txt | >>> yaml.safe_dump(yaml.safe_load(email_message))
"message:\n attachments:\n image1.gif: !!binary |\n (...) | |
ros_yaml/rclpyparamstutorialg_53.txt |
$ ros2 param list
/test_params_rclpy:
my_double_array
my_int
my_str
use_sim_time
$ ros2 param get /test_params_rclpy my_other_str
Parameter not set. | |
ros_yaml/UsingParametersInACl_20.txt | * 2 Write the Python node | |
ros_yaml/pythonyaml_38.txt | Historically, XML has had the best support across a wide range of technologies. JSON is an unbeatable all-around interchange format for transferring data on the Internet. So, who uses YAML and why? | |
ros_yaml/UsingParametersInACl_107.txt | You created a node with a custom parameter that can be set either from a
launch file or the command line. You added the dependencies, executables, and
a launch file to the package configuration files so that you could build and
run them, and see the parameter in action. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.