Reputation: 24996
In Visual Studio with PTVS I have two separate Python projects, one contains a Python source file named lib.py
for use as a library of functions and the other is a main that uses the functions in the library. I am using an import
statement in the main to reference the functions in the library project but get the following error:
No module named lib
I primarily program in F# using Visual Studio so my mindset is adding references to other .NET projects.
How do I think in the Pythonic way to accomplish this?
Upvotes: 8
Views: 7819
Reputation: 24996
Python does not use references like .NET does but uses a path which is searched. The search path needs to be modified to include the directory containing the source file. See: The Module Search Path
Looking at the project in Visual Studio with Solution Explorer
shows Search Paths
for each project.
To modify the search path:
Get the directory for the Python file containing the source code to import.
e.g. lib.py
In Solution Explorer right click on lib.py
and select Copy Path
Now for the project that will import the module
e.g. ConsoleDriver_Python
Right click Search Paths
and select Add Folder to Search Path...
which displays a select folder dialog
Right click and paste in the path from the clipboard. Also change it to a directory by removing the file name.
Click Select Folder
Now check the project to make sure Search Path
was updated.
The import error should now be cleared.
Upvotes: 16
Reputation: 4029
Or you can do this in code with the following:
sys.path.append("search path")
So that the code can be run outside the IDE.
Upvotes: 0
Reputation: 416
I just wanted to add the below in addition to the verified answer, for a very specific scenario.
I was recently asked to fix the same problem that the OP was experiencing for a work machine, which had recently had the user accounts migrated over to a new domain.
Setup: Visual Studio 2013 PTVS 2.2.30718 Anaconda 3.5
Basically, Anaconda was installed for localmachine/UserA.
Once the users were migrated over to the new domain (newdomain/UserA), the Python environment had to be updated from within VS2013, by clicking View > Other Windows > Python Environments.
Once that was setup, the python scripts would run as expected, although none of the Search Folder references would work. They were then removed and re-added but to no avail.
Various other things were tried, including setting up totally fresh projects, and linking them using the Search Paths, but to no avail.
The only thing that fixed the problem was to reinstall the Python Environment (in my case Anaconda3) outside of a user account (by clicking the "for all users, using administrator privileges" option during the install).
Then I restarted, removed and re-added the search folders, and the python worked as expected, including all the search paths.
I hope that helps someone, as I just wasted hours solving it...
D :)
Upvotes: 3