print(json.dumps(person, indent=4, default=str))
You create a dictionary and then call json.dumps() on it to dump a string. The parameter default specifies a function to call when Python can’t serialize an object to JSON, which is the case with the date of birth in this example. The built-in str() function will convert a datetime.date object to an ISO 8601 string.


>_import json
Now, run the code below to convert a YAML document to a JSON object and save it in a file called output.json.


# tree.py


ros2 param list


>_pip3 install pyyaml
To confirm that the installation was successful, you can run the command below:


Let’s say you forgot to declare the “my_str” parameter and then try to access
it (for reading or writing).


Remove ads
Load a Document From a String, a File, or a Stream
Once you choose the loader class or use one of the shorthand functions, you’re not limited to parsing only strings. The safe_load() and other functions exposed by PyYAML accept a single argument, which is a universal stream of characters or bytes. The most common examples of such streams are strings and Python bytes objects:


Because you’ll produce HTML output, you may streamline the typecasting function by returning only plain strings. At the same time, you can return an HTML <img> element for the Base64-encoded data and display that element instead of showing raw bytes. Other than that, regular scalars could be wrapped in either a <span> or an appropriately styled <div> element depending on if they contain single or multiline content:


script.py
Copydef read_and_write_one_block_of_yaml_data(filename,write_file):
    with open(f'{filename}.yaml','r') as f:
        data = yaml.safe_load(f)
    with open(f'{write_file}.yaml', 'w') as file:
        yaml.dump(data,file,sort_keys=False)
    print('done!')


Toggle


This tutorial will show you how to create those parameters in a Python class,
and how to set them in a launch file.


    $ ros2 param get /test_params_rclpy my_str
    String value is: Hello world


script.py
Copydef write_yaml_to_file(py_obj,filename):
    with open(f'{filename}.yaml', 'w',) as f :
        yaml.dump(py_obj,f,sort_keys=False)
    print('Written to file successfully')
write_yaml_to_file(data, 'output')
Upon calling the write_yaml_to_file() function with the data dictionary as the argument, the YAML file will be created in the working directory, as shown below:


>>> print(yaml.safe_dump(yaml.safe_load(email_message)))
message:
  attachments:
    image1.gif: !!binary |
      R0lGODdhCAAIAPAAAAIGAfr4+SwAAAAACAAIAAACDIyPeWCsClxDMsZ3CgA7
  cc:
  - jane.doe@domain.com
  content: 'Dear XYZ,


Get Source Code: Click here to get the source code you’ll use to work with YAML in Python.


Then you can use the ` get_parameter_or(name, Parameter) ` method. This method
will check if the parameter is declared. If yes, the parameter is retrieved.
If not, you can specify a default parameter. It’s probably a best practice to
always set default parameters when doing this.


Now, if you want to go further with ROS2 params:


* 3 Build and run


>>> from yaml2html import yaml2html
>>> for document in yaml2html("""
... ---
... title: "Document #1"
... ---
... title: "Document #2"
... ---
... title: "Document #3"
... """):
...     print(document)
...

title

Document #1

title

Document #2

title

Document #3

The example above demonstrates a stream consisting of three YAML documents, which the helper function turns into separate HTML fragments. Now that you understand the expected behavior, it’s time to implement the HTMLBuilder class.


    * [ Development process for a release ](../../Releases/Release-Process.html)
  * [ Tutorials ](../../Tutorials.html)
    * [ Beginner: CLI tools ](../Beginner-CLI-Tools.html)
      * [ Configuring environment ](../Beginner-CLI-Tools/Configuring-ROS2-Environment.html)
      * [ Using ` turtlesim  ` , ` ros2  ` , and ` rqt  ` ](../Beginner-CLI-Tools/Introducing-Turtlesim/Introducing-Turtlesim.html)
      * [ Understanding nodes ](../Beginner-CLI-Tools/Understanding-ROS2-Nodes/Understanding-ROS2-Nodes.html)
      * [ Understanding topics ](../Beginner-CLI-Tools/Understanding-ROS2-Topics/Understanding-ROS2-Topics.html)
      * [ Understanding services ](../Beginner-CLI-Tools/Understanding-ROS2-Services/Understanding-ROS2-Services.html)
      * [ Understanding parameters ](../Beginner-CLI-Tools/Understanding-ROS2-Parameters/Understanding-ROS2-Parameters.html)
      * [ Understanding actions ](../Beginner-CLI-Tools/Understanding-ROS2-Actions/Understanding-ROS2-Actions.html)
      * [ Using ` rqt_console  ` to view logs ](../Beginner-CLI-Tools/Using-Rqt-Console/Using-Rqt-Console.html)
      * [ Launching nodes ](../Beginner-CLI-Tools/Launching-Multiple-Nodes/Launching-Multiple-Nodes.html)
      * [ Recording and playing back data ](../Beginner-CLI-Tools/Recording-And-Playing-Back-Data/Recording-And-Playing-Back-Data.html)
    * [ Beginner: Client libraries ](../Beginner-Client-Libraries.html)
      * [ Using ` colcon  ` to build packages ](Colcon-Tutorial.html)
      * [ Creating a workspace ](Creating-A-Workspace/Creating-A-Workspace.html)
      * [ Creating a package ](Creating-Your-First-ROS2-Package.html)
      * [ Writing a simple publisher and subscriber (C++) ](Writing-A-Simple-Cpp-Publisher-And-Subscriber.html)
      * [ Writing a simple publisher and subscriber (Python) ](Writing-A-Simple-Py-Publisher-And-Subscriber.html)
      * [ Writing a simple service and client (C++) ](Writing-A-Simple-Cpp-Service-And-Client.html)
      * [ Writing a simple service and client (Python) ](Writing-A-Simple-Py-Service-And-Client.html)
      * [ Creating custom msg and srv files ](Custom-ROS2-Interfaces.html)
      * [ Implementing custom interfaces ](Single-Package-Define-And-Use-Interface.html)
      * [ Using parameters in a class (C++) ](Using-Parameters-In-A-Class-CPP.html)
      * Using parameters in a class (Python)
      * [ Using ` ros2doctor  ` to identify issues ](Getting-Started-With-Ros2doctor.html)
      * [ Creating and using plugins (C++) ](Pluginlib.html)
    * [ Intermediate ](../Intermediate.html)
      * [ Managing Dependencies with rosdep ](../Intermediate/Rosdep.html)
      * [ Creating an action ](../Intermediate/Creating-an-Action.html)
      * [ Writing an action server and client (C++) ](../Intermediate/Writing-an-Action-Server-Client/Cpp.html)
      * [ Writing an action server and client (Python) ](../Intermediate/Writing-an-Action-Server-Client/Py.html)
      * [ Composing multiple nodes in a single process ](../Intermediate/Composition.html)
      * [ Launch ](../Intermediate/Launch/Launch-Main.html)
        * [ Creating a launch file ](../Intermediate/Launch/Creating-Launch-Files.html)
        * [ Integrating launch files into ROS 2 packages ](../Intermediate/Launch/Launch-system.html)
        * [ Using substitutions ](../Intermediate/Launch/Using-Substitutions.html)
        * [ Using event handlers ](../Intermediate/Launch/Using-Event-Handlers.html)
        * [ Managing large projects ](../Intermediate/Launch/Using-ROS2-Launch-For-Large-Projects.html)
      * [ ` tf2  ` ](../Intermediate/Tf2/Tf2-Main.html)


Remove ads
Dump Custom Data Types
As you already know, at this point, you can use one of the Python-specific tags provided by PyYAML to serialize and deserialize objects of your custom data types, such as classes. You also know that those tags are only recognized by the unsafe loaders and dumpers, which explicitly allow potentially dangerous code execution. The library will refuse to serialize a Python-specific type like a complex number unless you choose the unsafe dumper class:


Now that you have PyYAML installed, you can start working with YAML in Python.


>>> yaml.safe_load("name: Иван")
{'name': 'Иван'}


Now run the node using the launch file we have just created:


After everything I told you about the errors due to undeclared parameters, I’m
now about to tell you how to allow them.


read_multiple_block_of_yaml_data('output2','output4')


    import os
    from glob import glob
    # ...

    setup(
      # ...
      data_files=[
          # ...
          (os.path.join('share', package_name), glob('launch/*launch.[pxy][yma]*')),
        ]
      )


Related Tutorial Categories: intermediate


def tokenize(text, loader=yaml.SafeLoader):
    last_token = yaml.ValueToken(None, None)
    for token in yaml.scan(text, loader):
        start = token.start_mark.index
        end = token.end_mark.index
        if isinstance(token, yaml.TagToken):
            yield start, end, token
        elif isinstance(token, yaml.ScalarToken):
            yield start, end, last_token
        elif isinstance(token, (yaml.KeyToken, yaml.ValueToken)):
            last_token = token
It’s a thin wrapper around PyYAML’s yaml.scan() function, which generates tuples comprising the start index, the end index, and a token instance. Here’s a more detailed breakdown:


Performance


You can use the same keyword arguments across all four dumping functions. They’re all optional because they have default values equal to either None or False, except for the sort_keys argument, which has a default value of True. In total, there are six Boolean flags that you can turn on and off to change the look of the resulting YAML:


###  Declare params with rclpy


In this tutorial, you learned how to:


Ironically, it was AJAX that ultimately led to XML’s decline in popularity. The verbose, complex, and redundant XML syntax wasted a lot of bandwidth when data was sent over the network. Parsing XML documents in JavaScript was slow and tedious because of XML’s fixed document object model (DOM), which wouldn’t match the application’s data model. The community finally acknowledged that they’d been using the wrong tool for the job.


Before moving on, it’s worth noting that PyYAML provides two more insecure tags:


(venv) $ python -m pip install pyyaml
The library is self-contained and doesn’t require any further dependencies because it’s written in pure Python. However, most distributions bundle a compiled C binding for the LibYAML library, which makes PyYAML run much faster. To confirm if your PyYAML installation comes with a C binding, open the interactive Python interpreter and run this code snippet:


How To Read A CSV File In Python
3 minute read
Learn how to read a CSV file in Python using both the `csv` and `pandas` libraries. Discover the different methods and possible delimiter issues, and find ou...


    $ ros2 run ros2_tutorials test_params_rclpy --ros-args -p my_int:=5
    [INFO] [test_params_rclpy]: str: default value, int: 5, double[]: [1.1, 2.2]


Get notified about new articles!
We won't send you spam. Unsubscribe at any time.
Subscribe to the Newsletter
Email Address


💡 The safe_load() function is used to read YAML from unreliable and untrusted sources. The load() function is not reliable, especially when it is used to load a supposedly malicious script. The authors recommend using the safe_load() function instead. However, both functions have Python objects as their return type.
The function read_one_block_of_yaml_data will open a yaml file in read mode, load its contents using the safe_load() function, and print out the output as a dictionary of dictionaries.


**Goal:** Create and run a class with ROS parameters using Python.


Expand the collapsible section below for the complete source code of your script:


Serialize YAML Documents as JSON
Even though Python doesn’t provide a dedicated YAML parser or serializer, you can sidestep this problem to some extent with the help of the built-in json module. After all, you’ve learned that YAML is a superset of JSON, so you could dump your data to a regular JSON format in Python and expect external YAML parsers to accept it.


OPEN_TAG_EVENTS = (ScalarEvent, SequenceStartEvent, MappingStartEvent)
CLOSE_TAG_EVENTS = (ScalarEvent, SequenceEndEvent, MappingEndEvent)


Confirming the pyyaml library installation
Creating YAML in Python
You can download the code snippets used in this tutorial from this GitHub repository.


Necessary


