SlideShare a Scribd company logo
Python 4 Delphi Developers
Max Kleiner
Python-Delphi: Potential Synergies
Jupyter Notebook
Jupyter is a spin-off project from IPython, aiming to standardize interactive computing in any
programming languages. The kernel provides interactive environment that executes user code as a
server, connected with a frontend through sockets. A Jupyter Notebook is also an open-source web
application that allows you to create and share documents that contain live code, equations,
visualizations, and describing text.
Google Colab
With Colab you can import an image dataset, train an image classifier on it, and evaluate the model, all in
just a few lines of code. Colab notebooks execute code on Google’s cloud servers, meaning you can
leverage the power of Google hardware, including GPUs and TPUs, regardless of the power of your
machine.
TPU
Tensor Processing Unit (TPU) is an AI accelerator application-specific integrated circuit (ASIC) developed
by Google specifically for neural network machine learning, particularly using Google’s own TensorFlow
software.
Popularity of Python
https://www.tiobe.com/tiobe-index/
P4D is a set of free components that wrap up the
Python DLL into Delphi and Lazarus (FPC).
Python vs. Java
Interest over time (Google Trends)
Java
Python
Be yourself; Everyone else is already taken.
— Oscar Wilde.
Delphi vs Python
Delphi/Pascal Python
Maturity (1995/1970!) (1989)
Object orientation
Multi-platform
Verbosity High (begin end) Low (indentation based)
REPL No Yes
Typing Strong static typing Dynamic (duck) typing
Memory management Manual Reference counting
Compiled bytecode
Performance
Multi-threading
RAD
Python for Delphi (I)
Imagine you need a 512bit hash (or another master of reality procedure) and you don’t have the available function.
eng:= TPythonEngine.Create(Nil);
eng.pythonhome:= PYHOME;
eng.opendll(PYDLL)
//eng.IO:= pyMemo;
try
eng.Execstring('with open(r"'+exepath+'maXbox4.exe","rb") as afile:'+
' fbuf = afile.read()');
println(eng.evalstr('__import__("hashlib").sha512('+
'fbuf).hexdigest().upper()'));
except
eng.raiseError;
finally
eng.Free;
end;
https://maxbox4.wordpress.com/2021/09/03/ekon-25-pypas/
Python for Delphi (I)
Imagine you need a 512bit hash (or another master of reality procedure).
https://maxbox4.wordpress.com/2021/07/28/python4maxbox-code/
● The eval() method parses the expression passed to it and runs python
expression(code) within the program.
● Exec() expects a statement, doesn’t return any value; import or assignment is a
statement with exec().
The eval() is not just limited to simple expression. We can execute functions, call methods,
reference variables and so on. So we use this by using the __import__() built-in function.
Note also that the computed hash is converted to a readable hexadecimal string by
hexdigest().upper()’ and uppercase the hex-values in one line, amazing isn’t it.
Python for Delphi (II)
•
Delphi version support
• 2009 or later (Unicode free also < D2009)
•
Platform support
• Windows 32 & 64 bits
• Linux
• MacOS
•
Mostly non-visual components
• Can be used in console applications
•
Lazarus/FPC/maXbox support
Getting Started – Installing Python
•
Select a Python distribution
• www.python.org (official distribution)
• Anaconda (recommended for heavy data-analytics work)
•
Python 2 vs. Python 3
•
32-bits vs. 64-bits
•
Download and run the installer
•
Installation options (location, for all users)
•
Install python packages you are planning to use (can be done later)
• Use the python package installer (pip) from the command prompt
• eg. > pip install numpy
Getting Started – Installing Python
for Delphi
•
Clone or download and unzip the Github repository into a directory (e.g.,
D:ComponentsP4D).
•
Start RAD Studio or maXbox4.
•
Add the source subdirectory (e.g., D:ComponentsP4DSource) to the IDE's library
path for the targets you are planning to use.
•
Open and install the Python4Delphi package specific to the IDE being used. For
Delphi Sydney and later it can be found in the PackagesDelphiDelphi 10.4+
directory. For earlier versions use the package in the PackagesDelphiDelphi 10.3-
directory.
Note:  The package is Design & Runtime together
P4D Primer Demo
http://www.softwareschule.ch/examples/cheatsheetpython.pdf
Start with a Cheatsheet:
http://www.softwareschule.ch/examples/pydemo13.txt
and a Script:
with an Engine:
https://sourceforge.net/projects/maxbox/
SIMPLE DEMO
(I)
SynEdit
Memo
SIMPLE
DEMOTIVATION
(II)
•
All components are using default properties
• PythonGUIInputOutput linked to PythonEngine and
Memo in maXbox
•
Source Code:
procedure TForm1.btnRunClick(Sender: TObject);
begin
GetPythonEngine.ExecString(UTF8Encode(sePythonC
ode.Text));
end;
http://www.softwareschule.ch/examples/pydemo29.txt
Using TPythonModule (I)
Python
def is_prime(n):
""" totally naive implementation """
if n <= 1:
return False
q = math.floor(math.sqrt(n))
for i in range(2, q + 1):
if (n % i == 0):
return False
return True
Delphi
function IsPrime(x: Integer): Boolean;
begin
if (x <= 1) then Exit(False);
var q := Floor(Sqrt(x));
for var i := 2 to q do
if (x mod i = 0) then
Exit(False);
Exit(True);
end;
Python
def count_primes(max_n):
res = 0
for i in range(2, max_n + 1):
if is_prime(i):
res += 1
return res
def test():
max_n = 1000000
print(f'Number of primes between 0 and {max_n} = {count_primes(max_n)}')
def main():
print(f'Elapsed time: {Timer(stmt=test).timeit(1)} secs')
if __name__ == '__main__':
main()
Using TPythonModule (II)
Output
Number of primes between 0 and 1000000 = 78498
Elapsed time: 3.4528134000000037 secs
Python
from delphi_module import delphi_is_prime
def count_primes(max_n):
res = 0
for i in range(2, max_n + 1):
if delphi_is_prime(i):
res += 1
return res
Using TPMod. & Threads
(III)
eng.Execstring('t1 =
threading.Thread(target=print_hello_three_times)');
eng.Execstring('t2 =
threading.Thread(target=print_hi_three_times)');
eng.EvalStr('t1.start()');
eng.EvalStr('t2.start()');
Master with 2 workers!
println('thread target1: '+eng.EvalStr('t1'));
println('thread target2: '+eng.EvalStr('t2'));
http://www.softwareschule.ch/examples/pydemo26.txt
const TH2 = 'def print_hi_three_times():'+LB+
' for i in range(3): '+LB+
' print("a") '+LB+
' winsound.Beep(440, 500) '+LB+
' return "Hi"';
Output
Number of primes between 0 and 1000000 = 78498
Elapsed time: 0.3073742000000017 secs
10x + improvement!
Defs in P4D (IV)
•
Add a Def() named convert as a const and link it to the PythonEngine
– ModuleName: http://www.softwareschule.ch/examples/pydemo25.txt
– Import the module with ExecStr()
• Implement python function hexconvert by writing a Pascal call
HEXCONVERT =
'""" convert hex string integer to int """ '+LF+
'def convert(n: str) -> int: '+LF+
' # get rid of ":", spaces and newlines '+LF+
' hex = n.replace(":", "").replace("n","").replace(" ","")'+LF+
' return int(hex,16)';
Using PyTemplate (V)
•
Minimal Shell Configuration:
with TPythonEngine.Create(Nil) do begin
pythonhome:= PYHOME;
try
loadDLL;
Println('Decimal: '+
EvalStr('__import__("decimal").Decimal(0.1)'));
except
raiseError;
finally
free;
end;
end;
Using PYDelphiWrapper (VI)
•
PyDelphiWrapper allows you to expose Delphi objects, records and types using
RTTI and cusomised wrapping of common Delphi objects.
•
Add a TPyDelphiWrapper on the form and link it to a PythonModule.
•
You can wrap a Delphi record containing a class function.
type
TDelphiFunctions = record
class function count_primes(MaxN: integer): integer; static;
end;
var
DelphiFunctions: TDelphiFunctions;
procedure TForm1.FormCreate(Sender: TObject);
begin
var Py := PyDelphiWrapper.WrapRecord(@DelphiFunctions,
TRttiContext.Create.GetType(TypeInfo(TDelphiFunctions))
as TRttiStructuredType);
PythonModule.SetVar('delphi_functions', Py);
PythonEngine.Py_DecRef(Py);
end;
Conclusions
•
With Python for Delphi you can get the best of both worlds
•
P4D makes it possible to integrate Python into Delphi applications in RAD way
•
Expose Delphi function, objects, records and types to Python using low or high-level
interfaces
•
More interesting topics
• Using python libraries and objects in Delphi code like variants (VarPyth)
• Python based data analytics in Delphi applications for example TensorFlow or Pandas
Creating Python extension modules using Delphi (from delphi_module import
delphi_is_prime)
• Python GUI development using the VCL
Resources & Sources
●
Python4Delphi library
– https://github.com/pyscripter/python4delphi
●
PyScripter IDE
– https://github.com/pyscripter/pyscripter
●
Thinking in CS – Python3 Tutorial
– https://openbookproject.net/thinkcs/python/english3e/
●
Delphi Scripter maXbox
●
https://sourceforge.net/projects/maxbox/
●
Webinar blog post
– https://blogs.embarcadero.com/python-for-delphi-developers-webinar/
Based on a Webinar by Kiriakos
Vlahos (aka PyScripter)
& Jim McKeeth (Embarcadero)

More Related Content

What's hot

Processor Verification Using Open Source Tools and the GCC Regression Test Suite
Processor Verification Using Open Source Tools and the GCC Regression Test SuiteProcessor Verification Using Open Source Tools and the GCC Regression Test Suite
Processor Verification Using Open Source Tools and the GCC Regression Test Suite
DVClub
 
Sour Pickles
Sour PicklesSour Pickles
Sour Pickles
SensePost
 
PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...
PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...
PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...
Tsundere Chen
 
Разработка кросс-платформенного кода между iPhone &lt; -> Windows с помощью o...
Разработка кросс-платформенного кода между iPhone &lt; -> Windows с помощью o...Разработка кросс-платформенного кода между iPhone &lt; -> Windows с помощью o...
Разработка кросс-платформенного кода между iPhone &lt; -> Windows с помощью o...
Yandex
 
How to integrate python into a scala stack
How to integrate python into a scala stackHow to integrate python into a scala stack
How to integrate python into a scala stack
Fliptop
 
PyPy's approach to construct domain-specific language runtime
PyPy's approach to construct domain-specific language runtimePyPy's approach to construct domain-specific language runtime
PyPy's approach to construct domain-specific language runtime
National Cheng Kung University
 
Verilator: Fast, Free, But for Me?
Verilator: Fast, Free, But for Me? Verilator: Fast, Free, But for Me?
Verilator: Fast, Free, But for Me?
DVClub
 
Understanding Android Benchmarks
Understanding Android BenchmarksUnderstanding Android Benchmarks
Understanding Android Benchmarks
Koan-Sin Tan
 
Algoritmi e Calcolo Parallelo 2012/2013 - OpenMP
Algoritmi e Calcolo Parallelo 2012/2013 - OpenMPAlgoritmi e Calcolo Parallelo 2012/2013 - OpenMP
Algoritmi e Calcolo Parallelo 2012/2013 - OpenMP
Pier Luca Lanzi
 
Communication between Java and Python
Communication between Java and PythonCommunication between Java and Python
Communication between Java and Python
Andreas Schreiber
 
Network Socket Programming with JAVA
Network Socket Programming with JAVANetwork Socket Programming with JAVA
Network Socket Programming with JAVA
Dudy Ali
 
Vladimir Ulogov - Beyond the Loadable Module
Vladimir Ulogov - Beyond the Loadable ModuleVladimir Ulogov - Beyond the Loadable Module
Vladimir Ulogov - Beyond the Loadable Module
Zabbix
 
Async await in C++
Async await in C++Async await in C++
Async await in C++
cppfrug
 
Flink Forward San Francisco 2019: Deploying ONNX models on Flink - Isaac Mcki...
Flink Forward San Francisco 2019: Deploying ONNX models on Flink - Isaac Mcki...Flink Forward San Francisco 2019: Deploying ONNX models on Flink - Isaac Mcki...
Flink Forward San Francisco 2019: Deploying ONNX models on Flink - Isaac Mcki...
Flink Forward
 
Behavioral Reflection
Behavioral ReflectionBehavioral Reflection
Behavioral Reflection
Marcus Denker
 
What do you mean it needs to be Java based? How jython saved the day.
What do you mean it needs to be Java based? How jython saved the day.What do you mean it needs to be Java based? How jython saved the day.
What do you mean it needs to be Java based? How jython saved the day.
Mark Rees
 
Using SWIG to Control, Prototype, and Debug C Programs with Python
Using SWIG to Control, Prototype, and Debug C Programs with PythonUsing SWIG to Control, Prototype, and Debug C Programs with Python
Using SWIG to Control, Prototype, and Debug C Programs with Python
David Beazley (Dabeaz LLC)
 
不深不淺,帶你認識 LLVM (Found LLVM in your life)
不深不淺,帶你認識 LLVM (Found LLVM in your life)不深不淺,帶你認識 LLVM (Found LLVM in your life)
不深不淺,帶你認識 LLVM (Found LLVM in your life)
Douglas Chen
 
08 - Return Oriented Programming, the chosen one
08 - Return Oriented Programming, the chosen one08 - Return Oriented Programming, the chosen one
08 - Return Oriented Programming, the chosen one
Alexandre Moneger
 
Two-level Just-in-Time Compilation with One Interpreter and One Engine
Two-level Just-in-Time Compilation with One Interpreter and One EngineTwo-level Just-in-Time Compilation with One Interpreter and One Engine
Two-level Just-in-Time Compilation with One Interpreter and One Engine
Yusuke Izawa
 

What's hot (20)

Processor Verification Using Open Source Tools and the GCC Regression Test Suite
Processor Verification Using Open Source Tools and the GCC Regression Test SuiteProcessor Verification Using Open Source Tools and the GCC Regression Test Suite
Processor Verification Using Open Source Tools and the GCC Regression Test Suite
 
Sour Pickles
Sour PicklesSour Pickles
Sour Pickles
 
PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...
PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...
PyCon TW 2017 - PyPy's approach to construct domain-specific language runtime...
 
Разработка кросс-платформенного кода между iPhone &lt; -> Windows с помощью o...
Разработка кросс-платформенного кода между iPhone &lt; -> Windows с помощью o...Разработка кросс-платформенного кода между iPhone &lt; -> Windows с помощью o...
Разработка кросс-платформенного кода между iPhone &lt; -> Windows с помощью o...
 
How to integrate python into a scala stack
How to integrate python into a scala stackHow to integrate python into a scala stack
How to integrate python into a scala stack
 
PyPy's approach to construct domain-specific language runtime
PyPy's approach to construct domain-specific language runtimePyPy's approach to construct domain-specific language runtime
PyPy's approach to construct domain-specific language runtime
 
Verilator: Fast, Free, But for Me?
Verilator: Fast, Free, But for Me? Verilator: Fast, Free, But for Me?
Verilator: Fast, Free, But for Me?
 
Understanding Android Benchmarks
Understanding Android BenchmarksUnderstanding Android Benchmarks
Understanding Android Benchmarks
 
Algoritmi e Calcolo Parallelo 2012/2013 - OpenMP
Algoritmi e Calcolo Parallelo 2012/2013 - OpenMPAlgoritmi e Calcolo Parallelo 2012/2013 - OpenMP
Algoritmi e Calcolo Parallelo 2012/2013 - OpenMP
 
Communication between Java and Python
Communication between Java and PythonCommunication between Java and Python
Communication between Java and Python
 
Network Socket Programming with JAVA
Network Socket Programming with JAVANetwork Socket Programming with JAVA
Network Socket Programming with JAVA
 
Vladimir Ulogov - Beyond the Loadable Module
Vladimir Ulogov - Beyond the Loadable ModuleVladimir Ulogov - Beyond the Loadable Module
Vladimir Ulogov - Beyond the Loadable Module
 
Async await in C++
Async await in C++Async await in C++
Async await in C++
 
Flink Forward San Francisco 2019: Deploying ONNX models on Flink - Isaac Mcki...
Flink Forward San Francisco 2019: Deploying ONNX models on Flink - Isaac Mcki...Flink Forward San Francisco 2019: Deploying ONNX models on Flink - Isaac Mcki...
Flink Forward San Francisco 2019: Deploying ONNX models on Flink - Isaac Mcki...
 
Behavioral Reflection
Behavioral ReflectionBehavioral Reflection
Behavioral Reflection
 
What do you mean it needs to be Java based? How jython saved the day.
What do you mean it needs to be Java based? How jython saved the day.What do you mean it needs to be Java based? How jython saved the day.
What do you mean it needs to be Java based? How jython saved the day.
 
Using SWIG to Control, Prototype, and Debug C Programs with Python
Using SWIG to Control, Prototype, and Debug C Programs with PythonUsing SWIG to Control, Prototype, and Debug C Programs with Python
Using SWIG to Control, Prototype, and Debug C Programs with Python
 
不深不淺,帶你認識 LLVM (Found LLVM in your life)
不深不淺,帶你認識 LLVM (Found LLVM in your life)不深不淺,帶你認識 LLVM (Found LLVM in your life)
不深不淺,帶你認識 LLVM (Found LLVM in your life)
 
08 - Return Oriented Programming, the chosen one
08 - Return Oriented Programming, the chosen one08 - Return Oriented Programming, the chosen one
08 - Return Oriented Programming, the chosen one
 
Two-level Just-in-Time Compilation with One Interpreter and One Engine
Two-level Just-in-Time Compilation with One Interpreter and One EngineTwo-level Just-in-Time Compilation with One Interpreter and One Engine
Two-level Just-in-Time Compilation with One Interpreter and One Engine
 

Similar to Ekon 25 Python4Delphi_MX475

Python for Delphi Developers - Part 1 Introduction
Python for Delphi Developers - Part 1 IntroductionPython for Delphi Developers - Part 1 Introduction
Python for Delphi Developers - Part 1 Introduction
Embarcadero Technologies
 
Pythonpresent
PythonpresentPythonpresent
Pythonpresent
Chui-Wen Chiu
 
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides:  Let's build macOS CLI Utilities using SwiftMobileConf 2021 Slides:  Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
Diego Freniche Brito
 
Python for Delphi Developers - Part 2
Python for Delphi Developers - Part 2Python for Delphi Developers - Part 2
Python for Delphi Developers - Part 2
Embarcadero Technologies
 
Python and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughPython and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthrough
gabriellekuruvilla
 
Reversingobfuscatedpythonapplications dropbox-140819110311-phpapp01
Reversingobfuscatedpythonapplications dropbox-140819110311-phpapp01Reversingobfuscatedpythonapplications dropbox-140819110311-phpapp01
Reversingobfuscatedpythonapplications dropbox-140819110311-phpapp01
Wajhi Ul Hassan Naqvi
 
Reversing the dropbox client on windows
Reversing the dropbox client on windowsReversing the dropbox client on windows
Reversing the dropbox client on windows
extremecoders
 
Tutorial_Python1.pdf
Tutorial_Python1.pdfTutorial_Python1.pdf
Tutorial_Python1.pdf
MuzamilFaiz
 
Php extensions workshop
Php extensions workshopPhp extensions workshop
Php extensions workshop
julien pauli
 
Facebook Glow Compiler のソースコードをグダグダ語る会
Facebook Glow Compiler のソースコードをグダグダ語る会Facebook Glow Compiler のソースコードをグダグダ語る会
Facebook Glow Compiler のソースコードをグダグダ語る会
Mr. Vengineer
 
Debugging Python with gdb
Debugging Python with gdbDebugging Python with gdb
Debugging Python with gdb
Roman Podoliaka
 
PHYTON-REPORT.pdf
PHYTON-REPORT.pdfPHYTON-REPORT.pdf
PHYTON-REPORT.pdf
PraveenKumar640562
 
Build your own discovery index of scholary e-resources
Build your own discovery index of scholary e-resourcesBuild your own discovery index of scholary e-resources
Build your own discovery index of scholary e-resources
Martin Czygan
 
3. build your own php extension ai ti aptech
3. build your own php extension   ai ti aptech3. build your own php extension   ai ti aptech
3. build your own php extension ai ti aptech
Quang Anh Le
 
Build your own PHP extension
Build your own PHP extensionBuild your own PHP extension
Build your own PHP extension
Võ Duy Tuấn
 
07 build your-own_php_extension
07 build your-own_php_extension07 build your-own_php_extension
07 build your-own_php_extension
Nguyen Duc Phu
 
Deployment of xlwings-powered spreadsheets (webinar)
Deployment of xlwings-powered spreadsheets (webinar)Deployment of xlwings-powered spreadsheets (webinar)
Deployment of xlwings-powered spreadsheets (webinar)
xlwings
 
Spsl iv unit final
Spsl iv unit  finalSpsl iv unit  final
Spsl iv unit final
Sasidhar Kothuru
 
Spsl iv unit final
Spsl iv unit  finalSpsl iv unit  final
Spsl iv unit final
Sasidhar Kothuru
 
Functions_in_Python.pptx
Functions_in_Python.pptxFunctions_in_Python.pptx
Functions_in_Python.pptx
krushnaraj1
 

Similar to Ekon 25 Python4Delphi_MX475 (20)

Python for Delphi Developers - Part 1 Introduction
Python for Delphi Developers - Part 1 IntroductionPython for Delphi Developers - Part 1 Introduction
Python for Delphi Developers - Part 1 Introduction
 
Pythonpresent
PythonpresentPythonpresent
Pythonpresent
 
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides:  Let's build macOS CLI Utilities using SwiftMobileConf 2021 Slides:  Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
 
Python for Delphi Developers - Part 2
Python for Delphi Developers - Part 2Python for Delphi Developers - Part 2
Python for Delphi Developers - Part 2
 
Python and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughPython and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthrough
 
Reversingobfuscatedpythonapplications dropbox-140819110311-phpapp01
Reversingobfuscatedpythonapplications dropbox-140819110311-phpapp01Reversingobfuscatedpythonapplications dropbox-140819110311-phpapp01
Reversingobfuscatedpythonapplications dropbox-140819110311-phpapp01
 
Reversing the dropbox client on windows
Reversing the dropbox client on windowsReversing the dropbox client on windows
Reversing the dropbox client on windows
 
Tutorial_Python1.pdf
Tutorial_Python1.pdfTutorial_Python1.pdf
Tutorial_Python1.pdf
 
Php extensions workshop
Php extensions workshopPhp extensions workshop
Php extensions workshop
 
Facebook Glow Compiler のソースコードをグダグダ語る会
Facebook Glow Compiler のソースコードをグダグダ語る会Facebook Glow Compiler のソースコードをグダグダ語る会
Facebook Glow Compiler のソースコードをグダグダ語る会
 
Debugging Python with gdb
Debugging Python with gdbDebugging Python with gdb
Debugging Python with gdb
 
PHYTON-REPORT.pdf
PHYTON-REPORT.pdfPHYTON-REPORT.pdf
PHYTON-REPORT.pdf
 
Build your own discovery index of scholary e-resources
Build your own discovery index of scholary e-resourcesBuild your own discovery index of scholary e-resources
Build your own discovery index of scholary e-resources
 
3. build your own php extension ai ti aptech
3. build your own php extension   ai ti aptech3. build your own php extension   ai ti aptech
3. build your own php extension ai ti aptech
 
Build your own PHP extension
Build your own PHP extensionBuild your own PHP extension
Build your own PHP extension
 
07 build your-own_php_extension
07 build your-own_php_extension07 build your-own_php_extension
07 build your-own_php_extension
 
Deployment of xlwings-powered spreadsheets (webinar)
Deployment of xlwings-powered spreadsheets (webinar)Deployment of xlwings-powered spreadsheets (webinar)
Deployment of xlwings-powered spreadsheets (webinar)
 
Spsl iv unit final
Spsl iv unit  finalSpsl iv unit  final
Spsl iv unit final
 
Spsl iv unit final
Spsl iv unit  finalSpsl iv unit  final
Spsl iv unit final
 
Functions_in_Python.pptx
Functions_in_Python.pptxFunctions_in_Python.pptx
Functions_in_Python.pptx
 

More from Max Kleiner

EKON26_VCL4Python.pdf
EKON26_VCL4Python.pdfEKON26_VCL4Python.pdf
EKON26_VCL4Python.pdf
Max Kleiner
 
EKON26_Open_API_Develop2Cloud.pdf
EKON26_Open_API_Develop2Cloud.pdfEKON26_Open_API_Develop2Cloud.pdf
EKON26_Open_API_Develop2Cloud.pdf
Max Kleiner
 
maXbox_Starter91_SyntheticData_Implement
maXbox_Starter91_SyntheticData_ImplementmaXbox_Starter91_SyntheticData_Implement
maXbox_Starter91_SyntheticData_Implement
Max Kleiner
 
maXbox Starter87
maXbox Starter87maXbox Starter87
maXbox Starter87
Max Kleiner
 
maXbox Starter78 PortablePixmap
maXbox Starter78 PortablePixmapmaXbox Starter78 PortablePixmap
maXbox Starter78 PortablePixmap
Max Kleiner
 
maXbox starter75 object detection
maXbox starter75 object detectionmaXbox starter75 object detection
maXbox starter75 object detection
Max Kleiner
 
BASTA 2020 VS Code Data Visualisation
BASTA 2020 VS Code Data VisualisationBASTA 2020 VS Code Data Visualisation
BASTA 2020 VS Code Data Visualisation
Max Kleiner
 
EKON 24 ML_community_edition
EKON 24 ML_community_editionEKON 24 ML_community_edition
EKON 24 ML_community_edition
Max Kleiner
 
maxbox starter72 multilanguage coding
maxbox starter72 multilanguage codingmaxbox starter72 multilanguage coding
maxbox starter72 multilanguage coding
Max Kleiner
 
EKON 23 Code_review_checklist
EKON 23 Code_review_checklistEKON 23 Code_review_checklist
EKON 23 Code_review_checklist
Max Kleiner
 
EKON 12 Running OpenLDAP
EKON 12 Running OpenLDAP EKON 12 Running OpenLDAP
EKON 12 Running OpenLDAP
Max Kleiner
 
EKON 12 Closures Coding
EKON 12 Closures CodingEKON 12 Closures Coding
EKON 12 Closures Coding
Max Kleiner
 
NoGUI maXbox Starter70
NoGUI maXbox Starter70NoGUI maXbox Starter70
NoGUI maXbox Starter70
Max Kleiner
 
maXbox starter69 Machine Learning VII
maXbox starter69 Machine Learning VIImaXbox starter69 Machine Learning VII
maXbox starter69 Machine Learning VII
Max Kleiner
 
maXbox starter68 machine learning VI
maXbox starter68 machine learning VImaXbox starter68 machine learning VI
maXbox starter68 machine learning VI
Max Kleiner
 
maXbox starter67 machine learning V
maXbox starter67 machine learning VmaXbox starter67 machine learning V
maXbox starter67 machine learning V
Max Kleiner
 
maXbox starter65 machinelearning3
maXbox starter65 machinelearning3maXbox starter65 machinelearning3
maXbox starter65 machinelearning3
Max Kleiner
 
EKON22_Overview_Machinelearning_Diagrams
EKON22_Overview_Machinelearning_DiagramsEKON22_Overview_Machinelearning_Diagrams
EKON22_Overview_Machinelearning_Diagrams
Max Kleiner
 
Ekon22 tensorflow machinelearning2
Ekon22 tensorflow machinelearning2Ekon22 tensorflow machinelearning2
Ekon22 tensorflow machinelearning2
Max Kleiner
 
EKON22 Introduction to Machinelearning
EKON22 Introduction to MachinelearningEKON22 Introduction to Machinelearning
EKON22 Introduction to Machinelearning
Max Kleiner
 

More from Max Kleiner (20)

EKON26_VCL4Python.pdf
EKON26_VCL4Python.pdfEKON26_VCL4Python.pdf
EKON26_VCL4Python.pdf
 
EKON26_Open_API_Develop2Cloud.pdf
EKON26_Open_API_Develop2Cloud.pdfEKON26_Open_API_Develop2Cloud.pdf
EKON26_Open_API_Develop2Cloud.pdf
 
maXbox_Starter91_SyntheticData_Implement
maXbox_Starter91_SyntheticData_ImplementmaXbox_Starter91_SyntheticData_Implement
maXbox_Starter91_SyntheticData_Implement
 
maXbox Starter87
maXbox Starter87maXbox Starter87
maXbox Starter87
 
maXbox Starter78 PortablePixmap
maXbox Starter78 PortablePixmapmaXbox Starter78 PortablePixmap
maXbox Starter78 PortablePixmap
 
maXbox starter75 object detection
maXbox starter75 object detectionmaXbox starter75 object detection
maXbox starter75 object detection
 
BASTA 2020 VS Code Data Visualisation
BASTA 2020 VS Code Data VisualisationBASTA 2020 VS Code Data Visualisation
BASTA 2020 VS Code Data Visualisation
 
EKON 24 ML_community_edition
EKON 24 ML_community_editionEKON 24 ML_community_edition
EKON 24 ML_community_edition
 
maxbox starter72 multilanguage coding
maxbox starter72 multilanguage codingmaxbox starter72 multilanguage coding
maxbox starter72 multilanguage coding
 
EKON 23 Code_review_checklist
EKON 23 Code_review_checklistEKON 23 Code_review_checklist
EKON 23 Code_review_checklist
 
EKON 12 Running OpenLDAP
EKON 12 Running OpenLDAP EKON 12 Running OpenLDAP
EKON 12 Running OpenLDAP
 
EKON 12 Closures Coding
EKON 12 Closures CodingEKON 12 Closures Coding
EKON 12 Closures Coding
 
NoGUI maXbox Starter70
NoGUI maXbox Starter70NoGUI maXbox Starter70
NoGUI maXbox Starter70
 
maXbox starter69 Machine Learning VII
maXbox starter69 Machine Learning VIImaXbox starter69 Machine Learning VII
maXbox starter69 Machine Learning VII
 
maXbox starter68 machine learning VI
maXbox starter68 machine learning VImaXbox starter68 machine learning VI
maXbox starter68 machine learning VI
 
maXbox starter67 machine learning V
maXbox starter67 machine learning VmaXbox starter67 machine learning V
maXbox starter67 machine learning V
 
maXbox starter65 machinelearning3
maXbox starter65 machinelearning3maXbox starter65 machinelearning3
maXbox starter65 machinelearning3
 
EKON22_Overview_Machinelearning_Diagrams
EKON22_Overview_Machinelearning_DiagramsEKON22_Overview_Machinelearning_Diagrams
EKON22_Overview_Machinelearning_Diagrams
 
Ekon22 tensorflow machinelearning2
Ekon22 tensorflow machinelearning2Ekon22 tensorflow machinelearning2
Ekon22 tensorflow machinelearning2
 
EKON22 Introduction to Machinelearning
EKON22 Introduction to MachinelearningEKON22 Introduction to Machinelearning
EKON22 Introduction to Machinelearning
 

Recently uploaded

Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
bijceesjournal
 
SCALING OF MOS CIRCUITS m .pptx
SCALING OF MOS CIRCUITS m                 .pptxSCALING OF MOS CIRCUITS m                 .pptx
SCALING OF MOS CIRCUITS m .pptx
harshapolam10
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
VICTOR MAESTRE RAMIREZ
 
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
ecqow
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
IJECEIAES
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
Prakhyath Rai
 
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
Paris Salesforce Developer Group
 
AI for Legal Research with applications, tools
AI for Legal Research with applications, toolsAI for Legal Research with applications, tools
AI for Legal Research with applications, tools
mahaffeycheryld
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
ijaia
 
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
PriyankaKilaniya
 
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURSCompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
RamonNovais6
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
IJECEIAES
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
MDSABBIROJJAMANPAYEL
 
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
upoux
 
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by AnantLLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
Anant Corporation
 
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
Gino153088
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
21UME003TUSHARDEB
 
An Introduction to the Compiler Designss
An Introduction to the Compiler DesignssAn Introduction to the Compiler Designss
An Introduction to the Compiler Designss
ElakkiaU
 
ITSM Integration with MuleSoft.pptx
ITSM  Integration with MuleSoft.pptxITSM  Integration with MuleSoft.pptx
ITSM Integration with MuleSoft.pptx
VANDANAMOHANGOUDA
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
co23btech11018
 

Recently uploaded (20)

Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
 
SCALING OF MOS CIRCUITS m .pptx
SCALING OF MOS CIRCUITS m                 .pptxSCALING OF MOS CIRCUITS m                 .pptx
SCALING OF MOS CIRCUITS m .pptx
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
 
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
一比一原版(CalArts毕业证)加利福尼亚艺术学院毕业证如何办理
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
 
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
AI + Data Community Tour - Build the Next Generation of Apps with the Einstei...
 
AI for Legal Research with applications, tools
AI for Legal Research with applications, toolsAI for Legal Research with applications, tools
AI for Legal Research with applications, tools
 
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODELDEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
DEEP LEARNING FOR SMART GRID INTRUSION DETECTION: A HYBRID CNN-LSTM-BASED MODEL
 
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
Prediction of Electrical Energy Efficiency Using Information on Consumer's Ac...
 
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURSCompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
CompEx~Manual~1210 (2).pdf COMPEX GAS AND VAPOURS
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
 
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
一比一原版(osu毕业证书)美国俄勒冈州立大学毕业证如何办理
 
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by AnantLLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
LLM Fine Tuning with QLoRA Cassandra Lunch 4, presented by Anant
 
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
4. Mosca vol I -Fisica-Tipler-5ta-Edicion-Vol-1.pdf
 
Mechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdfMechanical Engineering on AAI Summer Training Report-003.pdf
Mechanical Engineering on AAI Summer Training Report-003.pdf
 
An Introduction to the Compiler Designss
An Introduction to the Compiler DesignssAn Introduction to the Compiler Designss
An Introduction to the Compiler Designss
 
ITSM Integration with MuleSoft.pptx
ITSM  Integration with MuleSoft.pptxITSM  Integration with MuleSoft.pptx
ITSM Integration with MuleSoft.pptx
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
 

Ekon 25 Python4Delphi_MX475

  • 1. Python 4 Delphi Developers Max Kleiner
  • 2. Python-Delphi: Potential Synergies Jupyter Notebook Jupyter is a spin-off project from IPython, aiming to standardize interactive computing in any programming languages. The kernel provides interactive environment that executes user code as a server, connected with a frontend through sockets. A Jupyter Notebook is also an open-source web application that allows you to create and share documents that contain live code, equations, visualizations, and describing text. Google Colab With Colab you can import an image dataset, train an image classifier on it, and evaluate the model, all in just a few lines of code. Colab notebooks execute code on Google’s cloud servers, meaning you can leverage the power of Google hardware, including GPUs and TPUs, regardless of the power of your machine. TPU Tensor Processing Unit (TPU) is an AI accelerator application-specific integrated circuit (ASIC) developed by Google specifically for neural network machine learning, particularly using Google’s own TensorFlow software.
  • 3. Popularity of Python https://www.tiobe.com/tiobe-index/ P4D is a set of free components that wrap up the Python DLL into Delphi and Lazarus (FPC).
  • 4. Python vs. Java Interest over time (Google Trends) Java Python Be yourself; Everyone else is already taken. — Oscar Wilde.
  • 5. Delphi vs Python Delphi/Pascal Python Maturity (1995/1970!) (1989) Object orientation Multi-platform Verbosity High (begin end) Low (indentation based) REPL No Yes Typing Strong static typing Dynamic (duck) typing Memory management Manual Reference counting Compiled bytecode Performance Multi-threading RAD
  • 6. Python for Delphi (I) Imagine you need a 512bit hash (or another master of reality procedure) and you don’t have the available function. eng:= TPythonEngine.Create(Nil); eng.pythonhome:= PYHOME; eng.opendll(PYDLL) //eng.IO:= pyMemo; try eng.Execstring('with open(r"'+exepath+'maXbox4.exe","rb") as afile:'+ ' fbuf = afile.read()'); println(eng.evalstr('__import__("hashlib").sha512('+ 'fbuf).hexdigest().upper()')); except eng.raiseError; finally eng.Free; end; https://maxbox4.wordpress.com/2021/09/03/ekon-25-pypas/
  • 7. Python for Delphi (I) Imagine you need a 512bit hash (or another master of reality procedure). https://maxbox4.wordpress.com/2021/07/28/python4maxbox-code/ ● The eval() method parses the expression passed to it and runs python expression(code) within the program. ● Exec() expects a statement, doesn’t return any value; import or assignment is a statement with exec(). The eval() is not just limited to simple expression. We can execute functions, call methods, reference variables and so on. So we use this by using the __import__() built-in function. Note also that the computed hash is converted to a readable hexadecimal string by hexdigest().upper()’ and uppercase the hex-values in one line, amazing isn’t it.
  • 8. Python for Delphi (II) • Delphi version support • 2009 or later (Unicode free also < D2009) • Platform support • Windows 32 & 64 bits • Linux • MacOS • Mostly non-visual components • Can be used in console applications • Lazarus/FPC/maXbox support
  • 9. Getting Started – Installing Python • Select a Python distribution • www.python.org (official distribution) • Anaconda (recommended for heavy data-analytics work) • Python 2 vs. Python 3 • 32-bits vs. 64-bits • Download and run the installer • Installation options (location, for all users) • Install python packages you are planning to use (can be done later) • Use the python package installer (pip) from the command prompt • eg. > pip install numpy
  • 10. Getting Started – Installing Python for Delphi • Clone or download and unzip the Github repository into a directory (e.g., D:ComponentsP4D). • Start RAD Studio or maXbox4. • Add the source subdirectory (e.g., D:ComponentsP4DSource) to the IDE's library path for the targets you are planning to use. • Open and install the Python4Delphi package specific to the IDE being used. For Delphi Sydney and later it can be found in the PackagesDelphiDelphi 10.4+ directory. For earlier versions use the package in the PackagesDelphiDelphi 10.3- directory. Note:  The package is Design & Runtime together
  • 11. P4D Primer Demo http://www.softwareschule.ch/examples/cheatsheetpython.pdf Start with a Cheatsheet: http://www.softwareschule.ch/examples/pydemo13.txt and a Script: with an Engine: https://sourceforge.net/projects/maxbox/
  • 13. SIMPLE DEMOTIVATION (II) • All components are using default properties • PythonGUIInputOutput linked to PythonEngine and Memo in maXbox • Source Code: procedure TForm1.btnRunClick(Sender: TObject); begin GetPythonEngine.ExecString(UTF8Encode(sePythonC ode.Text)); end; http://www.softwareschule.ch/examples/pydemo29.txt
  • 14. Using TPythonModule (I) Python def is_prime(n): """ totally naive implementation """ if n <= 1: return False q = math.floor(math.sqrt(n)) for i in range(2, q + 1): if (n % i == 0): return False return True Delphi function IsPrime(x: Integer): Boolean; begin if (x <= 1) then Exit(False); var q := Floor(Sqrt(x)); for var i := 2 to q do if (x mod i = 0) then Exit(False); Exit(True); end;
  • 15. Python def count_primes(max_n): res = 0 for i in range(2, max_n + 1): if is_prime(i): res += 1 return res def test(): max_n = 1000000 print(f'Number of primes between 0 and {max_n} = {count_primes(max_n)}') def main(): print(f'Elapsed time: {Timer(stmt=test).timeit(1)} secs') if __name__ == '__main__': main() Using TPythonModule (II) Output Number of primes between 0 and 1000000 = 78498 Elapsed time: 3.4528134000000037 secs
  • 16. Python from delphi_module import delphi_is_prime def count_primes(max_n): res = 0 for i in range(2, max_n + 1): if delphi_is_prime(i): res += 1 return res Using TPMod. & Threads (III) eng.Execstring('t1 = threading.Thread(target=print_hello_three_times)'); eng.Execstring('t2 = threading.Thread(target=print_hi_three_times)'); eng.EvalStr('t1.start()'); eng.EvalStr('t2.start()'); Master with 2 workers! println('thread target1: '+eng.EvalStr('t1')); println('thread target2: '+eng.EvalStr('t2')); http://www.softwareschule.ch/examples/pydemo26.txt const TH2 = 'def print_hi_three_times():'+LB+ ' for i in range(3): '+LB+ ' print("a") '+LB+ ' winsound.Beep(440, 500) '+LB+ ' return "Hi"'; Output Number of primes between 0 and 1000000 = 78498 Elapsed time: 0.3073742000000017 secs 10x + improvement!
  • 17. Defs in P4D (IV) • Add a Def() named convert as a const and link it to the PythonEngine – ModuleName: http://www.softwareschule.ch/examples/pydemo25.txt – Import the module with ExecStr() • Implement python function hexconvert by writing a Pascal call HEXCONVERT = '""" convert hex string integer to int """ '+LF+ 'def convert(n: str) -> int: '+LF+ ' # get rid of ":", spaces and newlines '+LF+ ' hex = n.replace(":", "").replace("n","").replace(" ","")'+LF+ ' return int(hex,16)';
  • 18. Using PyTemplate (V) • Minimal Shell Configuration: with TPythonEngine.Create(Nil) do begin pythonhome:= PYHOME; try loadDLL; Println('Decimal: '+ EvalStr('__import__("decimal").Decimal(0.1)')); except raiseError; finally free; end; end;
  • 19. Using PYDelphiWrapper (VI) • PyDelphiWrapper allows you to expose Delphi objects, records and types using RTTI and cusomised wrapping of common Delphi objects. • Add a TPyDelphiWrapper on the form and link it to a PythonModule. • You can wrap a Delphi record containing a class function. type TDelphiFunctions = record class function count_primes(MaxN: integer): integer; static; end; var DelphiFunctions: TDelphiFunctions; procedure TForm1.FormCreate(Sender: TObject); begin var Py := PyDelphiWrapper.WrapRecord(@DelphiFunctions, TRttiContext.Create.GetType(TypeInfo(TDelphiFunctions)) as TRttiStructuredType); PythonModule.SetVar('delphi_functions', Py); PythonEngine.Py_DecRef(Py); end;
  • 20. Conclusions • With Python for Delphi you can get the best of both worlds • P4D makes it possible to integrate Python into Delphi applications in RAD way • Expose Delphi function, objects, records and types to Python using low or high-level interfaces • More interesting topics • Using python libraries and objects in Delphi code like variants (VarPyth) • Python based data analytics in Delphi applications for example TensorFlow or Pandas Creating Python extension modules using Delphi (from delphi_module import delphi_is_prime) • Python GUI development using the VCL
  • 21. Resources & Sources ● Python4Delphi library – https://github.com/pyscripter/python4delphi ● PyScripter IDE – https://github.com/pyscripter/pyscripter ● Thinking in CS – Python3 Tutorial – https://openbookproject.net/thinkcs/python/english3e/ ● Delphi Scripter maXbox ● https://sourceforge.net/projects/maxbox/ ● Webinar blog post – https://blogs.embarcadero.com/python-for-delphi-developers-webinar/ Based on a Webinar by Kiriakos Vlahos (aka PyScripter) & Jim McKeeth (Embarcadero)