Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #2845 - LocalCommandLineCodeExecutor is not working with virtual environments #2926

Merged
merged 8 commits into from
Jun 19, 2024
5 changes: 3 additions & 2 deletions autogen/coding/local_commandline_code_executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,10 +294,11 @@ def _execute_code_dont_check_setup(self, code_blocks: List[CodeBlock]) -> Comman
env = os.environ.copy()

if self._virtual_env_context:
path_with_virtualenv = rf"{self._virtual_env_context.bin_path}{os.pathsep}{env['PATH']}"
virtual_env_abs_path = os.path.abspath(self._virtual_env_context.bin_path)
path_with_virtualenv = rf"{virtual_env_abs_path}{os.pathsep}{env['PATH']}"
env["PATH"] = path_with_virtualenv
if WIN32:
activation_script = os.path.join(self._virtual_env_context.bin_path, "activate.bat")
activation_script = os.path.join(virtual_env_abs_path, "activate.bat")
cmd = [activation_script, "&&", *cmd]

try:
Expand Down
28 changes: 28 additions & 0 deletions test/coding/test_commandline_code_executor.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import os
import shutil
import sys
import tempfile
import uuid
Expand Down Expand Up @@ -411,3 +412,30 @@ def test_local_executor_with_custom_python_env():

assert execution.exit_code == 0
assert execution.output.strip() == "True"


def test_local_executor_with_custom_python_env_in_local_relative_path():
try:
relative_folder_path = "temp_folder"
if not os.path.isdir(relative_folder_path):
os.mkdir(relative_folder_path)

venv_path = os.path.join(relative_folder_path, ".venv")
env_builder = venv.EnvBuilder(with_pip=True)
env_builder.create(venv_path)
env_builder_context = env_builder.ensure_directories(venv_path)

executor = LocalCommandLineCodeExecutor(work_dir=relative_folder_path, virtual_env_context=env_builder_context)
code_blocks = [
CodeBlock(code="import sys; print(sys.executable)", language="python"),
]
execution = executor.execute_code_blocks(code_blocks)

assert execution.exit_code == 0

# Check if the expected venv is used
bin_path = os.path.abspath(env_builder_context.bin_path)
assert Path(execution.output.strip()).parent.samefile(bin_path)
finally:
if os.path.isdir(relative_folder_path):
shutil.rmtree(relative_folder_path)
Loading