###  3 Build and run  ï


  * [ Installation ](../../Installation.html)
    * [ Ubuntu (Debian) ](../../Installation/Ubuntu-Install-Debians.html)
    * [ Windows (binary) ](../../Installation/Windows-Install-Binary.html)
    * [ Alternatives ](../../Installation/Alternatives.html)
      * [ Ubuntu (source) ](../../Installation/Alternatives/Ubuntu-Development-Setup.html)
      * [ Ubuntu (binary) ](../../Installation/Alternatives/Ubuntu-Install-Binary.html)
      * [ Windows (source) ](../../Installation/Alternatives/Windows-Development-Setup.html)
      * [ macOS (source) ](../../Installation/Alternatives/macOS-Development-Setup.html)
      * [ macOS (binary) ](../../Installation/Alternatives/macOS-Install-Binary.html)
      * [ Fedora (source) ](../../Installation/Alternatives/Fedora-Development-Setup.html)
      * [ Latest development (source) ](../../Installation/Alternatives/Latest-Development-Setup.html)
    * [ Maintain source checkout ](../../Installation/Maintaining-a-Source-Checkout.html)
    * [ Testing with pre-release binaries ](../../Installation/Testing.html)
    * [ DDS implementations ](../../Installation/DDS-Implementations.html)
      * [ Connext security plugins ](../../Installation/DDS-Implementations/Install-Connext-Security-Plugins.html)
      * [ RTI Connext DDS ](../../Installation/DDS-Implementations/Install-Connext-University-Eval.html)
      * [ Eclipse Cyclone DDS ](../../Installation/DDS-Implementations/Working-with-Eclipse-CycloneDDS.html)
      * [ GurumNetworks GurumDDS ](../../Installation/DDS-Implementations/Working-with-GurumNetworks-GurumDDS.html)
      * [ eProsima Fast DDS ](../../Installation/DDS-Implementations/Working-with-eProsima-Fast-DDS.html)
  * [ Distributions ](../../Releases.html)
    * [ Iron Irwini ( ` iron  ` ) ](../../Releases/Release-Iron-Irwini.html)
      * [ Iron Irwini Changelog ](../../Releases/Iron-Irwini-Complete-Changelog.html)
    * [ Humble Hawksbill ( ` humble  ` ) ](../../Releases/Release-Humble-Hawksbill.html)
      * [ Humble Hawksbill changelog ](../../Releases/Humble-Hawksbill-Complete-Changelog.html)
    * [ Rolling Ridley ( ` rolling  ` ) ](../../Releases/Release-Rolling-Ridley.html)
    * [ Development Distribution ](../../Releases/Development.html)
      * [ Jazzy Jalisco (codename âjazzyâ; May, 2024) ](../../Releases/Release-Jazzy-Jalisco.html)
    * [ End-of-Life Distributions ](../../Releases/End-of-Life.html)
      * [ Galactic Geochelone ( ` galactic  ` ) ](../../Releases/Release-Galactic-Geochelone.html)
        * [ Galactic Geochelone changelog ](../../Releases/Galactic-Geochelone-Complete-Changelog.html)
      * [ Foxy Fitzroy ( ` foxy  ` ) ](../../Releases/Release-Foxy-Fitzroy.html)
      * [ Eloquent Elusor ( ` eloquent  ` ) ](../../Releases/Release-Eloquent-Elusor.html)
      * [ Dashing Diademata ( ` dashing  ` ) ](../../Releases/Release-Dashing-Diademata.html)
      * [ Crystal Clemmys ( ` crystal  ` ) ](../../Releases/Release-Crystal-Clemmys.html)
      * [ Bouncy Bolson ( ` bouncy  ` ) ](../../Releases/Release-Bouncy-Bolson.html)
      * [ Ardent Apalone ( ` ardent  ` ) ](../../Releases/Release-Ardent-Apalone.html)
      * [ Beta 3 ( ` r2b3  ` ) ](../../Releases/Beta3-Overview.html)
      * [ Beta 2 ( ` r2b2  ` ) ](../../Releases/Beta2-Overview.html)
      * [ Beta 1 ( ` Asphalt  ` ) ](../../Releases/Beta1-Overview.html)
      * [ Alphas ](../../Releases/Alpha-Overview.html)


Choose the Dumper Class
The all-around YAML serialization function in PyYAML is yaml.dump(), which takes an optional dumper class as an argument. If you don’t specify one during a function call, then it falls back to using the most feature-rich yaml.Dumper. Other choices are as follows:


* Prerequisites


>>> import yaml


Despite its popularity, PyYAML has some drawbacks. For example, if you need to use features introduced in YAML 1.2, such as full JSON compliance or safer literals, then you’re better off using the ruamel.yaml library, which is derived from an older PyYAML version. As a bonus, it can do round-trip parsing to preserve the comments and original formatting when needed.


#####  2.1.1 (Optional) Add ParameterDescriptor  ï


####  3.2 Change via a launch file  ï


One flavor of the syntax allows for setting the object’s initial state through a list of positional arguments, like so:


    colcon build --packages-select python_parameters

    colcon build --packages-select python_parameters

    colcon build --merge-install --packages-select python_parameters


$ python print_json.py | yq -y .
firstName: John
dateOfBirth: '1969-12-31'
married: false
spouse: null
children:
  - Bobby
  - Molly


If you’ve already started to experiment with ROS2 parameters and wondered why
your parameters don’t appear, well this is probably because you didn’t declare
them.


And here’s the result you should get after starting the node:


script.py
Copydef read_multiple_block_of_yaml_data(filename):
    with open(f'{filename}.yaml','r') as f:
        data = yaml.safe_load_all(f)
        print(list(data))
read_multiple_block_of_yaml_data('output2')
The output below shows the result as a list of dictionaries:


YAML came into existence the same year as JSON, and by pure coincidence, it was almost a complete superset of JSON on the syntactical and semantic levels. Starting from YAML 1.2, the format officially became a strict superset of JSON, meaning that every valid JSON document also happens to be a YAML document.


##  rclpy parameter callback


Load Multiple Documents
All four loading functions in PyYAML have their iterable counterparts, which can read multiple YAML documents from a single stream. They still expect exactly one argument, but instead of immediately parsing it into a Python object, they wrap it with a generator iterator that you can iterate over:


Here you can see that we set ` my_parameter  ` to ` earth  ` when we launch
our node ` parameter_node  ` . By adding the two lines below, we ensure our
output is printed in our console.


  * First it is declared in the code, so it can be set.
  * When you start the node, either you provide a value for “my_str”, or the default value will be used.
  * But, then “my_str” is set from the code, and the new value replaces any previous value.


Output2.yaml
CopyapiVersion: v1
kind: persistentVolume
metadata:
  name: mongodb-pv
  labels:
    type: local
spec:
  storageClassName: hostpath
capacity:
  storage: 3Gi
accessModes:
- ReadWriteOnce
hostpath:
  path: /mnt/data
---
apiVersion: v1
kind: persistentVolume
metadata:
  name: mysql-pv
  labels:
    type: local
spec:
  storageClassName: hostpath
capacity:
  storage: 2Gi
accessModes:
- ReadWriteOnce
hostpath:
  path: /mnt/data
Writing YAML to a File in Python
Writing YAML to a File in Python
Now that you’ve learned how to create YAML documents from Python objects, let’s learn how to write them into a file for future use.


As you can see the node “test_params_rclpy” now contains 3 ROS2 params – in
addition to the “use_sim_time” param, automatically created for each node.


Data Type	YAML
Null	null, ~
Boolean	true, false (Before YAML 1.2: yes, no, on, off)
Integer	10, 0b10, 0x10, 0o10 (Before YAML 1.2: 010)
Floating-Point	3.14, 12.5e-9, .inf, .nan
String	Lorem ipsum
Date and Time	2022-01-16, 23:59, 2022-01-16 23:59:59
You can write reserved words in YAML in lowercase (null), uppercase (NULL), or title case (Null) to parse them into the desired data type. Any other case variant of such words will be treated as plain text. The null constant or its tilde (~) alias lets you explicitly state the lack of a value, but you can also leave the value blank for the same effect.


ros2 run python_parameters minimal_param_node


Here’s a minimal [ ROS2 Python node ](https://roboticsbackend.com/write-
minimal-ros2-python-node/) which declares 3 parameters (with no default value,
we’ll see later how to do that):


