Skip to content

Windows 10: Enable Python Embedding Without Setting PYTHONPATH and PYTHONHOME #2369

@wolfleyb

Description

@wolfleyb

I would like to reopen this issue that was started here. I have to set my PYTHONPATH and PYTHONHOME environment variables in order to embed the python interpreter in C++. Everything I read on StackOverflow says that one should avoid setting those env variables.

For example, when trying to run this simple code:

#include <pybind11/embed.h>
void main() {
   pybind11::scoped_interpreter guard{};
   pybind11::exec("print('hello world')");
}

I always get the following error if those variables are not set:

Python path configuration:
PYTHONHOME = (not set)
PYTHONPATH = (not set)
program name = 'python'
isolated = 0
environment = 1
user site = 1
import site = 1
sys._base_executable = 'C:\\Users\\ben.wolfley\\Desktop\\Test3\\vsstudio\\Debug\\pybind11app.exe'
sys.base_prefix = 'C:\\Users\\ben.wolfley\\Anaconda3'
sys.base_exec_prefix = 'C:\\Users\\ben.wolfley\\Anaconda3'
sys.executable = 'C:\\Users\\ben.wolfley\\Desktop\\Test3\\vsstudio\\Debug\\pybind11app.exe'
sys.prefix = 'C:\\Users\\ben.wolfley\\Anaconda3'
sys.exec_prefix = 'C:\\Users\\ben.wolfley\\Anaconda3'
sys.path = [
'C:\\Users\\ben.wolfley\\Anaconda3\\python38.zip',
'.\\DLLs',
'.\\lib',
'C:\\Users\\ben.wolfley\\Desktop\\Test3\\vsstudio\\Debug',
]
Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
Python runtime state: core initialized
ModuleNotFoundError: No module named 'encodings'`

Once PYTHONHOME and PYTHONPATH are set, it runs fine. It would be nice to run the interpreter without relying on PYTHONPATH and PYTHONHOME.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions