3

I have a folder called Script and inside I have temp.py script. My temp script imports module from sub-folder called lib.

Lib folder has inside empty __init__.py and my parent_computer_test.py script.

in my temp.py script is the following code:

import lib.parent_computer_test as parent_computer_test
parent_computer_test.mainChunk()
parent_computer_test.splitChunks()

I managed to import module from sub-folder without any bigger problems.

This workflow/script works fine, BUT for a specific reason, my lib folder has to be somewhere else on my computer. There is a long story why, but it has to be that way.

Long story short. I want that my temp.py from the /Script folder imports modules from folder lib (or any other name) with parent_computer_test.py, but at the same time this folder is no sub-folder of /Script - so it is somewhere else in the computer. It can be C:/development/... or something.

So my question is how to import a module from a specific folder?

luator
  • 4,769
  • 3
  • 30
  • 51
Excalibur
  • 93
  • 1
  • 9

3 Answers3

7

Append the path to lib folder to the SYS PATH Environment Variable. Then it can be imported from anywhere

import os, sys
lib_path = os.path.abspath(os.path.join('..', '..', '..', 'lib'))
sys.path.append(lib_path)
import mymodule
Aswin Murugesh
  • 10,831
  • 10
  • 40
  • 69
5
import imp
yourModule = imp.load_source('yourModuleName', '/path/to/yourModule.py')
foo = yourModule.YourFunction("You", "get", "the", "idea.")

I realize this is a special case, but in general, I would avoid stuff like this. Things can get ugly when you use absolute paths, especially if you move things around, and I would only use this for throwaway scripts or on systems that aren't going to change very much.

EDIT: Aswin's answer is a much better longterm solution.

Luke
  • 431
  • 1
  • 4
  • 15
  • Thank you! It works like a charm. I know, that this is not the best practise, but as said before... in this case, this is the only scenario. – Excalibur Jun 11 '15 at 13:37
  • Glad to help. Just making sure you realized the risks. – Luke Jun 11 '15 at 13:38
  • Thank you for pointing that out. I am complete beginner, so and additional informations are always welcome. – Excalibur Jun 11 '15 at 13:41
1

You have to use sys.path.append("path") . But use this just one time. Then try import "my_module". IT should be fine. If you want to remove the path appended you can use, sys.path.remove("path").

Sujay Narayanan
  • 487
  • 4
  • 11