Developing and debugging python automation scripts

Good day.

I am trying to develop a couple of simple workflow automation scripts but have found the development experience somewhat tedious.

Specifically, I am looking to get some halfway decent code completion and debugging. I have managed to run the scripts just fine using the --python-script flag, as well as attach a debugger using the instructions provided here. However, I then noticed that there is no option to run the script directly from the GUI.

Is it possible to improve the code completion and actually debug the script directly? Any pointers would be greatly appreciated. Cheers.

You can get full-decent code completion and debugging in Slicer. The only trick is that you need to attach a debugger, as Slicer does not extend Python (cannot easily do import SlicerLib) but embeds Python. See instructions here.

Python support will be further improved in the near future. Most importantly, in about 6 months, Slicer Python wheels are coming (so you will be able to import SlicerLib). For now, you need a special build - see GitHub - KitwareMedical/trame-slicer: Bring the capabilities of 3D Slicer to the web with modern UI using the trame framework!. Hints will be also improved, which will improve static analysis, therefore Python IDEs will be able to do more (auto-completion, documentation, type checks) without attaching to a running Slicer instance.

If you want to have auto completion, you should also be able to configure PyCharm / VS Code or your favorite IDE to use 3D Slicer’s Python environment.

In PyCharm, this can be done by changing the interpreter settings, choosing a local interpreter and pointing to the PythonSlicer executable located in the bin folder.

This will give you auto imports and code completion for the Python packages installed in Slicer.

There is also the Slicer Python Test Runner extension which is useful for debugging and testing Slicer scripts using either unittest or pytest syntaxe.