source ros2 within a python script
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'
Asked by fury.nerd on 2023-05-09 21:49:47 UTC
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 thesourceword in your code? Something like:Asked by Andromeda on 2023-05-10 09:49:38 UTC
os.system("/opt/ros/foxy/setup.bash")comes out errorModuleNotFoundError: No module named 'rclpy'Asked by fury.nerd on 2023-05-10 19:23:04 UTC
How do you call your script? Something like:
or like:
???
Asked by Andromeda on 2023-05-11 12:22:00 UTC
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
Asked by Andromeda on 2023-05-11 12:23:40 UTC
thanks for discussion, I call the script like
python3 myprog.pyand that's why i wish includesource ..../setup.bashinside. to be precisely,shebangis declared withinmyprog.pyas#!/bin/usr/env python3, and I directly call./myprog.pyin the terminal.Asked by fury.nerd on 2023-05-11 19:27:27 UTC
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
openorsubprocesscalls. If they works indipendently from each other, then it should be possible to join them later in a single file.Asked by Andromeda on 2023-05-12 02:20:41 UTC
Look to this answer
Asked by Andromeda on 2023-05-12 02:35:32 UTC
thx, it's some issue about
env, i think i can export theseenvs withinpy, but just wonder if there is a simple way. after all, after compare theenvbefore/aftersource, there were not less to concern...Asked by fury.nerd on 2023-05-14 20:17:53 UTC