我在 OSX 上,我发现以下 Delphi (Firemonkey) 代码将控制台输出写入备忘录。当我使用像“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;
Rob Kennedy 有正确的答案,但遗憾的是他没有将其发布为答案,所以我会这样做。
问题是 youtube-dl 的控制台输出被打印到 stderr 而不是 stdout,所以我必须在运行它时将 2>&1 添加到控制台命令。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句