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'
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 thesource
word in your code? Something like:os.system("/opt/ros/foxy/setup.bash")
comes out errorModuleNotFoundError: No module named 'rclpy'
How do you call your script? Something like:
or like:
???
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
thanks for discussion, I call the script like
python3 myprog.py
and that's why i wish includesource ..../setup.bash
inside. to be precisely,shebang
is declared withinmyprog.py
as#!/bin/usr/env python3
, and I directly call./myprog.py
in the terminal.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
orsubprocess
calls. If they works indipendently from each other, then it should be possible to join them later in a single file.Look to this answer
thx, it's some issue about
env
, i think i can export theseenv
s withinpy
, but just wonder if there is a simple way. after all, after compare theenv
before/aftersource
, there were not less to concern...