Skip to content

Commit f2db172

Browse files
committed
fix(sys.argv): support unicode [3] fix sys.path issue
* PySys_SetArgv is deprecated since python 3.11. It's original behavior will insert script's directory into sys.path. It's replace by PyConfig, but PyConfig only update sys.path when executing Py_Main or Py_RunMain. So it's better to update sys.path by pyconcrete.
1 parent 6287f61 commit f2db172

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

src/pyconcrete_exe/pyconcrete_exe.c

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343
int createAndInitPyconcreteModule();
4444
int execPycContent(PyObject* pyc_content, const _CHAR* filepath);
4545
int runFile(const _CHAR* filepath);
46+
int prependSysPath0(const _CHAR* script_path);
4647
void initPython(int argc, _CHAR *argv[]);
4748
PyObject* getFullPath(const _CHAR* filepath);
4849

@@ -81,6 +82,7 @@ int main(int argc, char *argv[])
8182
}
8283
else
8384
{
85+
prependSysPath0(argv[1]);
8486
ret = runFile(argv[1]);
8587
}
8688
}
@@ -295,6 +297,35 @@ int runFile(const _CHAR* filepath)
295297
}
296298

297299

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+
298329
PyObject* getFullPath(const _CHAR* filepath)
299330
{
300331
// import os.path

0 commit comments

Comments
 (0)