Редактиране

Споделяне чрез


Python projects in Visual Studio

Python applications are typically defined by using only folders and files. This structure can become complex as applications grow and perhaps involve autogenerated files, JavaScript for web applications, and so on. A Visual Studio project can help you manage the complexity. The project (a .pyproj file) identifies all the source and content files associated with your project. It contains build information for each file, maintains the information to integrate with source-control systems, and helps you organize your application into logical components.

Screenshot that shows a Python project open in Solution Explorer in Visual Studio.

Projects are always managed within a Visual Studio solution. A solution can contain any number of projects that might reference one another, such as a Python project that references a C++ project that implements an extension module. With this relationship, Visual Studio automatically builds the C++ project (if necessary) when you start debugging the Python project. For more information, see Solutions and projects in Visual Studio.

Visual Studio provides various Python project templates to quickly create several types of application structures. You can choose a template to create a project from an existing folder tree or create a clean, empty project. For a list of available templates, see the table in the Project templates section.

Tips for working with Python projects

You don't have to use projects to run Python code in Visual Studio, but there are benefits to doing so. As you get started, review the following considerations about working with projects and Python.

  • In Visual Studio 2019 and later, you can open a folder that has Python code and run the code without creating Visual Studio project and solution files.

    The guided steps for this approach are available in the Quickstart: Open and run Python code in a folder article.

  • You don't need a project to run Python code in Visual Studio. All versions of Visual Studio work well with Python code.

    You can open a Python file by itself and immediately access autocomplete, IntelliSense, and debugging features. However, there are some potential drawbacks to working with the code without a project:

    • Because the code always uses the default global environment, you might see incorrect completions or errors if the code is meant for a different environment.
    • Visual Studio analyzes all files and packages in the folder from which the single file is opened. This process can consume considerable CPU time.
  • You can create a Visual Studio project from existing code. This approach is described in the Create a project from existing files section.

Basic project tasks: files, environments, and start up

When you use projects with your Python code, you complete basic tasks, including adding files, assigning a startup file, and setting the Python interpreter environment.

As you develop your application, you typically need to add new files of different types to your project. It's easy to add more files. Right-click your project, select Add > Existing Item, and browse to find the type of file to add. The Add > New Item option opens a dialog that shows item templates that you can use to create the new file. Options include empty Python files, a Python class, a unit test, and various files related to web applications. You can explore the template options with a test project to learn what's available in your version of Visual Studio. For more information, see the item templates reference.

Each Python project has one assigned startup file, which is shown in boldface in Solution Explorer. The startup file runs when you begin debugging (by selecting F5 or Debug > Start Debugging) or when you run your project in the Interactive window. You can open this window with the keyboard shortcut Shift + Alt + F5 or by selecting Debug > Execute Project in Python Interactive. To change the startup file, right-click the file to use and select Set as Startup Item (or Set as Startup File in older versions of Visual Studio).

If you remove the selected startup file from a project and don't select an alternate file, Visual Studio doesn't know what Python file to use to start the project. In this case, Visual Studio 2017 version 15.6 and later shows an error. Earlier versions either open an output window with the Python interpreter running, or the output window opens and then immediately closes. If you encounter any of these behaviors, check that you have an assigned startup file.

Tip

To keep the output window open, right-click your project and select Properties. In the dialog, select the Debug tab, and then add the -i flag to the Interpreter Arguments field. This argument causes the interpreter to go into interactive mode after a program completes. The window stays open until you close it, such as by using the keyboard shortcut Ctrl+E+Enter.

A new project is always associated with the default global Python environment. To associate the project with a different environment (including virtual environments), right-click the Python Environments node in the project. Select Add Environment and then select the environments you want. You can also use the environments drop-down control on the toolbar to select an environment or add another environment to the project.

Screenshot that shows the Add Environment command on the Python toolbar in Visual Studio.

To change the active environment, right-click the desired environment in Solution Explorer and select Activate Environment as shown in the following image. For more information, see Select an environment for a project.

Screenshot that shows how to activate an environment for a Python project in Visual Studio.

Project templates

