Run a python file outside the package_name folder

Hi, I read the documentation

I created a python file inside <package_name> folder then using ros2 run …
It works very well

But if I try to run a python file from another folder outside <package_name> folder, it will not work.
How can I run the python file outside <package_name> folder

Thanks

ros2 run only works for Python executable created within the ROS system and specifications, and properly specified in setup.py. You cannot use it for running any random Python executable.

You can, however, run a Python file the traditional way:

python /path/to/your/python_file.py

Please note that this might not work if your Python code is supposed to access ROS resources. If that is the case, they you must create it the “ROS way.”

Btw, why do you want to have the Python file outside the package?

I learned from ROS1. We create a script folder then creating python files in the folder.
I want to keep it in ROS2 but it does not work ^^.

So I am curious how I can do it the same as ROS1?

You can include other files in the console_scripts section of the setup.py file, as indicated in the image below:

  1. Create the other script(s) beside your main script.
  2. Add another entry (or entries) for the extra scripts in the console_scripts array.

PS: I think it’s named “console scripts” because we can have two or more scripts there :slight_smile:


After adding new scripts, you need to recompile:

cd ~/ros2_ws
rm -rf build/ install/ log/
colcon build
source install/setup.bash

You create a Python file inside the folder with the same name as the package name.

I read the documents, it works well.

In ROS1, we create a folder named script (not inside the folder same name as the package name) and then create a Python file. I still use the command “ros run”. But ros2 run does not work like that

So my question is if there is any way I can do ros2 run with the python file inside script folder that not inside the “package name” folder?

Hi @NguyenDuyDuc ,

Yes, you can. You need to make that package as ament_cmake_python type.

Refer to these links:

  1. ament_cmake_python user documentation — ROS 2 Documentation: Humble documentation
  2. Create a ROS2 package for Both Python and Cpp Nodes - The Robotics Back-End

I am sure you can get your problem solved from those two links. Let me know if you still have issues after following those pages.

Regards,
Girish

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.