# VenvPythonEnvironment

## ``autogen.environments.venv_python_environment.VenvPythonEnvironment``

```python
VenvPythonEnvironment(python_version=None, python_path=None, venv_path=None)
```

Bases: `PythonEnvironment`

A Python environment using a virtual environment (venv).

Initialize a virtual environment for Python execution.

If you pass in a `venv_path` the path will be checked for a valid venv. If the venv doesn't exist it will be created using the `python_version` or `python_path` provided.

If the `python_version` or `python_path` is provided and the `venv_path` is not, a temporary directory will be created for venv and it will be setup with the provided python version.

If `python_path` is provided, it will take precedence over `python_version`.

The python version will not be installed if it doesn't exist and a RuntimeError will be raised.

| PARAMETER | DESCRIPTION |
| --- | --- |
| `python_version` | The Python version to use (e.g., "3.11"), otherwise defaults to the current executing Python version. Ignored if `venv_path` is provided and has a valid environment already.<br>**TYPE:**`str | None`**DEFAULT:**`None` |
| `python_path` | Optional direct path to a Python executable to use (must include the executable). Takes precedence over `python_version` if both are provided.<br>**TYPE:**`str | None`**DEFAULT:**`None` |
| `venv_path` | Optional path for the virtual environment, will create it if it doesn't exist. If None, creates a temp directory.<br>**TYPE:**`str | None`**DEFAULT:**`None` |

Source code in `autogen/environments/venv_python_environment.py`

|     |     |
| --- | --- |
| ```<br>22<br>23<br>24<br>25<br>26<br>27<br>28<br>29<br>30<br>31<br>32<br>33<br>34<br>35<br>36<br>37<br>38<br>39<br>40<br>41<br>42<br>43<br>44<br>45<br>46<br>47<br>48<br>``` | ```<br>def __init__(<br>    self,<br>    python_version: str | None = None,<br>    python_path: str | None = None,<br>    venv_path: str | None = None,<br>):<br>    """Initialize a virtual environment for Python execution.<br>    If you pass in a venv_path the path will be checked for a valid venv. If the venv doesn't exist it will be created using the python_version or python_path provided.<br>    If the python_version or python_path is provided and the venv_path is not, a temporary directory will be created for venv and it will be setup with the provided python version.<br>    If python_path is provided, it will take precedence over python_version.<br>    The python version will not be installed if it doesn't exist and a RuntimeError will be raised.<br>    Args:<br>        python_version: The Python version to use (e.g., "3.11"), otherwise defaults to the current executing Python version. Ignored if venv_path is provided and has a valid environment already.<br>        python_path: Optional direct path to a Python executable to use (must include the executable). Takes precedence over python_version if both are provided.<br>        venv_path: Optional path for the virtual environment, will create it if it doesn't exist. If None, creates a temp directory.<br>    """<br>    self.python_version = python_version<br>    self.python_path = python_path<br>    self.venv_path = venv_path<br>    self.created_venv = False<br>    self._executable = None<br>    super().__init__()<br>``` |

### ``python_version`instance-attribute``

```
python_version = python_version
```

### ``python_path`instance-attribute``

```
python_path = python_path
```

### ``venv_path`instance-attribute``

```
venv_path = venv_path
```

### ``created_venv`instance-attribute``

```
created_venv = False
```

### ``get_executable``

```
get_executable()
```

Get the path to the Python executable in the virtual environment.

Source code in `autogen/environments/venv_python_environment.py`

|     |     |
| --- | --- |
| ```<br>114<br>115<br>116<br>117<br>118<br>``` | ```<br>def get_executable(self) -> str:<br>    """Get the path to the Python executable in the virtual environment."""<br>    if not self._executable or not os.path.exists(self._executable):<br>        raise RuntimeError("Virtual environment Python executable not found")<br>    return self._executable<br>``` |

### ``execute_code`async``

```
execute_code(code, script_path, timeout=30)
```

Execute code in the virtual environment.

Source code in `autogen/environments/venv_python_environment.py`

|     |     |
| --- | --- |
| ```<br>120<br>121<br>122<br>123<br>124<br>125<br>126<br>127<br>128<br>129<br>130<br>131<br>132<br>133<br>134<br>135<br>136<br>137<br>138<br>139<br>140<br>141<br>142<br>143<br>144<br>145<br>146<br>147<br>148<br>149<br>150<br>151<br>152<br>153<br>154<br>155<br>``` | ```<br>async def execute_code(self, code: str, script_path: str, timeout: int = 30) -> dict[str, Any]:<br>    """Execute code in the virtual environment."""<br>    try:<br>        # Get the Python executable<br>        python_executable = self.get_executable()<br>        # Verify the executable exists<br>        if not os.path.exists(python_executable):<br>            return {"success": False, "error": f"Python executable not found at {python_executable}"}<br>        # Ensure the directory for the script exists<br>        script_dir = os.path.dirname(script_path)<br>        if script_dir:<br>            os.makedirs(script_dir, exist_ok=True)<br>        # Write the code to the script file using anyio.to_thread.run_sync (from base class)<br>        await to_thread.run_sync(self._write_to_file, script_path, code)<br>        logging.info(f"Wrote code to {script_path}")<br>        try:<br>            # Execute directly with subprocess using anyio.to_thread.run_sync for better reliability<br>            result = await to_thread.run_sync(self._run_subprocess, [python_executable, script_path], timeout)<br>            # Main execution result<br>            return {<br>                "success": result.returncode == 0,<br>                "stdout": result.stdout,<br>                "stderr": result.stderr,<br>                "returncode": result.returncode,<br>            }<br>        except subprocess.TimeoutExpired:<br>            return {"success": False, "error": f"Execution timed out after {timeout} seconds"}<br>    except Exception as e:<br>        return {"success": False, "error": f"Execution error: {str(e)}"}<br>``` |

### ``get_current_python_environment`classmethod``

```
get_current_python_environment(python_environment=None)
```

Get the current Python environment or the specified one if provided.

| PARAMETER | DESCRIPTION |
| --- | --- |
| `python_environment` | Optional environment to return if specified.<br>**TYPE:**`Optional[PythonEnvironment]`**DEFAULT:**`None` |

| RETURNS | DESCRIPTION |
| --- | --- |
| `Optional[PythonEnvironment]` | The current Python environment or None if none is active. |

Source code in `autogen/environments/python_environment.py`

|     |     |
| --- | --- |
| ```<br>108<br>109<br>110<br>111<br>112<br>113<br>114<br>115<br>116<br>117<br>118<br>119<br>120<br>121<br>122<br>123<br>124<br>125<br>``` | ```<br>@classmethod<br>def get_current_python_environment(<br>    cls, python_environment: Optional["PythonEnvironment"] = None<br>) -> Optional["PythonEnvironment"]:<br>    """Get the current Python environment or the specified one if provided.<br>    Args:<br>        python_environment: Optional environment to return if specified.<br>    Returns:<br>        The current Python environment or None if none is active.<br>    """<br>    if python_environment is not None:<br>        return python_environment<br>    try:<br>        return cls._current_python_environment.get()<br>    except LookupError:<br>        return None<br>``` |
