|
43 | 43 | int createAndInitPyconcreteModule(); |
44 | 44 | int execPycContent(PyObject* pyc_content, const _CHAR* filepath); |
45 | 45 | int runFile(const _CHAR* filepath); |
| 46 | +int prependSysPath0(const _CHAR* script_path); |
46 | 47 | void initPython(int argc, _CHAR *argv[]); |
47 | 48 | PyObject* getFullPath(const _CHAR* filepath); |
48 | 49 |
|
@@ -81,6 +82,7 @@ int main(int argc, char *argv[]) |
81 | 82 | } |
82 | 83 | else |
83 | 84 | { |
| 85 | + prependSysPath0(argv[1]); |
84 | 86 | ret = runFile(argv[1]); |
85 | 87 | } |
86 | 88 | } |
@@ -295,6 +297,35 @@ int runFile(const _CHAR* filepath) |
295 | 297 | } |
296 | 298 |
|
297 | 299 |
|
| 300 | +/* |
| 301 | + PySys_SetArgv is deprecated since python 3.11. It's original behavior will insert script's directory into sys.path. |
| 302 | + It's replace by PyConfig, but PyConfig only update sys.path when executing Py_Main or Py_RunMain. |
| 303 | + So it's better to update sys.path by pyconcrete. |
| 304 | + */ |
| 305 | +int prependSysPath0(const _CHAR* script_path) |
| 306 | +{ |
| 307 | + // script_dir = os.path.dirname(script_path) |
| 308 | + // sys.path.insert(0, script_dir) |
| 309 | + int ret = RET_OK; |
| 310 | + |
| 311 | + PyObject* py_script_path = getFullPath(script_path); |
| 312 | + PyObject* path_module = PyImport_ImportModule("os.path"); |
| 313 | + PyObject* dirname_func = PyObject_GetAttrString(path_module, "dirname"); |
| 314 | + PyObject* script_dir = PyObject_CallOneArg(dirname_func, py_script_path); |
| 315 | + |
| 316 | + PyObject* sys_path = PySys_GetObject("path"); |
| 317 | + if (PyList_Insert(sys_path, 0, script_dir) < 0) { |
| 318 | + ret = RET_FAIL; |
| 319 | + } |
| 320 | + |
| 321 | + Py_XDECREF(py_script_path); |
| 322 | + Py_XDECREF(path_module); |
| 323 | + Py_XDECREF(dirname_func); |
| 324 | + Py_XDECREF(script_dir); |
| 325 | + return ret; |
| 326 | +} |
| 327 | + |
| 328 | + |
298 | 329 | PyObject* getFullPath(const _CHAR* filepath) |
299 | 330 | { |
300 | 331 | // import os.path |
|
0 commit comments