Skip to content

Commit

Permalink
Merge pull request #1679 from rstudio/fix/isolate-activate_this
Browse files Browse the repository at this point in the history
Rewrite `py_activate_virtualenv()` to run `activate_this.py` isolated
  • Loading branch information
t-kalinowski authored Oct 8, 2024
2 parents d2c83b0 + b35e722 commit 5fd3772
Showing 1 changed file with 16 additions and 18 deletions.
34 changes: 16 additions & 18 deletions src/python.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2725,30 +2725,28 @@ extern "C" PyObject* initializeRPYCall(void) {


// [[Rcpp::export]]
void py_activate_virtualenv(const std::string& script)
{
void py_activate_virtualenv(const std::string& script) {

// get main dict
PyObject* main = PyImport_AddModule("__main__");
PyObject* mainDict = PyModule_GetDict(main);
// import runpy
PyObjectPtr runpy_module(PyImport_ImportModule("runpy"));
if (runpy_module.is_null())
throw PythonException(py_fetch_error());

// inject __file__
PyObjectPtr file(as_python_str(script));
int res = PyDict_SetItemString(mainDict, "__file__", file);
if (res != 0)
// get ref to runpy.run_path()
PyObjectPtr run_path_func(PyObject_GetAttrString(runpy_module, "run_path"));
if (run_path_func.is_null())
throw PythonException(py_fetch_error());

// read the code in the script
std::ifstream ifs(script.c_str());
if (!ifs)
stop("Unable to open file '%s' (does it exist?)", script);
std::string code((std::istreambuf_iterator<char>(ifs)),
(std::istreambuf_iterator<char>()));
// make a Python string of the script path
PyObjectPtr py_script_path(PyUnicode_FromString(script.c_str()));
if (py_script_path.is_null())
throw PythonException(py_fetch_error());

// run string
PyObjectPtr runRes(PyRun_StringFlags(code.c_str(), Py_file_input, mainDict, NULL, NULL));
if (runRes.is_null())
// Call runpy.run_path(script_path) function
PyObjectPtr result(PyObject_CallFunctionObjArgs(run_path_func, py_script_path.get(), NULL));
if (result.is_null())
throw PythonException(py_fetch_error());

}

void trace_print(int threadId, PyFrameObject *frame) {
Expand Down

0 comments on commit 5fd3772

Please sign in to comment.