Jump to content
Celebr0

How to run one .py script in several instances at the same time ?

Recommended Posts

Hello, I am faced with a problem that I need to run one .py script in several instances, but I can’t achieve this through python4delphi (

I'm trying to do it like this, but since the script has been running for some time, the program just crashes:

program ParallelPython;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils,
  System.Diagnostics,
  System.Variants,
  System.SyncObjs,
  PythonEngine;

var
  PythonEngine: TPythonEngine;

type
  TPyThread = class(TPythonThread)
  protected
    procedure ExecuteWithPython; override;
  public
    constructor Create(createsuspended:boolean);
  end;

procedure CreatePyEngine;
begin
  PythonEngine := TPythonEngine.Create(nil);
  PythonEngine.LoadDll;
  TPythonThread.Py_Begin_Allow_Threads;
end;

procedure DestroyEngine;
begin
TPythonThread.Py_End_Allow_Threads;
PythonEngine.Free;
end;

procedure TPyThread.ExecuteWithPython;
const Arg =
'import sys'+#13#10+
'def run_python_script(args_str):'+#13#10+
'    args_list = args_str.split()'+#13#10+
'    sys.argv = [sys.argv[0]] + args_list';
begin
inherited;
while true do begin
PythonEngine.ExecString(Arg);
PythonEngine.ExecFile(extractfilepath(paramstr(0))+'script.py');
end;
end;

constructor TPyThread.Create(createsuspended:boolean);
begin
  inherited Create(CreateSuspended);
  ThreadExecMode := emNewInterpreterOwnGIL;
  FreeOnTerminate := True;
end;

var
I: Integer;
begin
try
CreatePyEngine;
for I := 1 to 10 do
TPyThread.Create(False);
finally
//DestroyEngine;
end;
ReadLn;
end.

And it probably also crashes because the script is trying to be executed in one interpreter (
 

Share this post


Link to post

If I run 10 instances of my own program, then all 10 instances work, and if I create and then destroy pythonengine, it will write an error that the python .dll is already in use ?
 

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×