How can I import variables used by my script from external files?

Asked by Unuldinei

I need to import variables used by my script for external files (config.any_file_extension). I need this so I can loop my script to import different config files every loop.

Example:

config_file1="Folder1\\config.*"
config_file2="Folder2\\config.*"
config_file3="Folder3\\config.*"

first loop:
import config_file1
pass

second loop:
import config_file2
pass

...

n loop:
import config_filen
pass

Question information

Language:
English Edit question
Status:
Solved
For:
SikuliX Edit question
Assignee:
No assignee Edit question
Solved by:
RaiMan
Solved:
Last query:
Last reply:
Revision history for this message
Best RaiMan (raimund-hocke) said :
#3

-- to use import, the files must either be xxx.sikuli scripts or have ending .py

-- If this is your plan, then the folder containing the file to import must be on sys.path at time of import:

# outside the loop to get the index of the entry in sys.path:
import os
sys.path.add("__myfiles__")
sys_path_entry = sys.path.index("__myfiles__")
file_folder = "abolute_path_of_folderNN" # without the number!
# e.g. file_folder = r"c:\mystuff\folder"

-- the import can be created and executed:
exec "from %s import *"%current_file

where n is the current loop index

So the loop might look like this:

for n in range(number_of_configs):
    current_folder = file_folder + str(n)
    current_file = "config_file" + str(n)
    sys.path[sys_path_entry] = current_folder
    exec "from %s import *"%
    # your other coding

Revision history for this message
Unuldinei (numaipotdeloc) said :
#4

Life saver!

Here is my code now:

import os
config_files_src = r"C:\\SomeFolder\\"
for n in range (10):
    execfile(os.path.join(config_files_src + str(n),"config.py"))
    popup(str(variable1))

... and it works! Thank you

Revision history for this message
Unuldinei (numaipotdeloc) said :
#5

Thanks RaiMan, that solved my question.