Premises

I have a version of ros_comm cloned from GitHub.

  • Ubuntu 16.04
  • ROS Lunar

Problem

In PyCharm Professional 2018.1.1, no completion for rospy was shown. The message said:

Cannot find reference 'init_node' in '__init__.py'

Screenshot of the error message

TL;DR

If $( rospack find rospy )/src exists, add it to PYTHONPATH.

Cause of the Problem

After sourcing setup.bash (and friends), PYTHONPATH points to /path/to/workspace/devel/lib/python2.7/dist-packages. Doing import rospy in the Python script uses the following __init__.py:

# -*- coding: utf-8 -*-
# generated from catkin/cmake/template/__init__.py.in
# keep symbol table as clean as possible by deleting all unnecessary symbols

from os import path as os_path
from sys import path as sys_path

from pkgutil import extend_path

__extended_path = "/home/naoki/ros/workspaces/lunar/hsas/src/ros_comm/clients/rospy/src".split(";")
for p in reversed(__extended_path):
    sys_path.insert(0, p)
    del p
del sys_path

__path__ = extend_path(__path__, __name__)
del extend_path

__execfiles = []
for p in __extended_path:
    src_init_file = os_path.join(p, __name__ + '.py')
    if os_path.isfile(src_init_file):
        __execfiles.append(src_init_file)
    else:
        src_init_file = os_path.join(p, __name__, '__init__.py')
        if os_path.isfile(src_init_file):
            __execfiles.append(src_init_file)
    del src_init_file
    del p
del os_path
del __extended_path

for __execfile in __execfiles:
    with open(__execfile, 'r') as __fh:
        exec(__fh.read())
    del __fh
    del __execfile
del __execfiles

The problem is that PyCharm expects __all__ to be populated in order for the completion to function correctly. That is done in /path/to/workspace/src/ros_comm/clients/rospy/src/rospy/__init__.py (i.e. $( rospack find rospy )/src/rospy).

Solution

Add $( rospack find rospy )/src to the front of PYTHONPATH if it exists. For rospy that’s installed with APT, there’s no src subdirectory (i.e. rospack find rospy gives you /opt/ros/DISTRO/share/rospy in which there is no src subdirectory).

if [[ -d $( rospack find rospy )/src ]]; then
    export PYTHONPATH="$( rospack find rospy )/src:$PYTHONPATH"
fi

After that if you start up PyCharm it should give you completion for rospy.