2
# tag: pep489, subinterpreter
4
PYTHON setup.py build_ext --inplace
5
PYTHON -c "import subtest; subtest.run_main()"
6
PYTHON -c "import subtest; subtest.run_sub()"
7
PYTHON -c "import subtest; subtest.run_main(); subtest.run_sub()"
9
######## setup.py ########
11
from Cython.Build.Dependencies import cythonize
12
from distutils.core import setup
15
ext_modules = cythonize("**/*.pyx"),
18
######## subtest.pyx ########
22
/* Copied from CPython's _testcapi.c module */
23
static PyObject *run_in_subinterpreter(const char *code) {
25
PyThreadState *substate, *mainstate;
27
mainstate = PyThreadState_Get();
29
PyThreadState_Swap(NULL);
31
substate = Py_NewInterpreter();
32
if (substate == NULL) {
33
/* Since no new thread state was created, there is no exception to
34
propagate; raise a fresh one after swapping in the old thread
36
PyThreadState_Swap(mainstate);
37
PyErr_SetString(PyExc_RuntimeError, "sub-interpreter creation failed");
40
r = PyRun_SimpleString(code);
41
Py_EndInterpreter(substate);
43
PyThreadState_Swap(mainstate);
44
return PyLong_FromLong(r);
47
object run_in_subinterpreter(const char *code)
50
MAIN_HAS_IMPORTED = False
53
global MAIN_HAS_IMPORTED
54
MAIN_HAS_IMPORTED = True
55
import package.subtest
56
from package import subtest
59
assert 0 == run_in_subinterpreter(b'1+1')
60
assert 0 == run_in_subinterpreter(b'2+2')
62
# The subinterpreter does not add the current working directory to
63
# sys.path, so we need to add it manually.
64
pre = b'import sys; sys.path.insert(0, "."); '
65
assert 0 == run_in_subinterpreter(pre + b'import package')
66
assert 0 == run_in_subinterpreter(pre + b'import package')
68
result = run_in_subinterpreter(pre + b'import package.subtest')
69
if not MAIN_HAS_IMPORTED:
70
assert result == 0, result # imports only in subinterpreters are ok
72
assert result == -1, result # re-import in a different subinterpreter fails in Py3.5+ (with PEP-489)
75
######## package/__init__.py ########
77
######## package/subtest.pyx ########
79
print("Module loaded: %s" % __name__)