0
$\begingroup$

Rosanswers logo

I'd like to perform a rospy.init_node() inside a file imported by another file. However, this doesn't seem to work - the program hangs whenever I try this.

Example (broken, both files in same folder):

main.py:

import test

test.py:

   import rospy
   rospy.init_node("node_name")

Running python main.py results in the program hanging. However, running python test.py works.


Originally posted by zplizzi on ROS Answers with karma: 1 on 2017-07-17

Post score: 0

$\endgroup$

1 Answer 1

0
$\begingroup$

Rosanswers logo

I have a similar project, it works like that:

  1. Inside the project folder, I have a folder called packages, with a init.py inside. It's empty, just to make the module available

  2. 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)
    
  3. 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).

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.