netbox icon indicating copy to clipboard operation
netbox copied to clipboard

Scripts: can't import modules relative to script file

Open XioNoX opened this issue 1 year ago • 0 comments

Deployment Type

Self-hosted

NetBox Version

v4.0.3

Python Version

3.11

Steps to Reproduce

  1. Set SCRIPT_ROOT to a directory outside Netbox's root
  2. Create/import a script that is meant to be imported by other scripts, for example _common.py which contains a class Importer (see this file for example)
  3. Create a regular script that imports the above mentioned file/class from _common import Importer (see this file for example)

Expected Behavior

Hi,

Not sure when that changed, but on 3.2.9, the imported module worked fine, this reduces duplicated code between scripts. That's why I'm opening it as bug report rather than feature request.

Observed Behavior

When opening the script's page, it shows the following error message:

Error loading script.
No module named '_common'

I've been thinking of possible workarounds, I'm obviously not knowledgeable enough on Netbox code, so not sure of all the tradeoff they brings.

  1. Add the following to the script being executed, tested and works as expected, but probably not optimal
import sys
from os.path import dirname
sys.path.append(dirname(__file__))
from _common import Importer
  1. In settings.py add sys.path.append(SCRIPTS_ROOT) but there is probably a risk of name collision between Netbox modules and scripts ?
  2. Add the scripts (or at least imported modules) inside Netbox's BASE_DIR (like the default /scripts. Here depending on Netbox deployment process, it might get wiped at each upgrade (like in our case).
  3. Same as (3), but using a symlink instead, so far my preferred workaround if there is no plans on changing this behavior upstream (and then do the import like from scripts._common import Importer as imports work from Netbox's root directory).

Let me know if I can be of any help.

Thanks

XioNoX avatar Jun 24 '24 13:06 XioNoX