1
#!/usr/bin/env python
import roslib
import rospy
import time
from nav_msgs.msg import Odometry 

def position_callback(data):
    global q2
    q2=data.pose.pose.position.x
    q1=data.pose.pose.position.y
    q3=data.pose.pose.position.z


def position():      
    rospy.init_node('position', anonymous=True)  #initialize the node"
    rospy.Subscriber("odom", Odometry, position_callback)

if __name__ == '__main__':

    try:
        position()
        print q2
        rospy.spin()
    except rospy.ROSInterruptException: pass

the error i get is like this:

print q2
NameError: global name 'q2' is not defined

I defined q2 as global variable already.

2 Answers 2

2

Declaring q2 as a global variable does make the global variable exist.

Actually calling the function and execution of the assignment statement q2 = ... cause the creation of the variable. Until then, the code cannot access the variable.

position function does not call the position_callback, but pass it to rospy.Subscriber (which probably register the callback function, and not call it directly).


Initialize q2 if you want to access the variable before it is set.

q2 = None

def position_callback(data):
    global q2
    q2 = data.pose.pose.position.x
    q1 = data.pose.pose.position.y
    q3 = data.pose.pose.position.z
Sign up to request clarification or add additional context in comments.

2 Comments

no.i want to actually access the value..its not for printing..i want to use this value in some other function.
@RuthvikVaila, Initialize the variable q2 to some value that represent null value if you want to access the variable before the callback is called. I updated the answer accordingly.
0

You never initialize q2. It cannot have a value. Try to define it in global scope - after the imports. Then call it iniside the functionposition().

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.