pythonmoduleptvs

PTVS: How to reference or use Python source code in one project from a second project


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?


Solution

  • 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.

    enter image description here

    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

    enter image description here

    Now for the project that will import the module
    e.g. ConsoleDriver_Python

    Right click Search Paths and select Add Folder to Search Path...

    enter image description here

    which displays a select folder dialog

    enter image description here

    Right click and paste in the path from the clipboard. Also change it to a directory by removing the file name.

    enter image description here

    Click Select Folder

    Now check the project to make sure Search Path was updated.

    enter image description here

    The import error should now be cleared.