53 lines
1.5 kB
1
defmodule Blog.PythonRunner do
2
require Logger
3
4
def init_python do
5
try do
6
config_str = """
7
[project]
8
name = "python_demo"
9
version = "0.0.1"
10
requires-python = ">=3.8"
11
"""
12
13
python_path = System.get_env("PYTHONX_PYTHON_PATH", "not set")
14
cache_dir = System.get_env("PYTHONX_CACHE_DIR", "not set")
15
Pythonx.uv_init(config_str)
16
:ok
17
rescue
18
e in RuntimeError ->
19
case String.contains?(Exception.message(e), "already been initialized") do
20
true ->
21
Logger.info("Python interpreter was already initialized, continuing")
22
:ok
23
false ->
24
Logger.error("Failed to initialize Python: #{Exception.message(e)}")
25
{:error, Exception.message(e)}
26
end
27
28
e ->
29
Logger.error("Unexpected error initializing Python: #{inspect(e)}")
30
{:error, inspect(e)}
31
end
32
end
33
34
def run_python_code(code) when is_binary(code) do
35
case init_python() do
36
:ok ->
37
try do
38
# Execute the provided Python code
39
{result, _} = Pythonx.eval(code, %{})
40
decoded = Pythonx.decode(result)
41
42
{:ok, decoded}
43
rescue
44
e ->
45
Logger.error("Error executing Python code: #{inspect(e)}")
46
{:error, "Failed to execute Python code: #{inspect(e)}"}
47
end
48
49
{:error, reason} ->
50
{:error, "Python initialization failed: #{reason}"}
51
end
52
end
53
end
54