次の方法で共有


PythonAppResourceBuilderExtensions.WithVirtualEnvironment<T> Method

Definition

Configures a custom virtual environment path for the Python application.

public static Aspire.Hosting.ApplicationModel.IResourceBuilder<T> WithVirtualEnvironment<T>(this Aspire.Hosting.ApplicationModel.IResourceBuilder<T> builder, string virtualEnvironmentPath, bool createIfNotExists = true) where T : Aspire.Hosting.Python.PythonAppResource;
static member WithVirtualEnvironment : Aspire.Hosting.ApplicationModel.IResourceBuilder<'T (requires 'T :> Aspire.Hosting.Python.PythonAppResource)> * string * bool -> Aspire.Hosting.ApplicationModel.IResourceBuilder<'T (requires 'T :> Aspire.Hosting.Python.PythonAppResource)> (requires 'T :> Aspire.Hosting.Python.PythonAppResource)
<Extension()>
Public Function WithVirtualEnvironment(Of T As PythonAppResource) (builder As IResourceBuilder(Of T), virtualEnvironmentPath As String, Optional createIfNotExists As Boolean = true) As IResourceBuilder(Of T)

Type Parameters

T

Parameters

builder
IResourceBuilder<T>

The resource builder.

virtualEnvironmentPath
String

The path to the virtual environment. Can be absolute or relative to the app directory. When relative, it is resolved from the working directory of the Python application. Common values include ".venv", "venv", or "myenv".

createIfNotExists
Boolean

Whether to automatically create the virtual environment if it doesn't exist. Defaults to true. Set to false to disable automatic venv creation (the venv must already exist).

Returns

A reference to the IResourceBuilder<T> for method chaining.

Examples

Configure a Python app to use a custom virtual environment:

var python = builder.AddPythonApp("api", "../python-api", "main.py")
    .WithVirtualEnvironment("myenv");

// Disable automatic venv creation (require venv to exist)
var python2 = builder.AddPythonApp("api2", "../python-api2", "main.py")
    .WithVirtualEnvironment("myenv", createIfNotExists: false);

Remarks

This method updates the Python executable path to use the specified virtual environment.

By default (createIfNotExists = true), if the virtual environment doesn't exist, it will be automatically created before running the application (when using pip package manager, not uv). Set createIfNotExists to false to disable this behavior and require the venv to already exist.

Virtual environments allow Python applications to have isolated dependencies separate from the system Python installation. This is the recommended approach for Python applications.

When you explicitly specify a virtual environment path using this method, the path is used verbatim. The automatic multi-___location lookup (checking both app and AppHost directories) only applies when using the default ".venv" path during initial app creation via AddPythonScript, AddPythonModule, or AddPythonExecutable.

Applies to