on master help sign in
prybar/languages/python3/pry_python3.c
119 lines 2.3 kB history raw
1#include "pry_python3.h"
3int pry_eval_file(FILE *f, const char *file, int argn, const char *argv)
4{
5 wchar_t *xargv[argn + 1];
6 const char *ptr = argv;
7 for (int i = 0; i < argn; ++i)
8 {
9 xargv[i] = Py_DecodeLocale(ptr, NULL);
10 ptr += strlen(ptr) + 1;
11 }
12 xargv[argn] = NULL;
13 PySys_SetArgvEx(argn, xargv, 1);
15 return PyRun_AnyFile(f, file);
18const char *pry_eval(const char *code, int start)
21 PyObject *m, *d, *s, *t, *v;
22 PyObject *c;
23 m = PyImport_AddModule("__main__");
25 if (m == NULL)
26 return NULL;
28 d = PyModule_GetDict(m);
29 c = Py_CompileString(code, "(eval)", start);
30 if (c == NULL)
31 {
32 PyErr_Print();
33 return NULL;
34 }
35 v = PyEval_EvalCode(c, d, d);
36 if (v == NULL)
37 {
38 PyErr_Print();
39 return NULL;
40 }
41 s = PyObject_Str(v);
42 if (s == NULL)
43 {
44 PyErr_Print();
45 return NULL;
46 }
48 t = PyUnicode_AsUTF8String(s);
49 if (t == NULL)
50 {
51 PyErr_Print();
52 return NULL;
53 }
56 char *str = PyBytes_AsString(t);
57 Py_DECREF(v);
58 Py_DECREF(s);
59 Py_DECREF(t);
60 return str;
63void pry_set_prompts(const char *ps1, const char *ps2)
65 PyObject *po1 = PyUnicode_FromString(ps1);
66 PyObject *po2 = PyUnicode_FromString(ps2);
67 PySys_SetObject("ps1", po1);
68 PySys_SetObject("ps2", po2);
69 Py_DECREF(po1);
70 Py_DECREF(po2);
73//From python3 sourcecode
74int
75pymain_run_interactive_hook(int *exitcode)
77 PyObject *sys, *hook, *result;
78 sys = PyImport_ImportModule("sys");
79 if (sys == NULL) {
80 goto error;
81 }
83 hook = PyObject_GetAttrString(sys, "__interactivehook__");
84 Py_DECREF(sys);
85 if (hook == NULL) {
86 PyErr_Clear();
87 return 0;
88 }
90 if (PySys_Audit("cpython.run_interactivehook", "O", hook) < 0) {
91 goto error;
92 }
94 result = _PyObject_CallNoArg(hook);
95 Py_DECREF(hook);
96 if (result == NULL) {
97 goto error;
98 }
99 Py_DECREF(result);
101 return 0;
103error:
104 PySys_WriteStderr("Failed calling sys.__interactivehook__\n");
105 return pymain_err_print(exitcode);
108int
109pymain_err_print(int *exitcode_p)
111 int exitcode;
112 if (_Py_HandleSystemExit(&exitcode)) {
113 *exitcode_p = exitcode;
114 return 1;
115 }
117 PyErr_Print();
118 return 0;