← Back to team overview

sikuli-driver team mailing list archive

Re: [Question #694329]: define import and call it randomly?

 

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

RaiMan proposed the following answer:
********************* corrections to comment #3

To get to the next level of insight ;-)
first read this:
https://sikulix-2014.readthedocs.io/en/latest/scripting.html#runScript

As mentioned in the cited answer, import should not be used to run code,
that is at indent level 0, because it is only executed at the first
import. There are a few exceptions, but an imported script should only
contain name definitions (variables, functions and classes).

so runScript() is your feature (see above).

a comment on your solution:
Your script is a sequence of lines produced by copy&paste.
That usually does not make sense, since scripting (as any programming language) has enough features to follow the DRY principle (Don't repeat yourself).

On top scripting usually is run by an Interpreter, which can be given
some piece of code, that is created on the fly and handed down to be
run.

The relevant Python features are eval() (evaluate an expression) and
exec() (run some lines of code). In both cases, the parameter is a
string, that must evaluate to a valid expression or valid code.

So your code as an example:

import random
scripts = ["Test" + str(x) for x in range(1, 9)] # a Python-typical construct: list-comprehension
random.shuffle(scripts)
for script in scripts:
    exec("import " + script)

... and with runScript()
import random
scripts = ["Test" + str(x) for x in range(1, 9)]
random.shuffle(scripts)
for script in scripts:
    exec("runScript(%s)" % script)

Have fun :-))

-- 
You received this question notification because your team Sikuli Drivers
is an answer contact for Sikuli.