cli/python: error-checking, python interpreter bugfix

* Less brittle method of adding script dirname to sys.path
* Check if scriptfp successfully opens before using it
* Move `log_error` to after `PyErr_Print()` is called
This commit is contained in:
Mohamed Gaber 2024-09-30 17:38:43 +03:00
parent 8dac27108e
commit 35c8ad61ac
No known key found for this signature in database
1 changed files with 8 additions and 2 deletions

View File

@ -665,13 +665,19 @@ int main(int argc, char **argv)
PyObject_SetAttrString(sys, "argv", new_argv); PyObject_SetAttrString(sys, "argv", new_argv);
Py_DECREF(old_argv); Py_DECREF(old_argv);
PyRun_SimpleString(("import os;sys.path.insert(0, os.path.dirname(os.path.abspath(\""+scriptfile+"\")))").c_str()); PyObject *py_path = PyUnicode_FromString(scriptfile.c_str());
PyObject_SetAttrString(sys, "_yosys_script_path", py_path);
Py_DECREF(py_path);
PyRun_SimpleString("import os, sys; sys.path.insert(0, os.path.dirname(os.path.abspath(sys._yosys_script_path)))");
FILE *scriptfp = fopen(scriptfile.c_str(), "r"); FILE *scriptfp = fopen(scriptfile.c_str(), "r");
if (scriptfp == nullptr) {
log_error("Failed to open file '%s' for reading.\n", scriptfile.c_str());
}
if (PyRun_SimpleFile(scriptfp, scriptfile.c_str()) != 0) { if (PyRun_SimpleFile(scriptfp, scriptfile.c_str()) != 0) {
log_error("Python interpreter encountered an error:\n");
log_flush(); log_flush();
PyErr_Print(); PyErr_Print();
log_error("Python interpreter encountered an exception.");
} }
#else #else
log_error("Can't execute Python script: this version of yosys is not built with Python support enabled.\n"); log_error("Can't execute Python script: this version of yosys is not built with Python support enabled.\n");