Visual Studio gives you many ways to set up a Python project, either from scratch or from existing code. To use a template, select File > New > Project or right-click the solution in Solution Explorer and select Add > New Project. In the new project dialog, you can see Python-specific templates by searching on Python or by selecting the Language > Python node:

Screenshot that shows the new project dialog with available Python templates in Visual Studio.

The following templates are available in Visual Studio version 2022.

Template Description
From existing Python code Creates a Visual Studio project from existing Python code in a folder structure.
Python Application Provides a basic project structure for a new Python application with a single, empty source file. By default, the project runs in the console interpreter of the default global environment. You can change assign a different environment.
Web projects Projects for web apps based on various frameworks including Bottle, Django, and Flask.
Background Application (IoT) Supports deploying Python projects to run as background services on devices. For more information, see the Windows IoT Dev Center.
Python Extension Module This template appears under Visual C++ if you install the Python native development tools with the Python workload in Visual Studio 2017 or later (see Installation). The template provides the core structure for a C++ extension DLL, similar to the structure described in Create a C++ extension for Python.

The following templates are available in Visual Studio version 2019. Not all templates available in version 2019 are available in earlier versions of Visual Studio.

Template Description
From existing Python code Creates a Visual Studio project from existing Python code in a folder structure.
Python Application Provides a basic project structure for a new Python application with a single, empty source file. By default, the project runs in the console interpreter of the default global environment. You can change assign a different environment.
Web projects Projects for web apps based on various frameworks including Bottle, Django, and Flask.
Background Application (IoT) Supports deploying Python projects to run as background services on devices. For more information, see the Windows IoT Dev Center.
Python Extension Module This template appears under Visual C++ if you install the Python native development tools with the Python workload in Visual Studio 2017 or later (see Installation). The template provides the core structure for a C++ extension DLL, similar to the structure described in Create a C++ extension for Python.
IronPython Application Uses IronPython by default and enables .NET interop and mixed-mode debugging with .NET languages. This template is similar to the Python Application template.
IronPython WPF Application Provides a project structure by using IronPython with Windows Presentation Foundation XAML files for the application user interface. Visual Studio provides a XAML UI designer, code-behind can be written in Python, and the application runs without displaying a console.
IronPython Silverlight Web Page Creates an IronPython project that runs in a browser by using Silverlight. The application's Python code is included in the web page as script. A boilerplate script tag pulls down JavaScript code to initialize IronPython running inside of Silverlight, from which your Python code can interact with the DOM.
IronPython Windows Forms Application Builds a project structure with IronPython and UI created by using code with Windows Forms. The application runs without displaying a console.

Note

Because Python is an interpreted language, Python projects in Visual Studio don't produce a stand-alone executable like other compiled language projects such as C#. For more information, see questions and answers.

Create a project from existing files

Follow these steps to create a project from existing files.

Important

The following process doesn't move or copy any original source files. If you want to work with a copy of your files, first duplicate the folder and then create the project.

  1. Launch Visual Studio and select File > New > Project.

  2. In the Create a new project dialog, search for python, and select the From Existing Python code template, and select Next.

  3. In the Configure your new project dialog, enter a project Name and Location, choose the solution to contain the project, and select Create.

  4. In the Create New Project from Existing Python Code wizard, set the Folder path to your existing code, set a Filter for file types, and specify any Search paths that your project requires, then select Next. If you don't know the search paths, leave the field blank.

    Screenshot of a New Project creation from Existing Code, including choosing the folder path, file type filters, and search paths.

  5. On the next page, select the Startup file for your project. Visual Studio selects the default global Python interpreter and version. You can change the environment by using the dropdown menu. When you're ready, select Next.

    Note

    The dialog shows only files in the root folder. If the file you want is in a subfolder, leave the startup file blank. You can set the startup file in Solution Explorer, as described in a later step.

    Screenshot of New Project Creation from Existing Code window, including choosing the startup file and Python environment.

  6. Select the location to store the project file (a .pyproj file on disk). If applicable, you can also include autodetection of virtual environments and customize the project for different web frameworks. If you're unsure of these options, leave the fields set to the defaults.

    Screenshot of a New Project creation from Existing Code window, including the location for the project file and other optional settings.

  7. Select Finish.

    Visual Studio creates the project and opens it in Solution Explorer. If you want to move the .pyproj file to a different location, select the file in Solution Explorer, and then select File > Save As on the toolbar. This action updates file references in the project, but it doesn't move any code files.

  8. To set a different startup file, locate the file in Solution Explorer, right-click the file, and select Set as Startup File.

