'How to configure embedded python in c

I am trying to embed python interpreter in c program to run python code from inside the c program

#include <stdio.h>
#include <python.h>

int main(void)
{
    putenv("PYTHONHOME=/f/_C_/py_in_c"); 
    putenv("PYTHONPATH=/f/_C_/py_in_c/a.exe"); 
    Py_SetProgramName("test");
    Py_Initialize();
    PyRun_SimpleString("print('hello world')");
    Py_Initialize();

    return 0;
}

The output I get

Python path configuration:
  PYTHONHOME = '/f/_C_/py_in_c'
  PYTHONPATH = '/f/_C_/py_in_c/a.exe'
  program name = '\u6574\u7473\u7000\u6972\u746e\u2728\u6568\u6c6c\u206f\u6f77\u6c72\u2764)'
  isolated = 0
  environment = 1
  user site = 1
  import site = 1
  sys._base_executable = 'F:/_C_/py_in_c/a.exe'
  sys.base_prefix = '/f/_C_/py_in_c'
  sys.base_exec_prefix = '/f/_C_/py_in_c'
  sys.platlibdir = 'lib'
  sys.executable = 'F:/_C_/py_in_c/a.exe'
  sys.prefix = '/f/_C_/py_in_c'
  sys.exec_prefix = '/f/_C_/py_in_c'
  sys.path = [
    '/f/_C_/py_in_c/a.exe',
    '/f/_C_/py_in_c/lib/python39.zip',
    '/f/_C_/py_in_c/lib/python3.9',
    '',
  ]
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'

Current thread 0x00000158 (most recent call first):
<no Python frame>

I downloaded the source code for python3.9 which is the same version running on my system then I compiled the main.c and linked python like so gcc main.c -L /f/_C_/Python-3.9.10/Lib -I /f/_C_/Python-3.9.10/Include -lpython3.9 now I got a file called a.exe that outputs the above error when I run, I am clueless to why I get such output and if I am missing something

Do I have to set the encoding in the environment variable and if so what encoding do I use



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source