Click here to Skip to main content
15,881,089 members
Articles / Programming Languages / Pascal

How to Integrate a Python script in Pascal Program

Rate me:
Please Sign up or sign in to vote.
2.54/5 (5 votes)
12 Jul 2021CPOL3 min read 8.8K   3   4
We use a Command Line Interface with OpenWeatherMap (PyOWM) to make it easier to use the OpenWeatherMap API in Python.
In the last article, we have seen that P4D is a set of free components that wrap up the Python DLL into Delphi and Lazarus (FPC). For this article, I want to show how a simple Python evaluator works and to gain low-level access to the Python API. We do have a Pascal script which invokes a Python script with results back.

Introduction

In this example, we combine an embedding Python script in a 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.

Background

On Windows, the standard Python installer already associates the .py extension with a file type (Python.File) and gives that file type an open command that runs the interpreter (F:\Program Files\Python\python.exe “%1” %*). This is enough to make scripts executable from the command prompt. We use the python-dll as we use a Windows DLL.

Therefore *.pyd files are dll’s, but there are a few differences:

So far you have to know 3 different file types:

  1. *.py: The norm input source code that we’ve written.
  2. *.pyc: The compiled bytecode. If you import a module, py will build a *.pyc file that contains bytecode to make
    importing it again later easier and faster.
  3. *.pyd: The mentioned windows dll file for Python.

Then you do have to install the PyOWM library:

Terminal
C:\maXbox>pip3 install pyowm

Collecting pyowm

Downloading pyowm-2.10.0-py3-none-any.whl (3.7 MB)

Have you installed the latest version of PyOwm and run into problems like

<code class="hljs language-python">'OWM' object has no attribute 'weather_at_place'</code>

? If yes, uninstall it, and install the previous version using the following command:

  • pip install pyowm==2.10.0

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.

Using the Code

The Python script is called '1046_openweather.py' which we call with writeln(getDosOutput('py '+RUNSCRIPT+' '+outputpath+' '+locate, exePath)); . This you can see often in P4D (later on), the script itself runs from a memo-control inside a form or to make it more comprehensive like an inline const text (script) to get the output via DOS output back in a memo2 as the following demonstrates:

Pascal
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...")            ';
 
 
Const ACTIVESCRIPT = PYSCRIPT6;
 
var RUNSCRIPT, outputPath, locate: string;
    startTime64, endTime64, freq64: Int64;
 
begin //@main
  //-init env
  maxform1.console1click(self);
  memo2.height:= 205;
  QueryPerformanceFrequency(freq64);
   
  //-config
  saveString(exepath+SCRIPTNAMEP, ACTIVESCRIPT);
  sleep(600)
  //outputPath:= '.\crypt\output\'+DETECTOUTFILE;
   
  if Not fileExists(exepath+DETECTOUTFILE) then
      CreateFileFromString(exepath+DETECTOUTFILE, 'Open_Weather_Data');
   
  outputPath:= Exepath+DETECTOUTFILE;
  locate:= '"Bern, CH"';
   
  if fileExists(exepath+SCRIPTNAMEP) then begin
     RUNSCRIPT:= exepath+SCRIPTNAMEP;
     QueryPerformanceCounter(startTime64);
     writeln(getDosOutput('py '+RUNSCRIPT+' '+outputpath+' '+locate, exePath));
     QueryPerformanceCounter(endTime64);
     println('elapsedSeconds:= '+floattostr((endTime64-startTime64)/freq64));
     openFile(outputPath)
  end;
 
end;

end.

Then, we authenticate using an API key. The authenticated connection to the API is stored in the owm_obj object. You will have to provide the API key that you got after signing up at the  Open Weather Map website.

Please use another API key: owm= pyowm.OWM(" <Your Enter_API_KEY> ")

By default, the API key that you get will be free. But, you can choose to go for the paid key which has additional privileges.

To get the current weather for a particular city, you need to create an observation object using the omw() object by providing the city name, id or coordinates. To get the observation object using the name of the city, use weather_at_place() method.

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().

Further we save the weather data in a file called 'openweather_out2.txt'.

The script you can found at:

http://www.softwareschule.ch/examples/openweather.txt.

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 (Bern, Basel, Cologne, Dusseldorf, Kiruna, etc.) of the returned weather-report (ParamIndex determines which parameter is returned):

Pascal
Writeln(getDosOutput(‘py ‘+RUNSCRIPT+’ ‘+outputpath+’ ‘+locate, exePath));

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…

Image 1

Console Output

This console output with the forecast term rain:True

OpenWeatherMap of Vienna, AT 2021-07-15 09:26:46.302472
<pyowm.weatherapi25.weather.Weather - reference time=2021-07-15 07:26:45+00, status=clear, detailed status=clear sky>
{'temp': 21.55, 'temp_max': 23.75, 'temp_min': 19.88, 'temp_kf': None}
rain:True
UTC:2021-07-15 07:26:46.302472

Note: You will need to adjust the demos accordingly, to successfully load the Python distribution that you have installed on your computer. One of the strengths of Python is that it comes with batteries included, by default, the library uses the value of the sys.argv[0] element to set the name of the program, which as you probably already know is the name of the Python script you have executed. Then we use argument vector 1 and 2 for our command line interface:

We use 'output_path = sys.argv[1] and 'locate = sys.argv[2] '.

History

  • 12th July, 2021: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Switzerland Switzerland
The Art of Coding: maXbox is a script tool engine, compiler and source lib all in one exe to design and code your scripts in a shellbook! Pure Code for Object Scripting. Principle is simplicity and reduce to the max.
The App is “out of the box” (self containment) and needs no installation nor registration.

Comments and Discussions

 
GeneralMy vote of 5 Pin
breitsch breitsch16-Dec-22 10:16
breitsch breitsch16-Dec-22 10:16 
GeneralMy vote of 5 Pin
Sandra Goncalves17-Sep-21 23:44
Sandra Goncalves17-Sep-21 23:44 
SuggestionScreenshot of Script Editor/Compiler maXbox Pin
Max Kleiner13-Jul-21 23:50
Max Kleiner13-Jul-21 23:50 
GeneralMy vote of 5 Pin
Vincent Radio12-Jul-21 6:56
professionalVincent Radio12-Jul-21 6:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.