Maxbox Starter With Python4Delphi
Maxbox Starter With Python4Delphi
Maxbox Starter With Python4Delphi
Python4Delphi
______________________________________________________________________________
maXbox Starter86_1 – Code with Python4Delphi
Be yourself; Everyone else is already taken.
— Oscar Wilde.
$IFDEF MSWINDOWS}
function IsPythonVersionRegistered(PythonVersion : string;
out InstallPath: string; out AllUserInstall: Boolean) : Boolean;
// The above convention was changed in Python 3.5. Now even for all user
1/8
// installations the dll is located at the InstallPath.
// Also from vers.3.5 onwards 32 bit version have a suffix -32 e.g. "3.6-32"
// See also PEP 514
var
key: string;
VersionSuffix: string;
MajorVersion : integer;
MinorVersion : integer;
begin
Result := False;
InstallPath := '';
AllUserInstall := False;
MajorVersion := StrToInt(PythonVersion[1]);
MinorVersion := StrToInt(PythonVersion[3]);
VersionSuffix := '';
{$IFDEF CPUX86}
if (MajorVersion > 3) or ((MajorVersion = 3) and (MinorVersion >= 5)) then
VersionSuffix := '-32';
{$ENDIF}
key:= Format('\Software\Python\PythonCore\%s%s\InstallPath',
[PythonVersion, VersionSuffix]);
2/8
In my case the path is on:
C:\Users\max\AppData\Local\Programs\Python\Python36\Lib\
procedure pyinit;
external 'Py_Initialize@C:\maXbox\EKON25\python37.dll cdecl';
procedure pyexit(retval: integer);
external 'Py_Exit@C:\maXbox\EKON24\python37.dll cdecl';
Now check your file system to get the pytest.txt also use to
invoke a Python script as an embedding const and use the dll like
above. Next example combines an embedding python script in a
1 Independent from imports and site-packages
3/8
pascal script. We’ll use the py-script language and an awesome
library called Python OpenWeatherMap (PyOWM) to make it easier to
use the OpenWeatherMap API in Python. You'll have to pip install
the library first in order to import the module:
C:\maXbox>pip3 install pyowm
Collecting pyowm
Downloading pyowm-2.10.0-py3-none-any.whl (3.7 MB)
Then we run a command prompt command ('py '+RUNSCRIPT) with
parameters like a command line interface and get the python output
back in maXbox with the function getDosOutput().
function GetDosOutput(CommandLine: string; Work: string = 'C:\: string;
Ex.: writeln(GetDosOutput('java -version','C:\'));
>>>java version "1.8.0_211"
Java(TM) SE Runtime Environment (build 1.8.0_211-b12)
Java HotSpot(TM) Client VM (build 25.211-b12, mixed mode)
This you can see often in P4D (later on), the script itself runs
from a memo-control inside a form.
program OpenWeatherMap_Py_integrate;
const C=CRLF;
const SCRIPTNAMEP= '1046_openweather.py';
const DETECTOUTFILE= 'openweather_out2.txt';
Const PYSCRIPT6 =
'import pyowm '+C+
'import wget '+C+
'import sys, datetime as dt '+C+
'#nltk.download("vader_lexicon") '+C+
'from time import sleep '+C+
'import pandas as pd '+C+
'pd.set_option("max_colwidth", 400) '+C+
'import numpy as np '+C+
'print("this first line after config & imports") '+C+
' '+C+
'output_path = sys.argv[1] '+C+
'locate = sys.argv[2] '+C+
' '+C+
'owm= pyowm.OWM("55013bf3d09cfb0619989a00ed5bed09") '+C+
'observation= owm.weather_at_place((locate)) '+C+
'we= observation.get_weather() '+C+
'temp = we.get_temperature("celsius") '+C+
'with open(output_path, "w") as file: '+C+
' file.write("OpenWeatherMap of "+locate+" "+str(dt.datetime.now())+ '+C+
' "\n"+str(we)+ '+C+
' "\n"+str(temp)+ '+C+
' "\n"+str(dt.datetime.utcnow())) '+C+
' '+C+
'print("\n") '+C+
'print("weather today:"+(locate)+" "+str(we)+"\n"+str(temp)) '+C+
'print("integrate weatherreport detector compute ends...") ';
4/8
Then we use the parameters from the script as paramstrings. The
ParamStr() function returns one of the parameters from the command
line used to invoke the current script with outputpath for the
file and locate, this means the place of the returned weather-
report (ParamIndex determines which parameter is returned):
Writeln(getDosOutput('py '+RUNSCRIPT+' '+outputpath+' '+locate,
exePath));
begin //@main
//-init env
maxform1.console1click(self);
memo2.height:= 205;
QueryPerformanceFrequency(freq64);
//-config
saveString(exepath+SCRIPTNAMEP, ACTIVESCRIPT);
sleep(600)
//outputPath:= '.\crypt\output\'+DETECTOUTFILE;
outputPath:= Exepath+DETECTOUTFILE;
locate:= '"Bern, CH"';
Output:
weather today:Bern, CH <pyowm.weatherapi25.weather.Weather - reference
time=2021-07-07 14:43:23+00, status=clouds, detailed status=scattered
clouds>
{'temp': 21.17, 'temp_max': 23.54, 'temp_min': 15.99, 'temp_kf': None}
integrate weatherreport detector compute ends...
5/8
This explains best the code behind, to evaluate an internal Python
expression. You are responsible for creating one and only one
TPythonEngine. Usually you just drop it on your main form.
With the PythonGUIInputOutput1 you wire the PythonEngine1 to a
memo2, the same as in maXbox with a memo2 as console (from object
Form1: TForm1 in Unit1.dfm):
_PIC: 1046_openweather_P4D_2.png
6/8
...
Py_BuildValue := Import('Py_BuildValue');
Py_Initialize := Import('Py_Initialize');
PyModule_GetDict := Import('PyModule_GetDict');
PyObject_Str := Import('PyObject_Str');
PyRun_String := Import('PyRun_String');
PyRun_SimpleString := Import('PyRun_SimpleString');
PyDict_GetItemString := Import('PyDict_GetItemString');
PySys_SetArgv := Import('PySys_SetArgv');
Py_Exit := Import('Py_Exit');
...
http://www.softwareschule.ch/examples/openweather.txt
http://www.softwareschule.ch/examples/1016_newsfeed_sentiment_integrate2.txt
_PIC: 1046_openweather_ansiview2.png
7/8
• https://learndelphi.org/python-native-windows-gui-with-delphi-vcl/
• http://www.softwareschule.ch/examples/weatherbox.txt
•
forecast = owm.three_hours_forecast('mumbai')
TypeError: 'module' object is not callable
8/8