Reputation: 537
#!/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.
Upvotes: 1
Views: 5264
Reputation: 368894
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
Upvotes: 2
Reputation: 1123
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()
.
Upvotes: 0