-
Content Count
991 -
Joined
-
Last visited
-
Days Won
62
Everything posted by pyscripter
-
TOML is a "config file format for humans", that has gained a lot of traction in the python and rust communities among others. It is basically the INI file format on steroids. It compares quite well to alternative formats such as JSON, YAML and XML. Compared to JSON is way more readable and compact. Since I could not find any Delphi library for processing TOML, I have created my own: toml-delphi. Features: TOML v1.0.0 compliant. Passes all 734 (valid/invalid) official validation tests. Fast. Single stream tokenizer and lexer that doesn't use regex. Converts TOML documents to Delphi's RTL's TJSONObject, thus allowing for easy traversal, manipulation and query of the generated documents. Includes TTOMLWriter for converting TJSONObjects back to TOML. Provides for easy (de)serialization of Delphi objects and records from/to TOML. This is the interface of the main unit: TJSONObjectHelper = class helper for TJSONObject function ToTOML(MultilineStrings: Boolean = False; Indent: Integer = 4): string; procedure StreamTOML(Stream: TStream; MultilineStrings: Boolean = False; Indent: Integer = 4); procedure SaveTOMLtoFile(const FileName: string; MultilineStrings: Boolean = False; Indent: Integer = 4); class function FromTOML(const Contents: string): TJSONObject; overload; class function FromTOML(Contents: TBytes): TJSONObject; overload; class function FromTOML(Stream: TStream): TJSONObject; overload; class function FromTOMLFile(const FileName: string): TJSONObject; end; ETOMLSerializer = class(Exception); TTOMLSerializer = class class function Serialize<T>(const AValue: T): string; overload; class function Deserialize<T>(const ATOML: string): T; overload; end; Example usage: You can convert TOML source to TJSONObject using one of the FromTOML functions. For example to parse a TOML file you use: var JsonObject := TJSONObject.FromTOMLFile(FileName); //or for parsing a TOML string: var JsonObject := TJSONObject.FromTOML(TOMLstring); To convert a TJSONObject to TOML you use one of the methods ToTOML, StreamTOML or SaveTOMLToFile. For example: TOMLString := JsonObject.ToTOML; // or JsonObject.SaveTOMLToFile(FileName); Example serialization: type TTestRec = record IntValue: Integer; FloatValue: double; StringValue: string; DateValue: TDateTime; ArrayValue: TArray<string>; end; procedure TestSerializer; var Rec: TTestRec; TOMLString: string; begin Rec.IntValue := 123; Rec.FloatValue := 3.14; Rec.StringValue := 'abc'; Rec.DateValue := Now; Rec.ArrayValue := ['A', 'B', 'C']; Writeln('Serialized record:'); WriteLn('=================='); TOMLString := TTOMLSerializer.Serialize(Rec); Writeln(TOMLString); Writeln('Record deserialized and serialized again:'); Writeln('========================================='); Rec := TTOMLSerializer.Deserialize<TTestRec>(TOMLString); TOMLString := TTOMLSerializer.Serialize(Rec); Writeln(TOMLString); end; Output: Serialized record: ================== IntValue = 123 FloatValue = 3.14 StringValue = "abc" DateValue = "2025-06-18T05:37:02.110+03:00" ArrayValue = [ "A", "B", "C" ] Record deserialized and serialized again: ========================================= IntValue = 123 FloatValue = 3.14 StringValue = "abc" DateValue = "2025-06-18T05:37:02.110+03:00" ArrayValue = [ "A", "B", "C" ] I hope you find it useful.
-
See https://github.com/genericptr/fpTOML/issues/5#issuecomment-2983448165
-
Getting exitcode (%errorlevel%) of python script
pyscripter replied to gmbouwer's topic in Python4Delphi
You can do something similar in python. You can use sys.exit(n) which raises the SystemExit exception. n can be a number or a string or anything else. But if you call sys.exit(n) with different integer values then you can do the following: try PythonEngine.ExecString(...); except on E: EPySystemExit do begin case IntToStr(e.EValue): 1: 2: end; end; end; -
Getting exitcode (%errorlevel%) of python script
pyscripter replied to gmbouwer's topic in Python4Delphi
PythonEngine1.ExecStrings(lines) will raise in exception (a subclass of EPyException) if an error occurs. If you redirecting the python output using for instance TPythonGUIInputOutput then error information is printed and you will be able to see where the error occurred including a traceback. You can also use the Traceback object to extract information about the error. If you want to handle the Exception you can use try PythonEngine1.ExecStrings(lines); except on E: EPyException // Do whatever you want. You can use the PythonEngine1.Traceback to get information about what went wrong end -
How to get Python functions running in the background (P4D)
pyscripter replied to JGMS's topic in Python4Delphi
I guess ExecStrings raises an exception so, the event is not signalled. You can modify ExecuteWithPython to always signal: procedure TPyThread.ExecuteWithPython; begin try GetPythonEngine.ExecString(Script); finally Event.Signal; end; end; Don't you get the error printed when running your script? You can also use the debugger to see if/what the exception is. Note that not all modules are compatible with PyInterpreterConfig_OWN_GIL. I suspect PIL isn't, Read the documentation about the limitations. Does you program work with emNewState? Note that emNewInterpreter does not offer any performance advantages compared to emNewState. Given that Demo 36 works, start from that and then gradually move towards what you want, until you find what fails. The first thing that I would test is the imports. Add: import sys print(sys.path) to make sure that you are using the correct version of python with your desired imports installed. Then add your imports to see whether they work. -
How to get Python functions running in the background (P4D)
pyscripter replied to JGMS's topic in Python4Delphi
Everything you need to know is here. -
Development of SynEdit at PyScripter has been moved to and merged with TurboPack SynEdit. The focus of the development is to modernize the code base and enhance the functionality (sometimes at the expense of backward compatibility). In addition to the earlier enhancements and fixes two more features have been recently added: Per-monitor DPI awareness Support for Font Ligatures (new option eoShowLigatures) Fonts like Cascadia Code and Fira Code contain ligatures relevant to programming. See this article for details. Are you using font ligatures? Do you like them? See sample. Thanks to vhanla for contributing the ligature support.
-
In Installing R and Python - TeeBI Documentation you say that I cannot find that unit. Also you say that: That folder does not exist.
-
The plugins are missing.
-
I would like to share the following in case you encounter the same issue. Class and Record Helpers (Delphi) - RAD Studio states that: Actually, this is not entirely correct. Consider the following: Unit HelperUnit1.pas: TObjectHelper1 = class helper for TObject procedure Test; end; Unit2 HelperUnit2.pas: TObjectHelper2 = class helper for TObject procedure Test; end; Unit SupportClasses,pas: uses HelperUnit1; type TMyClass: class end; Unit MainUnit.pas interface implementation uses SupportClasses, HelperUnit2; begin var MyClass:= TMyClass.Create; MyClass.Test; end; MyClass.Test will use the HelperUnit1.TObjectHelper1.Test implementation even if HelperUnit1 is not even in scope, let alone being "in nearest scope". So it appears that if a class helper is in scope where a class is defined, it is used unconditionally in all units of a project. If not, then what it is stated in the documentation applies.
-
Class helpers compiler or documentation error - RAD Studio Service - Jira Service Management
-
hydrobyte/TestJSON: A simple project to test JSON libraries with Delphi and C++Builder. presents JSON library benchmarks comparing a large number of alternatives. One thing that strikes me, is that the System.JSON rtl library is doing relatively well compared to the competition, both in terms of performance and in terms of JSON validation. With the exception of Find, is very competitive in all other areas. I have seen many claims that System.JSON is very slow and that the xyz library is so many times faster. Do these benchmarks suck (like most benchmarks)? Or is it the case that System.JSON is not that bad? What is your experience?
-
How to get a pandas dataframe in delphi
pyscripter replied to ricardo chapingo's topic in Python4Delphi
See python4delphi/Demos/Demo36 at master · pyscripter/python4delphi for an example of using the buffer protocol to read/write numpy arrays in Delphi using the buffer protocol. If you do not care about speed watch the video tutorials and the tutorial demos that show you how to create numpy arrays from delphi and pass them to python and back. In a similar way you can work with dataframes directly. -
When I serialize a an object with object fields that are nil I get null values in the Json result e.g. { "capabilities": { "positionEncoding": [], "textDocumentSync": { "openClose": true, "change": 2, "willSave": false, "willSaveWaitUntil": false, "save": null }, "notebookDocumentSync": null, "completionProvider": null, } How can I ignore fields that have nil values? System.JSON.Types defines the following: TJsonDefaultValueHandling = (Include, Ignore, Populate, IgnoreAndPopulate); but it is not used anywhere. I also tried to use a converter, but I could not get it to work. And in any case converters are used after the property name is written. Any ideas?
-
Ignoring nil values with ΤJsonSerializer
pyscripter replied to pyscripter's topic in RTL and Delphi Object Pascal
It includes a number of converters to handle generic collections, but I think you have to add them manually: -
Since you asked for Serializer benchmakrs: paolo-rossi/delphi-neon: JSON Serialization library for Delphi includes a benchmark against the Rest.Json serializer and it beats it hand down: I have replaced the Rest.Json serializer with the System.Json.Serializers TJSONSerializer. Here are the results: So now TJsonSerializer beats Neon hands down. TJsonSerializer looks good but it has some rough edges. To run the benchmarks I had to add a converter that handles Enumerated values as strings instead of the default integers: type TEnumStringConverter = class(TJsonConverter) public function CanConvert(ATypeInf: PTypeInfo): Boolean; override; function ReadJson(const AReader: TJsonReader; ATypeInf: PTypeInfo; const AExistingValue: TValue; const ASerializer: TJsonSerializer): TValue; override; procedure WriteJson(const AWriter: TJsonWriter; const AValue: TValue; const ASerializer: TJsonSerializer); override; end; { TEnumStringConverter } function TEnumStringConverter.CanConvert(ATypeInf: PTypeInfo): Boolean; begin // This converter can handle any type that is an enumeration Result := (ATypeInf.Kind = TTypeKind.tkEnumeration) and (ATypeInf <> TypeInfo(Boolean)); end; function TEnumStringConverter.ReadJson(const AReader: TJsonReader; ATypeInf: PTypeInfo; const AExistingValue: TValue; const ASerializer: TJsonSerializer): TValue; var LIntValue: Integer; begin LIntValue := System.TypInfo.GetEnumValue(ATypeInf, AReader.Value.AsString); if LIntValue = -1 then // GetEnumValue returns -1 if the name is not found raise EJsonSerializationException.CreateFmt('Invalid string value "%s" for enumeration "%s".', [AExistingValue.AsString, ATypeInf.Name]); // Create a TValue of the specific enum type using its ordinal value. Result := TValue.FromOrdinal(ATypeInf, LIntValue); end; procedure TEnumStringConverter.WriteJson(const AWriter: TJsonWriter; const AValue: TValue; const ASerializer: TJsonSerializer); begin AWriter.WriteValue(System.TypInfo.GetEnumName(AValue.TypeInfo, AValue.AsOrdinal)); end; See also: Bummer: System.Json.Converters already includes TJsonEnumNameConverter that does the job.
-
No. Most of the alternatives do not support serialization. Grizzy and Superobject do. Delphi offers a couple of ways. But serialization is not necessarily dependent on JSON parsing. For example NEON is using System.JSON.
-
Ignoring nil values with ΤJsonSerializer
pyscripter replied to pyscripter's topic in RTL and Delphi Object Pascal
Feature requests added: TJSONSerializer support for Null value and default value handling. - RAD Studio Service - Jira Service Management Add an overload to TJSONSerializer, that serializes without using converters - RAD Studio Service - Jira Service Management -
Component with sub-property event
pyscripter replied to Anders Melander's topic in Delphi IDE and APIs
It works with Components if you call SetSubComponent or set csSubComponent. Then Events are displayed. e.g, So you can change TTestSub to inherit from TComponent. -
Component with sub-property event
pyscripter replied to Anders Melander's topic in Delphi IDE and APIs
You need to overwrite the TTestSub.GetOwner. -
executing a command with ssh-pascal runs into timeout
pyscripter replied to dummzeuch's topic in Network, Cloud and Web
This is roughly what I had in mind. Suggestions: Have one event with an Enumerated parameter TExecOutput = (eoStdout, eoStdErr) Pass to the callback only the newly added bytes in a TBytes. They can be easily converted to strings using the ISshClient encoding. Keep the output as is. The user has a choice of not providing a callback. The overhead is small. -
executing a command with ssh-pascal runs into timeout
pyscripter replied to dummzeuch's topic in Network, Cloud and Web
This is how it is designed to work. I will add an event that is triggered whenever output is added. Add an event to access partial output of ISshExec.Exec · Issue #20 · pyscripter/Ssh-Pascal -
executing a command with ssh-pascal runs into timeout
pyscripter replied to dummzeuch's topic in Network, Cloud and Web
ISshExec.Exec was substantially revised and now works in non-blocking mode. Are you using the latest source? Are you using the latest linssh2 binaries? You can execute ISshExec in a thread. Note that then it can be cancelled from the main thread using ISshExec.Cancel. Also you memory leak in TSshExec.Exec · Issue #18 · pyscripter/Ssh-Pascal has been fixed. Can you confirm that? -
In the latest commits, I have added the ability to handle pointer fields and properties. They are converted to python integers. So you could store for example an integer to the TTreeNode.Data. You could also store pointers to python objects using ctypes. See for example the following: from ctypes import py_object, pointer, addressof, cast, POINTER # Create a py_object original = "Hello" py_obj = py_object(original) # Get its address addr = addressof(py_obj) # e.g., 0x7f8b5c403020 # Recover the py_object py_ptr = cast(addr, POINTER(py_object)) recovered_py_obj = py_ptr.contents recovered = recovered_py_obj.value print(recovered) # "Hello" print(original is recovered) # True (same object) addr is an int type (python integer) that can be stored in Delphi pointer property.
-
TTreeNode.Data is a Pointer property and WrapDelphi does not support raw pointer properties. The only pointer property supported is PPyObject. So if your wrapped class had a property declared as PPyObject it would work. This also explains the error message. To be able to use the Data property you would need to modify the TTreeNode wrapper and do some custom wrapping of the TreeNode.Data property. Alternatively you could save whatever info you need to store in a python data structure (possibly dict for easy access).