Site icon Embarcadero RAD Studio, Delphi, & C++Builder Blogs

Quickly Evaluate A Python Expression In Delphi Using Python4Delphi Sample App

Want to know how to evaluate a Python Expression in Delphi using Python4Delphi? Python for Delphi (P4D) is a set of free components that wrap up the Python DLL into Delphi and C++Builder. They let you easily execute Python scripts, create new Python modules and new Python types. This post will guide you on how to use these components, create a VCL application, run a simple python expression in it, and shows the output message.

Python4Delphi Demo2 Sample App shows how to Evaluate a Python Expression by typing the python expression in a Memo, execute and show the message. You can find the Demo2 source on GitHub. Check Demo1 on how to run a simple python script in Delphi.

Prerequisites: Download and install the latest Python for your platform. Follow the Python4Delphi installation instructions mentioned here. Alternatively, you can check out this video Getting started with Python4Delphi

Components used in Python4Delphi Demo2 App:

  1. TPythonEngine: A collection of relatively low-level routines for communicating with Python, creating Python types in Delphi, etc. It’s a Singleton class. Some of the key properties for the component listed here.

2.TPythonGUIInputOutput: Inherited from TPythonInputOutput (which works as a console for python outputs) Using this component Output property you can associate the Memo component to show the Output.

3.TMemo: A multiline text editing control, providing text scrolling. The text in the memo control can be edited as a whole or line by line.

You can find the Python4Delphi Demo2 sample project from the extracted GitHub repository ..\Python4Delphi\Demos\Demo02.dproj. Open this project in RAD Studio 10.4.1 and run the application.

Implementation Details:

[crayon-6742bc58efa4d061663352/]

EvalStrings will evaluate the Mathematical expression provided in the Memo1 and return the Python Object(PPyObject). We can convert the resulted Python object as a string using PyObjectAsString. Earlier in Demo1, we use ExecStrings to run the python script, so what’s the difference between the two? EvalStrings can only execute or evaluate expressions, whereas ExecStrings can execute any piece of Python code. To understand more about python expression check here.

Load the script to the Memo1 from a file using the code,

[crayon-6742bc58efa56487915739/]

Save the Script to the file using the code,

[crayon-6742bc58efa59434058410/]
<strong>Python4Delphi Demo02<strong>

Check some of the tutorials available for Python4Delphi here

Exit mobile version