-
Notifications
You must be signed in to change notification settings - Fork 39
Scripts
There are many ways to automate measurements and divide your code logically, but one of the main tools should be the use of scripts.
In QTLab a script is a python source file which can be used as a function, similar to matlab. It can take arguments and return a value, which makes it way more flexible than using a plain python file and using execfile('mycode.python'). They do also not suffer from the annoying problem of modules, which require lots of reload() commands if you change your code; a script always includes the latest changes you made to a file.
So, how to use these scripts? At startup, QTLab scans a list of directories (qt.config['scriptdirs'], set in userconfig.py) for all available scripts. You can see which scripts were located like this:
qt.scripts
This will give you an output:
Script list: take_spectra.py example_script.py take_spectrum.py
Upon startup, all scripts are plugged into the global namespace, which means that you can use them as a function:
example_script('a', 2)
This will execute the script example_script.py, and as you can see return a value set by the script. Note that the first commented lines will be used as the function comment, so typing:
example_script?
gives information that is set in the script.
There are two special variables in scripts: 'args' and 'kwargs', which resemble the use of positional arguments in python.
'args' is a variable length tuple with all the unnamed arguments, i.e.
example_script(1,2)
will result in args containing (1,2).
'kwargs' is a dictionary with keyword arguments, so
example_script(1,2,test='1',qtlab=true)
will result in kwargs containing a key test with value '1' and a key 'qtlab' with value true.
Scripts are executed in their own namespace, which means that you do not have access to global variables. This might seem annoying at first, but this is actually a good thing.
If you want to use instruments, that is still easy:
import qt
dsgen = qt.instruments['dsgen']
If you add a new script to one of the script directories, you can also get it as a function:`
new_script = qt.scripts['new_script']
(no need for the '.py')
You could also add a completely new directory to search for scripts:
qt.scripts.add_directory('c:/bla')
And automatically plug all new scripts in the global namespace:
qt.scripts.scripts_to_namespace(globals())