GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — kactus2dev/PythonAPI/PythonInterpreter.cpp at main · kactus2/kactus2dev

Expand file tree

/

PythonInterpreter.cpp

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
382 lines (314 loc) · 10.7 KB
/

PythonInterpreter.cpp

Copy path

File metadata and controls

382 lines (314 loc) · 10.7 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
//-----------------------------------------------------------------------------
// File: PythonInterpreter.cpp
//-----------------------------------------------------------------------------
// Project: Kactus2
// Author: Esko Pekkarinen
// Date: 03.02.2021
//
// Description:
// Convenience class for accessing Python interpreter.
//-----------------------------------------------------------------------------
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "PythonInterpreter.h"
#include <PythonAPI/extensions/IOCatcher.h>
#include <PythonAPI/PythonAPI.h>
#include <QApplication>
//-----------------------------------------------------------------------------
// Function: PythonInterpreter::PythonInterpreter()
//-----------------------------------------------------------------------------
PythonInterpreter::PythonInterpreter(WriteChannel* outputChannel, WriteChannel* errorChannel,
bool printPromt, QObject* parent) :
QObject(parent),
WriteChannel(),
printPrompt_(printPromt),
outputChannel_(outputChannel),
errorChannel_(errorChannel)
{
}
//-----------------------------------------------------------------------------
// Function: PythonInterpreter::initialize()
//-----------------------------------------------------------------------------
bool PythonInterpreter::initialize(bool interactive)
{
PyImport_AppendInittab("IOCatcher", &PyInit_IOCatcher);
Py_InitializeEx(0); //<! Disable signals.
if (Py_IsInitialized() == false)
{
errorChannel_->write(QStringLiteral("Could not initialize Python interpreter."));
return false;
}
threadState_ = Py_NewInterpreter();
outputChannel_->write(QStringLiteral("Python ") + QString(Py_GetVersion()) + QString("\n"));
PyObject *pyModule = PyImport_ImportModule("__main__");
localContext_ = PyModule_GetDict(pyModule);
globalContext_ = localContext_;
if (redirectIO(interactive) == false)
{
return false;
}
setAPI();
PyEval_ReleaseThread(threadState_);
printPrompt();
return true;
}
//-----------------------------------------------------------------------------
// Function: PythonInterpreter::finalize()
//-----------------------------------------------------------------------------
void PythonInterpreter::finalize()
{
PyEval_AcquireThread(threadState_);
Py_FinalizeEx();
}
//-----------------------------------------------------------------------------
// Function: PythonInterpreter::write()
//-----------------------------------------------------------------------------
void PythonInterpreter::write(QString const& command)
{
execute(command.toStdString());
}
//-----------------------------------------------------------------------------
// Function: PythonInterpreter::execute()
//-----------------------------------------------------------------------------
void PythonInterpreter::execute(std::string const& command)
{
Q_ASSERT_X(Py_IsInitialized(), "Python interpreter", "Trying to execute without initializing.");
if (command.empty() && inputBuffer_.empty())
{
printPrompt();
return;
}
inputBuffer_.append(command);
inputBuffer_.push_back('\n');
auto inputSize = inputBuffer_.length();
bool endMultiline = runMultiline_ && inputSize >= 2 && inputBuffer_.at(inputSize - 2) == '\n';
PyEval_AcquireThread(threadState_);
PyObject* src = Py_CompileString(inputBuffer_.c_str(), "<stdin>", Py_single_input);
/* compiled just fine - */
if (src != nullptr)
{
/* ">>> " or "... " and double '\n' */
if (runMultiline_ == false || endMultiline)
{ /* so execute it */
PyObject* dum = PyEval_EvalCode(src, globalContext_, localContext_);
Py_XDECREF(dum);
Py_XDECREF(src);
if (PyErr_Occurred())
{
PyErr_Print();
}
runMultiline_ = false;
inputBuffer_.clear();
}
else
{
runMultiline_ = true;
}
}
/* syntax error or E_EOF? */
else if (PyErr_ExceptionMatches(PyExc_SyntaxError))
{
PyObject* exc = nullptr;
PyObject* val = nullptr;
PyObject* trb = nullptr;
PyObject* obj = nullptr;
char *msg = nullptr;
/* clears exception! */
PyErr_Fetch(&exc, &val, &trb);
if (PyArg_ParseTuple(val, "sO", &msg, &obj) && !strcmp(msg, "unexpected EOF while parsing") &&
endMultiline == false) /* E_EOF */
{
Py_XDECREF(exc);
Py_XDECREF(val);
Py_XDECREF(trb);
runMultiline_ = true;
}
else /* some other syntax error */
{
PyErr_Restore(exc, val, trb);
PyErr_Print();
runMultiline_ = false;
inputBuffer_.clear();
}
}
else /* some non-syntax error */
{
PyErr_Print();
runMultiline_ = false;
inputBuffer_.clear();
}
PyEval_ReleaseThread(threadState_);
printPrompt();
emit executeDone();
}
//-----------------------------------------------------------------------------
// Function: PythonInterpreter::executeString()
//-----------------------------------------------------------------------------
void PythonInterpreter::executeString(QString const& string)
{
PyEval_AcquireThread(threadState_);
PyObject* result = PyRun_String(string.toStdString().c_str(), Py_file_input, globalContext_, localContext_);
if (result == nullptr)
{
PyErr_Print();
}
else
{
Py_DECREF(result);
}
PyEval_ReleaseThread(threadState_);
printPrompt();
emit executeDone();
}
//-----------------------------------------------------------------------------
// Function: PythonInterpreter::runFile()
//-----------------------------------------------------------------------------
int PythonInterpreter::runFile(QString const& filePath)
{
Q_ASSERT_X(Py_IsInitialized(), "Python interpreter", "Trying to execute file without initializing.");
int retVal = 1;
QFile scriptFile(filePath);
if (scriptFile.open(QIODevice::ReadOnly | QIODevice::Text))
{
int fd = scriptFile.handle();
FILE* f = fdopen(dup(fd), "rb");
PyEval_AcquireThread(threadState_);
retVal = PyRun_SimpleFile(f, scriptFile.fileName().toLocal8Bit());
PyEval_ReleaseThread(threadState_);
fclose(f);
scriptFile.close();
printPrompt();
}
emit executeDone();
return retVal;
}
//-----------------------------------------------------------------------------
// Function: PythonInterpreter::setOutputChannels()
//-----------------------------------------------------------------------------
bool PythonInterpreter::redirectIO(bool interative)
{
PyObject* IOCatcherName = PyUnicode_FromString("IOCatcher");
if (IOCatcherName == NULL)
{
return false;
}
PyObject* IOCatcherModule = PyImport_Import(IOCatcherName);
Py_DECREF(IOCatcherName);
if (IOCatcherModule == NULL)
{
return false;
}
PyObject* dict = PyModule_GetDict(IOCatcherModule);
Py_DECREF(IOCatcherModule);
if (dict == NULL)
{
PyErr_Print();
errorChannel_->write(QStringLiteral("Fails to get the output dictionary.\n"));
return false;
}
PyObject* python_class = PyDict_GetItemString(dict, "OutputCatcher");
if (python_class == NULL)
{
PyErr_Print();
errorChannel_->write(QStringLiteral("Fails to get the output Python class.\n"));
return false;
}
PyObject* outCatcher = nullptr;
PyObject* errCatcher = nullptr;
// Creates an instance of the class
if (PyCallable_Check(python_class))
{
outCatcher = PyObject_CallObject(python_class, nullptr);
errCatcher = PyObject_CallObject(python_class, nullptr);
}
else
{
outputChannel_->write(QStringLiteral("Cannot instantiate the Python class for output"));
return false;
}
((OutputCatcherObject*)outCatcher)->channel = outputChannel_;
if (PySys_SetObject("stdout", outCatcher) < 0)
{
return false;
}
((OutputCatcherObject*)errCatcher)->channel = errorChannel_;
if (PySys_SetObject("stderr", errCatcher) < 0)
{
return false;
}
if (interative == false)
{
PyObject* input_python_class = PyDict_GetItemString(dict, "InputCatcher");
if (input_python_class == NULL)
{
PyErr_Print();
errorChannel_->write(QStringLiteral("Fails to get the input Python class.\n"));
return false;
}
PyObject* inputBuffer;
// Creates an instance of the class
if (PyCallable_Check(input_python_class))
{
inputBuffer = PyObject_CallObject(input_python_class, nullptr);
}
if (PySys_SetObject("stdin", inputBuffer) < 0)
{
return false;
}
}
return true;
}
//-----------------------------------------------------------------------------
// Function: PythonInterpreter::setAPI()
//-----------------------------------------------------------------------------
bool PythonInterpreter::setAPI()
{
PyObject* emptyList = PyList_New(0);
PyObject* apiModule = PyImport_ImportModuleEx("pythonAPI", globalContext_, localContext_, emptyList);
Py_XDECREF(emptyList);
if (apiModule == NULL)
{
errorChannel_->write(QStringLiteral("Could not import Kactus2 PythonAPI.\n"));
PyErr_Print();
}
else
{
PyObject* dict = PyModule_GetDict(apiModule);
if (dict == NULL) {
PyErr_Print();
errorChannel_->write(QStringLiteral("Could not import Kactus2 PythonAPI.\n"));
return false;
}
PyObject* python_class = PyDict_GetItemString(dict, "PythonAPI");
if (python_class == NULL) {
PyErr_Print();
errorChannel_->write(QStringLiteral("Could not import Kactus2 PythonAPI.\n"));
return false;
}
// Creates an instance of the class
if (PyCallable_Check(python_class))
{
PyObject* apiObject = PyObject_CallObject(python_class, nullptr);
PyDict_SetItemString(localContext_, "kactus2", apiObject);
}
}
return true;
}
//-----------------------------------------------------------------------------
// Function: PythonInterpreter::printPrompt()
//-----------------------------------------------------------------------------
void PythonInterpreter::printPrompt() const
{
if (printPrompt_ == false)
{
return;
}
if (runMultiline_)
{
outputChannel_->write("... ");
}
else
{
outputChannel_->write(">>> ");
}
}
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.