1 | unit UExecute;
|
---|
2 |
|
---|
3 | interface
|
---|
4 |
|
---|
5 | uses
|
---|
6 | Classes, SysUtils, Process;
|
---|
7 |
|
---|
8 | type
|
---|
9 | { TExecute }
|
---|
10 |
|
---|
11 | TExecute = class
|
---|
12 | protected
|
---|
13 | function GetExecutable: string; virtual;
|
---|
14 | public
|
---|
15 | PrintOutput: Boolean;
|
---|
16 | PrintCommand: Boolean;
|
---|
17 | StandardOutput: string;
|
---|
18 | ErrorOutput: string;
|
---|
19 | procedure Execute(Parameters: array of string); virtual;
|
---|
20 | procedure ExecuteOutput(Parameters: array of string);
|
---|
21 | end;
|
---|
22 |
|
---|
23 |
|
---|
24 | implementation
|
---|
25 |
|
---|
26 |
|
---|
27 | { TExecute }
|
---|
28 |
|
---|
29 | function TExecute.GetExecutable: string;
|
---|
30 | begin
|
---|
31 | Result := '';
|
---|
32 | end;
|
---|
33 |
|
---|
34 | procedure TExecute.Execute(Parameters: array of string);
|
---|
35 | var
|
---|
36 | Process: TProcess;
|
---|
37 | I: Integer;
|
---|
38 | Buffer: string;
|
---|
39 | Count: Integer;
|
---|
40 | begin
|
---|
41 | StandardOutput := '';
|
---|
42 | ErrorOutput := '';
|
---|
43 | Buffer := '';
|
---|
44 | try
|
---|
45 | Process := TProcess.Create(nil);
|
---|
46 | Process.Executable := GetExecutable;
|
---|
47 | for I := 0 to Length(Parameters) - 1 do
|
---|
48 | Process.Parameters.Add(Parameters[I]);
|
---|
49 | Process.Options := [poUsePipes, poNoConsole];
|
---|
50 | if PrintCommand then begin
|
---|
51 | WriteLn(Process.Executable + ' ' + StringReplace(Process.Parameters.Text, LineEnding, ' ', [rfReplaceAll]));
|
---|
52 | end;
|
---|
53 | Process.Execute;
|
---|
54 | while Process.Running or (Process.Output.NumBytesAvailable > 0) or
|
---|
55 | (Process.Stderr.NumBytesAvailable > 0) do
|
---|
56 | begin
|
---|
57 | if Process.Output.NumBytesAvailable > 0 then begin
|
---|
58 | SetLength(Buffer, 1000);
|
---|
59 | Count := Process.Output.Read(Buffer[1], Length(Buffer));
|
---|
60 | SetLength(Buffer, Count);
|
---|
61 | StandardOutput := StandardOutput + Buffer;
|
---|
62 | if PrintOutput then Write(Buffer);
|
---|
63 | end;
|
---|
64 | if Process.Stderr.NumBytesAvailable > 0 then begin
|
---|
65 | SetLength(Buffer, 1000);
|
---|
66 | Count := Process.Stderr.Read(Buffer[1], Length(Buffer));
|
---|
67 | SetLength(Buffer, Count);
|
---|
68 | ErrorOutput := ErrorOutput + Buffer;
|
---|
69 | if PrintOutput then Write(Buffer);
|
---|
70 | end;
|
---|
71 | Sleep(1);
|
---|
72 | end;
|
---|
73 | finally
|
---|
74 | Process.Free;
|
---|
75 | end;
|
---|
76 | end;
|
---|
77 |
|
---|
78 | procedure TExecute.ExecuteOutput(Parameters: array of string);
|
---|
79 | begin
|
---|
80 | Execute(Parameters);
|
---|
81 | if StandardOutput <> '' then Write(StandardOutput);
|
---|
82 | if ErrorOutput <> '' then Write(ErrorOutput);
|
---|
83 | end;
|
---|
84 |
|
---|
85 | end.
|
---|
86 |
|
---|