Add dirname of script file to sys.path

This matches the behavior of running a Python interpreter, where the
first element of sys.path is the dirname of the script being run.

This allows importing of files and modules in the same directory without
messing with PYTHONPATH or similar.
This commit is contained in:
Mohamed Gaber 2024-09-10 13:41:04 +03:00
parent 38f9e6c3a2
commit 738b5eef0b
No known key found for this signature in database
1 changed files with 4 additions and 2 deletions

View File

@ -660,11 +660,13 @@ int main(int argc, char **argv)
PyList_SetItem(new_argv, 0, PyUnicode_FromString(scriptfile.c_str()));
for (int i = optind; i < argc; ++i)
PyList_SetItem(new_argv, i - optind + 1, PyUnicode_FromString(argv[i]));
PyObject *old_argv = PyObject_GetAttrString(sys, "argv");
PyObject_SetAttrString(sys, "argv", new_argv);
Py_DECREF(old_argv);
PyRun_SimpleString(("import os;sys.path.insert(0, os.path.dirname(os.path.abspath(\""+scriptfile+"\")))").c_str());
FILE *scriptfp = fopen(scriptfile.c_str(), "r");
if (PyRun_SimpleFile(scriptfp, scriptfile.c_str()) != 0) {
log_error("Python interpreter encountered an error:\n");