forked from jamct/agsi-data
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1050_pydemo2trackip.txt
418 lines (357 loc) · 13.2 KB
/
1050_pydemo2trackip.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
program PyDemo2;
//https://github.com/maxkleiner/python4delphi/blob/master/Demos/Demo02/Unit1.pas
//https://stackoverflow.com/questions/21464102/reset-python4delphi-engine
//https://stackoverflow.com/questions/21464102/reset-python4delphi-engine
//interface
{uses
Classes, SysUtils,
Windows, Messages, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComCtrls, ExtCtrls,
PythonEngine, Vcl.PythonGUIInputOutput, PythonVersions.pas ; }
type
TForm1 = TForm;
var
PythonEngine1: TPythonEngine;
PythonModule1: TPythonModule;
PythonType1: TPythonType ;
aMemo2: TMemo;
Panel1: TPanel;
Button1: TButton;
Splitter1: TSplitter;
Button2: TButton;
Button3: TButton;
OpenDialog1: TOpenDialog;
SaveDialog1: TSaveDialog;
PythonGUIInputOutput1: TPythonGUIInputOutput;
aMemo1: TMemo;
procedure TForm1Button1Click(Sender: TObject); forward;
procedure TForm1Button2Click(Sender: TObject); forward;
procedure TForm1Button3Click(Sender: TObject); forward;
//private
{ Déclarations privées }
//public
{ Déclarations publiques }
//end;
const PYDLLNAME = 'python36.dll';
PSCRIPTNAME = 'initpy.py';
PYHOME = 'C:\Users\max\AppData\Local\Programs\Python\Python36-32\';
PYSCRIPT = 'C:\maXbox\maxbox3\maxbox3\maXbox3\examples\module1maxbox1.py';
PYSCRIPT2 = 'C:\maXbox\maxbox3\maxbox3\maXbox3\examples\896_textclassification.py';
LB = CR+LF;
const PyModule =
'def printData(data): '+#13#10+
' return data+data+"/n"';
const PYCMD = 'print("this is box")'+LB+
'import sys'+LB+
'f=open(r"1050pytest2hhhh.txt","w")'+LB+
'f.write("Hello PyWorld_mX4, \n")'+LB+
'f.write("This data will be written on the file.")'+LB+
'f.close()';
var
Form1: TForm1;
//implementation
//{$R *.DFM}
procedure TForm1Button1Click(Sender: TObject);
var
//aResult : PPyObject;
codstr: TStrings;
begin
codstr:= TStringlist.create;
with PythonEngine1 do begin
UseLastKnownVersion := true;
//AutoFinalize:= False;
//dllpath:= PyHOME;
//dllname:= PYDLLNAME;
try
//unloadDLL;
loadDLL;
//unloadDLL;
//openDLL(Pyhome+pydllname)
writeln('IsHandleValid_after: '+botostr(IsHandleValid));
except
writeln('dll EXCEPT '+ExceptionToString(ExceptionType,ExceptionParam));
//free;
finally
free;
end;
// DllPath := '/usr/lib/x86_64-linux-gnu';
// DllName := 'libpython3.9.so.1.0';
{Result := EvalStrings( Memo1.Lines );
if Assigned(Result) then
begin
ShowMessage(Format('Eval: %s',[PyObjectAsString(Result)]));
Py_DECREF(Result);
end
else }
// ShowMessage('Could not evaluate the script');
// Or you could simply use:
//Writeln('Eval: ' + EvalStringsAsStr( aMemo1.Lines ) );
codstr.text:= '2+3';
writeln(botostr(CheckEvalSyntax(codstr.text)));
//Writeln('Eval: ' + EvalStringsAsStr(codstr));
//free;
end;
codstr.Free;
end;
procedure TForm1CreatePythonComponents;
var PyVersions: TPythonVersions;
cbPyVersions: Tlistbox;
begin
if cbPyVersions.ItemIndex <0 then begin
ShowMessage('No Python version is selected');
Exit;
end; //}
// Destroy P4D components
{
FreeAndNil(PythonEngine1);
FreeAndNil(PythonType1);
FreeAndNil(PythonModule1); }
if assigned(PythonEngine1) then PythonEngine1.free;
if assigned(PythonModule1) then PythonModule1.free;
if assigned(PythonType1) then PythonType1.free;
{ TPythonEngine }
PythonEngine1 := TPythonEngine.Create(Self);
//writeln('mapdll EXCEPT '+ExceptionToString(ExceptionType,ExceptionParam));
PythonEngine1.pythonhome:= PYHOME;
PythonEngine1.dllpath:= PyHOME;
PythonEngine1.dllname:= PYDLLNAME;
PyVersions[cbPyVersions.ItemIndex].AssignTo(PythonEngine1);
PythonEngine1.IO := PythonGUIInputOutput1;
{ TPythonModule }
PythonModule1 := TPythonModule.Create(Self);
//PythonModule1.Name := 'PythonModule1';
PythonModule1.Engine := PythonEngine1;
PythonModule1.ModuleName := 'spam';
with PythonModule1.Errors.Add do begin
Name := 'PointError';
ErrorType := etClass;
end;
with PythonModule1.Errors.Add do begin
Name := 'EBadPoint';
ErrorType := etClass;
ParentClass.Name := 'PointError';
end;
{ TPythonType }
PythonType1 := TPythonType.Create;
PythonType1.Name := 'PythonType1';
PythonType1.Engine := PythonEngine1;
//PythonType1.OnInitialization := PythonType1Initialization;
PythonType1.TypeName := 'Point';
PythonType1.Prefix := 'Create';
PythonType1.Services.Basic := [pbsRepr,pbsStr,pbsGetAttrO,pbsSetAttrO];
PythonType1.TypeFlags := [tpTypeSubclass, tpBytesSubclass, tpfHaveGC];
//[tpfHaveGetCharBuffer,tpfHaveSequenceIn,tpfHaveInplaceOps,
// [tpfHaveRichCompare,tpfHaveWeakRefs,tpfHaveIter,tpfHaveClass,tpfBaseType];
PythonType1.Module := PythonModule1;
try
PythonEngine1.LoadDll;
except
writeln('mapdll EXCEPT '+ExceptionToString(ExceptionType,ExceptionParam));
end;
PythonEngine1.free;
end;
procedure TForm1Button2Click(Sender: TObject);
begin
with OpenDialog1 do
begin
if Execute then
aMemo1.Lines.LoadFromFile( FileName );
end; //}
end;
procedure TForm1Button3Click(Sender: TObject);
begin
with SaveDialog1 do
begin
if Execute then
aMemo1.Lines.SaveToFile( FileName );
end;
end;
procedure createPYEngine;
begin
//object PythonEngine1: TPythonEngine
PythonGUIInputOutput1:= TPythonGUIInputOutput.create(nil)
PythonEngine1:= TPythonEngine.create(nil)
PythonEngine1.IO := PythonGUIInputOutput1
OpenDialog1:= TOpenDialog.create(self);
with opendialog1 do begin
DefaultExt := '*.py'
Filter := 'Python files|*.py|Text files|*.txt|All files|*.*'
//Left = 176
end;
{object SaveDialog1: TSaveDialog
DefaultExt = '*.py'
Filter = 'Python files|*.py|Text files|*.txt|All files|*.*'
Left = 208
end }
//PythonGUIInputOutput1:= TPythonGUIInputOutput.create(self)
with PythonGUIInputOutput1 do begin
UnicodeIO:= False
RawOutput:= False
Output:= Memo2
//Left = 64
end;
end;
var myloadscript, myloadscript2: string;
PyForm: TForm; pyMemo: TMemo;
Procedure PYLaz_P4D_Demo;
//https://wiki.freepascal.org/Python4Delphi
var eng : TPythonEngine;
Out1: TPythonGUIInputOutput;
begin
eng:= TPythonEngine.Create(Nil);
Out1:= TPythonGUIInputOutput.create(nil)
Out1.output:= pyMemo; //debugout.output; //memo2;
Out1.RawOutput:= False;
Out1.UnicodeIO:= False;
Out1.maxlines:= 20;
out1.displaystring('this string')
//eng.IO:= Out1;
Out1.writeline('draw the line');
//eng.free;
try
eng.LoadDll;
eng.IO:= Out1;
if eng.IsHandleValid then begin
writeln('DLLhandle: '+botostr(eng.IsHandleValid))
WriteLn('evens: '+ eng.EvalStringAsStr('[x**2 for x in range(15)]'));
WriteLn('gauss: '+ eng.EvalStringAsStr('sum([x for x in range(101)])'));
WriteLn('gauss2: '+ eng.EvalStr('sum([x % 2 for x in range(10100)])'));
writeln('syncheck '+
botostr(eng.CheckEvalSyntax('print("powers:",[x**2 for x in range(10)])')));
eng.ExecString('print("powers:",[x**2 for x in range(10)])');
eng.ExecString(PYCMD);
writeln('ExecSynCheck1 '+botostr(eng.CheckExecSyntax(myloadscript)));
//writeln('ExecSynCheck2 '+
// botostr(eng.CheckExecSyntax(filetostring(PYSCRIPT))));
//eng.ExecString(filetostring(PYSCRIPT));
writeln(eng.Run_CommandAsString('print("powers:",[x**2 for x in range(10)])',eval_input));
writeln(eng.Run_CommandAsString('sum([x for x in range(201)])',eval_input));
eng.ExecString('from sympy import *');
eng.ExecString('from sympy.plotting import plot');
writeln(eng.EvalStr('list(primerange(7, 150))'));
writeln(eng.EvalStr('sum(list(primerange(0, 100)))'));
writeln(eng.EvalStr('(list(primerange(0, 101)))'));
//https://medium.com/catalysts-reachout/track-anyones-ip-address-using-python-5a1a76146615
eng.ExecString('import os'+LF+'import json'+LF+'import urllib.request');
eng.ExecString('url = "http://ip-api.com/json/"');
eng.ExecString('targetip = "129.42.38.1"');
//eng.ExecString('response=urllib.request.urlopen(url)');
eng.ExecString('response=urllib.request.urlopen(url+targetip)');
//response=urllib2.urlopen(url+ip)
//writeln(eng.EvalStr('response.read()'));
eng.ExecString('data=response.read()');
eng.ExecString('values=json.loads(data)');
println(eng.EvalStr('"ISP: "+values["isp"]'));
println(eng.EvalStr('"city: "+values["city"]'));
println(eng.EvalStr('"IP: "+values["query"]'));
// response=urllib2.urlopen(url+ip)
{print("IP: "+values["query"])
print("City: "+values["city"])
print("ISP: "+values["isp"])
print("Country: "+values["country"])
print("Region: "+values["region"])
print("Timezone: "+values["timezone"]) }
pymemo.update;
end
else writeln('invalid library handle! '+Getlasterrortext);
writeln('PythonOK '+botostr(PythonOK));
out1.free;
//pyImport(PyModule);
except
eng.raiseError;
finally
eng.free;
end;
end;
//https://stackoverflow.com/questions/67759582/find-correct-python4delphi-tpythonengine-parameters
//https://medium.com/@SergiAlfonso/small-python-script-ff68ee7687fb
{$DEFINE MSWINDOWS}
procedure TPythonEngineConfigSetPythonengineValues(PythonEngine
: TPythonEngine);
var
FPyVersions: TPythonVersions;
var self: TPythonEngine;
begin
///
/// convert this https://github.com/pyscripter/python4delphi/wiki/FindingPython
/// into a small automatic setting of parameter
///
PythonEngine.UseLastKnownVersion := Self.UseLastKnownVersion;
if Self.UseLastKnownVersion then
begin
{$IFDEF MSWINDOWS}
FPyVersions := GetRegisteredPythonVersions;
FPyVersions[0].AssignTo(PythonEngine);
{$ENDIF}
{$IFDEF LINUX}
/// not supported on LINUX
/// https://en.delphipraxis.net/topic/4700-getregisteredpythonversions-for-linux/
{$ENDIF}
end
else begin
//var self: TPythonEngine;
self:= TPythonEngine(PythonEngine);
PythonEngine.APIVersion := self.APIVersion ;
PythonEngine.DllName := Self.DllName;
PythonEngine.DllPath := Self.DllPath;
PythonEngine.AutoFinalize := Self.AutoFinalize;
PythonEngine.AutoLoad := Self.AutoLoad;
PythonEngine.AutoUnload := Self.AutoUnload;
PythonEngine.RedirectIO := Self.RedirectIO;
PythonEngine.UseWindowsConsole := Self.UseWindowsConsole;
PythonEngine.RegVersion := Self.RegVersion;
end;
end;
var OriginalOwner: TPythonEngine;
begin //@main
{ createPYEngine;
TForm1Button1Click(self)}
//TForm1CreatePythonComponents;
{OriginalOwner := GetPythonEngine; //.Owner;
GetPythonEngine.Free;
TPythonEngine.Create(OriginalOwner); }
//GetPythonEngine.Free;
{writeln('PythonOK '+botostr(PythonOK));
try
pyImport(PYSCRIPT)
except
writeln('ImportEXCEPT '+ExceptionToString(ExceptionType,ExceptionParam));
end; }
//PythonEngine1.Free;
//myloadscript:= filetostring(PYSCRIPT);
//myloadscript2:= filetostring(PYSCRIPT2);
PyForm:= loadForm2(300,200, clgreen, 'PyFrm4D');
pyMemo:= TMemo.create(PyForm);
pyMemo.parent:= PyForm
PyForm.show;
PYLaz_P4D_Demo;
//register_PYthonGUI;
//PyForm.show;
with TFastStringStream.create('') do begin
free;
end;
with TPythonGUIInputOutput.create(self) do begin
displaystring('');
free;
end; //}
End.
----app_template_loaded_code----
----File newtemplate.txt not exists - now saved!----
Doc: Destroying it calls Py_Finalize, which frees all memory allocated by the Python DLL.
Or, if you're just using the Python API without the VCL wrappers, you can probably just call Py_NewInterpreter on your TPythonInterface object to get a fresh execution environment without necessarily discarding everything done before.
Ref:
--------------------------------------------------------
dll EXCEPT Exception: There is already one instance of TPythonEngine running.
TRUE
Exception: Python is not properly initialized.
PascalScript maXbox4 - RemObjects & SynEdit
dll EXCEPT Exception: There is already one instance of TPythonEngine running.
TRUE
Exception: Python is not properly initialized.
dll EXCEPT Exception: Access violation at address 00345A76 in module 'maXbox4.exe'. Read of address 4365636E.
TRUE
Exception: Access violation at address 6BA3BA66 in module 'python36.dll'. Read of address 000000AD.
mapdll EXCEPT Exception: There is already one instance of TPythonEngine running.
PythonOK TRUE
ImportEXCEPT Exception: Access violation at address 6BA3BA66 in module 'python36.dll'. Read of address 000000AC.
mX4 executed: 26/07/2021 13:30:51 Runtime: 0:0:2.48 Memload: 71% use