0

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?

martineau
  • 119,623
  • 25
  • 170
  • 301
DfM
  • 529
  • 6
  • 19
  • Use `sys.path.append()`? – Tuwuh S Nov 30 '17 at 14:37
  • @TuwuhS It still has to occur before importing things from openslide, right? If yes, then it doesn't change anything. – DfM Nov 30 '17 at 14:39
  • Yes it does, why do you think it is a problem? – Tuwuh S Nov 30 '17 at 14:42
  • @TuwuhS As I understand, according to PEP 8 I have ho have something like: `import os` `from io import *` `from openslide import *` `sys.path.append('...')` – DfM Nov 30 '17 at 14:44
  • 1
    I see your point. This might help you https://stackoverflow.com/a/36829884/6102131 (edit: linking to the answer instead) – Tuwuh S Nov 30 '17 at 14:47

1 Answers1

1

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.

Mike Müller
  • 82,630
  • 20
  • 166
  • 161