Also, one thing you could wish to do, is to have some parameters globally
available to all nodes. As you know, ROS2 parameters are specific to a node
and only exist with this node. If you want to set a parameter shared by
multiple nodes, one way you could achieve that is to create a [ dedicated node
only for global params ](https://roboticsbackend.com/ros2-global-parameters/)
. You’d launch this node first, and always keep it alive so other nodes can
retrieve parameters (and get notified) from it.


There are also a few counterpart functions for writing YAML to a stream:


     [ Iron (latest) ](../../../iron/Tutorials/Beginner-Client-Libraries/Using-Parameters-In-A-Class-Python.html)
     [ Humble ](../../../humble/Tutorials/Beginner-Client-Libraries/Using-Parameters-In-A-Class-Python.html)
     [ Galactic (EOL) ](../../../galactic/Tutorials/Beginner-Client-Libraries/Using-Parameters-In-A-Class-Python.html)
     [ Foxy (EOL) ](Using-Parameters-In-A-Class-Python.html)
     [ Eloquent (EOL) ](../../../eloquent/index.html)
     [ Dashing (EOL) ](../../../dashing/index.html)
     [ Crystal (EOL) ](../../../crystal/index.html)


_You want to learn ROS2 efficiently?_


script.py
Copydata = {
    'Name':'John Doe',
    'Position':'DevOps Engineer',
    'Location':'England',
    'Age':'26',
    'Experience': {'GitHub':'Software Engineer',\
    'Google':'Technical Engineer', 'Linkedin':'Data Analyst'},
    'Languages': {'Markup':['HTML'], 'Programming'\
    :['Python', 'JavaScript','Golang']}
}
The dump() Function
Now, to create a yaml representation of the data dictionary created above, you can use the dump() function in the yaml module . The dump() function expresses Python objects in YAML format. It accepts two arguments, data (which is a Python object) which is required, and optionally, a file to store the YAML format of the Python object.


script.py
Copy
 def read_and_modify_one_block_of_yaml_data(filename,write_file, key,value):
    with open(f'{filename}.yaml', 'r') as f:
        data = yaml.safe_load(f)
        data[f'{key}'] = f'{value}'
        print(data)
    with open(f'{write_file}.yaml', 'w') as file:
        yaml.dump(data,file,sort_keys=False)
    print('done!')

read_and_modify_one_block_of_yaml_data('output', \
'output5', key='Age', value=30)
Once executed successfully, you should have the following output:


image: !!binary
  R0lGODdhCAAIAPAAAAIGAfr4+SwAA
  AAACAAIAAACDIyPeWCsClxDMsZ3CgA7


>>> import yaml
>>> yaml.dump(data)
'name: John\n'


center_at: !!python/complex 3.14+2.72j


recursive: &cycle [*cycle]


You can also use a [ ROS2 launch file
](https://roboticsbackend.com/ros2-launch-file-example/) instead of adding all
your params manually in the terminal (additional improvement: you can also [
set all your params in a YAML config file
](https://roboticsbackend.com/ros2-yaml-params/) ).


Okay, that felt like cheating, and it works only one way, as you can’t read a YAML file back into Python using the json module. Thankfully, there are ways to do that.


Maybe you’ll decide to adopt YAML in your future project after completing this tutorial!


Note that dump_all() is the only function used under the hood because all the other ones, including dump() and safe_dump(), delegate processing to it. So, regardless of which function you call, they will all have the same list of formal parameters.


class User:
    def __init__(self, name):
        self.name = name
You place the User class in a separate source file named models.py to keep things organized. User objects have only one attribute—the name. By using just one attribute and implementing the initializer explicitly, you’ll be able to observe the way PyYAML calls the individual methods.


[INFO] [parameter_node]: Hello world!


Recommended Video Course: YAML: Python's Missing Battery


>>> yaml.safe_load("name: Иван".encode("utf-8"))
{'name': 'Иван'}


Writing Function	Input	Example
yaml.emit()	Events	yaml.emit(yaml.parse(data))
yaml.serialize()	Node	yaml.serialize(yaml.compose(data))
yaml.serialize_all()	Nodes	yaml.serialize_all(yaml.compose_all(data))
Note that whatever function you choose, you’ll probably have more work to do than before. For example, handling YAML tags or interpreting string values as the correct native data type will be in your court now. Some of these steps may be unnecessary, though, depending on your use case.


[ ROS 2 Documentation: Foxy ![Logo](../../_static/foxy-small.png)
](../../index.html)


Data types
Tags
Anchors and aliases
Merged attributes
Flow and block styles
Multiple-document streams
While XML is all about text, and JSON inherits JavaScript’s few data types, YAML’s defining feature is tight integration with the type systems of modern programming languages. For example, you can use YAML to serialize and deserialize data types built into Python, such as date and time:


You May Also Enjoy
Running Python on Docker
9 minute read
Learn how to run Python applications using Docker, a containerization tool that simplifies managing dependencies and allows for easy sharing of projects with...


The ` --dependencies  ` argument will automatically add the necessary
dependency lines to ` package.xml  ` and ` CMakeLists.txt  ` .


Parameter	Type	Meaning
indent	int	Block indent level, which must be greater than 1 and less than 10
width	int	Line width, which must be bigger than twice the indent
default_style	str	Scalar quotation style, which must be one of the following: None, "'", or '"'
encoding	str	Character encoding, which produces bytes instead of str when set
line_break	str	Newline character, which must be one of the following: '\r', '\n', or '\r\n'
tags	dict	Additional tag directives comprised of tag handles
version	tuple	Major and minor YAML version, such as (1, 2) for version 1.2
Most of them are self-explanatory. However, the tags argument must be a dictionary that maps custom tag handles to valid URI prefixes recognized by a YAML parser:


* Next steps


###  Get params one by one


YAML is arguably the easiest on the eyes, as readability has always been one of its core principles, but JSON isn’t bad either. Some might even find JSON less cluttered and noisy due to its minimalistic syntax and resemblance to Python lists and dictionaries. XML is the most verbose, as it requires wrapping every piece of information in a pair of opening and closing tags.


      * [ Contributing to ROS 2 Documentation ](../../The-ROS2-Project/Contributing/Contributing-To-ROS-2-Documentation.html)
    * [ Features Status ](../../The-ROS2-Project/Features.html)
    * [ Feature Ideas ](../../The-ROS2-Project/Feature-Ideas.html)
    * [ Roadmap ](../../The-ROS2-Project/Roadmap.html)
    * [ ROSCon Talks ](../../The-ROS2-Project/ROSCon-Content.html)
    * [ Project Governance ](../../The-ROS2-Project/Governance.html)
      * [ ROS 2 Technical Steering Committee Charter ](../../The-ROS2-Project/Governance/ROS2-TSC-Charter.html)
      * [ ROS 2 TSC applicant intake process ](../../The-ROS2-Project/Governance/ROS2-TSC-Intake-process.html)
      * [ How to Start a Community Working Group ](../../The-ROS2-Project/Governance/How-To-Start-A-Community-Working-Group.html)
    * [ Marketing ](../../The-ROS2-Project/Marketing.html)
  * [ Related Projects ](../../Related-Projects.html)
    * [ Intel ROS 2 Projects ](../../Related-Projects/Intel-ROS2-Projects.html)
    * [ NVIDIA ROS 2 Projects ](../../Related-Projects/Nvidia-ROS2-Projects.html)
  * [ Glossary ](../../Glossary.html)
  * [ Citations ](../../Citations.html)


####  2.2 Add an entry point  ï


Necessary cookies are absolutely essential for the website to function
properly. These cookies ensure basic functionalities and security features of
the website, anonymously.  Cookie  |  Duration  |  Description
---|---|---
cookielawinfo-checkbox-analytics  |  11 months  |  This cookie is set by GDPR
Cookie Consent plugin. The cookie is used to store the user consent for the
cookies in the category "Analytics".
cookielawinfo-checkbox-functional  |  11 months  |  The cookie is set by GDPR
cookie consent to record the user consent for the cookies in the category
"Functional".
cookielawinfo-checkbox-necessary  |  11 months  |  This cookie is set by GDPR
Cookie Consent plugin. The cookies is used to store the user consent for the
cookies in the category "Necessary".
cookielawinfo-checkbox-others  |  11 months  |  This cookie is set by GDPR
Cookie Consent plugin. The cookie is used to store the user consent for the
cookies in the category "Other.
cookielawinfo-checkbox-performance  |  11 months  |  This cookie is set by
GDPR Cookie Consent plugin. The cookie is used to store the user consent for
the cookies in the category "Performance".
viewed_cookie_policy  |  11 months  |  The cookie is set by the GDPR Cookie
Consent plugin and is used to store whether or not user has consented to the
use of cookies. It does not store any personal data.

Functional


    source install/setup.bash

    . install/setup.bash

    call install/setup.bat


  * Any parameter not declared within a node won’t appear in the parameter list, and won’t be available.
  * Any time you try to access a parameter in your code without declaring it first, you’ll get an error.


    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.INTEGER)
        self.declare_parameter('my_double_array', rclpy.Parameter.Type.DOUBLE_ARRAY)

        param_str = self.get_parameter('my_str')
        param_int = self.get_parameter('my_int')
        param_double_array = self.get_parameter('my_double_array')

        self.get_logger().info("str: %s, int: %s, double[]: %s" %
                               (str(param_str.value),
                                str(param_int.value),
                                str(param_double_array.value),))


The names of params must be identical to the ones we declared in the node’s
code.


>>> import yaml
>>> yaml.__with_libyaml__
True
Even though PyYAML is the name of the library you’ve installed, you’ll be importing the yaml package in Python code. Also, note that you need to explicitly request that PyYAML take advantage of the noticeably faster shared C library, or else it’ll fall back to its default of pure Python. Read on to find out how to change this default behavior.


##  Next steps  ï


How to get started with PyMongo
18 minute read
Learn how to get started with PyMongo, the official MongoDB driver for Python. This tutorial covers setting up a remote MongoDB database using MongoDB Atlas,...


class User:
    __slots__ = ["name"]


>>> import yaml
>>> print(yaml.dump([
...     {"title": "Document #1"},
...     {"title": "Document #2"},
...     {"title": "Document #3"},
... ]))
- title: 'Document #1'
- title: 'Document #2'
- title: 'Document #3'
They always assume the latter, dumping a single YAML document with a list of elements. To dump multiple documents, use either dump_all() or safe_dump_all():


In this tutorial, you’ll learn how to work with YAML in Python using the available third-party libraries, with a focus on PyYAML. If you’re new to YAML or haven’t used it in a while, then you’ll have a chance to take a quick crash course before diving deeper into the topic.


text: !!str 2022-01-16


Aldren Santos
Aldren


Browse Topics Guided Learning Paths
 Basics  Intermediate  Advanced
api best-practices career community databases data-science data-structures data-viz devops django docker editors flask front-end gamedev gui machine-learning numpy projects python testing tools web-dev web-scraping
Table of Contents


[ ![The Robotics Back-End](https://roboticsbackend.com/wp-
content/uploads/2020/02/favicon_white.png) ](https://roboticsbackend.com/ "The
Robotics Back-End")


>>> visit(root)
[42, {'pi': 3.14, 'e': 2.72}]


>>> yaml.safe_load(jdoe)
<__main__.Person object at 0x7f6fb7ba9ab0>
The Walrus operator (:=) lets you define a variable and use it as an argument to the print() function in one step. Marking classes as safe is a nice compromise, allowing you to make exceptions to some of your classes by shrugging off security and letting them in. Naturally, you must be absolutely sure that there’s nothing suspicious about them before you try loading the associated YAML.


##  Want to learn ROS2?


Remove ads
Dump to a String, a File, or a Stream
Serializing JSON in Python requires you to choose between calling json.dump() or json.dumps() depending on where you want the content to be dumped. On the other hand, PyYAML provides a two-in-one dumping function, which behaves differently depending on how you call it:


You can experiment with the available keyword arguments by changing their values and rerunning your code to see the result. However, this sounds like a tedious task. The supporting materials for this tutorial come with an interactive app that will let you test different combinations of arguments and their values in a web browser:


>>> from yaml import BaseLoader
>>> yaml.load("""
... number: 3.14
... string: !!str 3.14
... """, BaseLoader)
{'number': '3.14', 'string': '3.14'}
Numeric literals such as 3.14 are treated as floats by default, but you can request a type conversion to string with the !!str tag. Almost all loaders respect standard YAML tags. The only exception is the BaseLoader class, which represents scalars with strings whether you tag them or not.


The next piece of code creates the class and the constructor. The line `
self.declare_parameter('my_parameter',  'world')  ` of the constructor creates
a parameter with the name ` my_parameter  ` and a default value of ` world  `
. The parameter type is inferred from the default value, so in this case it
would be set to a string type. Next the ` timer  ` is initialized with a
period of 1, which causes the ` timer_callback  ` function to be executed once
a second.


>>> with open("sample.yaml", mode="wb") as file:
...     file.write(b"name: \xd0\x98\xd0\xb2\xd0\xb0\xd0\xbd")
...
14


What Are Python Data Classes?
21 minute read
In this tutorial, you'll learn about Python data classes and how they provide a convenient way to define and manage data-oriented classes. You'll explore the...


Output[{'apiVersion': 'v1', 'kind': 'persistentVolume', 'metadata': \
{'name': 'mongodb-pv', 'labels': {'type': 'local'}}, 'spec': \
{'storageClassName': 'hostpath'}, 'capacity': {'storage': '3Gi'}, \
'accessModes': ['ReadWriteOnce'], 'hostpath': {'path': '/mnt/data'}}, \
{'apiVersion': 'v1', 'kind': 'persistentVolume', 'metadata': \
{'name': 'mysql-pv', 'labels': {'type': 'local'}}, 'spec': \
{'storageClassName': 'hostpath'}, 'capacity': {'storage': '2Gi'}, \
'accessModes': ['ReadWriteOnce'], 'hostpath': {'path': '/mnt/data'}}]
If you try to load the data as it is, without converting it to a list, you’ll get a generator object and a memory location and not the contents of the yaml file:


grandparent:
  parent:
    child:
      name: Bobby
    sibling:
      name: Molly
This sample document defines a family tree with grandparent as the root element, whose immediate child is the parent element, which has two children with the name attribute on the lowest level in the tree. You can think of each element as an opening statement followed by a colon (:) in Python.


>>> yaml.safe_load(b"name: \xd0\x98\xd0\xb2\xd0\xb0\xd0\xbd")
{'name': 'Иван'}
According to the YAML 1.2 specification, parsers should support Unicode encoded with UTF-8, UTF-16, or UTF-32 for compatibility with JSON. However, because the PyYAML library supports only YAML 1.1, your only options are UTF-8 and UTF-16:


Linux  macOS  Windows


Other Versions  v: foxy


$ echo '[42, {pi: 3.14, e: 2.72}]' | python yaml2html.py | html2text
    * 42
    *   pi
            3.14
        e
            2.72
The echo command should work on all major operating systems. It prints a piece of text in the terminal, which you can hook up to another command pipeline using the vertical bar character (|). In this case, you process a short YAML document with your yaml2html.py script and then convert the resulting HTML to a simplified textual form that you can preview in the terminal without starting a full-fledged web browser.


When you run the script against some test data, then it’ll output a piece of HTML code that you can redirect to a local file, which you can open with your default web browser:


* 1 Create a package


(For the same params tutorial with Cpp, checkout the [ rclcpp params tutorial
](https://roboticsbackend.com/rclcpp-params-tutorial-get-set-ros2-params-with-
cpp/) )


SAVE & ACCEPT


**Don't miss this opportunity:**


>>> user = yaml.unsafe_load("""
... !!python/object:models.User
... no_such_attribute: 42
... """)


rectangle:
  << : *shape
  << : *square
  b: 3
  color: green
The rectangle object inherits properties of shape and square while adding a new attribute, b, and changing the value of color.


To insist on the importance of declaring your ROS2 params, let’s run the node
with a parameter which was not declared before.


>>> import yaml
>>> yaml.safe_load(email_message)
{
    'message': {
        'date': datetime.datetime(2022, 1, 16, 12, 46, 17, tzinfo=(...)),
        'from': 'john.doe@domain.com',
        'to': ['bobby@domain.com', 'molly@domain.com'],
        'cc': ['jane.doe@domain.com'],
        'subject': 'Friendly reminder',
        'content': 'Dear XYZ,\n\nLorem ipsum dolor sit amet...\n',
        'attachments': {
            'image1.gif': b'GIF87a\x08\x00\x08\x00\xf0\x00\x00\x02...'
        }
    }
}
Calling safe_load() is currently the recommended way of handling content received from untrusted sources, which could contain malicious code. YAML has an expressive syntax full of convenient features, which unfortunately open the door to a host of vulnerabilities. You’ll learn more about exploiting YAML’s weaknesses later.


🐍 Python Tricks 💌


import yaml


You can also declare multiple parameters at once.


Remove ads
Compare Loaders’ Features
Below, you’ll get a quick demonstration of the features mentioned above. First, import the yaml module and check out an anchors and aliases example:


script.py
Copyyaml_output = yaml.dump(data, sort_keys=False)


$ python print_json.py | shyaml get-value
firstName: John
dateOfBirth: '1969-12-31'
married: false
spouse: null
children:
- Bobby
- Molly
Nice! Both parsers formatted your data in a more canonical YAML format without complaining. However, because yq is a thin wrapper around JSON’s jq, you must request that it do the transcoding with the -y option and a trailing dot as a filtering expression. Also, notice a slight difference in the resulting indentation between yq and shyaml.


text: >
   Lorem
     ipsum
   dolor
   sit
   amet


    @property
    def html(self):
        return "".join(self._html)


To find out, take a look at this high-level overview of the loaders at your disposal. The brief descriptions should give you a general idea about the available choices:


>>> import yaml
>>> print(yaml.dump(3.14, Dumper=yaml.Dumper))
3.14
...


>>> yaml.safe_load(io.StringIO("name: Иван"))
{'name': 'Иван'}


And, if you ever need to, at any moment you can also undeclare a parameter: `
self.undeclare_parameter('my_str') ` .


For the 2 other parameters (“my_str” and “my_double_array”), as we did not
specify any value, then they take the default value.


        if isinstance(event, CLOSE_TAG_EVENTS):
            self._handle_tag(close=True)
# ...
You start processing an event by checking if there are any open tags on the stack pending some action. You delegate this check to another helper method, ._handle_tag(), which you’ll add later. Then, you append the HTML tag corresponding to the current event and again update the context.


Introducing this additional parameter was a breaking change that resulted in many complaints from people maintaining software dependent on PyYAML. There’s still a pinned issue on the library’s GitHub repository about this backward incompatibility.


In addition to this, you might find it useful to install these command-line tools with pip into your virtual environment to help with debugging:


# print_json.py


Following the ` timer_callback  ` is our ` main  ` . Here ROS 2 is
initialized, an instance of the ` MinimalParam  ` class is constructed, and `
rclpy.spin  ` starts processing data from the node.


script.py
Copydef write_yaml_to_file(py_obj,filename) :
    with open(f'{filename}.yaml', 'w',) as f :
        yaml.dump_all(py_obj,f,sort_keys=False)
    print('written to file successfully')
write_yaml_to_file(data2, 'output2')


Here we only set the “my_int” parameter to 5. The default value (7) is not
used.


script.py
Copydef convert_yaml_to_json(yfile, jfile):
    with open(f'{yfile}.yaml', 'r') as f:
        yaml_file = yaml.safe_load(f)
    with open(f'{jfile}.json', 'w') as json_file:
        json.dump(yaml_file, json_file, indent=3)
    print('done!')
convert_yaml_to_json('output','output')
The json.dump() function converts a Python object (YAML in this case) into a JSON object. It takes in the following arguments: the Python object you want to convert, the JSON file you’d like to write it to, and an optional index value to specify how you want the JSON object to be formatted.
Once converted successfully, you should have an output.json file in your working directory:


Necessary


read_and_write_one_block_of_yaml_data('output', 'output3')
You should have the following output:


Close


Other uncategorized cookies are those that are being analyzed and have not
been classified into a category as yet.


Remove ads
Practical Uses of YAML
As noted earlier, YAML is mostly praised for its readability, which makes it perfect for storing all kinds of configuration data in a human-readable format. It became especially popular among DevOps engineers, who’ve built automation tools around it. A few examples of such tools include:


        if isinstance(event, OPEN_TAG_EVENTS):
            self._handle_tag()


>>> import yaml


ros2 launch python_parameters python_parameters_launch.py


Linux  macOS  Windows


def visit(node):
    if isinstance(node, yaml.ScalarNode):
        return cast(node.value, node.tag)
    elif isinstance(node, yaml.SequenceNode):
        return html_list(node)
    elif isinstance(node, yaml.MappingNode):
        return html_map(node)


>>> import yaml
>>> for event in yaml.parse("[42, {pi: 3.14, e: 2.72}]", yaml.SafeLoader):
...     print(event)
...
StreamStartEvent()
DocumentStartEvent()
SequenceStartEvent(anchor=None, tag=None, implicit=True)
ScalarEvent(anchor=None, tag=None, implicit=(True, False), value='42')
MappingStartEvent(anchor=None, tag=None, implicit=True)
ScalarEvent(anchor=None, tag=None, implicit=(True, False), value='pi')
ScalarEvent(anchor=None, tag=None, implicit=(True, False), value='3.14')
ScalarEvent(anchor=None, tag=None, implicit=(True, False), value='e')
ScalarEvent(anchor=None, tag=None, implicit=(True, False), value='2.72')
MappingEndEvent()
SequenceEndEvent()
DocumentEndEvent()
StreamEndEvent()
As you can see, there are various types of events that correspond to different elements in a YAML document. Some of those events expose additional attributes, which you can inspect to learn more about the element at hand.


When you decide to use the !!python/object tag in YAML, then the library calls .__new__() without any arguments and never calls .__init__(). Instead, it directly manipulates the .__dict__ attribute of your newly created object, which can have some undesired effects:


**Time:** 20 minutes


ros2 param set /minimal_param_node my_parameter earth


[ ![ROS2 For Beginners - Step by Step Course](https://roboticsbackend.com/wp-
content/uploads/2020/04/ROS2_for_beginners_step_by_step.jpg)
](https://rbcknd.com/ros2-for-beginners)


shape: &shape
  color: blue


rosdep install -i --from-path src --rosdistro foxy -y


Here’s one way of loading your encoded state from YAML:


>>> visit(yaml.compose("when: 2022-01-16 23:59:59"))
{'when': datetime.datetime(2022, 1, 16, 23, 59, 59)}
You’re all set to generate an HTML string instead of a Python object. Replace the return values in visit() with calls to even more helper functions:


Donât forget to save.


If you just want to set a parameter’s value in case it is not specified when
you start the node, then prefer using a default value (as you saw before in
this tutorial).


Note: Before version 6.0 of the PyYAML library, the default way of parsing YAML documents had always been the yaml.load() function, which defaulted to using an unsafe parser. With the latest release, you can still use this function, but it requires you to explicitly specify a particular loader class as a second parameter.


Bartosz Zaczyński
Bartosz is a bootcamp instructor, author, and polyglot programmer in love with Python. He helps his students get into software engineering by sharing over a decade of commercial experience in the IT industry.


    <description>Python parameter tutorial</description>
    <maintainer email="you@email.com">Your Name</maintainer>
    <license>Apache License 2.0</license>


>>> import yaml


In Python, performance when working with these data formats will vary, and it’ll be highly sensitive to the implementation you choose. A pure Python implementation will always lose to a compiled C library. In addition to this, using different XML processing models—(DOM, SAX, or StAX)—will also impact performance.


Some of the widely used data serialization languages include YAML, XML, and JSON. While XML and JSON are used for data transfer between applications, YAML is often used to define the configuration for applications.


>>> data = {"name": "John"}


  * [ Learn how to handle params with Cpp and rclcpp ](https://roboticsbackend.com/rclcpp-params-tutorial-get-set-ros2-params-with-cpp/) .
  * [ Learn how to set all your parameters in YAML config files ](https://roboticsbackend.com/ros2-yaml-params/) (very useful to scale your application properly).


    '
  date: 2022-01-16 12:46:17+00:00
  from: john.doe@domain.com
  subject: Friendly reminder
  to:
  - bobby@domain.com
  - molly@domain.com
The result is a string object with your email message serialized to YAML again. However, it’s not quite the same YAML that you originally started with. As you can see, safe_dump() sorted the dictionary keys for you, quoted the multiline strings, and used a slightly different indentation. You can change some of this and apply more tweaks to the formatting through several keyword arguments that you’ll explore in one of the upcoming sections.


On the other hand, if type safety is your main concern or you’d like to validate YAML documents against a schema, then have a look at StrictYAML, which intentionally restricts the YAML specification by disregarding its most risky features. Just keep in mind that it won’t run as quickly as the other two libraries.


Note: The PyYAML library used in this tutorial is based on the older YAML 1.1 specification, which supports base-60 numbers through the colon (:) notation. This means that a literal like 59:59 gets interpreted as an integer value of 3,599 because 59 × 601 + 59 × 600 adds up to it.


Common binary data serialization formats you’d find in the wild include Google’s Protocol Buffers and Apache’s Avro.


Implementations aside, YAML’s versatile, liberal, and complex syntax makes it by far the slowest to parse and serialize. On the other side of the spectrum, you’ll find JSON, whose grammar can fit on a business card. In contrast, YAML’s own grammar documentation claims that creating a fully compliant parser has proven almost impossible.


>>> yaml.safe_load("name: Иван".encode("utf-16"))
{'name': 'Иван'}


Don't Configure Control Flow
8 minute read
Learn why using YAML for control flow configuration can lead to complex and hard-to-understand code, and why it's better to use existing programming language...


##  Tasks  ï


##  Prerequisites  ï


Python Tricks Dictionary Merge
Email Address
About Bartosz Zaczyński


    from app.models import User

    def test_new_user():
        '''
        Given a User model
        When a new user is being logged in
        Check the User database columns
        '''

       # username  hashed_password  emai  confirmation_email  reset_email_password
        user = User('aiohrgihrtg', 'jotpjgjbgt','nojafa5998@royins.com', True, False)
        # Just for testing ?
        assert user.username == 'aiohrgihrtg'
        '''
        # check if the user exists in the other file by checking if email exists
        assert user.email == 'nojafa5998@royins.com'
        # check to make sure the hashed password doesn't contain plaintext.
        assert user.hashed_password!= 'jotpjgjbgt'
        # check if the email is registered
        assert user.confirmation_email == True
        '''


    """A pure Python implementation of import."""
    __all__ = ['__import__', 'import_module', 'invalidate_caches', 'reload']

    # Bootstrap help #####################################################

    # Until bootstrapping is complete, DO NOT import any modules that attempt
    # to import importlib._bootstrap (directly or indirectly). Since this
    # partially initialised package would be present in sys.modules, those
    # modules would get an uninitialised copy of the source version, instead
    # of a fully initialised version (either the frozen one or the one
    # initialised below if the frozen one is not available).
    import _imp  # Just the builtin component, NOT the full Python module
    import sys

    try:
        import _frozen_importlib as _bootstrap
    except ImportError:
        from . import _bootstrap
        _bootstrap._setup(sys, _imp)
    else:
        # importlib._bootstrap is the built-in import, ensure we don't create
        # a second copy of the module.
        _bootstrap.__name__ = 'importlib._bootstrap'
        _bootstrap.__package__ = 'importlib'
        try:
            _bootstrap.__file__ = __file__.replace('__init__.py', '_bootstrap.py')
        except NameError:
            # __file__ is not guaranteed to be defined, e.g. if this code gets
            # frozen by a tool like cx_Freeze.
            pass
        sys.modules['importlib._bootstrap'] = _bootstrap

    try:
        import _frozen_importlib_external as _bootstrap_external
    except ImportError:
        from . import _bootstrap_external
        _bootstrap_external._set_bootstrap_module(_bootstrap)
        _bootstrap._bootstrap_external = _bootstrap_external


fantastic!
The error disappeared by following your instruction!
Thank you very much for your help. ![:blush:](https://emoji.discourse-
cdn.com/twitter/blush.png?v=12)


* Change width


    from app.models import User

    def test_new_user():
        '''
        Given a User model
        When a new user is being logged in
        Check the User database columns
        '''

       # username  hashed_password  emai  confirmation_email  reset_email_password
        user = User('aiohrgihrtg', 'jotpjgjbgt','nojafa5998@royins.com', True, False)
        # Just for testing ?
        assert user.username == 'aiohrgihrtg'
        '''
        # check if the user exists in the other file by checking if email exists
        assert user.email == 'nojafa5998@royins.com'
        # check to make sure the hashed password doesn't contain plaintext.
        assert user.hashed_password!= 'jotpjgjbgt'
        # check if the email is registered
        assert user.confirmation_email == True
        '''

    app/tests/functional/test_login.py
    from app import create_appdef test_login_page():
        """
        GIVEN a Flask application configured for testing
        WHEN the '/login'page requested (GET)
        THEN check that the response is valid
        """
        # what is 'flask_test.cfg'?
        flask_app = create_app('flask_test.cfg')
        # The with statemnt allows you to open and close files safely by making sure there is no errors
        # What is test_client?  test_client makes requests to the application without running a live server
        # Use the test_client to check the route which is a get request
        with flask_app.test_client() as test_client:
            response = test_client.post('/login')
            """
            In Python, the assert statement is used to continue the execute if the given condition evaluates to True.


Copy link


Code:


I solved it, in api.py I imported:


conda list:


Yes, api.py and views.py are in the same directory.


[ ![@mitchellwills](https://avatars.githubusercontent.com/u/427009?s=80&v=4)
](/mitchellwills)


Repositories


    ================================================================================== short test summary info ==================================================================================
    ERROR  - ValueError: source code string cannot contain null bytes
    ! Interrupted: 1 error during collection !


__ Gold Member


[ mitchellwills ](/mitchellwills) opened this issue  Jan 6, 2015  · 15
comments


* Apr 20, 2022


> aniroodhs-mbp:ros_catkin_ws aniroodhravikumar$ which python
>  /opt/local/bin/python
>  aniroodhs-mbp:ros_catkin_ws aniroodhravikumar$ python --version
>  Python 2.7.14

---

All reactions


Sorry, something went wrong.


More options


[ ](https://github.com/)


I am getting the error still when I type pytest -m python .

.


[ KenWhitesell  ](https://forum.djangoproject.com/u/KenWhitesell) February 22,
2022, 12:53pm  2


Insert quotes…


Copy link


Please put your code and transcripts directly in code blocks instead of
linking to a pastebin. The pastebin linking destroys your code formatting,
which with Python is a big problem.


* Open Source


#  rosdep fails if pip is not installed  #367


Replies


* [ Insights  Schrödinger’s Cat and the Qbit ](/threads/schroedingers-cat-and-the-qbit.1061433/ "Schrödinger’s Cat and the Qbit")


error:


Have already tried it, I get the same error message


###  Footer navigation


|  2  |  1521  |  November 14, 2023
[ Heroku throws ModuleNotFoundError for app that is installed
](https://forum.djangoproject.com/t/heroku-throws-modulenotfounderror-for-app-
that-is-installed/24237)


[ Sign up
](/signup?ref_cta=Sign+up&ref_loc=header+logged+out&ref_page=%2F%3Cuser-
name%3E%2F%3Crepo-
name%3E%2Fvoltron%2Fissues_fragments%2Fissue_layout&source=header-
repo&source_repo=ros-infrastructure%2Frosdep)


Thank you for response


No milestone


> rgtr said:
>
> Here is the error.


Sorry, something went wrong.


#  Search code, repositories, users, issues, pull requests...


**[ NikolausDemmel ](/NikolausDemmel) ** commented  Apr 4, 2018


* [ Insights  The Slinky Drop Experiment Analysed ](/threads/the-slinky-drop-experiment-analysed.1061307/ "The Slinky Drop Experiment Analysed")


* Apr 20, 2022


    pyparsing                 2.4.7                      py_0    anaconda
    pytest                    7.1.1           py310haa95532_0
    python                    3.10.4               hbb2ffb3_0
    python-dateutil           2.8.1                      py_0    anaconda
    python-editor             1.0.4                      py_0    anaconda
    setuptools                61.2.0          py310haa95532_0
    six                       1.15.0                     py_0    anaconda
    sqlalchemy                1.4.32          py310h2bbff1b_0
    sqlite                    3.38.2               h2bbff1b_0
    tk                        8.6.11               h2bbff1b_0
    tomli                     1.2.2              pyhd3eb1b0_0
    tzdata                    2020b                h7b6447c_0    anaconda
    vc                        14.1                 h0510ff6_4    anaconda
    vs2015_runtime            14.16.27012          hf0eaf9b_3    anaconda
    werkzeug                  2.0.3              pyhd3eb1b0_0
    wheel                     0.35.1                     py_0    anaconda
    wincertstore              0.2             py310haa95532_2
    wtforms                   2.3.3                      py_0    anaconda
    xz                        5.2.5                h62dcd97_0    anaconda
    zipp                      3.3.1                      py_0    anaconda
    zlib                      1.2.11           vc14h1cdd9ab_1  [vc14]  anaconda


* [ Chemistry ](https://www.physicsforums.com/forums/chemistry.83/)


You signed in with another tab or window. [ Reload ]() to refresh your
session.  You signed out in another tab or window. [ Reload ]() to refresh
your session.  You switched accounts on another tab or window. [ Reload ]() to
refresh your session.  Dismiss alert


Close Menu


Ok, well in the case that a ` pip ` key is needed it will assert that ` pip `
is available, that is intended behavior. If that was the case then I'll close
this for now. Feel free to comment further, I can reopen the issue if
something is still left to be resolved.


[ Mystery Errors  ](/c/users/mystery-errors/22)


Powered by [ Discourse ](https://www.discourse.org) , best viewed with
JavaScript enabled


Views


[ Deployment  ](/c/users/deployment/24)


Greetings,


and, “python manage runserver” also success.


[ ![@wjwwood](https://avatars.githubusercontent.com/u/100427?s=80&v=4)
](/wjwwood)


Closed


Skip to content


* [ Python  Who can find the largest prime number with the own programmed code? ](/threads/who-can-find-the-largest-prime-number-with-the-own-programmed-code.1059010/ "Who can find the largest prime number with the own programmed code?")


* [ Insights Blog ](https://www.physicsforums.com/insights/)


##  2\. Why am I getting this error?


    * [ Enterprise ](/enterprise)
    * [ Teams ](/team)
    * [ Startups ](/enterprise/startups)
    * [ Education  ](https://education.github.com)


[ Chemistry ](https://www.physicsforums.com/forums/chemistry.83/) [ Biology
and Medical ](https://www.physicsforums.com/forums/biology-and-medical.82/) [
Earth Sciences ](https://www.physicsforums.com/forums/earth-sciences.84/) [
Computer Science ](https://www.physicsforums.com/forums/programming-and-
computer-science.165/) [ Computing and Technology
](https://www.physicsforums.com/forums/computing-and-technology.188/) [ DIY
Projects ](https://www.physicsforums.com/forums/diy-projects.264/)


1 Like


2 Likes


__ Mentor


Replies


New issue


Sorry, something went wrong.


[ Using Django  ](/c/users/6)


rgtr  __


Is this issue fixed? I am getting the same message as below by typing the
command


![](https://sea2.discourse-
cdn.com/business7/user_avatar/forum.djangoproject.com/mihamarkovi/48/9681_2.png)
MihaMarkovi:


[ Log in  ](/login/) [ Register  ](/login/register)


Woops, sorry. I ran the following in the root of my catkin workspace


Here is the error when I run python -m pytest


    * [ Actions  Automate any workflow  ](/features/actions)
    * [ Packages  Host and manage packages  ](/features/packages)
    * [ Security  Find and fix vulnerabilities  ](/features/security)
    * [ Codespaces  Instant dev environments  ](/features/codespaces)
    * [ Copilot  Write better code with AI  ](/features/copilot)
    * [ Code review  Manage code changes  ](/features/code-review)
    * [ Issues  Plan and track work  ](/features/issues)
    * [ Discussions  Collaborate outside of code  ](/features/discussions)


  * __
  * #2


__ Homework Helper


Views


What kind of setup is this that you have python in ` /opt/local/bin ` on a
mac? With homebrew it should be in ` /usr/local/bin ` or with system python in
` /usr/bin/python ` , I guess?


[ MihaMarkovi  ](https://forum.djangoproject.com/u/MihaMarkovi) August 16,
2022, 9:36am  9


[ ![@mitchellwills](https://avatars.githubusercontent.com/u/427009?s=80&v=4)
](/mitchellwills)


You can try checking for any typos in the module or package name, ensuring
that the module or package is installed correctly, or updating your code or
environment to be compatible with the module or package.


[ pbuk  ](/members/pbuk.385977/)


rosdep install -i --from-paths src


[ MihaMarkovi  ](https://forum.djangoproject.com/u/MihaMarkovi) August 16,
2022, 8:50am  7


                msg = ("the 'package' argument is required to perform a relative "
                       "import for {!r}")
                raise TypeError(msg.format(name))
            for character in name:
                if character != '.':
                    break
                level += 1
        return _bootstrap._gcd_import(name[level:], package, level)

    _RELOADING = {}

    def reload(module):
        """Reload the module and return it.

        The module must have been successfully imported before.

        """
        try:
            name = module.__spec__.name
        except AttributeError:
            try:
                name = module.__name__
            except AttributeError:
                raise TypeError("reload() argument must be a module")

        if sys.modules.get(name) is not module:
            msg = "module {} not in sys.modules"
            raise ImportError(msg.format(name), name=name)
        if name in _RELOADING:
            return _RELOADING[name]
        _RELOADING[name] = module
        try:
            parent_name = name.rpartition('.')[0]
            if parent_name:
                try:
                    parent = sys.modules[parent_name]
                except KeyError:
                    msg = "parent {!r} not in sys.modules"


from .models import Company


* [ How to change screen orientation in Godot with code? ](/threads/how-to-change-screen-orientation-in-godot-with-code.1057539/ "How to change screen orientation in Godot with code?")


I get the following error when I try to run server:


Sorry, something went wrong.


> python manage.py diffsettings


[ MihaMarkovi  ](https://forum.djangoproject.com/u/MihaMarkovi) August 16,
2022, 8:35am  5


[ KenWhitesell  ](https://forum.djangoproject.com/u/KenWhitesell) April 18,
2022, 11:28am  7


though I do have pip installed, which seems to suggest that the issue might be
with the directory that pip is installed in, so I will see if changing that
fixes the error.

---

All reactions


Share:


Is your current directory your project directory when you try to run django-
admin? If not, try it from there.


Any other django-admin commands such as makemessages is same.


    def main(args=None):
        rclpy.init(args=args)

        sensor = Vl53l1x_publisher()
        rclpy.on_shutdown(Vl53l1x_publisher.stop)
        rclpy.spin(sensor)

        # Destroy the node explicitly
        # (optional - otherwise it will be done automatically
        # when the garbage collector destroys the node object)
        sensor.destroy_node()
        rclpy.shutdown()

        return

    ### main ###

    if __name__ == '__main__':
        main()

    And then run:

        rosdep install --from-paths src -y --ignore-src
        . install/local_setup.bash
         ros2 run sensor_vl53l1x talker

####  Expected behavior
A running vl53l1x publisher module.
####  Actual behavior
$ conda activate rpi
(rpi) arnold@ockeghem:/media/i-files/home/arnold/development/ros2/bottie
$ . install/local_setup.bash
(rpi) arnold@ockeghem:/media/i-files/home/arnold/development/ros2/bottie
$ ros2 run sensor_vl53l1x talker
Traceback (most recent call last):
File
"/media/i-files/home/arnold/development/ros2/bottie/install/sensor_vl53l1x/lib/sensor_vl53l1x/talker",


     ERROR collecting test session _______________________________________________________________________________
    ..\..\..\..\anaconda3\envs\flaskblog2\lib\importlib\__init__.py:126: in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
    <frozen importlib._bootstrap>:1050: in _gcd_import
        ?
    <frozen importlib._bootstrap>:1027: in _find_and_load
        ?
    <frozen importlib._bootstrap>:992: in _find_and_load_unlocked
        ?
    <frozen importlib._bootstrap>:241: in _call_with_frames_removed
        ?
    <frozen importlib._bootstrap>:1050: in _gcd_import
        ?
    <frozen importlib._bootstrap>:1027: in _find_and_load
        ?
    <frozen importlib._bootstrap>:1006: in _find_and_load_unlocked
        ?
    <frozen importlib._bootstrap>:688: in _load_unlocked
        ?
    <frozen importlib._bootstrap_external>:879: in exec_module
        ?
    <frozen importlib._bootstrap_external>:1017: in get_code
        ?
    <frozen importlib._bootstrap_external>:947: in source_to_code
        ?
    <frozen importlib._bootstrap>:241: in _call_with_frames_removed
        ?
    E   ValueError: source code string cannot contain null bytes
    ===================================================================================== warnings summary ======================================================================================
    ..\..\..\..\anaconda3\envs\flaskblog2\lib\site-packages\flask_sqlalchemy\__init__.py:851
      C:\Users\nmyle\anaconda3\envs\flaskblog2\lib\site-packages\flask_sqlalchemy\__init__.py:851: UserWarning: Neither SQLALCHEMY_DATABASE_URI nor SQLALCHEMY_BINDS is set. Defaulting SQLALCHEMY_DATABASE_URI to "sqlite:///:memory:".
        warnings.warn(

    ..\..\..\..\anaconda3\envs\flaskblog2\lib\site-packages\flask_sqlalchemy\__init__.py:872
      C:\Users\nmyle\anaconda3\envs\flaskblog2\lib\site-packages\flask_sqlalchemy\__init__.py:872: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.  Set it to True or False to suppress this warning.
        warnings.warn(FSADeprecationWarning(

    -- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html


In any case, you should be able to upgrade / reinstall pip with ` python -m
pip install --force-reinstall -U pip ` , but you need check where the
executables are installed and make sure that directory is on your path...

---

All reactions


When installing the base ros system nothing appears to depend on pip. This
leads to issues when trying to use rosdep to install dependencies. I have
experienced this issue on hydro 12.04 and indigo 13.10. I get the following
error message when running rosdep


Post reply


TL;DR Summary


No one assigned


[ ros-infrastructure ](/ros-infrastructure) /  **[ rosdep ](/ros-
infrastructure/rosdep) ** Public


[ ![@wjwwood](https://avatars.githubusercontent.com/u/100427?s=80&v=4)
](/wjwwood)


Replies


No, I think you are not bootstrapping flask properly (or at all).

Take a look at e.g. [ https://testdriven.io/blog/flask-pytest/
](https://testdriven.io/blog/flask-pytest/)


Cancel  Submit feedback


* [ DIY Projects ](https://www.physicsforums.com/forums/diy-projects.264/)


You can add ` --simulate ` to get what it would try to install, that shouldn't
except if ` pip ` is not installed.

---

All reactions


* Solutions


I’m importing it as such in views.py:


line 33, in
sys.exit(load_entry_point('sensor-vl53l1x==0.0.0', 'console_scripts',
'talker')())
File
"/media/i-files/home/arnold/development/ros2/bottie/install/sensor_vl53l1x/lib/sensor_vl53l1x/talker",
line 25, in importlib_load_entry_point
return next(matches).load()
File "/usr/lib/python3.10/importlib/metadata/ **init** .py", line 171, in load
module = import_module(match.group('module'))
File "/usr/lib/python3.10/importlib/ **init** .py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "", line 1050, in _gcd_import
File "", line 1027, in _find_and_load
File "", line 1006, in _find_and_load_unlocked
File "", line 688, in _load_unlocked
File "", line 883, in exec_module
File "", line 241, in _call_with_frames_removed
File
"/media/i-files/home/arnold/development/ros2/bottie/install/sensor_vl53l1x/lib/python3.10/site-
packages/sensor_vl53l1x/vl53l1x_publisher.py", line 5, in
import board
File "/usr/local/lib/python3.10/dist-packages/board.py", line 22, in
from adafruit_blinka.agnostic import board_id, detector
File "/usr/local/lib/python3.10/dist-packages/adafruit_blinka/agnostic/
**init** .py", line 21, in
chip_id = detector.chip.id
File "/usr/local/lib/python3.10/dist-
packages/adafruit_platformdetect/chip.py", line 90, in id
import hid
ModuleNotFoundError: No module named 'hid'
[ros2run]: Process exited with failure 1
####  Additional information
I am not sure it is a bug. However, installing as root is warned against by
pip during install. Fact is that when I run the install of Adafruit-Blinka
myself as root I get exactly the same error. When I do this without sudo
everything works fine. Is there a reason to install as root? As far as I can
see it breaks as well the environments which are needed manging all these
libraries.

---


|  3  |  574  |  May 21, 2020
[ Django Tutorial Errors ](https://forum.djangoproject.com/t/django-tutorial-
errors/29671)


All reactions


__ Science Advisor


Have you also tried to kill you run_server and launch it again?


I can’t figure out the reason why django-admin command cause that error.
I would appreciate it if someone tell me it.


__ __ __


#  [ Issue with importing python file ](/t/issue-with-importing-python-
file/15447)


  * Apr 5, 2023
Programming and Computer Science


Cancel  Create saved search


* [ Insights  Digital Filtering and Exact Reconstruction of Digital Audio ](/threads/digital-filtering-and-exact-reconstruction-of-digital-audio.1058252/ "Digital Filtering and Exact Reconstruction of Digital Audio")


then `from .api import FOO’


##  5\. Is there a way to prevent this error from occurring?


![](https://sea2.discourse-
cdn.com/business7/user_avatar/forum.djangoproject.com/mihamarkovi/48/9681_2.png)
MihaMarkovi:


Sorry, something went wrong.


` rosdep install --from-paths src --ignore-src --rosdistro kinetic -y `


##  Use saved searches to filter your results more quickly


##  3\. How can I fix this error?


    * [ Topics ](/topics)
    * [ Trending ](/trending)
    * [ Collections ](/collections)


[ How can I fix the error in my custom Python exception class? ](/threads/how-
can-i-fix-the-error-in-my-custom-python-exception-class.484249/)


[ Using Django  ](/c/users/deployment/24) [ Deployment
](/c/users/deployment/24)


[ ![@wjwwood](https://avatars.githubusercontent.com/u/100427?s=80&v=4)
](/wjwwood)


  * [ Research team improves fuel cell durability with fatigue-resistant membranes ](https://techxplore.com/news/2024-02-team-fuel-cell-durability-fatigue.html)
  * [ Self-extinguishing batteries could reduce the risk of deadly and costly battery fires ](https://techxplore.com/news/2024-02-extinguishing-batteries-deadly-battery.html)
  * [ Chemists decipher reaction process that could improve lithium-sulfur batteries ](https://techxplore.com/news/2024-02-chemists-decipher-reaction-lithium-sulfur.html)


    from django.shortcuts import render, redirect
    from django.views import generic
    from django.views.generic.edit import FormMixin
    from .models import Bill, Company, Product
    from .forms import BillDetailsForm, ProductDetailsForm, CompanyDetailsForm
    from datetime import datetime
    from api import GetRequest # this one

    class IndexView(generic.ListView):
        template_name = 'racuni/index.html'
        context_object_name = 'bills_list'
        GetRequest()


    else:
        _bootstrap_external.__name__ = 'importlib._bootstrap_external'
        _bootstrap_external.__package__ = 'importlib'
        try:
            _bootstrap_external.__file__ = __file__.replace('__init__.py', '_bootstrap_external.py')
        except NameError:
            # __file__ is not guaranteed to be defined, e.g. if this code gets
            # frozen by a tool like cx_Freeze.
            pass
        sys.modules['importlib._bootstrap_external'] = _bootstrap_external

    # To simplify imports in test code
    _pack_uint32 = _bootstrap_external._pack_uint32
    _unpack_uint32 = _bootstrap_external._unpack_uint32

    # Fully bootstrapped at this point, import whatever you like, circular
    # dependencies and startup overhead minimisation permitting :)

    import warnings

    # Public API #########################################################

    from ._bootstrap import __import__

    def invalidate_caches():
        """Call the invalidate_caches() method on all meta path finders stored in
        sys.meta_path (where implemented)."""
        for finder in sys.meta_path:
            if hasattr(finder, 'invalidate_caches'):
                finder.invalidate_caches()

    def find_loader(name, path=None):
        """Return the loader for the specified module.

        This is a backward-compatible wrapper around find_spec().

        This function is deprecated in favor of importlib.util.find_spec().


rgtr  __


Views


I have the same issue as @taegoobot , and the issue seems to persist even
after pip is installed.

---

All reactions


##  4\. Can this error be caused by a missing dependency?


[ Search syntax tips ](https://docs.github.com/search-github/github-code-
search/understanding-github-code-search-syntax)


[ ![@wjwwood](https://avatars.githubusercontent.com/u/100427?s=52&v=4)
](/wjwwood) [
![@mitchellwills](https://avatars.githubusercontent.com/u/427009?s=52&v=4)
](/mitchellwills) [
![@NikolausDemmel](https://avatars.githubusercontent.com/u/479562?s=52&v=4)
](/NikolausDemmel) [ ![@bryan-
bisonai](https://avatars.githubusercontent.com/u/1245675?s=52&v=4) ](/bryan-
bisonai) [ ![@aniroodh-
ravikumar](https://avatars.githubusercontent.com/u/30080678?s=52&v=4)
](/aniroodh-ravikumar)


Skip to content
Toggle navigation
[ ](https://github.com/)
[ Sign in
](/login?return_to=https%3A%2F%2Fgithub.com%2Fros2%2Fros2%2Fissues%2F1478)
  * Product
    * [ Actions  Automate any workflow  ](/features/actions)
    * [ Packages  Host and manage packages  ](/features/packages)
    * [ Security  Find and fix vulnerabilities  ](/features/security)
    * [ Codespaces  Instant dev environments  ](/features/codespaces)
    * [ Copilot  Write better code with AI  ](/features/copilot)
    * [ Code review  Manage code changes  ](/features/code-review)
    * [ Issues  Plan and track work  ](/features/issues)
    * [ Discussions  Collaborate outside of code  ](/features/discussions)
Explore
    * [ All features ](/features)
    * [ Documentation  ](https://docs.github.com)
    * [ GitHub Skills  ](https://skills.github.com/)
    * [ Blog  ](https://github.blog)
  * Solutions
For
    * [ Enterprise ](/enterprise)
    * [ Teams ](/team)
    * [ Startups ](/enterprise/startups)
    * [ Education  ](https://education.github.com)
By Solution
    * [ CI/CD & Automation ](/solutions/ci-cd/)
    * [ DevOps ](/solutions/devops/)
    * [ DevSecOps  ](https://resources.github.com/devops/fundamentals/devsecops/)
Resources
    * [ Learning Pathways  ](https://resources.github.com/learn/pathways/)
    * [ White papers, Ebooks, Webinars  ](https://resources.github.com/)
    * [ Customer Stories ](/customer-stories)
    * [ Partners  ](https://partner.github.com/)
  * Open Source
    * [ GitHub Sponsors  Fund open source developers  ](/sponsors)
    * [ The ReadME Project  GitHub community articles  ](/readme)
Repositories
    * [ Topics ](/topics)
    * [ Trending ](/trending)


  * [ Security  ](/ros2/ros2/security)
  * [ Insights  ](/ros2/ros2/pulse)
Additional navigation options
  * [ Code  ](/ros2/ros2)
  * [ Issues  ](/ros2/ros2/issues)
  * [ Pull requests  ](/ros2/ros2/pulls)
  * [ Actions  ](/ros2/ros2/actions)
  * [ Security  ](/ros2/ros2/security)
  * [ Insights  ](/ros2/ros2/pulse)
New issue
**Have a question about this project?** Sign up for a free GitHub account to
open an issue and contact its maintainers and the community.
Pick a username

Email Address

Password

Sign up for GitHub
By clicking “Sign up for GitHub”, you agree to our [ terms of service
](https://docs.github.com/terms) and [ privacy statement
](https://docs.github.com/privacy) . We’ll occasionally send you account
related emails.
Already on GitHub? [ Sign in
](/login?return_to=%2Fros2%2Fros2%2Fissues%2Fnew%2Fchoose) to your account
Jump to bottom
#  Rosdep - installing as sudo results in dependency errors  #1478
Closed
[ RnoldR ](/RnoldR) opened this issue  Aug 28, 2023  · 2 comments
Closed
#  Rosdep - installing as sudo results in dependency errors  #1478
[ RnoldR ](/RnoldR) opened this issue  Aug 28, 2023  · 2 comments
##  Comments
[ ![@RnoldR](https://avatars.githubusercontent.com/u/9727056?s=80&v=4)
](/RnoldR)
Copy link
###
**[ RnoldR ](/RnoldR) ** commented  Aug 28, 2023


Thank you for helping me ![:smiley:](https://emoji.discourse-
cdn.com/twitter/smiley.png?v=12)


By clicking “Sign up for GitHub”, you agree to our [ terms of service
](https://docs.github.com/terms) and [ privacy statement
](https://docs.github.com/privacy) . We’ll occasionally send you account
related emails.


    Traceback (most recent call last):
      File "/home/akakatsu/.local/lib/python3.10/site-packages/django/core/management/base.py", line 373, in run_from_argv
        self.execute(*args, **cmd_options)
      File "/home/akakatsu/.local/lib/python3.10/site-packages/django/core/management/base.py", line 412, in execute
        self.check()
      File "/home/akakatsu/.local/lib/python3.10/site-packages/django/core/management/base.py", line 438, in check
        all_issues = checks.run_checks(
      File "/home/akakatsu/.local/lib/python3.10/site-packages/django/core/checks/registry.py", line 77, in run_checks
        new_errors = check(app_configs=app_configs, databases=databases)
      File "/home/akakatsu/.local/lib/python3.10/site-packages/django/core/checks/caches.py", line 62, in check_file_based_cache_is_absolute
        for alias, config in settings.CACHES.items():
      File "/home/akakatsu/.local/lib/python3.10/site-packages/django/conf/__init__.py", line 84, in __getattr__
        self._setup(name)
      File "/home/akakatsu/.local/lib/python3.10/site-packages/django/conf/__init__.py", line 71, in _setup
        self._wrapped = Settings(settings_module)
      File "/home/akakatsu/.local/lib/python3.10/site-packages/django/conf/__init__.py", line 179, in __init__
        mod = importlib.import_module(self.SETTINGS_MODULE)
      File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
      File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
      File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
      File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked
      File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
      File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
      File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
      File "<frozen importlib._bootstrap>", line 992, in _find_and_load_unlocked
      File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
      File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
      File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
      File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked
    ModuleNotFoundError: No module named 'KFIPtutorial'


**[ aniroodh-ravikumar ](/aniroodh-ravikumar) ** commented  Apr 4, 2018


[ Contact us ](/misc/contact)


[ AK-8420  ](https://forum.djangoproject.com/u/AK-8420) February 22, 2022,
4:48am  1


**[ wjwwood ](/wjwwood) ** commented  Jan 6, 2015


I have already try to import like .api or app.api but didn’t work. When i
delete import of api, application starts working again.


I guess I was mistaken, it will except if you use ` --simulate ` , but it will
not when nothing in your workspace depends on a key which resolves to ` pip `
. I just tested it by getting ` ros_base ` 's source and uninstall ` pip ` ,
then adding the ` python-cpplint ` depend to catkin's ` package.xml ` .

---

All reactions


I'm afraid there are too many unknowns here to effectively provide direct
help, you are going to need to work this out yourself.

Try removing all your test files except one with a trivial test like assert
1=1. If that works you know that pytest is working.

Add a unit test like your User model test. If that works then good; if it
doesn't then work out why: if your model uses SQL then obviously it will need
some configuration of a test database to work.

Add a SIMPLE functional test like get /...

Add more complex functional test like your post /login which presumably
expects some encoded data in the body which it checks against a user database
which will need to be mocked in test.cfg.

Alternatively start again from scratch following one of the many flask+pytest
app development tutorials out there.


> Content of get.py:


    ├── db.sqlite3
    ├── geckodriver.log
    ├── locale
    ├── requirements.txt
    └── staticfiles


|  6  |  6946  |  August 4, 2022
[ ModuleNotFoundError
](https://forum.djangoproject.com/t/modulenotfounderror/3404)


However, when I try to run pip --version, I get:


instead of:


Name


[ Sign in ](/login?return_to=https%3A%2F%2Fgithub.com%2Fros-
infrastructure%2Frosdep%2Fissues%2F367)


[ \-- Browse All Articles --
](https://www.physicsforums.com/insights/postindex/) [ Physics Articles
](https://www.physicsforums.com/insights/science-math-articles/physics-
articles/) [ Physics Tutorials
](https://www.physicsforums.com/insights/science-math-tutorials/physics-
tutorials/) [ Physics Guides ](https://www.physicsforums.com/insights/science-
math-guides/physics-guides/) [ Physics FAQ
](https://www.physicsforums.com/insights/science-math-faqs/physics-faqs/) [
Math Articles ](https://www.physicsforums.com/insights/science-math-
articles/math-articles/) [ Math Tutorials
](https://www.physicsforums.com/insights/science-math-tutorials/math-
tutorials/) [ Math Guides ](https://www.physicsforums.com/insights/science-
math-guides/math-guides/) [ Math FAQ
](https://www.physicsforums.com/insights/science-math-faqs/math-faqs/) [
Education Articles ](https://www.physicsforums.com/insights/science-math-
articles/education-articles/) [ Education Guides
](https://www.physicsforums.com/insights/science-math-guides/education-
guides/) [ Bio/Chem Articles ](https://www.physicsforums.com/insights/science-
math-articles/biology-chemistry-articles/) [ Technology Guides
](https://www.physicsforums.com/insights/science-math-guides/technology-
guides/) [ Computer Science Tutorials
](https://www.physicsforums.com/insights/science-math-tutorials/computer-
science-tutorials/)


Everywhere  Threads  This forum  This thread


In the file in the pastebin above I am getting the error Import
"_frozen_importlib" could not be resolved.

I tried googling this and just can't seem to solve it.
Do you think this could be an error with conda?

Thanks for the help.


    KFIPtutorial (project name)
    │
    ├── manage.py
    ├── KFIPtutorial
    │   ├── __init__.py
    │   │
    │   ├── setting_base.py
    │   ├── setting_local.py      (import setting_base.py)
    │   ├── setting_production.py (import setting_base.py)
    │   │
    │   ├── urls.py
    │   ├── asgi.py
    │   └── wsgi.py
    ├── Procfile
    ├── README.md
    ├── blackjack (my app)
    │   ├── static
    │   ├── templates
    │   ├── locale
    │   ├── migrations
    │   ├── fixtures
    │   │
    │   ├── __init__.py
    │   ├── admin.py
    │   ├── apps.py
    │   ├── forms.py
    │   ├── models.py
    │   ├── tests.py
    │   ├── urls.py
    │   ├── views.py
    │   │
    │   ├── node_modules
    │   ├── src
    │   │
    │   ├── babel.config.json
    │   ├── package-lock.json
    │   ├── package.json
    │   └── webpack.config.js


Python  [ FineTune the Pixel2Style2Pixel model with my custom data set
](/threads/finetune-the-pixel2style2pixel-model-with-my-custom-data-
set.1051365/)


**[ mitchellwills ](/mitchellwills) ** commented  Jan 6, 2015


Last edited:  Apr 19, 2022


Jump to bottom


Contributor


__ __ __


Topic  |  |  Replies  |  Views  |  Activity
---|---|---|---|---
[ Django configuration error ](https://forum.djangoproject.com/t/django-
configuration-error/25307)


  * [ Notifications ](/login?return_to=%2Fros-infrastructure%2Frosdep)
  * [ Fork  164  ](/login?return_to=%2Fros-infrastructure%2Frosdep)
  * [ Star  71  ](/login?return_to=%2Fros-infrastructure%2Frosdep)


JavaScript is disabled. For a better experience, please enable JavaScript in
your browser before proceeding.


Copy link


  * [ Contact ](/misc/contact)
  * [ About ](https://www.physicsforums.com/insights/about-physics-forums/)
  * [ Terms ](https://www.physicsforums.com/help/terms-of-service/)
  * [ Privacy ](https://www.physicsforums.com/help/member-privacy-policy/)
  * [ Help ](/help/)
  * [ __ RSS  ](/forums/-/index.rss "RSS")


Yes, you need to make sure that ` pip ` is runnable from the shell.


Sorry, I made a typo.


                    raise ImportError(msg.format(parent_name),
                                      name=parent_name) from None
                else:
                    pkgpath = parent.__path__
            else:
                pkgpath = None
            target = module
            spec = module.__spec__ = _bootstrap._find_spec(name, pkgpath, target)
            if spec is None:
                raise ModuleNotFoundError(f"spec not found for the module {name!r}", name=name)
            _bootstrap._exec(spec, module)
            # The module may have replaced itself in sys.modules!
            return sys.modules[name]
        finally:
            try:
                del _RELOADING[name]
            except KeyError:
                pass


* [ Biology and Medical ](https://www.physicsforums.com/forums/biology-and-medical.82/)


Sorry, something went wrong.


from models import Company


Query


##  Comments


* [ Pricing ](/pricing)


Powered by [ Discourse ](https://www.discourse.org) , best viewed with
JavaScript enabled


> export DJANGO_SETTINGS_MODULE=KFIPtutorial.setting_local
>  django-admin dumpdata -a


Author


[ Mystery Errors  ](/c/users/mystery-errors/22)


Navigation


* [ Forums ](https://www.physicsforums.com/)


    Django version 4.0.2, using settings 'KFIPtutorial.setting_local'
    Starting development server at http://127.0.0.1:8000/
    Quit the server with CONTROL-C.


Copy link


__ Share


[ pbuk  ](/members/pbuk.385977/)


**[ NikolausDemmel ](/NikolausDemmel) ** commented  Dec 28, 2017


  * [ Terms ](https://docs.github.com/site-policy/github-terms/github-terms-of-service)
  * [ Privacy ](https://docs.github.com/site-policy/privacy-policies/github-privacy-statement)
  * [ Security ](/security)
  * [ Status ](https://www.githubstatus.com/)
  * [ Docs ](https://docs.github.com/)
  * [ Contact ](https://support.github.com?tags=dotcom-footer)
  * Manage cookies
  * Do not share my personal information


* [ GitHub Sponsors  Fund open source developers  ](/sponsors)


    # Name                    Version                   Build  Channel
    alembic                   1.4.3                      py_0    anaconda
    atomicwrites              1.4.0                      py_0    anaconda
    attrs                     20.2.0                     py_0    anaconda
    bcrypt                    3.2.0           py310h2bbff1b_0
    blinker                   1.4             py310haa95532_0
    bootstrap                 4.4.1                         0    conda-forge
    bzip2                     1.0.8                he774522_0    anaconda
    ca-certificates           2020.10.14                    0    anaconda
    certifi                   2021.5.30       py310haa95532_0
    cffi                      1.15.0          py310h2bbff1b_1
    click                     7.1.2                      py_0    anaconda
    colorama                  0.4.4                      py_0    anaconda
    dataclasses               0.8                pyh6d0b6a4_7
    dnspython                 1.16.0          py310haa95532_0
    email-validator           1.1.1                      py_0    anaconda
    flask                     2.0.3              pyhd3eb1b0_0
    flask-login               0.5.0              pyhd3eb1b0_0
    flask-mail                0.9.1                      py_2    conda-forge
    flask-migrate             3.1.0              pyhd8ed1ab_0    conda-forge
    flask-sqlalchemy          2.5.1              pyhd3eb1b0_0
    flask-wtf                 0.15.1             pyhd3eb1b0_0
    greenlet                  1.1.1           py310hd77b12b_0
    idna                      2.10                       py_0    anaconda
    importlib-metadata        2.0.0                      py_1    anaconda
    importlib_metadata        2.0.0                         1    anaconda
    iniconfig                 1.1.1                      py_0    anaconda
    itsdangerous              2.0.1              pyhd3eb1b0_0
    jinja2                    3.0.3              pyhd3eb1b0_0
    libffi                    3.4.2                h604cdb4_1
    mako                      1.1.3                      py_0    anaconda
    markupsafe                2.0.1           py310h2bbff1b_0
    openssl                   1.1.1n               h2bbff1b_0
    packaging                 20.4                       py_0    anaconda
    pip                       21.2.4          py310haa95532_0
    pluggy                    0.12.0                     py_0    anaconda
    py                        1.9.0                      py_0    anaconda
    pycparser                 2.20                       py_2    anaconda


##  1\. What does the error "Import "_frozen_importlib" could not be resolved"
mean?


            return

        ### __init__ ###

        def timer_callback(self):
            # create an integer message
            msg = Int32()

            # assign data
            msg.data = self.sensor.distance

            # publish the data
            self.publisher_.publish(msg)

            # show what you have seen
            self.get_logger().info(f'Distance published: {msg.data} cm.')
            self.i += 1

            return

        ### timer_callback ###

        def start(self):
            # self.sensor.start()

            return

        ### start ###

        def stop(self):
            # self.sensor.stop()

            return

        ### stop ###

    ### Class: Vl53l1xWrapper ###


    ERROR: Rosdep experienced an internal error.
    Please go to the rosdep page [1] and file a bug report with the message below.
    [1] : http://www.ros.org/wiki/rosdep

    rosdep version: 0.11.8

    Bad installer [pip]: [Errno 2] No such file or directory: 'pip': 'pip'

---

All reactions


Password


    Watching for file changes with StatReloader
    Performing system checks...

    Exception in thread django-main-thread:
    Traceback (most recent call last):
      File "/usr/lib/python3.10/threading.py", line 1009, in _bootstrap_inner
        self.run()
      File "/usr/lib/python3.10/threading.py", line 946, in run
        self._target(*self._args, **self._kwargs)
      File "/home/person/.local/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper
        fn(*args, **kwargs)
      File "/home/person/.local/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 134, in inner_run
        self.check(display_num_errors=True)
      File "/home/person/.local/lib/python3.10/site-packages/django/core/management/base.py", line 487, in check
        all_issues = checks.run_checks(
      File "/home/person/.local/lib/python3.10/site-packages/django/core/checks/registry.py", line 88, in run_checks
        new_errors = check(app_configs=app_configs, databases=databases)
      File "/home/person/.local/lib/python3.10/site-packages/django/core/checks/urls.py", line 42, in check_url_namespaces_unique
        all_namespaces = _load_all_namespaces(resolver)
      File "/home/person/.local/lib/python3.10/site-packages/django/core/checks/urls.py", line 61, in _load_all_namespaces
        url_patterns = getattr(resolver, "url_patterns", [])
      File "/home/person/.local/lib/python3.10/site-packages/django/utils/functional.py", line 49, in __get__
        res = instance.__dict__[self.name] = self.func(instance)
      File "/home/person/.local/lib/python3.10/site-packages/django/urls/resolvers.py", line 696, in url_patterns
        patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
      File "/home/person/.local/lib/python3.10/site-packages/django/utils/functional.py", line 49, in __get__
        res = instance.__dict__[self.name] = self.func(instance)
      File "/home/person/.local/lib/python3.10/site-packages/django/urls/resolvers.py", line 689, in urlconf_module
        return import_module(self.urlconf_name)
      File "/usr/lib/python3.10/importlib/__init__.py", line 126, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
      File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
      File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
      File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
      File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
      File "<frozen importlib._bootstrap_external>", line 883, in exec_module
      File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
      File "/home/person/job/project/project/urls.py", line 21, in <module>


` from .get import GetRequest ` ?


|  1  |  1535  |  November 8, 2020
[ django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
](https://forum.djangoproject.com/t/django-core-exceptions-
appregistrynotready-apps-arent-loaded-yet/27293)


__ __ __


> -bash: /usr/local/bin/pip: No such file or directory


* [ Insights  How to Solve a Multi-Atwood Machine Assembly ](/threads/how-to-solve-a-multi-atwood-machine-assembly.1060080/ "How to Solve a Multi-Atwood Machine Assembly")


Copy link


[ ![@wjwwood](https://avatars.githubusercontent.com/u/100427?s=40&v=4)
](/wjwwood) [ wjwwood ](/wjwwood) closed this as [ completed ](/ros-
infrastructure/rosdep/issues?q=is%3Aissue+is%3Aclosed+archived%3Afalse+reason%3Acompleted)
Jan 6, 2015


---

All reactions
Sorry, something went wrong.
[ ![@RnoldR](https://avatars.githubusercontent.com/u/9727056?s=40&v=4)
](/RnoldR) [ RnoldR ](/RnoldR) closed this as [ completed
](/ros2/ros2/issues?q=is%3Aissue+is%3Aclosed+archived%3Afalse+reason%3Acompleted)
Aug 28, 2023
[ Sign up for free ](/join?source=comment-repo) **to join this conversation on
GitHub** . Already have an account? [ Sign in to comment
](/login?return_to=https%3A%2F%2Fgithub.com%2Fros2%2Fros2%2Fissues%2F1478)
Assignees
No one assigned
Labels
None yet
Projects
None yet
Milestone
No milestone
Development
No branches or pull requests
2 participants
[ ![@gavanderhoorn](https://avatars.githubusercontent.com/u/4550046?s=52&v=4)
](/gavanderhoorn) [
![@RnoldR](https://avatars.githubusercontent.com/u/9727056?s=52&v=4)
](/RnoldR)
##  Footer
[ ](https://github.com "GitHub") © 2024 GitHub, Inc.
###  Footer navigation
  * [ Terms ](https://docs.github.com/site-policy/github-terms/github-terms-of-service)
  * [ Privacy ](https://docs.github.com/site-policy/privacy-policies/github-privacy-statement)
  * [ Security ](/security)
  * [ Status ](https://www.githubstatus.com/)
  * [ Docs ](https://docs.github.com/)
  * [ Contact ](https://support.github.com?tags=dotcom-footer)
  * Manage cookies
  * Do not share my personal information
You can’t perform that action at this time.


[ __ Insights Author
](https://www.physicsforums.com/insights/author/PeterDonis/)


|  16  |  40310  |  March 22, 2022
[ ModuleNotFoundError: No module named 'macelleria_progetto.settings'
](https://forum.djangoproject.com/t/modulenotfounderror-no-module-named-
macelleria-progetto-settings/7487)


|  5  |  10994  |  December 15, 2021
[ __import__() error? ](https://forum.djangoproject.com/t/import-error/2545)


Content of **api.py**


[ Getting Started  ](/c/users/getting-started/16)


[ plopidou  ](https://forum.djangoproject.com/u/plopidou) August 16, 2022,
8:19am  2


        """
        warnings.warn('Deprecated since Python 3.4 and slated for removal in '
                      'Python 3.12; use importlib.util.find_spec() instead',
                      DeprecationWarning, stacklevel=2)
        try:
            loader = sys.modules[name].__loader__
            if loader is None:
                raise ValueError('{}.__loader__ is None'.format(name))
            else:
                return loader
        except KeyError:
            pass
        except AttributeError:
            raise ValueError('{}.__loader__ is not set'.format(name)) from None

        spec = _bootstrap._find_spec(name, path)
        # We won't worry about malformed specs (missing attributes).
        if spec is None:
            return None
        if spec.loader is None:
            if spec.submodule_search_locations is None:
                raise ImportError('spec for {} missing loader'.format(name),
                                  name=name)
            raise ImportError('namespace packages do not have loaders',
                              name=name)
        return spec.loader

    def import_module(name, package=None):
        """Import a module.

        The 'package' argument is required when performing a relative import. It
        specifies the package to use as the anchor point from which to resolve the
        relative import to an absolute import.

        """
        level = 0
        if name.startswith('.'):
            if not package:


[ mitchellwills ](/mitchellwills) opened this issue  Jan 6, 2015  · 15
comments


Milestone


###  Related Topics


[ MihaMarkovi  ](https://forum.djangoproject.com/u/MihaMarkovi) August 16,
2022, 8:23am  3


**[ wjwwood ](/wjwwood) ** commented  Jan 6, 2015


[ ![@aniroodh-
ravikumar](https://avatars.githubusercontent.com/u/30080678?s=80&u=04eb43d29f4d17087678782b5cae8bdf2c7b127a&v=4)
](/aniroodh-ravikumar)


Include my email address so I can be contacted


[ Using Django  ](/c/users/getting-started/16) [ Getting Started
](/c/users/getting-started/16)


__ Science Advisor


* [ The ReadME Project  GitHub community articles  ](/readme)


In summary, the conversation is about an error that occurs when running a
command in Python. The error is related to a source code string containing
null bytes. The conversation also includes warnings and a short summary of the
error. Additionally, the conversation mentions importing certain modules and
using deprecated functions. The conversation also includes a code snippet for
a Python implementation of import.


|  0  |  244  |  September 30, 2023
[ ModuleNotFoundError - but it exists.
](https://forum.djangoproject.com/t/modulenotfounderror-but-it-exists/15222)


Closed


Author


[ ![Physics Forums: Science Discussion, Homework Help,
Articles](https://www.physicsforums.com/styles/physicsforums/xenforo/logo.png)
![Physics Forums: Science Discussion, Homework Help,
Articles](https://www.physicsforums.com/styles/physicsforums/xenforo/logosmall.png)
](/)


Copy link


Could you provide the command you ran to produce this error?

---

All reactions


  * __
  * #6


* Apr 19, 2022


Not sure what you mean. Did you read the responses? The issue should be the
same as always, i.e. it would be great if the error message read differently.


5 participants


* [ Insights  The Lambert W Function in Finance ](/threads/the-lambert-w-function-in-finance.1059849/ "The Lambert W Function in Finance")


###  Search


[ ![@NikolausDemmel](https://avatars.githubusercontent.com/u/479562?s=80&v=4)
](/NikolausDemmel)


* [ Automatically adjust font size in Godot to fit text in a label? ](/threads/automatically-adjust-font-size-in-godot-to-fit-text-in-a-label.1059046/ "Automatically adjust font size in Godot to fit text in a label?")


Sign up for GitHub