I have a similar project, it works like that:
Inside the project folder, I have a folder called packages, with a init.py inside. It's empty, just to make the module available
In the packages folder yet, a file called initialize.py, where I have:
import rospy as _rospy
from std_msgs.msg import String as _String, Empty as _Empty
def init():
_rospy.init_node('controller', anonymous=True)
global _sub
_sub = _rospy.Subscriber("/model_name", _String, _nameCallback)
global _pub
_pub = _rospy.Publisher(_controllerName+'/encoder_updated',_Empty)
In the root folder, my script that imports the initialize library:
import packages.initialize
initialize.init()
Originally posted by marcoarruda with karma: 541 on 2017-07-18
This answer was ACCEPTED on the original site
Post score: 0
Original comments
Comment by zplizzi on 2017-07-18:
Yep, this works - since the init_node() call is in a method called by the main file, it seems to work. What I can't figure out is why it doesn't work in the example I described - where init_node() is called implicitly during the import. This method works, but still curious why the other doesn't.
Comment by marcoarruda on 2017-07-18:
I think the answers for this question https://stackoverflow.com/questions/6523791/why-is-python-running-my-module-when-i-import-it-and-how-do-i-stop-it can explain better. The question is the opposite of yours, but there are some explanation there.
Comment by zplizzi on 2017-07-18:
Yep, I understand how that works. Python will run all the code in an imported file upon import. What my question is asking is why the init_node() function doesn't work when run in that way (versus being run directly from the main script).