In the entry that is placed at the bottom of the main GiD window Tcl code can be executed by adding the prefix -np-
followed by a space and then the desired tcl code and pressing <Return> .
Note: -np-
mean 'No-Process' (that is, the words are not GiD known process keywords) and instead the next command is expected to be Tcl code. It is used as a fast way to run a simple procedure or to re-define code.
Use copy/paste code after -np-
In particular there are some predefined Tcl procs that run python code, like GiD_Python_Exec
which expects the python code to be evaluated.
Example: matplotlib graph of a line
This is simple example calls a Python code from Tcl and uses the matplotlib module to draw a graph (in a new Tk window opened by tkinter):
GiD_Python_Exec { import matplotlib.pyplot as plt plt.plot([1, 2, 3, 4]) plt.ylabel('some numbers') plt.show() }
GiD_Python_Exec
does an implicit package require tohil
and then calls tohil::exec
with the provided script.
This Tcl code can be executed, for example, by pasting it after -np-
in the command line (with one or more spaces separating the code pasted), and pressing the <Return> key.
Then a window like this will appear:
There are other procs similar to GiD_Python_Exec
, like GiD_Python_Eval
to evaluate a single instruction which will return a value, or GiD_Python_Call
to invoke a function that has been previously defined.
Source a file with the code
The normal way to write long Python code is to write it in a .py
file.
Note: Visual Studio Code is our recommended editor accompanied by the MS Python extension for this language.
GiD_Python_Source
is a Tcl proc that expects the name of a python file with the code to be sourced, i.e. loaded and executed.
Example: matplotlib graph of two curves
The file <GiDdirectory>/scripts/tohil/doc/demo_matplotlib.py
contains a code like the one of the image:
This demo file can be sourced ( loaded and executed ) writing this command ( replace <GiDdirectory>
with the correct path)-np- GiD_Python_Source {<GiDdirectory>/scripts/tohil/doc/demo_matplotlib.py}
and then this window will appear:
Force reload of a Python file
Other Tcl procs related to Python code are GiD_Python_Import_File
and GiD_Python_Import
.
Our Tcl command GiD_Python_Import
(that does tohil::import)
will import a module in Python from its tail name without .py
extension. The module to import must be found based on the path environment variables.
GiD_Python_Import_File
is similar to GiD_Python_Import
but expects the full path.
But if we are developing and modify the .py
file doing a new import won't refresh the code in the interpreter.
A trick to do this ‘reload’ is to use the Tcl command GiD_Python_Source
. Using this, then the new code of the file is used, reloaded, without the need to restart GiD.
In fact it seems that this is similar, in Python, to the function reload
of the importlib
module:
import importlib importlib.reload( module)