source ros2 within a python script

asked 2023-05-09 21:49:47 -0500

fury.nerd gravatar image

hi, is it possible do the source /opt/ros/foxy/setup.bash within a python script, then no need do that in terminal before run the py script?

I tried

    import os
    os.system("source /opt/ros/foxy/setup.bash")
    os.popen("source /opt/ros/foxysetup.bash")  

    import subprocess
    subprocess.call("source /opt/ros/foxy/setup.bash") 
    subprocess.Popen("source /opt/ros/foxy/setup.bash") 

    import rclpy

but none works, always get error like

FileNotFoundError: [Errno 2] No such file or directory: 'source /opt/ros/foxy/setup.bash'

edit retag flag offensive close merge delete

Comments

I understand your logic, but commands like ros2 run <pkg> <prog> will never run, since ROS doesn't know, where that pkg/prog is located. If you use the python way ($python3 <file.py>) did you try removing the source word in your code? Something like:

 import os
    os.system("/opt/ros/foxy/setup.bash")
Andromeda gravatar image Andromeda  ( 2023-05-10 09:49:38 -0500 )edit

os.system("/opt/ros/foxy/setup.bash") comes out error ModuleNotFoundError: No module named 'rclpy'

fury.nerd gravatar image fury.nerd  ( 2023-05-10 19:23:04 -0500 )edit

How do you call your script? Something like:

$python3 myprog.py

or like:

$ros2 run mypkg myprog

???

Andromeda gravatar image Andromeda  ( 2023-05-11 12:22:00 -0500 )edit

As far as I know the bash command are active in the shell, where you called them. I really do not know, how it behaves, if the bash commands are called from inside a python program

Andromeda gravatar image Andromeda  ( 2023-05-11 12:23:40 -0500 )edit

thanks for discussion, I call the script like python3 myprog.py and that's why i wish include source ..../setup.bash inside. to be precisely, shebang is declared within myprog.py as #!/bin/usr/env python3, and I directly call ./myprog.py in the terminal.

fury.nerd gravatar image fury.nerd  ( 2023-05-11 19:27:27 -0500 )edit

Maybe it is a stupid idea, but could you create 2 different python files: file #1 sources only the setup.bash file and nothing else. File #2 is your ros program without any open or subprocess calls. If they works indipendently from each other, then it should be possible to join them later in a single file.

Andromeda gravatar image Andromeda  ( 2023-05-12 02:20:41 -0500 )edit

Look to this answer

Andromeda gravatar image Andromeda  ( 2023-05-12 02:35:32 -0500 )edit

thx, it's some issue about env, i think i can export these envs within py, but just wonder if there is a simple way. after all, after compare the env before/after source, there were not less to concern...

fury.nerd gravatar image fury.nerd  ( 2023-05-14 20:17:53 -0500 )edit