pythonroscatkinpx4

How can I import system packages (i.e. rospy, std_msgs, geoemtry_msgs) into my virtual environment that's using python2?


Previously, I had installed PX4 Firmware, ROS, and Gazebo using:

wget https://raw.githubusercontent.com/PX4/Devguide/master/build_scripts/ubuntu_sim_ros_melodic.sh
bash ubuntu_sim_ros_melodic.sh

I believe these two lines install all the packages needed for ROS and whatnot and I just needed to install python 2.7 because I am running ros-melodic. However, I had tried to install anaconda and then I tried to import the needed packages (rospy, std_msgs, geometry_msgs <- couldn't find geometry_msgs), but it was running on Python 3.8. I decided to uninstall anaconda in the end because I keep hearing that it is difficult to work with ros in a conda environment. Since I already have python2.7 on my machine for some reason, I just went ahead to create a python virtual environment instead and there is a lot of tutorial on how to do this anyways.

First I created a ros workspace with catkin

mkdir -p drone/src
catkin_make
cd src
catkin_create_pkgs bigdrone std_msgs geometry_msgs rospy

I open Pycharm-Professional and set the interpreter from drone/venv/bin/python. Now I tried to import my packages again, but all of them are missing. I thought maybe it is because it can't find the packages because it is a virtual environment, so I switched to the python in /usr/bin/python2.7. The packages I needed are still missing but I do have access to some like rosdep and whatnot. In addition when I simply run on the terminal:

python
>>> import rospy
>>> import std_msgs
>>> import geometry_msgs

Everything seems to work just fine for some reason.


Solution

  • The reason it cannot find those packages in Pycharm, but can from your terminal, is you have run source /opt/ros/melodic/setup.bash in your terminal. This file sets environmental variables and will update PYHTONPATH to include ros specific modules like the ones you mentioned. You can probably get it to work by starting Pycharm from a terminal that has the file in /opt/ sourced.

    That being said, a more complete solution is to add the ros distpackages to your virtual environment. You can find the steps to add an external package here and the path you want to add is /opt/ros/melodic/lib/python2.7/distpackages. After that you can go to File > Settings > Project: > Project interpreter. From there you can specify the ROS Python interpreter from the list.