0

Im pip-ing all my libraries to a folder called lib. My source code is in the directory scr.

My directory structure

Folder
    -lib
       -different libraries
    -scr
       -main.py

I just want to reference my libraries so my code will run.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
oharr
  • 163
  • 1
  • 3
  • 12
  • What does "pip-ing all my libraries to a folder" mean? How are you installing them there? And, just as importantly, why? – Daniel Roseman Jun 18 '18 at 15:38
  • From `main.py`, use `HERE = os.path.dirname(os.path.abspath(__file__))`, then use `sys.path.insert(0, os.path.abspath(os.path.join(HERE, '..', 'lib')))` to update your `sys.path` to include the other folder. That way you get to include the correct absolute folder whatever the current path of `Folder` might be. – Martijn Pieters Jun 18 '18 at 15:43
  • Im using codebuild. when i pip the libraries i have to store them someone so i can reference them in my lambda. Is that not correct? – oharr Jun 18 '18 at 16:04

2 Answers2

0

You can use the sys module to append the path.

import sys
sys.path.insert(0,'/Folder/src')
-1

You need to append a path to Python's system path:

import os.path
import sys
sys.path += [os.path.abspath('../lib')]
import my_lib
Jonas Byström
  • 25,316
  • 23
  • 100
  • 147
  • This assumes that the current working directory is `Folder`. Do not rely on the current working directory. – Martijn Pieters Jun 18 '18 at 15:40
  • @MartijnPieters: Nope, `src`. It relies on a relative path, which is a good way to organize a project. – Jonas Byström Jun 18 '18 at 20:31
  • Sorry, yes, `Folder/src`. No, relative paths like these are resolved against something that is not part of the project, the *current working directory*. You can't count on the current working directory being `Folder/src`. It could be somewhere else on the filesystem entirely, at which point `os.path.abspath('../lib')` will be resolved to an incorrect path. Do not rely on the current working directory. – Martijn Pieters Jun 18 '18 at 20:44
  • Instead, explicitly resolve your paths against a path derived from `__file__`. For example, `os.path.dirname(os.path.abspath(__file__))`. `__file__` can be an absolute or relative path, but if it is a relative path, then Python will have set it as relative to the current working directory, so can be relied upon to be resolved correctly. – Martijn Pieters Jun 18 '18 at 20:45
  • @MartijnPieters: "somewhere else on the filesystem entirely" was not the question. The good part about Python is not over-generalizing. – Jonas Byström Jun 19 '18 at 10:01
  • I'm trying to tell you that your code **won't work in many situations**, because you are assuming that the current working directory will always be set to the path of `src`. That is simply not the case, so your answer is, unfortunately, incomplete. – Martijn Pieters Jun 19 '18 at 12:26