← Back to team overview

sikuli-driver team mailing list archive

Re: [Question #258260]: Need global Var for mult scripts

 

Question #258260 on Sikuli changed:
https://answers.launchpad.net/sikuli/+question/258260

    Status: Open => Answered

RaiMan proposed the following answer:
Every module (scripts in your case) has it's own namespace.

The only way, to add (and hence access) variables in other modules is to
use import.

import mod1
print mod1.var1

or 
from mod1 import *
print var1

if var1 is a variable in module mod1

Since you cannot import the main script, you cannot access names defined
in main in modules, that are imported in the main workflow.

To inject values into imported modules, you need a function inside the
module, that accepts values and makes them globally available inside the
module (some init function).

This is the principal approach.
I am using a dictionary as the most flexible approach as a container for whatever variables.

--- in main
globalVars = {}
globalVars["var1"] = "whatever"

import sub
reload(sub)
sub.init(globalVars)
# from now on changes in globalvars are known 
# in every module, whose init function was called.
sub.someFunction()
globalVars["var1"] = "somethingelse"
sub.someFunction()

--- in sub

def init(vars):
    global globalVars # needed to make globalVars a global variable in the namespace sub
    globalVars = vars

def someFunction():
    print "from sub:", globalVars["var1"]

-- 
You received this question notification because you are a member of
Sikuli Drivers, which is an answer contact for Sikuli.