Skip to content

Commit ed981ff

Browse files
author
Christopher Rowley
committed
pass libptr by env var instead
1 parent 6aeeba0 commit ed981ff

2 files changed

Lines changed: 16 additions & 9 deletions

File tree

pysrc/juliacall/__init__.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -240,6 +240,11 @@ def args_from_config(config):
240240
jl_parse_opts(c.pointer(argc), c.pointer(argv))
241241
assert argc.value == 0
242242

243+
# override some environment variables
244+
# we do this here because PythonCall is initialised during jl_init if it is in a sysimg
245+
os.environ['JULIA_PYTHONCALL_EXECUTABLE'] = sys.executable or ''
246+
os.environ['__JULIA_PYTHONCALL_EMBEDDED_LIBPTR__'] = hex(c.pythonapi._handle)
247+
243248
# initialise julia
244249
try:
245250
jl_init = lib.jl_init_with_image__threading
@@ -269,23 +274,22 @@ def jlstr(x):
269274
return 'raw"' + x + '"'
270275
script = '''
271276
try
272-
Base.require(Main, :CompilerSupportLibraries_jll)
273-
global __PythonCall_libptr = Ptr{{Cvoid}}(UInt({}))
274-
ENV["JULIA_PYTHONCALL_EXE"] = {}
277+
import CompilerSupportLibraries_jll as _
275278
using PythonCall
276279
catch err
277280
print(stderr, "ERROR: ")
278281
showerror(stderr, err, catch_backtrace())
279282
flush(stderr)
280283
rethrow()
281284
end
282-
'''.format(
283-
hex(c.pythonapi._handle),
284-
jlstr(sys.executable or ''),
285-
)
285+
'''
286286
res = jl_eval(script.encode('utf8'))
287287
if res is None:
288288
raise Exception('PythonCall.jl did not start properly')
289+
290+
# unset this env var so any other julia processes started do not think they are
291+
# embedded in python
292+
os.environ.pop('__JULIA_PYTHONCALL_EMBEDDED_LIBPTR__', None)
289293

290294
CONFIG['inited'] = True
291295

src/C/context.jl

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -105,11 +105,14 @@ on_main_thread
105105

106106
function init_context()
107107

108-
CTX.is_embedded = hasproperty(Base.Main, :__PythonCall_libptr)
108+
CTX.is_embedded = haskey(ENV, "__JULIA_PYTHONCALL_EMBEDDED_LIBPTR__")
109109

110110
if CTX.is_embedded
111111
# In this case, getting a handle to libpython is easy
112-
CTX.lib_ptr = Base.Main.__PythonCall_libptr::Ptr{Cvoid}
112+
CTX.lib_ptr = Ptr{Cvoid}(parse(UInt, ENV["__JULIA_PYTHONCALL_EMBEDDED_LIBPTR__"]))
113+
# Delete the env var so subprocesses don't think they are embedded
114+
delete!(ENV, "__JULIA_PYTHONCALL_EMBEDDED_LIBPTR__")
115+
# Initialise pointers from libpython
113116
init_pointers()
114117
# Check Python is initialized
115118
Py_IsInitialized() == 0 && error("Python is not already initialized.")

0 commit comments

Comments
 (0)