Linked files

Linked files are files that are brought into a project but typically reside outside of the application's project folders. These files appear in Solution Explorer as normal files with an overlaid shortcut icon:

Linked files are specified in the .pyproj file by using the <Compile Include="..."> element. Linked files are implicit if they use a relative path outside of the directory structure. If the files use paths within Solution Explorer, the linked files are explicit. The following example shows explicitly linked files:

<Compile Include="..\test2.py">
    <Link>MyProject\test2.py</Link>
</Compile>

Linked files are ignored under the following conditions:

  • The linked file contains Link metadata and the path specified in the Include attribute lives within the project directory.
  • The linked file duplicates a file that exists within the project hierarchy.
  • The linked file contains Link metadata and the Link path is a relative path outside of the project hierarchy.
  • The link path is rooted.

Work with linked files

To add an existing item as a link, right-click the folder in the project where you want to add the file and select Add > Existing Item. In the dialog, select a file and then select Add > Add as Link. If there are no conflicting files, this command creates a link in the selected folder. However, the link isn't added if there's an existing file with the same name or a link to that file already exists in the project.

If you attempt to link to a file that already exists in the project folders, the file is added as a normal file and not as a link. To convert a file into a link, select File > Save As to save the file to a location outside of the project hierarchy. Visual Studio automatically converts the file into a link. Similarly, a link can be converted back by using File > Save As to save the file somewhere within the project hierarchy.

If you move a linked file in Solution Explorer, the link is moved but the actual file is unaffected. Similarly, deleting a link removes the link without affecting the file.

Linked files can't be renamed.

References

Visual Studio projects support adding references to projects and extensions, which appear under the References node in Solution Explorer:

Screenshot that shows how to Add an extension reference in Python projects in Visual Studio.

Extension references typically indicate dependencies between projects and are used to provide IntelliSense at design time or linking at compile time. Python projects use references in a similar fashion, but due to the dynamic nature of Python they're primarily used at design time to provide improved IntelliSense. They can also be used for deployment to Microsoft Azure to install other dependencies.

Work with extension modules

A reference to a .pyd file enables IntelliSense for the generated module. Visual Studio loads the .pyd file into the Python interpreter and introspects its types and functions. Visual Studio also attempts to parse the doc strings for functions to provide signature help.

If at any time the extension module is updated on disk, Visual Studio reanalyzes the module in the background. This action has no effect on run-time behavior but some completions aren't available until analysis is complete.

You might also need to add a search path to the folder that contains the module.

Work with .NET projects

When working with IronPython, you can add references to .NET assemblies to enable IntelliSense. For .NET projects in your solution, right-click the References node in your Python project, and select Add Reference. In the dialog, select the Projects tab, and browse to the desired project. For DLLs that you downloaded separately, select the Browse tab instead and browse to the desired DLL.

Because references in IronPython aren't available until after a call to the clr.AddReference('<AssemblyName>') method, you also need to add an appropriate clr.AddReference method call to the assembly. This call is typically added at the beginning of your code. For example, the code created by the IronPython Windows Forms Application (available in Visual Studio 2019) project template in Visual Studio includes two calls at the top of the file:

import clr
clr.AddReference('System.Drawing')
clr.AddReference('System.Windows.Forms')

from System.Drawing import *
from System.Windows.Forms import *

# Other code omitted

Work with WebPI projects

You can add references to Web Platform Installer (WebPI) product entries for deployment to Microsoft Azure Cloud Services where you can install more components via the WebPI feed. By default, the feed displayed is Python-specific and includes Django, CPython, and other core components. You can also select your own feed as shown in the following image. When you publish to Microsoft Azure, a setup task installs all of the referenced products.

Important

WebPI projects aren't available in Visual Studio 2017 or Visual Studio 2019.

Screenshot that shows Web Platform Installer (WebPI) references in Visual Studio.