How to set PATH before imports occur in a nice way?

1k Views Asked by At

I have a Python script which uses openslide-python.

openslide-python requires that OpenSlide binaries are in the DLL search path on Windows.

I am planning to distribute my application in the future and I don't want that users download OpenSlide binaries and set PATH. So I am going to include OpenSlide binaries with my application.

The problem is that PATH has to be set before any imports from OpenSlide occur.

Currently I have the following code (simplified with *):

import os
from io import *

os.environ['PATH'] = os.path.dirname(os.path.realpath(__file__)) + os.sep + 'openslide' + os.pathsep + os.environ[
    'PATH']

from openslide import *

I realize that it doesn't correspond with PEP 8, because I have a module level import not at top of file.

Any ideas how to make it nicely?

1

There are 1 best solutions below

0
On

Create a file my_path_helper.py:

os.environ['PATH'] = os.path.dirname(os.path.realpath(__file__)) + os.sep + 'openslide' + os.pathsep + os.environ[
    'PATH']

and put it into same directory as your script. Now import it:

import os
from io import *

import my_path_helper

from openslide import *

This still violates PEP8 a bit because it imports your own module before the third party module openslide. But all imports are at the top of your script.