#!/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.
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
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().
Related
Hey im having some trouble understanding what I did wrong/finding a way to fix it, can you guys help me?
def main():
Keys = 0
def Function1():
global all
def Function2():
global all
print(str(Keys))
Function2()
Keys = Keys + 1
Function1()
main()
every time i try to run this i get this error "free variable 'Keys' referenced before assignment in enclosing scope"
Thanks in advance!
You need to define global Keys for every function. A function thinks that Keys is a local variable.
def main():
global Keys
Keys = 0
def Function1():
global Keys
global all
def Function2():
global Keys
global all
print(str(Keys))
Function2()
Keys = Keys + 1
Function1()
main()
However, using global is bad. Here are a list of reasons why using global is bad
So, instead of using global, you can pass it as an parametre.
def main():
Keys = 0
def Function1(Keys):
def Function2(Keys):
print(str(Keys))
Function2(Keys)
Keys = Keys + 1
Function1(Keys)
main()
Also, all is a function in python. There is absolutely no need to make it global
I have declared global variable in function a
def a():
global my_var
my_var = 3
If I want to read this variable from function main, everything works
if __name__ == "__main__":
main()
def main():
print(my_var)
Output:
3
However I have another function b, where the var is not defined
def b():
try:
random_numbers = (random.sample(range(1, my_var), 2))
except Exception as e:
print(e)
Output:
NameError: name 'my_var' is not defined
Could someone explain me, why in function main I can access my_var, while in another it is not defined? How can I solve this problem?
I am getting issue with global variable declared in python file.
I do not have class declaration in the file.
i am just declaring some variables in the class with none type.
and modifying that variables in the function.
when i was calling those variables inside another class by importing them,
instead of modified value it is returning None type only.
Below is the code
from selenium import webdriver
from Pages.PageMethods.Google_Methods import Methods
browser = None
s = None
def before_feature(context, feature):
print("before feature")
def before_scenario(context, scenario):
print('before scenario', scenario.name)
context.driver = webdriver.Firefox()
#context.driver.maximize_window()
browser = context.driver
global s
s = Methods(browser)
s.samplemethod()
def after_scenario(context, scenario):
print("after scenario", scenario.name)
context.driver.quit()
def after_feature(context, feature):
print("after feature")
->Here i was calling that 's' variable inside another class,it is returning None type only instead of object for that assigned class
Please someone help
Here is the code that i am calling that variable
from features.environment import *
use_step_matcher("re")
fileConfig('logging.ini')
log = logging.getLogger('sLogger')
#given("i am on google page '(.*)'")
def navigate(context, url1):
context.url = url1
log.info("this is log statement")
context.driver.get(url1)
context.driver.implicitly_wait(10)
#then("I enter value into search box as '(.*)'")
def step_impl(context, text):
print("selector:=>", Google.search_box)
context.driver.find_element(*Google.search_box).send_keys(text)
print("url in second step is:=>", context.url)
time.sleep(1)
s.printtitle()
and i was getting this error:
AttributeError: 'NoneType' object has no attribute 'printtitle'
You need use global operator
example:
global_var = list()
def somefunc():
global global_var
global_var.append(1)
somefunc()
print global_var
out:
[1]
I have a method that inside it I scan an excel file in python and in another method I want to check an entry in a list in which I extracted the data from the excel sheet in the first method as follows:
def first():
nodes_sh = xlrd.open_workbook(file_location)
sh_method = nodes_sh.sheet_by_index(0)
global node_data_inter
node_data_inter = [[sh_method.cell_value(rr, co) for co in range(sh_method.ncols)] for rr in range(sh_method.nrows)] #O(rows*cols) # A loop to get all the data in the excel sheet of "Nodes Co-ordinates"
global node_positions_ascending_inter
node_positions_ascending_inter = dc.deepcopy(node_data_inter) #O(rows*cols)
for rowss in range(len(node_positions_ascending_inter)): #O(rows)
del (node_positions_ascending_inter[rowss][0:3])
del (node_positions_ascending_inter[rowss][2])
def using_from_first_method():
global node_positions_ascending_inter
if node_positions_ascending_inter[0][0] == 1.25:
print "Yes"
An error message is outputted when I type using_from_first_method()
NameError: global name 'node_positions_ascending_inter' is not defined
Why is it outputted as I already have defined node_positions_ascending_inter to be a global variable?
You need to declare node_positions_ascending_inter as a global in the using_from_first_method function. I got the below code (simplification) to run just fine.
def first():
global node_positions_ascending_inter
node_positions_ascending_inter = [1.25, 1.5, 1.3, 1.45]
def using_from_first_method():
global node_positions_ascending_inter
if node_positions_ascending_inter[0] == 1.25:
print("Yes")
first()
using_from_first_method()
If you are still having issues maybe the problem lies in the filling of the array. Are you sure the first method is being called and successfully creating the global before the second tries to access it? Also, see the docs on globals here.
Say I have the following function in a module called "firstModule.py":
def calculate():
# addCount value here should be used from the mainModule
a=random.randint(0,5) + addCount
Now I have a different module called "secondModule.py":
def calculate():
# addCount value here too should be used from the mainModule
a=random.randint(10,20) + addCount
I am running a module called "mainModule.py" which has the following (notice the global "addCount" var):
import firstModule
import secondModule
addCount=0
Class MyThread(Thread):
def __init__(self,name):
Thread.__init__(self)
self.name=name
def run(self):
global addCount
if self.name=="firstModule":
firstModule.calculate()
if self.name=="secondModule":
secondModule.calculate()
def main():
the1=MyThread("firstModule");
the2=MyThread("secondModule");
the1.start()
the2.start()
the1.join()
the2.join()
# This part doesn't work:
print firstModule.a
print secondModule.a
Basically I want the "addCount" value in both modules to be the one from "mainModule". After that, when the threads are finished, I want to print the value
of "a" in both of them. The example above doesn't work. I was wondering how can I fix it.
Pass 'addCount' to the function 'calculate', return the value of 'a' in 'calculate', and assign it to a new attribute in MyThread instance.
def calculate(addCount):
a = random.randint(0, 5) + addCount
return a
Modules in python are singletons, so you can put your global variables in module globalModule.py and have both firstModule, secondModule, and mainModule import globalModule and they will all access the same addCount.
However, in general it's a bad practice for threads to have a global state.
This will never work:
print firstModule.a
print secondModule.a
because in here:
def calculate():
# addCount value here should be used from the mainModule
a=random.randint(0,5) + addCount
a is a local variable to the function calculate.
If you really want to write a as a module-level variable, add global declaration:
def calculate():
# addCount value here should be used from the mainModule
global a
a=random.randint(0,5) + addCount