我在OSX上,我发现以下Delphi(Firemonkey)代码将控制台输出写入Memo。当我使用像“ls”这样的普通命令时,这样可以正常工作,但它不会捕获外部终端应用程序的输出。
例如,如果我运行命令行应用程序“youtube-dl”,则输出仅显示在PAServer日志中,而不显示在备忘录中。
有办法做到这一点吗?或者有人可以修改代码以使其工作吗?
const
libc = '/usr/lib/libc.dylib';
type
PIOFile = Pointer;
//Create a new stream connected to a pipe running the given command.
function popen(const Command: PAnsiChar; Modes: PAnsiChar): PIOFile; cdecl;
external libc name '_popen';
//Close a stream opened by popen and return the status of its child.
function pclose(Stream: PIOFile): Integer; cdecl; external libc name '_pclose';
//Return the EOF indicator for STREAM.
function feof(Stream: PIOFile): Integer; cdecl; external libc name '_feof';
//Read chunks of generic data from STREAM.
function fread(Ptr: Pointer; Size: LongWord; N: LongWord;
Stream: PIOFile): LongWord; cdecl; external libc name '_fread';
//Wait for a child to die. When one does, put its status in *STAT_LOC
//and return its process ID. For errors, return (pid_t) -1.
function wait(__stat_loc: PInteger): Integer; cdecl;
external libc name '_wait';
procedure TForm1.ExecCmdine(const CmdLine: string);
var
Output: PIOFile;
Buffer: PAnsiChar;
TempString: Ansistring;
Line: AnsiString;
BytesRead: Integer;
const
BufferSize: Integer = 1000;
begin
TempString := '';
Output := popen(PAnsiChar(Ansistring(CmdLine)), 'r');
GetMem(Buffer, BufferSize);
if Assigned(Output) then
try
while feof(Output) = 0 do
begin
BytesRead := fread(Buffer, 1, BufferSize, Output);
SetLength(TempString, Length(TempString) + BytesRead);
Move(Buffer^, TempString[length(TempString) - (BytesRead - 1)], BytesRead);
while Pos(#10, TempString) > 0 do
begin
Line := Copy(TempString, 1, Pos(#10, TempString) - 1);
Memo1.Lines.Add(UTF8ToString(Line));
TempString := Copy(TempString, Pos(#10, TempString) + 1, Length(TempString));
end;
end;
finally
pclose(output);
wait(nil);
FreeMem(Buffer, BufferSize);
end;
end;
答案 0 :(得分:1)
问题是youtube-dl的控制台输出被打印到stderr而不是stdout,因此我必须在运行它时向控制台命令添加2>& 1。
答案 1 :(得分:0)
上面的代码给了我错误(Delphi 10.3.2和macOS 64位)
[dccosx64 Error] E2597 Undefined symbols for architecture x86_64:
Error: "__pclose", referenced from: __ZN9Functions6pcloseEPv in functions.o;
Error: "__popen", referenced from: __ZN9Functions5popenEPKcPc in functions.o;
Error: "__feof", referenced from: __ZN9Functions4feofEPv in functions.o;
Error: "__fread", referenced from: __ZN9Functions5freadEPvmmS0_ in functions.o;
Error: "__wait", referenced from: __ZN9Functions4waitEPi in functions.o;
ld: symbol(s) not found for architecture x86_64