Incomplete sys.path with embeddable python (Windows)!?
Ralf M.
Ralf_M at t-online.de
Sat Apr 22 18:04:16 EDT 2023
Am 21.04.2023 um 18:07 schrieb Thomas Passin:
> On 4/20/2023 5:47 PM, Ralf M. wrote:
>> 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:
>> [...]
>> * 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
>> [...]
Thank your for your hints.
> I haven't worked with embeddable python, but here are some possibilities
> that came to mind, depending on how your system works -
>
> 1. If your script is started from the command line, sys.argv[0] gives
> the path to the script;
I didn't think of sys.argv[0] to get at the path; this might be quite
useful, I'll try it out next week.
> You could use os.path.dirname() to get its
> directory. This will end up the same place as your code fragment, but
> looks nicer and handles different path separators (e.g., Linux vs Windows);
Yes, but it requires another import and the embedded package is only
available for windows anyway, I think. I'll consider the idea, though.
> 2. You could write a little module that figures out the script's path
> and import that first in all your scripts.
>
> 3. If you know all the directories that your scripts will be in, you
> could add them all to a xx.pth file (do a search to make sure where to
> put .pth files for an embeddable case).
I thought about that, but for that to work all local modules across all
script locations must have unique names, otherwise import might get hold
of a module from the wrong directory. Certainly doable for a few
scripts, but might become a source of hard to track errors when the
number of scripts increases and later maintainers are not aware of the
naming restriction.
> [...}
More information about the Python-list
mailing list