8000 fix: add support for running python main function in UnsafeLocalCodeE… · NSFWExpert/adk-python@95e33ba · GitHub
[go: up one dir, main page]

Skip to content

Commit 95e33ba

Browse files
google-genai-botcopybara-github
authored andcommitted
fix: add support for running python main function in UnsafeLocalCodeExecutor when the code has an if __name__ == "__main__" statement.
Fixes google#791 PiperOrigin-RevId: 765359512
1 parent 4075290 commit 95e33ba

File tree

1 file changed

+11
-0
lines changed

1 file changed

+11
-0
lines changed

src/google/adk/code_executors/unsafe_local_code_executor.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,12 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
from __future__ import annotations
16+
1517
from contextlib import redirect_stdout
1618
import io
19+
import re
20+
from typing import Any
1721

1822
from pydantic import Field
1923
from typing_extensions import override
@@ -24,6 +28,12 @@
2428
from .code_execution_utils import CodeExecutionResult
2529

2630

31+
def _prepare_globals(code: str, globals_: dict[str, Any]) -> None:
32+
"""Prepare globals for code execution, injecting __name__ if needed."""
33+
if re.search(r"if\s+__name__\s*==\s*['\"]__main__['\"]", code):
34+
globals_['__name__'] = '__main__'
35+
36+
2737
class UnsafeLocalCodeExecutor(BaseCodeExecutor):
2838
"""A code executor that unsafely execute code in the current local context."""
2939

@@ -55,6 +65,7 @@ def execute_code(
5565
error = ''
5666
try:
5767
globals_ = {}
68+
_prepare_globals(code_execution_input.code, globals_)
5869
locals_ = {}
5970
stdout = io.StringIO()
6071
with redirect_stdout(stdout):

0 commit comments

Comments
 (0)
0