Python 3.6, inline C ++, add module path, TypeError: Byte object needed, not 'str'

I am trying to expand the search path of a module when nesting Python 3.6 in a C ++ application. Code to insert the current working directory into the system module search path:

PyObject *sysPath = PySys_GetObject("path");
PyObject *path = PyBytes_FromString(".");
int result = PyList_Insert(sysPath, 0, path);

      

This works fine (no errors), but Python doesn't really like it when I try to run the module:

PyObject *pModule = PyImport_ImportModule("python_demo_x");

      

The error reported by Python:

Could not load module python_demo_x
Traceback (most recent call last):
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 946, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 885, in _find_spec
  File "<frozen importlib._bootstrap_external>", line 1157, in find_spec
  File "<frozen importlib._bootstrap_external>", line 1129, in _get_spec
  File "<frozen importlib._bootstrap_external>", line 1245, in find_spec
  File "<frozen importlib._bootstrap_external>", line 1302, in _fill_cache
TypeError: a bytes-like object is required, not 'str'

      

Through trial and error, I found that wrapping the path in double quotes solves the problem:

PyObject *path = PyBytes_FromString("\".\"");

      

I can't find any documentation indicating the need to wrap the path. Is this required or is there something else wrong?

+3


source to share


1 answer


Python 3 has changed the way strings are displayed. I ran into this when using Popen to execute other applications and code from outside.

Try changing all your strings from "some-string" to b "some-string" which encodes it as a byte string. You may need to decode the resulting byte object into a string if you need to return a string value. You would do it like this: .decode ('utf-8')



From the Python 3.6 docs: "In Python 3.x, these implicit conversions are gone - conversions between 8-bit binary data and Unicode text must be explicit, and bytes and string objects will always compare unequal."

More information is available here: https://docs.python.org/3/library/stdtypes.html

0


source







All Articles