Incomplete sys.path with embeddable python (Windows)!?

Ralf M. Ralf_M at t-online.de
Thu Apr 20 17:47:01 EDT 2023


Hello,

when I run a script with a "normally" installed python, the directory 
the script resides in is automatically added as first element to 
sys.path, so that "import my_local_module" finds my_local_module.py in 
the directory of the script.

However, when I run the same script with embeddable python ("Windows 
embeddable package (64-bit)", download link
https://www.python.org/ftp/python/3.11.3/python-3.11.3-embed-amd64.zip) 
the script directory is *not* prepended to the path, thus "import 
my_local_module" gives an ImportError.

I couldn't find an option to get the "normal" behaviour. Any ideas how 
to do that?

What I tried so far:

* The start-up value for sys.path seems to be defined in python311._pth. 
It looks that I can add further static paths to it, but I don't know how 
to make it add the script path (which can be different for different 
scripts).

* Uncommenting "import site" in python311._pth doesn't help.

* It seems that I could import something else in python311._pth, but I 
don't know how something imported from there could find out the path of 
the script that is about to be started.

* I read the (rather short) documentation of the embeddable package and 
of the site module several times but couldn't recognize a hint as to how 
to solve the issue.

* I can add the following lines to every script:
     import sys
     script_path = __file__.rsplit("\\", 1)[0]
     if script_path not in sys.path:
         sys.path[0:0] = [script_path]
     import my_local_modul
That works, but it's ugly, executing code between imports is frowned 
upon, and it needs to be added to every script.

Does anybody have a better idea?
Any help is appreciated.

Ralf M.


More information about the Python-list mailing list