Skip to content

Commit

Permalink
Fix #2845 - LocalCommandLineCodeExecutor is not working with virtual …
Browse files Browse the repository at this point in the history
…environments (#2926)

* Used absolute path of virtual environment bin path in local command executors

* Checked if the expected venv is used or not

* Added code comments for documentation

* fix: format issue - shutil lib

---------

Co-authored-by: Chi Wang <[email protected]>
Co-authored-by: Li Jiang <[email protected]>
  • Loading branch information
3 people authored Jun 19, 2024
1 parent 0bc08ce commit ded8e1b
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
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)

0 comments on commit ded8e1b

Please sign in to comment.