如何在Delphi中运行命令行程序?

gra*_*amm 23 delphi command-line shellexecute

我需要从Delphi软件执行Windows"find"命令.我试图使用该ShellExecute命令,但它似乎不起作用.在C中,我会使用该system程序,但在这里...我不知道.我想做这样的事情:

System('find "320" in.txt > out.txt');
Run Code Online (Sandbox Code Playgroud)

编辑:谢谢你的答案:)我试图运行'查找'作为可执行文件,而不是作为cmd.exe的参数.

mgh*_*hie 31

使用示例ShellExecute():

procedure TForm1.Button1Click(Sender: TObject);
begin
  ShellExecute(0, nil, 'cmd.exe', '/C find "320" in.txt > out.txt', nil, SW_HIDE);
  Sleep(1000);
  Memo1.Lines.LoadFromFile('out.txt');
end;
Run Code Online (Sandbox Code Playgroud)

请注意,使用CreateProcess()而不是ShellExecute()允许更好地控制过程.

理想情况下,您也可以在辅助线程中调用它,并调用WaitForSingleObject()进程句柄以等待进程完成.将Sleep()在本例中只是一个黑客等待一段时间,节目开始通过ShellExecute()到结束- ShellExecute()不会那么做的.如果它确实你不能简单地打开一个notepad用于编辑文件的实例,ShellExecute()则会阻止你的父应用程序直到编辑器关闭.

  • `ShellExecute()`将启动应用程序但不等待它完成 - 否则你无法真正使用它来打开标准的GUI程序.在小文本文件上运行`find`可能无关紧要,但对于执行时间较长的任务,您必须确保在处理`out.txt`中的结果之前完成它们.这就是为什么使用`CreateProcess()`并等待进程句柄是一个更好的方法. (2认同)

WeG*_*ars 18

VARIANT1:

这将运行'DOS'程序并检索其输出:

function GetDosOutput(CommandLine: string; Work: string = 'C:\'): string;  { Run a DOS program and retrieve its output dynamically while it is running. }
var
  SecAtrrs: TSecurityAttributes;
  StartupInfo: TStartupInfo;
  ProcessInfo: TProcessInformation;
  StdOutPipeRead, StdOutPipeWrite: THandle;
  WasOK: Boolean;
  pCommandLine: array[0..255] of AnsiChar;
  BytesRead: Cardinal;
  WorkDir: string;
  Handle: Boolean;
begin
  Result := '';
  with SecAtrrs do begin
    nLength := SizeOf(SecAtrrs);
    bInheritHandle := True;
    lpSecurityDescriptor := nil;
  end;
  CreatePipe(StdOutPipeRead, StdOutPipeWrite, @SecAtrrs, 0);
  try
    with StartupInfo do
    begin
      FillChar(StartupInfo, SizeOf(StartupInfo), 0);
      cb := SizeOf(StartupInfo);
      dwFlags := STARTF_USESHOWWINDOW or STARTF_USESTDHANDLES;
      wShowWindow := SW_HIDE;
      hStdInput := GetStdHandle(STD_INPUT_HANDLE); // don't redirect stdin
      hStdOutput := StdOutPipeWrite;
      hStdError := StdOutPipeWrite;
    end;
    WorkDir := Work;
    Handle := CreateProcess(nil, PChar('cmd.exe /C ' + CommandLine),
                            nil, nil, True, 0, nil,
                            PChar(WorkDir), StartupInfo, ProcessInfo);
    CloseHandle(StdOutPipeWrite);
    if Handle then
      try
        repeat
          WasOK := windows.ReadFile(StdOutPipeRead, pCommandLine, 255, BytesRead, nil);
          if BytesRead > 0 then
          begin
            pCommandLine[BytesRead] := #0;
            Result := Result + pCommandLine;
          end;
        until not WasOK or (BytesRead = 0);
        WaitForSingleObject(ProcessInfo.hProcess, INFINITE);
      finally
        CloseHandle(ProcessInfo.hThread);
        CloseHandle(ProcessInfo.hProcess);
      end;
  finally
    CloseHandle(StdOutPipeRead);
  end;
end;
Run Code Online (Sandbox Code Playgroud)

变式2:

在[Realtime]中捕获控制台输出以及它在TMemo中的输出方式:

procedure CaptureConsoleOutput(const ACommand, AParameters: String; AMemo: TMemo);
 const
   CReadBuffer = 2400;
 var
   saSecurity: TSecurityAttributes;
   hRead: THandle;
   hWrite: THandle;
   suiStartup: TStartupInfo;
   piProcess: TProcessInformation;
   pBuffer: array[0..CReadBuffer] of AnsiChar;      <----- update
   dRead: DWord;
   dRunning: DWord;
 begin
   saSecurity.nLength := SizeOf(TSecurityAttributes);
   saSecurity.bInheritHandle := True;  
   saSecurity.lpSecurityDescriptor := nil; 

   if CreatePipe(hRead, hWrite, @saSecurity, 0) then
   begin    
     FillChar(suiStartup, SizeOf(TStartupInfo), #0);
     suiStartup.cb := SizeOf(TStartupInfo);
     suiStartup.hStdInput := hRead;
     suiStartup.hStdOutput := hWrite;
     suiStartup.hStdError := hWrite;
     suiStartup.dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW;    
     suiStartup.wShowWindow := SW_HIDE; 

     if CreateProcess(nil, PChar(ACommand + ' ' + AParameters), @saSecurity,
       @saSecurity, True, NORMAL_PRIORITY_CLASS, nil, nil, suiStartup, piProcess)
       then
     begin
       repeat
         dRunning  := WaitForSingleObject(piProcess.hProcess, 100);        
         Application.ProcessMessages(); 
         repeat
           dRead := 0;
           ReadFile(hRead, pBuffer[0], CReadBuffer, dRead, nil);          
           pBuffer[dRead] := #0; 

           OemToAnsi(pBuffer, pBuffer);
           AMemo.Lines.Add(String(pBuffer));
         until (dRead < CReadBuffer);      
       until (dRunning <> WAIT_TIMEOUT);
       CloseHandle(piProcess.hProcess);
       CloseHandle(piProcess.hThread);    
     end; 

     CloseHandle(hRead);
     CloseHandle(hWrite);
   end;
end;
Run Code Online (Sandbox Code Playgroud)

资料来源:delphi.wikia.com

  • 实际上,最好使用完整的限定符:“winapi.windows.readfile” (3认同)