Integrate Python Threading, Windows Console, And Command Line Arguments In Delphi Windows GUI Apps

We know how to do Multithreading in Delphi. How about a simple python script that performs threading in Python and runs the script in the Delphi application? This brings the advantage of using existing multithreaded or new python scripts in your Delphi application. This post guide you to do that with the Python4Delphi Sample app. You can also use Python4Delphi with C++Builder.

Python4Delphi Demo22 Sample App shows how to create a Python script in Delphi Application which demonstrates creating thread and output the result in windows console, passing arguments in the command line. You can find the Demo22 source on GitHub.

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 Demo22 App:

  • TPythonEngine: A collection of relatively low-level routines for communicating with Python, creating Python types in Delphi, etc. It’s a singleton class.

You can find the Python4Delphi Demo22 sample project from the extracted GitHub repository ..Python4DelphiDemosDemo22.dproj. Open this project in RAD Studio 10.4.1 and run the application.

Implementation Details:

  • PythonEngine1 provides the connection to Python or rather the Python API. This project uses Python3.9 which can be seen in TPythonEngine DllName property.
  • It uses a Python Script file threading_test.py where the below list of modules was used.
    • threading: This module constructs higher-level threading interfaces on top of the lower level _thread module. 
    • collections: This module implements specialized container datatypes providing alternatives to Python’s general-purpose built-in containers, dictlistset, and tuple. In this sample, deque is used.
    • time: This module provides various time-related functions.
    • threading_test.py contains, ProducerThread, ConsumerThread, BoundedQueue class within the function _test.
  • Memo1, used for providing the Python Script to execute.
  • On Clicking Execute Button the below code executes the python script.

The script below is executed which will opens a window console, create threads put in a queue and execute one after other.

demo22-5751609

Head over and check out the open source Python4Delphi project which makes it easy to build Python GUIs for Windows with Delphi.