Effect of using sys.path.insert(0, path) and sys.path(append) when loading modules
Because python checks in the directories in sequential order starting at the first directory in sys.path
list, till it find the .py
file it was looking for.
Ideally, the current directory or the directory of the script is the first always the first element in the list, unless you modify it, like you did. From documentation -
So, most probably, you had aAs initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.
.py
file with the same name as the module you were trying to import from, in the current directory (where the script was being run from).Also, a thing to note about ImportError
s , lets say the import error says -ImportError: No module named main
- it doesn't mean the main.py
is overwritten, no if that was overwritten we would not be having issues trying to read it. Its some module above this that got overwritten with a .py
or some other file.
Example -
My directory structure looks like -
- test
- shared
- __init__.py
- phtest.py
- testmain.py
Now From testmain.py
, I call from shared import phtest
, it works fine.Now lets say I introduce a shared.py in test
directory` , example -
- test
- shared
- __init__.py
- phtest.py
- testmain.py
- shared.py
Now when I try to do from shared import phtest
from testmain.py
, I will get the error -ImportError: cannot import name 'phtest'
As you can see above, the file that is causing the issue is shared.py
, not phtest.py
. Why use sys.path.append(path) instead of sys.path.insert(1, path)?
If you have multiple versions of a package / module, you need to be using virtualenv (emphasis mine):
That's why people considervirtualenv
is a tool to create isolated Python environments.The basic problem being addressed is one of dependencies and versions, and indirectly permissions. Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into
/usr/lib/python2.7/site-packages
(or whatever your platform’s standard location is), it’s easy to end up in a situation where you unintentionally upgrade an application that shouldn’t be upgraded.Or more generally, what if you want to install an application and leave it be? If an application works, any change in its libraries or the versions of those libraries can break the application.
Also, what if you can’t install packages into the global
site-packages
directory? For instance, on a shared host.In all these cases,
virtualenv
can help you. It creates an environment that has its own installation directories, that doesn’t share libraries with other virtualenv environments (and optionally doesn’t access the globally installed libraries either).
insert(0,
to be wrong -- it's an incomplete, stopgap solution to the problem of managing multiple environments. Sys.path.insert inserts path to module but imports are not working
Replace the code as this you dont need to add the folder to the path all you need is the path to the folder
import sys
import os
sys.path.insert(0, os.path.abspath('../../'))
import myfolder
print(sys.path)
Why do I need to include sys.path.append to import a module with Python 3.6 and my colleges doesn't need?
Just set the PYTHONPATH
environment variable to (the full path to) Myproject
. That tells Python where to find modules to import, and it works regardless of which directory you run the script from. This avoids the need to modify sys.path
.
import python module using sys.path.append
I'm afraid you can't do it that way.
Because of structure:
/home/sam/pythonModules/module1/lib/module1.py
/home/sam/pythonModules/module2/lib/module2.py
You can't put both: /home/sam/pythonModules/module1
and/home/sam/pythonModules/module2
sys.path
and expect that Python will find:module1
inmodule1/lib
andmodule2
inmodule2/lib
from lib.module1 import A
from lib.module2 import B
If you put /home/sam/pythonModules/module1
before /home/sam/pythonModules/module2
in sys.path
array, then import lib.MODULE
will search for MODULE
in /home/sam/pythonModules/module1/lib
.Since there is only module1
and no module2
in it, you get error.
What you can do is to put both
/home/sam/pythonModules/module1/lib/
and/home/sam/pythonModules/module2/lib/
sys.path
and expect Python to correctly import them with next lines:from module1 import A
from module2 import B
sys.path.insert cannnot import other python files
The sys.path.insert()
command inserts a path into the system path and should not contain the filename.
Please try below using your structure:
little main.py:
import sys
import sample_tree1
sys.path.insert(0, r'/my/absolute/path/5.0.8/treetwo')
print(sys.path) # view the path and verify your insert
import sample_tree2
print(sample_tree2.tree2_func())
sample_tree2.py in treetwodef tree2_func():
return 'called tree2'
Outputs:['/my/absolute/path/5.0.8/treetwo', '... other paths']called tree2
Related Topics
How to Use Python-Docx to Replace Text in a Word Document and Save
Does 'Anaconda' Create a Separate Pythonpath Variable for Each New Environment
Pandas - Filter Dataframe by Another Dataframe by Row Elements
In Python, Is It Better to Use List Comprehensions or For-Each Loops
Stop Matplotlib Repeating Labels in Legend
Python Element-Wise Tuple Operations Like Sum
How to Add Trendline in Python Matplotlib Dot (Scatter) Graphs
How to Define a Class Constant Inside an Enum
Turning Off Logging in Selenium (From Python)
Using Python Requests: Sessions, Cookies, and Post
Adding a Y-Axis Label to Secondary Y-Axis in Matplotlib
How to Strip All Whitespace from String
How to Avoid Infinite Recursion with Super()
Cartesian Product of a Dictionary of Lists
How to Build a Systemtray App for Windows
How May I Override the Compiler (Gcc) Flags That Setup.Py Uses by Default