Printing a variable in the Python built-in interpreter

I wrote a small C program that embeds Python. I configure it correctly with Py_Initialize () and Py_Finalize () and I can run scripts with either PyRun_SimpleString or PyRun_SimpleFile. However, I do not know how to simulate the behavior of a native Python interpreter when printing variables.

In particular:

a = (1, 2, 3) print a 

Works great for me: it prints (1, 2, 3)

But:

 a = (1, 2, 3) a 

Prints nothing. In Python, the native interpreter also prints (1, 2, 3). How to get my code to do what users expected and print the value?

Thanks in advance!

+4
source share
1 answer

To start the interactive interpreter loop, you must use the PyRun_InteractiveLoop() function. Otherwise, your code will behave as if it were written in a Python script file, and not interactively.

Change Here is the full code of a simple interactive interpreter:

 #include <Python.h> int main() { Py_Initialize(); PyRun_InteractiveLoop(stdin, "<stdin>"); Py_Finalize(); } 

Edit2 . Implementing a complete interactive interpreter in a graphical interface is a bit of a project. Probably the easiest way to understand this is to write a basic terminal emulator connected to a pseudo-terminal device and use the above code on this device. This will automatically get all the subtleties.

If your goal is not a full-blown interactive editor, the option might be to use PyRun_String() with Py_single_input as the start token. This will allow you to run some Python code, as in an interactive interpreter, and if this code is the only expression that does not evaluate to None , then its value will be printed - of course. Here is a sample code (without error checking for simplicity):

 #include <Python.h> int main() { PyObject *main, *d; Py_Initialize(); main = PyImport_AddModule("__main__"); d = PyModule_GetDict(main); PyRun_String("a = (1, 2, 3)", Py_single_input, d, d); PyRun_String("a", Py_single_input, d, d); Py_Finalize(); } 

It will open (1, 2, 3) .

There are many more problems:

  • No error handling and tracing.
  • There is no "incremental input" for block commands, for example, in the interactive interpreter. Login must be completed.
  • Output to standard output.
  • If multiple input lines are specified, nothing is printed.

To really reproduce the behavior of an interactive interpreter is not easy. So my initial recommendation was to write a basic terminal emulator in your GUI that shouldn't be too complicated - or maybe even one available.

+7
source

Source: https://habr.com/ru/post/1399476/


All Articles