-
-
Notifications
You must be signed in to change notification settings - Fork 486
/
debugging.rst
68 lines (44 loc) · 2.31 KB
/
debugging.rst
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
Debugging
=========
Since xlwings runs in every Python environment, you can use your preferred way of debugging.
* **RunPython**: When calling Python through ``RunPython``, you can set a ``mock_caller`` to make it easy to switch
back and forth between calling the function from Excel and Python.
* **UDFs**: For debugging User Defined Functions, xlwings offers a convenient debugging server
To begin with, Excel will show Python errors in a Message Box:
.. figure:: ./images/debugging_error.png
.. note:: On Mac, if the ``import`` of a module/package fails before ``xlwings`` is imported, the popup will not be shown and the StatusBar
will not be reset. However, the error will still be logged in the log file (``/Users/<User>/Library/Containers/com.microsoft.Excel/Data/xlwings.log``).
RunPython
---------
Consider the following sample code of your Python source code ``my_module.py``:
.. code-block:: python
# my_module.py
import os
import xlwings as xw
def my_macro():
wb = xw.Book.caller()
wb.sheets[0]['A1'].value = 1
if __name__ == '__main__':
# Expects the Excel file next to this source file, adjust accordingly.
xw.Book('myfile.xlsm').set_mock_caller()
my_macro()
``my_macro()`` can now easily be run from Python for debugging and from Excel via ``RunPython`` without having to change the
source code:
.. code-block:: vb.net
Sub my_macro()
RunPython "import my_module; my_module.my_macro()"
End Sub
UDF debug server
----------------
Windows only: To debug UDFs, just check the ``Debug UDFs`` in the :ref:`xlwings_addin`, at the top of the xlwings VBA module.
Then add the following lines at the end of your Python source file and run it. Depending on which IDE you use, you
might need to run the code in "debug" mode (e.g. in case you're using PyCharm or PyDev)::
if __name__ == '__main__':
xw.serve()
When you recalculate the Sheet (``Ctrl-Alt-F9``), the code will stop at breakpoints or output any print calls that you
may have.
The following screenshot shows the code stopped at a breakpoint in the community version of PyCharm:
.. figure:: ./images/udf_debugging.png
.. note::
When running the debug server from a command prompt, there is currently no gracious way to terminate it, but closing
the command prompt will kill it.