且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PTVS:如何在一个项目中引用另一个项目中的Python源代码或使用它

更新时间:2022-12-03 14:30:31

Python不像.NET那样使用引用,而是使用要搜索的路径.需要修改搜索路径以包括包含源文件的目录.请参阅:模块搜索路径 >

在Visual Studio中使用Solution Explorer查看项目时,每个项目都显示Search Paths.

要修改搜索路径:

获取包含要导入源代码的Python文件的目录.

例如lib.py

在解决方案资源管理器中,右键单击lib.py并选择Copy Path

现在要导入模块的项目
例如ConsoleDriver_Python

右键单击Search Paths并选择Add Folder to Search Path...

显示选择文件夹对话框

右键单击并粘贴剪贴板中的路径.还可以通过删除文件名将其更改为目录.

点击Select Folder

现在检查项目以确保Search Path已更新.

现在应该清除导入错误.

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?

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.