pyscripter / python4delphi Goto Github PK
View Code? Open in Web Editor NEWFree components that wrap up Python into Delphi and Lazarus (FPC)
License: MIT License
Free components that wrap up Python into Delphi and Lazarus (FPC)
License: MIT License
Hi,
I've a suggestion - make exposing Delphi objects to python painless by
utilizing the new RTTI (runtime type information) feature in D2010 (and above).
Currently exposing a class to the hosted Python code needs to you to write too
much code (check demo06), I guess if we take advantage of the new RTTI feature
in the newer versions of Delphi, the process can be improved a lot.
For example, check out the Delphi chromium embedded project, all you have to do
to expose the interface of any Delphi class to the JavaScript environment, is
to register the class:
// this is your class exposed to JS
Test = class
class procedure doit(const v: string);
end;
initialization
// Register your class
TCefRTTIExtension.Register('app', Test);
// and in JavaScript code to call that class above:
app.doit(''foo'')', '', 0);
Cool! Isn't it?
The above code was extracted from:
http://groups.google.com/group/delphichromiumembedded/browse_thread/thread/1793e
7ca66012f0c/8ab31a5ecdb6bf48?lnk=gst&q=JavaScript+return+#
Some intro about RTTI introduced since D2010:
http://robstechcorner.blogspot.com/2009/09/delphi-2010-rtti-basics.html
Original issue reported on code.google.com by [email protected]
on 29 Oct 2011 at 8:51
What steps will reproduce the problem?
1. Create a sample application in Delphi XE2 targeting the Win64 platform,
using Python 2.7 (win64 build)
2. Run the application and note the errors.
The first error appears in the MapDll() routine in PythonEngine.pas. The 64-bit
version of Py_InitModule4() is renamed Py_InitModule4_64().
After this change is made, everything will compile but upon execution, access
violations will be present.
I tracked this problem down to differences in the expected sizes of data
structures. Removing the "packed" directive fixes the issues, and appears to
work in both the 32 and 64-bit builds.
I have attached the modified PythonEngine.pas to this issue for your
consideration.
Original issue reported on code.google.com by [email protected]
on 27 Oct 2011 at 4:49
Attachments:
python4delphi/Delphinus.Info.json
Line 6 in 11e07af
You wrote "LicenCe" but your file is named "LicenSe" ;)
Therefore Delphinus can't read it atm.
What steps will reproduce the problem?
1. Use P4D 3.33 with DelphiXE and Python25 on Win7
I'm migrating a project from Delphi 2006 to XE, so I needed to upgrade P4D too.
It compiles normally, but when I try to execute the following code, I get an
error.
Code:
import os
Error
exceptions.ImportError: No module named os.
It's working fine on Delphi 2006.
Thanks,
Weverton
Original issue reported on code.google.com by [email protected]
on 16 May 2013 at 9:20
What steps will reproduce the problem?
1. Install python 2.7
2. Install P4D ver. 3.32
3. Install OpenCV 2.2
4. Compile P4D Demo01 (Project1.exe)
5. Copy cv.pyd and python27.dll to Project1.exe folder
6. execute script "import cv"
Exception
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: Module use of python27.dll conflicts with this version of Python.
Original test script "print 2+2" works well.
Original issue reported on code.google.com by [email protected]
on 30 May 2011 at 8:27
on the program startup, PythonEngine.pas read the registry to read the Python
install directory, and append path PythonXX.dll.
after that, it call loadlibrary to load the PythonXX.dll to program.
but the pythonXX.dll is in the c:\windows\system32 or c:\windows\syswow64
directory.
so...
Original issue reported on code.google.com by [email protected]
on 25 Jul 2011 at 8:53
I've checked out the r16 from svn and my app no longer works.
In my app I've added TPyObject derived classes with attributes and methods
but I no longer can access the methods added by AddMethod. I've noticed
that the TPyObject.GetAttr has changed from origin MMM-Experts 3.32 and svn
3.33 (r16)
3.32:
function TPyObject.GetAttr(key : PChar) : PPyObject;
begin
with GetPythonEngine do
begin
// check for a method
Result := Py_FindMethod( PythonType.MethodsData, GetSelf, key);
if not Assigned(Result) then
PyErr_SetString (PyExc_AttributeError^, PChar(Format('Unknown
attribute "%s"',[key])));
end;
end;
3.33:
function TPyObject.GetAttr(key : PChar) : PPyObject;
var
PyKey : PPyObject;
begin
with GetPythonEngine do
begin
PyKey := PyString_FromString(key);
try
Result := PyObject_GenericGetAttr(GetSelf, PyKey)
finally
Py_XDecRef(PyKey);
end;
// // check for a method
// if IsPython3000 then
// // I think Python 3000 from beta 2 gets the methods from the
tp_methods field
// Result := nil
// else
// Result := Py_FindMethod( PythonType.MethodsData, GetSelf, key);
// if not Assigned(Result) then
// PyErr_SetString (PyExc_AttributeError^, PChar(Format('Unknown
attribute "%s"',[key])));
end;
end;
Can anyone give some info regarding the changes and how to fix my app?
Original issue reported on code.google.com by [email protected]
on 23 Oct 2009 at 7:44
In CudaText with python4d fork, user sees sys.stdout encoding as CP1251 (rus).
We need to change it to utf8.
How to do it automatically always on start?
I found
import sys
sys.stdout = open(sys.stdout.fileno(), mode='w', encoding='utf-8', buffering=1)
https://stackoverflow.com/questions/4374455/how-to-set-sys-stdout-encoding-in-python-3
how to use it in python4d?
Sorry to use this space for this question.
But, coudn't find any other place (forum, maybe)
Original issue reported on code.google.com by [email protected]
on 18 Sep 2013 at 7:11
This is bug: line with //AT must not exist. If it does, output gives duplicate
line with OnSendUniData.
procedure TPythonGUIInputOutput.SendUniData(const Data: UnicodeString);
begin
//inherited; //AT commented
if Assigned(FOnSendUniData) then
inherited
else
DisplayString( Data );
end;
Original issue reported on code.google.com by [email protected]
on 19 Dec 2013 at 3:25
Hi,
I've a suggestion - make exposing Delphi objects to python painless by
utilizing the new RTTI (runtime type information) feature in D2010 (and above).
Currently exposing a class to the hosted Python code needs to you to write too
much code (check demo06), I guess if we take advantage of the new RTTI feature
in the newer versions of Delphi, the process can be improved a lot.
For example, check out the Delphi chromium embedded project, all you have to do
to expose the interface of any Delphi class to the JavaScript environment, is
to register the class:
// this is your class exposed to JS
Test = class
class procedure doit(const v: string);
end;
initialization
// Register your class
TCefRTTIExtension.Register('app', Test);
// and in JavaScript code to call that class above:
app.doit(''foo'')', '', 0);
Cool! Isn't it?
The above code was extracted from:
http://groups.google.com/group/delphichromiumembedded/browse_thread/thread/1793e
7ca66012f0c/8ab31a5ecdb6bf48?lnk=gst&q=JavaScript+return+#
Some intro about RTTI introduced since D2010:
http://robstechcorner.blogspot.com/2009/09/delphi-2010-rtti-basics.html
Original issue reported on code.google.com by [email protected]
on 29 Oct 2011 at 8:50
my repo has support for FreeBsd. it is in pythonengine.pas
https://github.com/alexey-t/python-for-lazarus
CudaText user says Cud crashes with Py 3.7 on macOS. (carbon x32 build)
i use my own Py4D fork.
does your code work with 3.7 on macOS?
Hello, I am new in P4D.
I would like to know if it's possible to expose
c++ builder or delphi classes and objects to python.
I couldn't find an example or documentation.
Thanks!
Claudio
Original issue reported on code.google.com by [email protected]
on 20 Aug 2013 at 4:42
Wrapping Python objects as Variants in currently implemented with Delphi custom
variants.
Formerly this was done using the PythonAtom unit which used the COM disp
interface (IDispatch) mechanism.
The adavantage of the PythonAtom way is that you can pass on the wrapped Python
objects via COM, even out of process, because COM is taking care of marshalling
etc.
With VarPath-wrapped objects this is not possible.
Event in-process things go wrong as soon as you assign the variant to an
OleVariant. The Custom Variant-mechanis casts the VarPyth instance
automatically into an OleString.
I still need the PythonAtom implementiation as i'm using the wrapped python
objects via COM. I just copied PythonAtom.pas and AtomPythonEngine.pas from an
older version of PythonForDelphi and it works.
Please bring back these units into the trunk.
Cheers
Samuel
Original issue reported on code.google.com by [email protected]
on 14 Jul 2011 at 3:29
What steps will reproduce the problem?
1. In program "console" (my prog has it) I enter "print(input('Test'))"
2. In dialog I enter "Про"
What is the expected output?
Dialog with label named "Test". And output line "Про".
What do you see instead?
Dialog with label "Enter text". And output line "TestПро". Surprise.
What version of the product are you using? On what operating system?
Delphi7, WinXP SP3, Py3.2.5, Py4D 3.32(last one)
Original issue reported on code.google.com by [email protected]
on 26 Dec 2013 at 6:49
What steps will reproduce the problem?
1. download p4d
2. use it
3. profit
What is the expected output? What do you see instead?
i see expected output
What version of the product are you using? On what operating system?
Windows, Python 3.2 or 2.7
Please provide any additional information below.
Thank You for this great project! :)
Original issue reported on code.google.com by [email protected]
on 14 Aug 2011 at 8:42
I need some help. I am currently using/maintaining a Delphi 2007 application
that runs Python 2.5 scripts via python4delphi. I have downloaded the latest
version of p4d (3.32) and it does not seem to know about Delphi later than 2006
and Python later than 2.5.
I have installed Python 2.5 and uninstalled Python 2.5. When I compile the
Delphi program and run it, it crashes because it cannot find python25.dll.
How do I get my Delphi program working with Python 2.7?
I have no experience with the use of external programs in Delphi, so I would
appreciate a simple solution for dummies.
Thanks and regards
Original issue reported on code.google.com by [email protected]
on 22 Apr 2013 at 4:01
When I want to use Python 2.7.x I have to insert some lines in PythenEngine.pas :
In line 4794 :
AssignPyFlags;
if DirectoryExists('C:\Python27') then
Py_SetPythonHome('C:\Python27')
else
raise Exception.Create('Pythonfolder not found : "C:\Python27"');
Py_Initialize;
and before Py_Initialize: procedure; cdecl;
in line 1683:
Py_SetPythonHome: procedure ( s: PAnsiChar); cdecl;
and before Py_Initialize := Import('Py_Initialize');
in line 3742 :
Py_SetPythonHome := Import('Py_SetPythonHome');
Hey,
i created a patch for the lazarus package file, now it could be compiled
again under lazarus
Original issue reported on code.google.com by [email protected]
on 4 May 2009 at 12:41
Attachments:
I have module with e.g. such func
function xy_pos(Self, Args: PPyObject): PPyObject; cdecl;
var
X, Y, N: Integer;
begin
with GetPythonEngine do
begin
if PyArg_ParseTuple(Args, 'ii:xy_pos', @X, @Y) <> 0 then
begin
N:= X + Y;
Result:= PyInt_FromLong(N);
end;
end;
end;
now i call it from my "console": I enter line into edit, and call
"PythonEngine.ExecString(Str)".
i call: "print(xy_pos('test'))"
expected: TypeError after this call.
seen: this call does NOT give error, but next same call gives TypeError.
I see TypeError each two calls, but now after each signle call.
Delphi7 IDE doesn't give exception TypeError.
Original issue reported on code.google.com by [email protected]
on 19 Dec 2013 at 3:33
Need Delphi 2009 Compatibility
Original issue reported on code.google.com by [email protected]
on 21 May 2009 at 7:28
Does python4delphi support Python3?
thks!
//I got a DLL error, I read some close issue, find out the issue. It is about the 32bit and 64bit DLL file.
What steps will reproduce the problem?
1. download python4delphi component
2. download python 3.2
3. compile demo11
What is the expected output? What do you see instead?
expected output(as on python 2.7) - sorted columns
but application just crashes
What version of the product are you using? On what operating system?
trunk version, windows 7
Original issue reported on code.google.com by [email protected]
on 28 May 2011 at 12:42
Hi,
using the library project (compiled as pyd
) of the Demo14
, I get the following error when try to load the database
module from the python console:
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import database
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
SystemError: initialization of database failed without raising an exception
The behavior is the same also coping database.pyd
in Python' Lib folder.
Considering that I don't have the BDE installed, I removed the pyDBTables.pas
reference in the sources of pyDB.pas
and pyDatabase.pas
.
the pythonEngine.pas file.
in the function:
function IsPythonVersionRegistered(PythonVersion : string;
out InstallPath: string; out AllUserInstall: Boolean) : Boolean;
code like this:
RootKey := HKEY_LOCAL_MACHINE;
if KeyExists(key) then begin
AllUserInstall := True;
Result := True;
end;
it does not OpenKey and read the default value from registry, but it set
AllUserInstall = True. so it cannot read python path from registry.
i think it can modify like this:
RootKey := HKEY_LOCAL_MACHINE;
if KeyExists(key) then begin
OpenKey(key, FALSE);
InstallPath := ReadString('');
AllUserInstall := True;
Result := True;
end;
sorry english is not my Mother tongue
Original issue reported on code.google.com by [email protected]
on 25 Jul 2011 at 8:48
What steps will reproduce the problem?
1. Install Python 3.4
2. Install P4D
3. Run any Demo
What is the expected output? What do you see instead?
PyCFunction_New not found (replaced by PyCFunction_NewEx)
What version of the product are you using? On what operating system?
WinXP
Please provide any additional information below.
Original issue reported on code.google.com by [email protected]
on 29 May 2014 at 2:07
1. create file webserver.py:
from wsgiref.simple_server import make_server
def app(environ, start_response):
status = '200 OK' # HTTP Status
headers = [('Content-type', 'text/plain; charset=utf-8')] # HTTP Headers
start_response(status, headers)
# The returned object is going to be printed
return [b'Hello world!']
def start():
server = make_server('127.0.0.1', 8070, app)
server.serve_forever()
2. in Delphi use next to call script:
fModule: variant;
PE: TPythonEngine;
...
PE := TPythoneEngine.Create;
...
with GetPythonEngine do begin
fModule := import('webserver');
fModule.start();
end;
3. in browser type 'http://localhost:8070', as expected message 'Hello World!'
appears, but then Delphi rise an error "AttributeError: NoneType object has no
attribute write"
Windows 7 Pro 64bit, Delphi 2006, Python 3.3 32bit
Original issue reported on code.google.com by [email protected]
on 4 Sep 2013 at 4:40
What steps will reproduce the problem?
1. Programmatically setup a TPythonEngine instance.
2. Programmatically create modules (clients).
3. Each module creation/destruction generates a new TPythonEngine instance.
What is the expected output? What do you see instead?
The issue consists that for each module creation/destruction a new
TPythonEngine is created, taking time on loading the python dll.
I want share the same TPythonEngine across multiple modules
creation/destruction.
What version of the product are you using? On what operating system?
Trunk clone.
Please provide any additional information below.
I'm using P4D to access a template engine (Jinja2) from Delphi, to render out
our reports.
I'm sharing the source code that fix this issue.
Tks in advance.
Original issue reported on code.google.com by [email protected]
on 23 May 2011 at 8:31
Attachments:
when execute import pandas , the python4 delphi will raise float divide by zero exception. I attached a patch to address this issue
0001-fix-divide-by-zero-error-when-import-pandas.zip
What steps will reproduce the problem?
1. Open the DPK in Delphi5
2. try to compile
3. happens a lot of errors...
What is the expected output? What do you see instead?
N/A
What version of the product are you using? On what operating system?
revision 98 - on Windows 7
Please provide any additional information below.
Original issue reported on code.google.com by [email protected]
on 7 Oct 2013 at 4:09
python3.7.
It seems unable to load Lib
Ask for advice
What steps will reproduce the problem?
1.Using Delphi 2010 install P4D from SVN (Python_2010.dproj)
2.Drop a PythonEngine VCL into a form
3.Modify the attribute to match 2.7 python version (DLLPATH: C:\python27,
DLLNAME: python27.dll, RegVersion: 2.7 and uncheck UseLastKnownVersion )
4. Execute the application
What is the expected output? I expect to see the application running with an
empty form.
What do you see instead?
---------------------------
Error
---------------------------
Error 193: Could not open Dll "python27.dll"
---------------------------
OK
---------------------------
and after ...
---------------------------
Error
---------------------------
Python could not be properly initialized. We must quit.
---------------------------
OK
---------------------------
Application just quit.
What version of the product are you using?
Delphi 2010 update 5
On what operating system?
Windows 7 x64
Original issue reported on code.google.com by [email protected]
on 5 Sep 2010 at 6:08
Attachments:
Hi
Do you think changes in your repo needed for my fork https://github.com/Alexey-T/Python-for-lazarus
?
i don't have time to check...
Hi , can i check whether we can create a python list = [("name","=","Kelvin"),("title","=","MR"),...]
using VarPythonCreate ? Or is there any where we can do that ?
For your information the list has to be created in Delphi and pass it back to a python class
to get evaluated and then return the result back to Delphi app.
Thanks.
The code in SVN is mostly compatible with Python 3.0. That is it works OK,
but on exit or when you run programs you get Access Violations.
What steps will reproduce the problem?
1. Load the Demo 1 program
2. Change the Engine properties
UseLastKnownVersion to False
APIVersion to 1013
DLLName to python30.dll
3. Run the program.
Executing statements works fine. But even if you exit without executing
any statements you get an Access Violation at exit.
With the release of Python 3.0 this issue is critical.
Please use labels and text to provide additional information.
Original issue reported on code.google.com by pyscripter
on 10 Dec 2008 at 12:40
Hi
Compiled error at python 3.6
Can you fix it as following.
{$IFDEF PYTHON36}
COMPILED_FOR_PYTHON_VERSION_INDEX = 12;
{$ENDIF}
{$IFDEF PYTHON36} ==> {$IFDEF PYTHON37}
COMPILED_FOR_PYTHON_VERSION_INDEX = 13;
Another question.
Do you have any reason for gPythonEngine and gVarType as global variables in PythonEngine.pas?
(3141 line in PytonEngine.pas)
I cannot make it more one pythonengine component because of these global variables.
Thanks.
I see problem in CudaText, don't know how to see in PyScripter. maybe you can help even here?
I have OnSendData, OnSendUniData
procedure TfmMain.PythonIOSendData(Sender: TObject; const Data: AnsiString);
begin
MsgLogConsole(Data);
end;
procedure TfmMain.PythonIOSendUniData(Sender: TObject;
const Data: UnicodeString);
begin
MsgLogConsole(UTF8Encode(Data));
end;
then MsgLogConsole does output to ATSynedit editor.
On starting CudaText, i see broken output lines for started plugins:
Init: cuda_project_manInit: cuda_tst_coInit: cuda_sess_managerInit: cuda_brackets_hiliteInit: cuda_lint
Init: cuda_project_manInit: cuda_tst_coInit: cuda_sess_managerInit: cuda_brackets_hilite
Init: cuda_project_manInit: cuda_tst_coInit: cuda_sess_manager
Init: cuda_project_manInit: cuda_tst_co
Init: cuda_project_man
Init: cuda_tabs_list
Startup: total: 423ms, including plugins: 68ms
here are 4 first lines are broken: then have other lines added.
Hi,
thanks for great project.
I am testing this in Lazarus:
Lazarus version: 1.7
Lazarus svn revision: 54250M
Lazarus build date: 2018/05/11
Lazarus was compiled for i386-win32 on win7 64bit
Lazarus was compiled with fpc 3.1.1
Seems like
function PyPoint_OffsetBy(self, args : PPyObject) : PPyObject; cdecl;
is not properly registered and python code:
p.OffsetBy( 5, 5 )
causes Access violation error.
I am able to run demo01 without problem and using embedded distribution downloaded from python.org.
For details please see:
PyCFunction_NewEx: function(md:PPyMethodDef;self, ob:PPyObject):PPyObject; cdecl;
I don't know engine part. pls tell, what patch with _NewEx does? what works not ok w/out this patch?
when i run your P4D demos found "brcc32" exited with code 1.
win7+python3.6
I checked out the source, and when trying to install the component, I got the
following errr:
[Fatal Error] Python_d7.dpk(41): File not found: 'AtomPythonEngine.dcu'
Original issue reported on code.google.com by [email protected]
on 15 Mar 2011 at 7:52
steps to reproduce:
after code below
...
var
S: String;
Engine: TPythonEngine;
PObj: PPyObject;
...
S := 'ABC'#0'D';
PObj := Engine.VariantAsPyObject(S)
we have 'ABC'in PObj
Below bug fix:
in TPythonEngine.VariantAsPyObject
replace all occurrence of
Result := PyString_FromString( PAnsiChar(s) )
to
Result := PyString_FromStringAndSize(PAnsiChar(s), Length(s))
Original issue reported on code.google.com by [email protected]
on 30 Jul 2012 at 1:20
Title says it all.
Original issue reported on code.google.com by pyscripter
on 12 May 2009 at 12:51
I wrote simple function which returns list of opened Excel workbooks names on the basis of the demodll example:
function getOpenedWorkbooks(Self, Args : PPyObject) : PPyObject; cdecl;
var
i: integer;
begin
with GetPythonEngine do
begin
try
Excel := GetActiveOleObject('Excel.Application');
Result := PyList_New(Excel.workbooks.count);
for i := 1 to Excel.workbooks.count do
begin
PyList_SetItem(Result, i-1, VariantAsPyObject(Excel.workbooks[i].Name));
end;
except
on E:Exception do
begin
PyErr_SetString(PyExc_IndexError^, PAnsiChar(E.Message));
Result := nil;
end;
end;
end;
end;
in python script I call it successfully and got valid results:
import xlslib
print(xlslib.getOpenedWorkbooks())
print(xlslib.add(10,15))
But after that process python.exe is not responding(console window didn't disappear). If I call only function Add(imported from demodll), everything works good. I used python 3.5.
Up:
I set Excel := 0 in finalization block of module and here program hanged up. Interesting thing, if I set Excel := 0 in particular function everything works good.
What steps will reproduce the problem?
Hi, I'm using py4d on delphi2010 on windows vista. No matter what type of image
i load, the prompt always reads:
Traceback (most recent call last):
File "<string>", line 6, in ProcessImage
File "C:\Python27\lib\site-packages\PIL\Image.py", line 1982, in open
raise IOError("cannot identify image file")
IOError: cannot identify image file'
Does anyone know how to make it work?
Original issue reported on code.google.com by [email protected]
on 18 Aug 2012 at 8:04
Hi,
if you compile in non-mswindows mode, the unit MethodCallback.pas complains in line 182 that says:
page := getmem(pagesize);
but maybe you wanted to write?:
page := getmemory(pagesize);
Regards
Hi,
I'm interested in use python4delphi in a multi threaded environment, more specifically in an Indy TCP Server.
I need to execute python scripts inside threads in a high concurrent environment.
Looking at source code, I found that gPythonEngine is a global variable so obviously I can't have more that one PythonEngine at the same time in my application.
Is TPythonEngine thread safe?
If yes, how should be the right way to implement python4delphi in a threaded application?
Regards
Some fixes to make Demo8 work
- Use Python framework instead of load library
- Stack alignment in asm routines
- Some compiler incompatibilities
Original issue reported on code.google.com by [email protected]
on 9 Nov 2010 at 4:31
Attachments:
Does it work with XE3 / 64 ?
Original issue reported on code.google.com by [email protected]
on 11 Oct 2012 at 5:45
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.