Executing External Programs/zh CN: what changed
Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.
Title: Executing External Programs/zh CN
| Old | New | Line | |
|---|---|---|---|
| 1 | + | 执行外部程序 | |
| 2 | + | ||
| 3 | + | ## Contents | |
| 4 | + | ||
| 5 | + | * 1 概述:对比 | |
| 6 | + | * 2 (Process.)RunCommand | |
| 7 | + | * 2.1 RunCommand 的扩展版本 | |
| 8 | + | * 3 SysUtils.ExecuteProcess | |
| 9 | + | * 4 微软 Windows 系统:CreateProcess、ShellExecute 和 WinExec | |
| 10 | + | * 4.1 针对提权/管理员权限使用 ShellExecuteEx | |
| 11 | + | * 5 Unix 的 fpsystem、fpexecve 和 shell | |
| 12 | + | * 6 TProcess | |
| 13 | + | * 6.1 最简单的示例 | |
| 14 | + | * 6.2 简单示例 | |
| 15 | + | * 6.3 改良后的示例(但仍不够正确) | |
| 16 | + | * 6.4 大数据量输出的读取 | |
| 17 | + | * 6.5 TProcess 输入输出的用法 | |
| 18 | + | * 6.6 TProcess 用法提示 | |
| 19 | + | * 6.7 前台显示 macOS 应用程序包 | |
| 20 | + | * 6.8 让程序独立运行 | |
| 21 | + | * 6.9 与 aspell 进程通讯的示例代码 | |
| 22 | + | * 6.10 替换“| < >”之类的 shell 操作符 | |
| 23 | + | * 6.10.1 为什么用操作符重定向输出无效 | |
| 24 | + | * 6.11 如何实现 TProcess 输出重定向 | |
| 25 | + | * 6.11.1 注意 | |
| 26 | + | * 6.12 重定向输入和输出,并在 root 权限下运行 | |
| 27 | + | * 6.13 在 Linux 中用 sudo 运行 fdisk | |
| 28 | + | * 6.14 包含空格的参数(替换 Shell 命令中的引号) | |
| 29 | + | * 7 LCLIntf 替代方案 | |
| 30 | + | * 7.1 用默认应用程序打开文档 | |
| 31 | + | * 7.2 用默认浏览器打开网页 | |
| 32 | + | * 8 WinExec | |
| 33 | + | * 9 参阅 | |
| 34 | + | * 10 贡献者和更改 | |
| 35 | + | ||
| 36 | + | ## 概述:对比 | |
| 37 | + | ||
| 38 | + | 以下是 RTL、FCL 和 LCL 库中执行外部命令/进程/程序的各种方法。 | |
| 39 | + | ||
| 40 | + | 方法 | 库 | 平台 | 可单行完成 | 功能 | |
| 41 | + | ---|---|---|---|--- | |
| 42 | + | [[Executing External Programs|ExecuteProcess]] | RTL | 跨平台 | 是 | 非常有限,以同步方式执行 | |
| 43 | + | [[Executing External Programs|ShellExecute]] | WinAPI | 仅限微软的 Windows 系统 | 是 | 很多。能够提权启动需管理员权限的程序。 | |
| 44 | + | [[Executing External Programs|fpsystem、fpexecve]] | Unix | 仅限 Unix 系统 | | | |
| 45 | + | [[Executing External Programs|TProcess]] | FCL | 跨平台 | 否 | 完整 | |
| 46 | + | [[Executing External Programs|RunCommand]]RunCommand> "Executing External Programs") | FCL | 跨平台 需要FPC 2.6.2+ | 是 | 支持常用的 TProcess 用法 | |
| 47 | + | [[Executing External Programs|OpenDocument]] | LCL | 跨平台 | 是 | 只能打开文档。将会用该文档类型关联的应用程序打开。 | |
| 48 | + | ||
| 49 | + | ## (Process.)RunCommand | |
| 50 | + | ||
| 51 | + | * [RunCommand](<http://www.freepascal.org/docs-html/fcl/process/runcommand.html>)参考手册 | |
| 52 | + | * [RunCommandInDir](<http://www.freepascal.org/docs-html/fcl/process/runcommandindir.html>)参考手册 | |
| 53 | + | ||
| 54 | + | FPC 2.6.2 为 process 单元的 TProcess 加入了一些有用的函数,来自 [[Projects using Lazarus|fpcup]] 项目的封装。 这些函数适用于初、中级应用,能将输出捕获到单个字符串中,并完全支持 _大数据量输出_ 。 | |
| 55 | + | ||
| 56 | + | 以下是简单示例: | |
| 57 | + | ``` | |
| 58 | + | program project1; | |
| 59 | + | ||
| 60 | + | {$mode objfpc}{$H+} | |
| 61 | + | ||
| 62 | + | uses | |
| 63 | + | Process; | |
| 64 | + | ||
| 65 | + | var | |
| 66 | + | s : ansistring; | |
| 67 | + | ||
| 68 | + | begin | |
| 69 | + | ||
| 70 | + | if RunCommand('/bin/bash',['-c','echo $PATH'],s) then | |
| 71 | + | writeln(s); | |
| 72 | + | ||
| 73 | + | end. | |
| 74 | + | ``` | |
| 75 | + | ||
| 76 | + | 但请注意,并不是所有 shell“内置”命令(如 alias)都能支持,因为默认情况下,在非交互式 shell 中不会用到别名。除非设置了 BASH_ENV 环境变量,不然非交互式 shell 也不会读取 .bashrc 文件。因此,以下代码不会输出任何结果: | |
| 77 | + | ``` | |
| 78 | + | program project2; | |
| 79 | + | ||
| 80 | + | {$mode objfpc}{$H+} | |
| 81 | + | ||
| 82 | + | uses | |
| 83 | + | Process; | |
| 84 | + | ||
| 85 | + | var | |
| 86 | + | s : ansistring; | |
| 87 | + | ||
| 88 | + | begin | |
| 89 | + | ||
| 90 | + | if RunCommand('/bin/bash',['-c','alias'],s) then | |
| 91 | + | writeln(s); | |
| 92 | + | ||
| 93 | + | end. | |
| 94 | + | ``` | |
| 95 | + | ||
| 96 | + | RunCommand 有一个重载版本,可返回程序的退出码。RunCommandInDir 则可在指定目录中运行命令(设置 p.CurrentDirectory): | |
| 97 | + | ``` | |
| 98 | + | function RunCommandIndir(const curdir:string;const exename:string;const commands:array of string;var outputstring:string; var exitstatus:integer): integer; | |
| 99 | + | function RunCommandIndir(const curdir:string;const exename:string;const commands:array of string;var outputstring:string): boolean; | |
| 100 | + | function RunCommand(const exename:string;const commands:array of string;var outputstring:string): boolean; | |
| 101 | + | ``` | |
| 102 | + | ||
| 103 | + | 在 FPC 3.2.0 以上版本中,Runcommand 有了新的版本,允许覆盖 TProcessOptions 和 TShowWindowOptions。 | |
| 104 | + | ||
| 105 | + | ||
| 106 | + | ||
| 107 | + | ### RunCommand 的扩展版本 | |
| 108 | + | ||
| 109 | + | 在 **FPC 3.2.0 以上** 版本中,RunCommand 实现了泛型化,并重新归入了 TProcess,以便能更迅速地构建自己的 RunCommand。以下是带有超时机制的 RunCommand: | |
| 110 | + | ``` | |
| 111 | + | program TestTProcessTimeout; | |
| 112 | + | ||
| 113 | + | uses classes, sysutils, process, dateutils; | |
| 114 | + | ||
| 115 | + | type | |
| 116 | + | { TProcessTimeout } | |
| 117 | + | TProcessTimeout = class(TProcess) | |
| 118 | + | protected | |
| 119 | + | timeoutperiod: TTime; | |
| 120 | + | timedout : boolean; | |
| 121 | + | started : TDateTime; | |
| 122 | + | procedure LocalnIdleSleep(Sender,Context : TObject;status:TRunCommandEventCode;const message:string); | |
| 123 | + | public | |
| 124 | + | class function RunCommandwithTimeout(const exename:TProcessString;const commands:array of TProcessString;const dir:string;out outputstring:string;out errorstring:string;out exitstate:integer; ProcessOptions : TProcessOptions = [];SWOptions:TShowWindowOptions=swoNone;timeout:integer=15):boolean;static; | |
| 125 | + | end; | |
| 126 | + | ||
| 127 | + | procedure TProcessTimeout.LocalnIdleSleep(Sender,Context : TObject;status:TRunCommandEventCode;const message:string); | |
| 128 | + | begin | |
| 129 | + | if status=RunCommandIdle then | |
| 130 | + | begin | |
| 131 | + | writeln(Executable+'('+ Parameters.CommaText+')' +' time: '+TimeToStr(now-started)); | |
| 132 | + | if (now-started)>timeoutperiod then | |
| 133 | + | begin | |
| 134 | + | writeln('process timed out '); | |
| 135 | + | timedout:=true; | |
| 136 | + | Terminate(255); | |
| 137 | + | exit; | |
| 138 | + | end; | |
| 139 | + | sleep(RunCommandSleepTime); | |
| 140 | + | end; | |
| 141 | + | end; | |
| 142 | + | ||
| 143 | + | class function TProcessTimeout.RunCommandwithTimeout( | |
| 144 | + | const exename : TProcessString; | |
| 145 | + | const commands : array of TProcessString; | |
| 146 | + | const dir : string; | |
| 147 | + | out outputstring : string; | |
| 148 | + | out errorstring : string; | |
| 149 | + | out exitstate : integer; | |
| 150 | + | ProcessOptions : TProcessOptions = []; | |
| 151 | + | SWOptions : TShowWindowOptions=swoNone; | |
| 152 | + | timeout : integer=15 | |
| 153 | + | ):boolean; | |
| 154 | + | Var | |
| 155 | + | p : TProcessTimeout; | |
| 156 | + | i : integer; | |
| 157 | + | begin | |
| 158 | + | p:=TProcessTimeout.create(nil); | |
| 159 | + | p.OnRunCommandEvent:=@p.LocalnIdleSleep; | |
| 160 | + | p.CurrentDirectory:=dir; | |
| 161 | + | ||
| 162 | + | //timeout 单位为分钟,每秒检测一次 | |
| 163 | + | p.timeoutperiod:=timeout/MinsPerDay; | |
| 164 | + | ||
| 165 | + | (* | |
| 166 | + | //若要求 Timeout 单位为秒 | |
| 167 | + | p.timeoutperiod:=timeout/SecsPerDay; | |
| 168 | + | *) | |
| 169 | + | ||
| 170 | + | // 每秒检测一次是否该结束 | |
| 171 | + | p.runcommandsleeptime := 1000; | |
| 172 | + | ||
| 173 | + | if ProcessOptions<>[] then | |
| 174 | + | P.Options:=ProcessOptions - [poRunSuspended,poWaitOnExit]; | |
| 175 | + | p.options:=p.options+[poRunIdle]; // 需要运行 RUNIDLE 事件。参见 User Changes 3.2.0 | |
| 176 | + | ||
| 177 | + | P.ShowWindow:=SwOptions; | |
| 178 | + | p.Executable:=exename; | |
| 179 | + | if high(commands)>=0 then | |
| 180 | + | for i:=low(commands) to high(commands) do | |
| 181 | + | p.Parameters.add(commands[i]); | |
| 182 | + | p.timedout:=false; | |
| 183 | + | p.started:=now; | |
| 184 | + | try | |
| 185 | + | // runcommand() 的主循环。最初基于本 wiki 内的“大数据量输出”场景,只是 5 年内不断有所扩展。 | |
| 186 | + | RunCommandwithTimeout:=p.RunCommandLoop(outputstring,errorstring,exitstate)=0; | |
| 187 | + | if p.timedout then | |
| 188 | + | RunCommandwithTimeout:=false; | |
| 189 | + | finally | |
| 190 | + | p.free; | |
| 191 | + | end; | |
| 192 | + | if exitstate<>0 then RunCommandwithTimeout:=false; | |
| 193 | + | end; | |
| 194 | + | ||
| 195 | + | ||
| 196 | + | // 用法示例 | |
| 197 | + | ||
| 198 | + | var | |
| 199 | + | output,errors : string; | |
| 200 | + | exitcode :integer; | |
| 201 | + | begin | |
| 202 | + | //Windows 和 Unix 还有其他程序可用 | |
| 203 | + | {$if defined(WINDOWS)} | |
| 204 | + | if TProcessTimeout.RunCommandwithTimeout('cmd',['/c','dir','C:\*.exe','/s'],'c:\',output,errors,exitcode,[],swoNone,1) then // dir c:\*.exe /s | |
| 205 | + | {$else$} | |
| 206 | + | if TProcessTimeout.RunCommandwithTimeout('find',['/','-name','"*.sh"'],'/',output,errors,exitcode,[],swoNone,1) then // find / -name "*.sh" | |
| 207 | + | {$endif} | |
| 208 | + | begin | |
| 209 | + | writeln('program finished'); | |
| 210 | + | writeln('--------------------output-------------------'); | |
| 211 | + | writeln(output); | |
| 212 | + | writeln('--------------------errors-------------------'); | |
| 213 | + | writeln(errors); | |
| 214 | + | if not(exitcode=0) then | |
| 215 | + | begin | |
| 216 | + | writeln('-program finished with errors (exitcode: '+exitcode.tostring+')-'); | |
| 217 | + | end; | |
| 218 | + | readln(); | |
| 219 | + | end | |
| 220 | + | else | |
| 221 | + | begin | |
| 222 | + | writeln('program not finished'); | |
| 223 | + | writeln('--------------------output-------------------'); | |
| 224 | + | writeln(output); | |
| 225 | + | writeln('--------------------errors-------------------'); | |
| 226 | + | writeln(errors); | |
| 227 | + | writeln('-------------------EXITCODE------------------'); | |
| 228 | + | writeln(exitcode); | |
| 229 | + | readln(); | |
| 230 | + | end; | |
| 231 | + | end. | |
| 232 | + | ``` | |
| 233 | + | ||
| 234 | + | ## SysUtils.ExecuteProcess | |
| 235 | + | ||
| 236 | + | (跨平台) | |
| 237 | + | ||
| 238 | + | 尽管存在很多限制,但启动一个程序(模态、没有管道或任何控制)最简单的方式就是用: | |
| 239 | + | ``` | |
| 240 | + | SysUtils.ExecuteProcess(UTF8ToSys('/full/path/to/binary'), '', []); | |
| 241 | + | ``` | |
| 242 | + | ||
| 243 | + | 发起调用的进程将以同步方式运行:暂时“挂起”直至外部程序运行完毕 - 但如果要求用户在程序继续运行之前执行某些操作,同步方式可能很有用。更多的执行方式请参阅推荐的跨平台 **RunCommand** 或其他 **TProcess** 函数;如果只需要考虑 Windows 系统,则可以使用 **ShellExecute** 。 | |
| 244 | + | ||
| 245 | + | 调用进程同步运行:它'挂起(hangs)',直到内部出现完成 - 但是,在你的程序中继续前,如果你想要用户来做 一些事,这可能是有用的。对于更多用途的方法,看下一关于优先考虑跨平台的**TProcess** 部分, 或如果你仅希望瞄准Windows,你可以使用**ShellExecute** 。 | |
| 246 | + | ||
| 247 | + | * [ExecuteProcess 参考手册](<http://www.freepascal.org/docs-html/rtl/sysutils/executeprocess.html>) | |
| 248 | + | ||
| 249 | + | ## 微软 Windows 系统:CreateProcess、ShellExecute 和 WinExec | |
| 250 | + | ||
| 251 | + |  **Note:** 虽然 FPC/Lazarus 已支持 **CreateProcess** 、**ShellExecute** 和 **WinExec** ,但仅限 Win32/64环境。跨平台程序请考虑采用 **RunCommand** 或 **TProcess** 。 | |
| 252 | + | ||
| 253 | + |  **Note:** WinExec 是 16 位调用,在 Windows API 中已废弃多年。最新版的 FPC 中会对其生成警告。 | |
| 254 | + | ||
| 255 | + | **ShellExecute** 是标准的微软 Windows 函数(ShellApi.h),[documentation on MSDN](<http://msdn.microsoft.com/en-us/library/windows/desktop/bb762153\(v=vs.85\).aspx>) 中有完善的文档。(如果函数无法可靠运行,请注意查看关于初始化 COM 的评论). | |
| 256 | + | ``` | |
| 257 | + | uses ..., ShellApi; | |
| 258 | + | ||
| 259 | + | // 简单的单行代码调用(忽略返回错误): | |
| 260 | + | if ShellExecute(0,nil, PChar('"C:\my dir\prog.exe"'),PChar('"C:\somepath\some_doc.ext"'),nil,1) =0 then; | |
| 261 | + | ||
| 262 | + | // 执行批命令: | |
| 263 | + | if ShellExecute(0,nil, PChar('cmd'),PChar('/c mybatch.bat'),nil,1) =0 then; | |
| 264 | + | ||
| 265 | + | // 在给定目录打开命令行窗口: | |
| 266 | + | if ShellExecute(0,nil, PChar('cmd'),PChar('/k cd \path'),nil,1) =0 then; | |
| 267 | + | ||
| 268 | + | // 用“start”命令在默认浏览器中打开 URL(通过短暂显示并隐藏的 cmd 窗口): | |
| 269 | + | if ShellExecute(0,nil, PChar('cmd'),PChar('/c start www.lazarus.freepascal.org/'),nil,0) =0 then; | |
| 270 | + | ||
| 271 | + | // 助手函数: | |
| 272 | + | procedure RunShellExecute(const prog,params:string); | |
| 273 | + | begin | |
| 274 | + | // ( Handle, nil/'open'/'edit'/'find'/'explore'/'print', // 'open' 不是必需的 | |
| 275 | + | // path+prog, params, working folder, | |
| 276 | + | // 0=hide / 1=SW_SHOWNORMAL / 3=max / 7=min) //要使用 SW_ constants 请 uses Windows 单元 | |
| 277 | + | if ShellExecute(0,'open',PChar(prog),PChar(params),PChar(extractfilepath(prog)),1) >32 then; //success | |
| 278 | + | // 返回 0..32 表示出错 | |
| 279 | + | end; | |
| 280 | + | ``` | |
| 281 | + | ||
| 282 | + | 还有个 WideChar 版本的 ShellExecuteExW,而 ShellExecuteExA 则是 AnsiChar 版。 | |
| 283 | + | ||
| 284 | + | fMask 选项还可以是 SEE_MASK_DOENVSUBST、SEE_MASK_FLAG_NO_UI、SEE_MASK_NOCLOSEPROCESS 等。 | |
| 285 | + | ||
| 286 | + | 若是在 Delphi 中,要对 Word 文档或 URL 之类的 **文档** 调用 ShellExecute ,请查阅 lclintf 中的 open*(OpenUrl 等)函数(参见本页下方的替代方案)。 | |
| 287 | + | ||
| 288 | + | ### 针对提权/管理员权限使用 ShellExecuteEx | |
| 289 | + | ||
| 290 | + | 若要用管理员/提权的权限执行外部程序,可使用各版本 ShellExecuteEx 函数的 **runas** 方法: | |
| 291 | + | ``` | |
| 292 | + | uses ShellApi, ...; | |
| 293 | + | ||
| 294 | + | function RunAsAdmin(const Handle: Hwnd; const Path, Params: string): Boolean; | |
| 295 | + | var | |
| 296 | + | sei: TShellExecuteInfoA; | |
| 297 | + | begin | |
| 298 | + | FillChar(sei, SizeOf(sei), 0); | |
| 299 | + | sei.cbSize := SizeOf(sei); | |
| 300 | + | sei.Wnd := Handle; | |
| 301 | + | sei.fMask := SEE_MASK_FLAG_DDEWAIT or SEE_MASK_FLAG_NO_UI; | |
| 302 | + | sei.lpVerb := 'runas'; | |
| 303 | + | sei.lpFile := PAnsiChar(Path); | |
| 304 | + | sei.lpParameters := PAnsiChar(Params); | |
| 305 | + | sei.nShow := SW_SHOWNORMAL; | |
| 306 | + | Result := ShellExecuteExA(@sei); | |
| 307 | + | end; | |
| 308 | + | ||
| 309 | + | procedure TFormMain.RunAddOrRemoveApplication; | |
| 310 | + | begin | |
| 311 | + | // 用提权后的 rundll 打开控制面板,访问“程序和功能”面板 | |
| 312 | + | RunAsAdmin(FormMain.Handle, 'rundll32.exe shell32.dll,Control_RunDLL appwiz.cpl', ''); | |
| 313 | + | end; | |
| 314 | + | ``` | |
| 315 | + | ||
| 316 | + | ## Unix 的 fpsystem、fpexecve 和 shell | |
| 317 | + | ||
| 318 | + | 这些函数是依赖于特定平台的。 | |
| 319 | + | ||
| 320 | + | * [fpsystem 参考手册](<http://www.freepascal.org/docs-html/rtl/unix/fpsystem.html>) | |
| 321 | + | * [fpexecve 参考手册](<http://www.freepascal.org/docs-html/rtl/baseunix/fpexecve.html>) | |
| 322 | + | ||
| 323 | + | Linux.Shell/Unix.Shell 相当于 fpsystem 的 1.0.x 版本,但其错误处理方式定义得不太严格,经过长时间废弃后最终被移除了。Shell 几乎在任何场合下都可替换为 fpsystem,后者的错误处理方式更像 POSIX。 | |
| 324 | + | ||
| 325 | + | ## TProcess | |
| 326 | + | ||
| 327 | + | TProcess 可用于启动外部程序。采用 TProcess 有一些好处: | |
| 328 | + | ||
| 329 | + | * 平台无关 | |
| 330 | + | * 支持读取 stdout 和写入 stdin。 | |
| 331 | + | * 程序可以等待命令完成,也可以在命令运行的同时继续运行。 | |
| 332 | + | ||
| 333 | + | 重要注意事项: | |
| 334 | + | ||
| 335 | + | * TProcess 不是终端/shell!不能直接执行脚本,不能用“|”、“>”、“<”、“&”之类的运算符重定向输出。通过调用 TProcess 的 pascal 代码,可以得到相同的效果,下面有一些示例。 | |
| 336 | + | * 在 Linux/Unix 中,很可能**必须** 指定可执行文件的完整路径。比如用 '/bin/cp' 替代 'cp'。如果程序位于标准的 PATH 内,那可以使用 LCL 的[FileUtil](<http://lazarus-ccr.sourceforge.net/docs/lcl/fileutil/index.html> "doc:lcl/fileutil/index.html") 单元中的 [FindDefaultExecutablePath](<http://lazarus-ccr.sourceforge.net/docs/lcl/fileutil/finddefaultexecutablepath.html> "doc:lcl/fileutil/finddefaultexecutablepath.html") 函数。 | |
| 337 | + | * 在 Windows 中,如果命令位于 PATH 中,则无需给定完整路径。 | |
| 338 | + | * [TProcess 参考手册](<http://lazarus-ccr.sourceforge.net/docs/fcl/process/tprocess.html> "doc:fcl/process/tprocess.html") | |
| 339 | + | ||
| 340 | + | ### 最简单的示例 | |
| 341 | + | ||
| 342 | + | 在 [[Executing External Programs|Runcommand]] 函数中已给出了很多例程。在开始复制和粘贴以下示例之前,请先予以查看。 | |
| 343 | + | ||
| 344 | + | ### 简单示例 | |
| 345 | + | ||
| 346 | + | 本例仅仅是展示运行外部程序的方法,**不能用于生产性代码,请参阅大数据量输出或更好的[[Executing External Programs|Runcommand]]**。 | |
| 347 | + | ``` | |
| 348 | + | // 本例程展示了如何启动外部程序 | |
| 349 | + | program launchprogram; | |
| 350 | + | ||
| 351 | + | // 包含必要的单元文件,里面有需要用到的函数和过程 | |
| 352 | + | uses | |
| 353 | + | Classes, SysUtils, Process; | |
| 354 | + | ||
| 355 | + | // 定义 "TProcess" 类型的变量 "AProcess" | |
| 356 | + | var | |
| 357 | + | AProcess: TProcess; | |
| 358 | + | ||
| 359 | + | // 开始运行 | |
| 360 | + | begin | |
| 361 | + | // 创建 TProcess 对象并赋给变量 AProcess | |
| 362 | + | AProcess := TProcess.Create(nil); | |
| 363 | + | ||
| 364 | + | // 将需要执行的外部程序告知 AProcess | |
| 365 | + | // 这里要调用 Free Pascal 编译器(i386版) | |
| 366 | + | AProcess.Executable:= 'ppc386'; | |
| 367 | + | ||
| 368 | + | // 给 ppc386 带上参数 -h,实际执行的是 'ppc386 -h' 命令: | |
| 369 | + | AProcess.Parameters.Add('-h'); | |
| 370 | + | ||
| 371 | + | // 定义运行选项 | |
| 372 | + | // 让主程序暂停运行,直至外部程序停止执行。 | |
| 373 | + | // vvvvvvvvvvvvvv | |
| 374 | + | AProcess.Options := AProcess.Options + [poWaitOnExit]; | |
| 375 | + | ||
| 376 | + | // 让 AProcess 运行外部程序 | |
| 377 | + | AProcess.Execute; | |
| 378 | + | ||
| 379 | + | // ppc386 停止执行后才会运行至此 | |
| 380 | + | AProcess.Free; | |
| 381 | + | end. | |
| 382 | + | ``` | |
| 383 | + | ||
| 384 | + | 这样就可以从自己的程序中运行外部程序了。 | |
| 385 | + | ||
| 386 | + | ### 改良后的示例(但仍不够正确) | |
| 387 | + | ||
| 388 | + | 上述例子运行良好,但外部程序的输出结果该如何读取呢? | |
| 389 | + | ||
| 390 | + | 那就稍微添加一些代码来实现吧: **为了便于学习,本例程已尽量做了简化。请不要在产品代码中使用本例,而应采用#大数据量输出的读取中的代码**。 | |
| 391 | + | ``` | |
| 392 | + | // 本示例待有缺陷, | |
| 393 | + | // 演示了如何启动外部程序,并读取其输出 | |
| 394 | + | program launchprogram; | |
| 395 | + | ||
| 396 | + | // 包含必要的单元文件,内有需要用到的函数和过程 | |
| 397 | + | uses | |
| 398 | + | Classes, SysUtils, Process; | |
| 399 | + | ||
| 400 | + | // 定义 "TProcess" 类型的变量 "AProcess" | |
| 401 | + | // 还增加了一个 TStringList,用于存放从外部程序输出中读取的数据。 | |
| 402 | + | var | |
| 403 | + | AProcess: TProcess; | |
| 404 | + | AStringList: TStringList; | |
| 405 | + | ||
| 406 | + | // 开始运行 | |
| 407 | + | begin | |
| 408 | + | // 创建 TProcess 对象并赋给变量 AProcess | |
| 409 | + | AProcess := TProcess.Create(nil); | |
| 410 | + | ||
| 411 | + | // 将需要执行的外部程序告知 AProcess | |
| 412 | + | AProcess.Executable := '/usr/bin/ppc386'; | |
| 413 | + | AProcess.Parameters.Add('-h'); | |
| 414 | + | ||
| 415 | + | // 定义执行时的选项 | |
| 416 | + | // 确保主程序暂停运行,直至外部程序停止执行。 | |
| 417 | + | // 还要读取输出 | |
| 418 | + | AProcess.Options := AProcess.Options + [poWaitOnExit, poUsePipes]; | |
| 419 | + | ||
| 420 | + | // AProcess 知道要执行的命令行了 | |
| 421 | + | AProcess.Execute; | |
| 422 | + | ||
| 423 | + | // AProcess 执行完毕后,继续运行 | |
| 424 | + | ||
| 425 | + | // 读取刚执行完毕的外部程序的输出,并存入 TStringList。 | |
| 426 | + | AStringList := TStringList.Create; | |
| 427 | + | AStringList.LoadFromStream(AProcess.Output); | |
| 428 | + | ||
| 429 | + | // 将输出结果存入文件,并清空 TStringList。 | |
| 430 | + | AStringList.SaveToFile('output.txt'); | |
| 431 | + | AStringList.Free; | |
| 432 | + | ||
| 433 | + | // 现在 AProcess 的输出处理完毕,可以释放了 | |
| 434 | + | AProcess.Free; | |
| 435 | + | end. | |
| 436 | + | ``` | |
| 437 | + | ||
| 438 | + | ### 大数据量输出的读取 | |
| 439 | + | ||
| 440 | + | 上一示例中,主程序在外部程序退出之前一直处于等待状态,然后再读取其写到输出中去的数据。 | |
| 441 | + | ||
| 442 | + | 假定外部程序会往输出写入很多数据。这就会填满输出管道,然后被调用的程序就会进入等待状态,直至管道中的数据被读走。 | |
| 443 | + | ||
| 444 | + | 但在被调用程序结束之前,调用方程序不会去读取其输出。于是死锁发生了。 | |
| 445 | + | ||
| 446 | + | 因此以下示例不采用 poWaitOnExit 方式,而是在执行外部程序的同时读取其输出。输出数据存于内存流中,以供后续读取并输出至 TStringList 中。 | |
| 447 | + | ||
| 448 | + | 若要读取外部进程的输出数据,又无法使用 RunCommand,那就应该以下面的示例为基础编写生产代码。 | |
| 449 | + | ``` | |
| 450 | + | program LargeOutputDemo; | |
| 451 | + | ||
| 452 | + | {$mode objfpc}{$H+} | |
| 453 | + | ||
| 454 | + | uses | |
| 455 | + | Classes, SysUtils, Process; // TProcess 位于 Process 单元内 | |
| 456 | + | ||
| 457 | + | const | |
| 458 | + | BUF_SIZE = 2048; // 分块读取输出数据的缓冲区大小 | |
| 459 | + | ||
| 460 | + | var | |
| 461 | + | AProcess : TProcess; | |
| 462 | + | OutputStream : TStream; | |
| 463 | + | BytesRead : longint; | |
| 464 | + | Buffer : array[1..BUF_SIZE] of byte; | |
| 465 | + | ||
| 466 | + | begin | |
| 467 | + | // 设置 TProcess, | |
| 468 | + | // 这里采用递归搜索目录作为例子,因为这通常会生成大量数据 | |
| 469 | + | AProcess := TProcess.Create(nil); | |
| 470 | + | ||
| 471 | + | // Windows 和 *nix 的命令往往不同,因此用了 $IFDEFs | |
| 472 | + | {$IFDEF Windows} | |
| 473 | + | // Windows 中的 dir 是个内置命令,所以不能直接使用 | |
| 474 | + | // 因此需要采用 cmd.exe 加参数的方式。 | |
| 475 | + | AProcess.Executable := 'c:\windows\system32\cmd.exe'; | |
| 476 | + | AProcess.Parameters.Add('/c'); | |
| 477 | + | AProcess.Parameters.Add('dir /s c:\windows'); | |
| 478 | + | {$ENDIF Windows} | |
| 479 | + | ||
| 480 | + | {$IFDEF Unix} | |
| 481 | + | AProcess.Executable := '/bin/ls'; | |
| 482 | + | ||
| 483 | + | {$IFDEF Darwin} | |
| 484 | + | AProcess.Parameters.Add('-recursive'); | |
| 485 | + | AProcess.Parameters.Add('-all'); | |
| 486 | + | {$ENDIF Darwin} | |
| 487 | + | ||
| 488 | + | {$IFDEF Linux} | |
| 489 | + | AProcess.Parameters.Add('--recursive'); | |
| 490 | + | AProcess.Parameters.Add('--all'); | |
| 491 | + | {$ENDIF Linux} | |
| 492 | + | ||
| 493 | + | {$IFDEF FreeBSD} | |
| 494 | + | AProcess.Parameters.Add('-R'); | |
| 495 | + | AProcess.Parameters.Add('-a'); | |
| 496 | + | {$ENDIF FreeBSD} | |
| 497 | + | ||
| 498 | + | AProcess.Parameters.Add('-l'); | |
| 499 | + | {$ENDIF Unix} | |
| 500 | + | ||
| 501 | + | // 用到了 poUsePipes 选项以便捕获输出结果。 | |
| 502 | + | // 不能使用 poWaitOnExit 选项,因为会阻塞当前程序,也就无法读取进程输出的结果 | |
| 503 | + | AProcess.Options := [poUsePipes]; | |
| 504 | + | ||
| 505 | + | // 启动进程(运行 dir 或 ls 命令) | |
| 506 | + | AProcess.Execute; | |
| 507 | + | ||
| 508 | + | // 创建流对象,用于存放进程生成的输出数据。 | |
| 509 | + | // 也可以采用文件流,直接将结果存入磁盘。 | |
| 510 | + | OutputStream := TMemoryStream.Create; | |
| 511 | + | ||
| 512 | + | // 循环读取 AProcess 输出的全部数据,直至无数据可读 | |
| 513 | + | repeat | |
| 514 | + | // 读取由进程新生成的数据,最多读取已申请缓冲区的上限。 | |
| 515 | + | // 注意每次 read(...) 都会阻塞式调用,只有最后一次除外(返回0)。 | |
| 516 | + | BytesRead := AProcess.Output.Read(Buffer, BUF_SIZE); | |
| 517 | + | ||
| 518 | + | // 将读到的字节加入流,以供后续使用 | |
| 519 | + | OutputStream.Write(Buffer, BytesRead) | |
| 520 | + | ||
| 521 | + | until BytesRead = 0; // 无数据可读时停止循环 | |
| 522 | + | ||
| 523 | + | // 进程结束,可被释放 | |
| 524 | + | AProcess.Free; | |
| 525 | + | ||
| 526 | + | // 全部读到的数据已可用,比如可存入磁盘 | |
| 527 | + | with TFileStream.Create('output.txt', fmCreate) do | |
| 528 | + | begin | |
| 529 | + | OutputStream.Position := 0; // 需确保从头开始复制所有数据 | |
| 530 | + | CopyFrom(OutputStream, OutputStream.Size); | |
| 531 | + | Free | |
| 532 | + | end; | |
| 533 | + | ||
| 534 | + | // 或者可显示到屏幕上 | |
| 535 | + | with TStringList.Create do | |
| 536 | + | begin | |
| 537 | + | OutputStream.Position := 0; // 需确保从头开始复制所有数据 | |
| 538 | + | LoadFromStream(OutputStream); | |
| 539 | + | writeln(Text); | |
| 540 | + | writeln('--- Number of lines = ', Count, '----'); | |
| 541 | + | Free | |
| 542 | + | end; | |
| 543 | + | ||
| 544 | + | // Clean up | |
| 545 | + | OutputStream.Free; | |
| 546 | + | end. | |
| 547 | + | ``` | |
| 548 | + | ||
| 549 | + | 注意上述代码也可以利用 RunCommand 来实现: | |
| 550 | + | ``` | |
| 551 | + | var s: string; | |
| 552 | + | ... | |
| 553 | + | RunCommand('c:\windows\system32\cmd.exe', ['/c', 'dir /s c:\windows'], s); | |
| 554 | + | ``` | |
| 555 | + | ||
| 556 | + | ### TProcess 输入输出的用法 | |
| 557 | + | ||
| 558 | + | 请参阅 [Lazarus-CCR SVN](<https://lazarus-ccr.svn.sourceforge.net/svnroot/lazarus-ccr/examples/process>) 中的 processdemo 示例。 | |
| 559 | + | ||
| 560 | + | ### TProcess 用法提示 | |
| 561 | + | ||
| 562 | + | 在创建跨平台程序时,可用“{$IFDEF}”和“{$ENDIF}”指令根据各操作系统设置不同的可执行文件名称。 | |
| 563 | + | ||
| 564 | + | 示例: | |
| 565 | + | ``` | |
| 566 | + | {...} | |
| 567 | + | AProcess := TProcess.Create(nil) | |
| 568 | + | ||
| 569 | + | {$IFDEF WIN32} | |
| 570 | + | AProcess.Executable := 'calc.exe'; | |
| 571 | + | {$ENDIF} | |
| 572 | + | ||
| 573 | + | {$IFDEF LINUX} | |
| 574 | + | AProcess.Executable := FindDefaultExecutablePath('kcalc'); | |
| 575 | + | {$ENDIF} | |
| 576 | + | ||
| 577 | + | AProcess.Execute; | |
| 578 | + | {...} | |
| 579 | + | ``` | |
| 580 | + | ||
| 581 | + | ### 前台显示 macOS 应用程序包 | |
| 582 | + | ||
| 583 | + | TProcess 可启动**应用程序包** 中的可执行文件。例如: | |
| 584 | + | ``` | |
| 585 | + | AProcess.Executable:='/Applications/iCal.app/Contents/MacOS/iCal'; | |
| 586 | + | ``` | |
| 587 | + | ||
| 588 | + | 上述代码将会启动 _Calendar_ ,但其窗口位于当前应用程序之后。若要让应用程序显示于前台,可用带 **-n** 参数的 **open** : | |
| 589 | + | ``` | |
| 590 | + | AProcess.Executable:='/usr/bin/open'; | |
| 591 | + | AProcess.Parameters.Add('-n'); | |
| 592 | + | AProcess.Parameters.Add('-a'); // 可选参数:指定应用程序,仅搜索 Application 目录 | |
| 593 | + | AProcess.Parameters.Add('-W'); // 可选参数:open 保持等待,直至打开(或已打开状态)的外部程序退出 | |
| 594 | + | AProcess.Parameters.Add('Pages.app'); // 可选的包含 .app | |
| 595 | + | ``` | |
| 596 | + | ||
| 597 | + | 如果应用程序需要参数,可以给 **open** 传入 **\--args** 参数,后面加入的所有参数都会传给应用程序: | |
| 598 | + | ``` | |
| 599 | + | AProcess.Parameters.Add('--args'); | |
| 600 | + | AProcess.Parameters.Add('argument1'); | |
| 601 | + | AProcess.Parameters.Add('argument2'); | |
| 602 | + | ``` | |
| 603 | + | ||
| 604 | + | 参见:[[macOS Open Sesame|macOS open 命令]] | |
| 605 | + | ||
| 606 | + | ### 让程序独立运行 | |
| 607 | + | ||
| 608 | + | 通常,由其他应用程序启动的是一个子进程,主应用终止时子应用也将被终止。若要启动一个保持运行的独立应用,可以采用以下方式: | |
| 609 | + | ``` | |
| 610 | + | var | |
| 611 | + | Process: TProcess; | |
| 612 | + | I: Integer; | |
| 613 | + | begin | |
| 614 | + | Process := TProcess.Create(nil); | |
| 615 | + | try | |
| 616 | + | Process.InheritHandles := False; | |
| 617 | + | Process.Options := []; | |
| 618 | + | Process.ShowWindow := swoShow; | |
| 619 | + | ||
| 620 | + | // 复制包含 DISPLAY 在内的默认环境变量,以便 GUI 应用能够正常运行 | |
| 621 | + | for I := 1 to GetEnvironmentVariableCount do | |
| 622 | + | Process.Environment.Add(GetEnvironmentString(I)); | |
| 623 | + | ||
| 624 | + | Process.Executable := '/usr/bin/gedit'; | |
| 625 | + | Process.Execute; | |
| 626 | + | finally | |
| 627 | + | Process.Free; | |
| 628 | + | end; | |
| 629 | + | end; | |
| 630 | + | ``` | |
| 631 | + | ||
| 632 | + | ### 与 aspell 进程通讯的示例代码 | |
| 633 | + | ||
| 634 | + | [pasdoc](<https://github.com/pasdoc/pasdoc/wiki>) 的源代码中有两个单元,演示了通过管道与正在运行的 aspell 进程进行通讯,以执行拼写检查功能: | |
| 635 | + | ||
| 636 | + | * [PasDoc_ProcessLineTalk.pas 单元](<https://github.com/pasdoc/pasdoc/blob/master/source/component/PasDoc_ProcessLineTalk.pas>)实现了 TProcessLineTalk 类,衍生自 TProcess,便于以行为单位与任何进程进行对话。 | |
| 637 | + | * [PasDoc_Aspell.pas 单元](<https://github.com/pasdoc/pasdoc/blob/master/source/component/PasDoc_Aspell.pas>)实现了 TAspellProcess 类,执行拼写检查功能,通过底层的 TProcessLineTalk 实例执行 aspell,并与运行中的 aspell 进 程通讯完成拼写检查. | |
| 638 | + | ||
| 639 | + | 这两个单元都相对独立于其他 pasdoc 源代码,因此可作为用 TProcess 运行其它程序并通过管道与之通讯的真实案例。 | |
| 640 | + | ||
| 641 | + | ### 替换“| < >”之类的 shell 操作符 | |
| 642 | + | ||
| 643 | + | 有时需要运行更为复杂的命令,将数据通过管道传给另一个命令或文件。类似于: | |
| 644 | + | ``` | |
| 645 | + | ShellExecute('firstcommand.exe | secondcommand.exe'); | |
| 646 | + | ``` | |
| 647 | + | ||
| 648 | + | 或 | |
| 649 | + | ``` | |
| 650 | + | ShellExecute('dir > output.txt'); | |
| 651 | + | ``` | |
| 652 | + | ||
| 653 | + | 这是 TProcess 无法完成的,比如: | |
| 654 | + | ``` | |
| 655 | + | // 无法生效 | |
| 656 | + | Process.CommandLine := 'firstcommand.exe | secondcommand.exe'; | |
| 657 | + | Process.Execute; | |
| 658 | + | ``` | |
| 659 | + | ||
| 660 | + | #### 为什么用操作符重定向输出无效 | |
| 661 | + | ||
| 662 | + | TProcess 不是 shell 环境,而是进程。进程只有一个,不是两个。不过还是有办法实现重定向输出的。请参阅[[Executing External Programs|下一节]]。 | |
| 663 | + | ||
| 664 | + | ### 如何实现 TProcess 输出重定向 | |
| 665 | + | ||
| 666 | + | 可为**每一条** 命令使用一个 TProcess 实例,将输出重定向至另一命令。 | |
| 667 | + | ||
| 668 | + | 以下示例说明了如何将一个进程的输出重定向至另一个进程。要将进程的输出重定向到文件/流,请参阅示例 [[Executing External Programs|大数据量输出的读取]] | |
| 669 | + | ||
| 670 | + | 如果指定了 poStderrToOutPut 选项,则不仅可以重定向“常规” 输出(也称 stdout),还可以重定向错误输出 (stderr),参见第二个进程的选项。 | |
| 671 | + | ``` | |
| 672 | + | program Project1; | |
| 673 | + | ||
| 674 | + | uses | |
| 675 | + | Classes, sysutils, process; | |
| 676 | + | ||
| 677 | + | var | |
| 678 | + | FirstProcess, | |
| 679 | + | SecondProcess: TProcess; | |
| 680 | + | Buffer: array[0..127] of char; | |
| 681 | + | ReadCount: Integer; | |
| 682 | + | ReadSize: Integer; | |
| 683 | + | begin | |
| 684 | + | FirstProcess := TProcess.Create(nil); | |
| 685 | + | SecondProcess := TProcess.Create(nil); | |
| 686 | + | ||
| 687 | + | FirstProcess.Options := [poUsePipes]; | |
| 688 | + | FirstProcess.Executable := 'pwd'; | |
| 689 | + | ||
| 690 | + | SecondProcess.Options := [poUsePipes,poStderrToOutPut]; | |
| 691 | + | SecondProcess.Executable := 'grep'; | |
| 692 | + | SecondProcess.Parameters.Add(DirectorySeparator+ ' -'); | |
| 693 | + | // 等效于 "pwd | grep / -" | |
| 694 | + | ||
| 695 | + | FirstProcess.Execute; | |
| 696 | + | SecondProcess.Execute; | |
| 697 | + | ||
| 698 | + | while FirstProcess.Running or (FirstProcess.Output.NumBytesAvailable > 0) do | |
| 699 | + | begin | |
| 700 | + | if FirstProcess.Output.NumBytesAvailable > 0 then | |
| 701 | + | begin | |
| 702 | + | // 确保读取的数据不会超过申请的缓冲区大小 | |
| 703 | + | ReadSize := FirstProcess.Output.NumBytesAvailable; | |
| 704 | + | if ReadSize > SizeOf(Buffer) then | |
| 705 | + | ReadSize := SizeOf(Buffer); | |
| 706 | + | // 将输出读入缓冲区 | |
| 707 | + | ReadCount := FirstProcess.Output.Read(Buffer[0], ReadSize); | |
| 708 | + | // 将缓冲区内容写入第二个进程 | |
| 709 | + | SecondProcess.Input.Write(Buffer[0], ReadCount); | |
| 710 | + | ||
| 711 | + | // 如果 SecondProcess 输出数据太多, | |
| 712 | + | // 应当在此读出数据,以防死锁 | |
| 713 | + | // 参见上面的例子 "大数据量输出的读取" | |
| 714 | + | end; | |
| 715 | + | end; | |
| 716 | + | // 关闭 SecondProcess 的输出 | |
| 717 | + | // 数据处理结束 | |
| 718 | + | SecondProcess.CloseInput; | |
| 719 | + | ||
| 720 | + | // 等待完成 | |
| 721 | + | // 小心所执行的命令可能在输入关闭时不会退出 | |
| 722 | + | // 以下代码可能陷入死循环 | |
| 723 | + | while SecondProcess.Running do | |
| 724 | + | Sleep(1); | |
| 725 | + | // 好了! | |
| 726 | + | // 余下的代码只是为了让本例稍显有用 | |
| 727 | + | ||
| 728 | + | // 复用一下缓冲区 Buffer, | |
| 729 | + | // 将 SecondProcess 的输出内容输出到本程序的 stdout 去 | |
| 730 | + | ||
| 731 | + | WriteLn('Grep output Start:'); | |
| 732 | + | ReadSize := SecondProcess.Output.NumBytesAvailable; | |
| 733 | + | if ReadSize > SizeOf(Buffer) then | |
| 734 | + | ReadSize := SizeOf(Buffer); | |
| 735 | + | if ReadSize > 0 then | |
| 736 | + | begin | |
| 737 | + | ReadCount := SecondProcess.Output.Read(Buffer, ReadSize); | |
| 738 | + | WriteLn(Copy(Buffer,0, ReadCount)); | |
| 739 | + | end | |
| 740 | + | else | |
| 741 | + | WriteLn('grep did not find what we searched for. ', SecondProcess.ExitStatus); | |
| 742 | + | WriteLn('Grep output Finish:'); | |
| 743 | + | ||
| 744 | + | // 释放进程对象 | |
| 745 | + | FirstProcess.Free; | |
| 746 | + | SecondProcess.Free; | |
| 747 | + | end. | |
| 748 | + | ``` | |
| 749 | + | ||
| 750 | + | 就此结束。现在可以将输出重定向到另一个程序了。 | |
| 751 | + | ||
| 752 | + | #### 注意 | |
| 753 | + | ||
| 754 | + | 上述例子貌似有些夸张了,因为可以通过 TProcess 再用 shell 运行“复杂”命令,比如: | |
| 755 | + | ``` | |
| 756 | + | Process.Commandline := 'sh -c "pwd | grep / -"'; | |
| 757 | + | ``` | |
| 758 | + | ||
| 759 | + | 但上述例子更具跨平台性,无需修改即可在 Windows、Linux 等平台运行。“sh”可能不一定存在,一般仅在 *nix 平台可用。另外,上述例子的灵活性更高,因为可以单独读写每个进程的输、输出和 stderr,可能对项目开发非常有用。 | |
| 760 | + | ||
| 761 | + | ### 重定向输入和输出,并在 root 权限下运行 | |
| 762 | + | ||
| 763 | + | 在 Unix(FreeBSD、macOS)和 Linux 平台中,有一个常见问题就是需在 root(或更通用些是另一个用户)账户下执行某些程序。比如执行 _ping_ 命令。 | |
| 764 | + | ||
| 765 | + | 如果有 sudo 可用,则把以下例子改改即可实现,此例改自 andyman 在论坛上发布的一个帖子([[1]](<http://lazarus.freepascal.org/index.php/topic,14479.0.html>))。此例会在 `/root` 目录中运行 `ls` 命令,当然可以自行修改代码。 | |
| 766 | + | ||
| 767 | + | 更好的方案是使用 PolicyKit 包,所有新版 Linux 上都会提供。详情请参阅[论坛帖子](<http://lazarus.freepascal.org/index.php/topic,14479.0.html>)。 | |
| 768 | + | ||
| 769 | + | 以下代码的大部分与上述例子类似,不过还演示了如何将单独调用的进程的 stdout 和 stderr 重定向至当前代码的 stdout 和 stderr。 | |
| 770 | + | ``` | |
| 771 | + | program rootls; | |
| 772 | + | ||
| 773 | + | { 演示使用 TProcess 时将 stdout/stderr 重定向至当前 stdout/stderr, | |
| 774 | + | 在 FreeBSD/Linux/macOS 中调用 sudo, 并在 stdin 提供输入} | |
| 775 | + | {$mode objfpc}{$H+} | |
| 776 | + | ||
| 777 | + | uses | |
| 778 | + | Classes, | |
| 779 | + | Math, {提供 min 函数} | |
| 780 | + | Process; | |
| 781 | + | ||
| 782 | + | procedure RunsLsRoot; | |
| 783 | + | var | |
| 784 | + | Proc: TProcess; | |
| 785 | + | CharBuffer: array [0..511] of char; | |
| 786 | + | ReadCount: integer; | |
| 787 | + | ExitCode: integer; | |
| 788 | + | SudoPassword: string; | |
| 789 | + | begin | |
| 790 | + | WriteLn('Please enter the sudo password:'); | |
| 791 | + | Readln(SudoPassword); | |
| 792 | + | ExitCode := -1; //初始值为失败,观察后续是否生效 | |
| 793 | + | Proc := TProcess.Create(nil); //新建进程 | |
| 794 | + | try | |
| 795 | + | Proc.Options := [poUsePipes, poStderrToOutPut]; //用管道重定向程序的 stdin、stdout、stderr | |
| 796 | + | Proc.CommandLine := 'sudo -S ls /root'; //用 sudo 以 root 权限运行 ls /root | |
| 797 | + | // -S 使得 sudo 从 stdin 读取 root 账户的口令 | |
| 798 | + | Proc.Execute; //启动进程。sudo 会要求输入口令 | |
| 799 | + | ||
| 800 | + | // 向 sudo 程序的 stdin 写入口令 | |
| 801 | + | SudoPassword := SudoPassword + LineEnding; | |
| 802 | + | Proc.Input.Write(SudoPassword[1], Length(SudoPassword)); | |
| 803 | + | SudoPassword := '%*'; //用短字符串填充,希望会稍稍搅乱一些内存数据,更安全的做法是用 PChars | |
| 804 | + | SudoPassword := ''; // 能让程序更难破解?!? | |
| 805 | + | ||
| 806 | + | // 主循环从 sudo 的 stdout 和 stderr 读取输出数据 | |
| 807 | + | while Proc.Running or (Proc.Output.NumBytesAvailable > 0) or | |
| 808 | + | (Proc.Stderr.NumBytesAvailable > 0) do | |
| 809 | + | begin | |
| 810 | + | // 读取 stdout 并写入当前 stdout | |
| 811 | + | while Proc.Output.NumBytesAvailable > 0 do | |
| 812 | + | begin | |
| 813 | + | ReadCount := Min(512, Proc.Output.NumBytesAvailable); //读入缓冲区,不超过最大值 | |
| 814 | + | Proc.Output.Read(CharBuffer, ReadCount); | |
| 815 | + | Write(StdOut, Copy(CharBuffer, 0, ReadCount)); | |
| 816 | + | end; | |
| 817 | + | // read stderr and write to our stderr | |
| 818 | + | while Proc.Stderr.NumBytesAvailable > 0 do | |
| 819 | + | begin | |
| 820 | + | ReadCount := Min(512, Proc.Stderr.NumBytesAvailable); //读入缓冲区,不超过最大值 | |
| 821 | + | Proc.Stderr.Read(CharBuffer, ReadCount); | |
| 822 | + | Write(StdErr, Copy(CharBuffer, 0, ReadCount)); | |
| 823 | + | end; | |
| 824 | + | end; | |
| 825 | + | ExitCode := Proc.ExitStatus; | |
| 826 | + | finally | |
| 827 | + | Proc.Free; | |
| 828 | + | Halt(ExitCode); | |
| 829 | + | end; | |
| 830 | + | end; | |
| 831 | + | ||
| 832 | + | begin | |
| 833 | + | RunsLsRoot; | |
| 834 | + | end. | |
| 835 | + | ``` | |
| 836 | + | ||
| 837 | + | 其他想法:无疑最好是验证一下 sudo 是否真的提示输入口令。可将环境变量 SUDO_PROMPT 设为自定义值,并在读取 TProcess 的 stdout 时检查是否一致,这样即可避免不同语言环境下的提示符不同问题。设置环境变量会清除其默认值(从当前进程继承),因此用到的时候得去程序当前环境复制。 | |
| 838 | + | ||
| 839 | + | ### 在 Linux 中用 sudo 运行 fdisk | |
| 840 | + | ||
| 841 | + | 以下例子展示了如何用 sudo 命令获取 root 权限,在 Linux 计算机上运行 fdisk。**注意:仅供演示,不适合大数据量输出。** | |
| 842 | + | ``` | |
| 843 | + | program getpartitioninfo; | |
| 844 | + | { {最初由 Lazarus 论坛 wjackon153 贡献,有问题、评论请联系他。 | |
| 845 | + | 由 BigChimp 将 Lazarus 代码修改为 FPC 程序, 便于理解和简化} | |
| 846 | + | ||
| 847 | + | Uses | |
| 848 | + | Classes, SysUtils, FileUtil, Process; | |
| 849 | + | ||
| 850 | + | var | |
| 851 | + | hprocess: TProcess; | |
| 852 | + | sPass: String; | |
| 853 | + | OutputLines: TStringList; | |
| 854 | + | ||
| 855 | + | begin | |
| 856 | + | sPass := 'yoursudopasswordhere'; // 需要改为自己的 sudo 口令 | |
| 857 | + | OutputLines:=TStringList.Create; // 最好用 try...finally 块 | |
| 858 | + | // 确保 OutputLines 能被释放,hProcess 同理 | |
| 859 | + | ||
| 860 | + | // 以下代码将在后台打开 fdisk 并获取分区信息 | |
| 861 | + | // 因为 fdisk 需要提权 | |
| 862 | + | // 需要用 -S 选项将口令作为参数传给 sudo | |
| 863 | + | // 因此程序将进入等待状态,直至密码发送至 sudo 程序 | |
| 864 | + | hProcess := TProcess.Create(nil); | |
| 865 | + | // 在 Linux/Unix/FreeBSD/macOS 中,需要指定可执行程序的完整路径 | |
| 866 | + | hProcess.Executable := '/bin/sh'; | |
| 867 | + | // 现在加入所有命令行参数 | |
| 868 | + | hprocess.Parameters.Add('-c'); | |
| 869 | + | // 现在将口令通过管道传给 sudo 命令,让它执行 fdisk -l | |
| 870 | + | hprocess.Parameters.add('echo ' + sPass + ' | sudo -S fdisk -l'); | |
| 871 | + | // 同步方式执行(等待进程退出)并使用管道,以便由管道读取输出数据 | |
| 872 | + | hProcess.Options := hProcess.Options + [poWaitOnExit, poUsePipes]; | |
| 873 | + | // 执行进程 | |
| 874 | + | hProcess.Execute; | |
| 875 | + | ||
| 876 | + | // 现在 hProcess 应该将外部程序执行完毕(因为用了 poWaitOnExit) | |
| 877 | + | // 可以处理进程的输出数据了(stdout 和 strerr 等) | |
| 878 | + | OutputLines.Add('stdout:'); | |
| 879 | + | OutputLines.LoadFromStream(hprocess.Output); | |
| 880 | + | OutputLines.Add('stderr:'); | |
| 881 | + | OutputLines.LoadFromStream(hProcess.Stderr); | |
| 882 | + | // 在屏幕上显示输出数据 | |
| 883 | + | writeln(OutputLines.Text); | |
| 884 | + | ||
| 885 | + | // 释放资源,避免内存泄漏 | |
| 886 | + | hProcess.Free; | |
| 887 | + | OutputLines.Free; | |
| 888 | + | ||
| 889 | + | // 以下给出了一些示例,可传递非法字符,就像在终端中一样 | |
| 890 | + | // 即使其他地方说是无法实现,我也保证以下方法有效 :) | |
| 891 | + | ||
| 892 | + | //hprocess.Parameters.Add('ping -c 1 www.google.com'); | |
| 893 | + | //hprocess.Parameters.Add('ifconfig wlan0 | grep ' + QuotedStr('inet addr:') + ' | cut -d: -f2'); | |
| 894 | + | ||
| 895 | + | // QuotedStr() 不是必需的,但可以让代码更清晰 | |
| 896 | + | // 用双引号效果也一样 | |
| 897 | + | //hprocess.Parameters.Add('glxinfo | grep direct'); | |
| 898 | + | ||
| 899 | + | // 以下方法还可以用于从软件包仓库中安装应用 | |
| 900 | + | ||
| 901 | + | //hprocess.Parameters.add('echo ' + sPass + ' | sudo -S apt-get install -y pkg-name'); | |
| 902 | + | ||
| 903 | + | end. | |
| 904 | + | ``` | |
| 905 | + | ||
| 906 | + | ### 包含空格的参数(替换 Shell 命令中的引号) | |
| 907 | + | ||
| 908 | + | Linux shell 可以接受引号包裹的参数,例如: | |
| 909 | + | ``` | |
| 910 | + | gdb --batch --eval-command="info symbol 0x0000DDDD" myprogram | |
| 911 | + | ``` | |
| 912 | + | ||
| 913 | + | 这里 GDB 可以接受 3 个参数(除第一个参数外),第一个参数是可执行文件的完整路径: | |
| 914 | + | ||
| 915 | + | 1. \--batch | |
| 916 | + | 2. \--eval-command=info symbol 0x0000DDDD | |
| 917 | + | 3. myprogram 的完整路径 | |
| 918 | + | ||
| 919 | + | 若要避免复杂的引号处理,最佳方案是在复杂场景下改用 TProcess.Parameters.Add,而不是直接给 CommandLine 赋值,例如:: | |
| 920 | + | ``` | |
| 921 | + | AProcess.Executable:='/usr/bin/gdb'; | |
| 922 | + | AProcess.Parameters.Add('--batch'); | |
| 923 | + | AProcess.Parameters.Add('--eval-command=info symbol 0x0000DDDD'); // 注意这里没有用到引号 | |
| 924 | + | AProcess.Parameters.Add('/home/me/myprogram'); | |
| 925 | + | ``` | |
| 926 | + | ||
| 927 | + | 还请记得只传递完整路径。 | |
| 928 | + | ||
| 929 | + | 不过 TProcess.Commandline 确实支持对带有引号的参数进行一些简单的转义。用双引号包裹含有空格的 _整个_ 参数。比如: | |
| 930 | + | ``` | |
| 931 | + | AProcess.CommandLine := '/usr/bin/gdb --batch "--eval-command=info symbol 0x0000DDDD" /home/me/myprogram'; | |
| 932 | + | ``` | |
| 933 | + | ||
| 934 | + | .CommandLine 属性已[废弃](<http://bugs.freepascal.org/view.php?id=14446>),涉及更复杂的引号处理的缺陷报告,将不予接受或处理。 | |
| 935 | + | ||
| 936 | + | ## LCLIntf 替代方案 | |
| 937 | + | ||
| 938 | + | 有时不用显式调用外部程序,即可获取所需功能。不用既打开应用程序又把文档告诉它,只需让操作系统直接打开文档即可,操作系统会去选择与文档类型关联的默认应用。以下是一些示例。 | |
| 939 | + | ||
| 940 | + | ### 用默认应用程序打开文档 | |
| 941 | + | ||
| 942 | + | 某些时候需要用默认关联应用程序打开文档,而不是非要执行某个程序。不同的操作系统有不同的做法。Lazarus 提供了一个平台无关的过程 OpenDocument,可以完成这个操作。调用程序会继续运行,无需等待文档处理进程的关闭。 | |
| 943 | + | ``` | |
| 944 | + | uses LCLIntf; | |
| 945 | + | ... | |
| 946 | + | OpenDocument('manual.pdf'); | |
| 947 | + | ... | |
| 948 | + | ``` | |
| 949 | + | ||
| 950 | + | * [[opendocument|OpenDocument 参考手册]] | |
| 951 | + | ||
| 952 | + | ### 用默认浏览器打开网页 | |
| 953 | + | ||
| 954 | + | 只需传入所需的 URL,在有些环境下好像可以省略前面的 <http://。此外,传入文件名可能效果等同于> OpenDocument()。 | |
| 955 | + | ``` | |
| 956 | + | uses LCLIntf; | |
| 957 | + | ... | |
| 958 | + | OpenURL('www.lazarus.freepascal.org/'); | |
| 959 | + | ``` | |
| 960 | + | ||
| 961 | + | 请参阅: | |
| 962 | + | ||
| 963 | + | * [[OpenURL|OpenURL 参考手册]] | |
| 964 | + | ||
| 965 | + | 或者可以以以下方式使用 **TProcess** : | |
| 966 | + | ``` | |
| 967 | + | uses Process; | |
| 968 | + | ||
| 969 | + | procedure OpenWebPage(URL: string); | |
| 970 | + | // 看来传入的 URL 需用双引号包裹,比如 "www.lazarus.freepascal.org" | |
| 971 | + | var | |
| 972 | + | Browser, Params: string; | |
| 973 | + | begin | |
| 974 | + | FindDefaultBrowser(Browser, Params); | |
| 975 | + | with TProcess.Create(nil) do | |
| 976 | + | try | |
| 977 | + | Executable := Browser; | |
| 978 | + | Params:=Format(Params, [URL]); | |
| 979 | + | Params:=copy(Params,2,length(Params)-2); // 移除双引号,新版 TProcess.Parameters 会自动处理 | |
| 980 | + | Parameters.Add(Params); | |
| 981 | + | Options := [poNoConsole]; | |
| 982 | + | Execute; | |
| 983 | + | finally | |
| 984 | + | Free; | |
| 985 | + | end; | |
| 986 | + | end; | |
| 987 | + | ``` | |
| 988 | + | ||
| 989 | + | ## WinExec | |
| 990 | + | ||
| 991 | + | 在陈旧的 Delphi 代码中,有时还会存在 Windows 3.x 时代的 CreateProcess。请用上述一种方案替换。CreateProcess 在 Windows 单元中依然存在,已标记为废弃状态。 | |
| 992 | + | ||
| 993 | + | ## 参阅 | |
| 994 | + | ||
| 995 | + | * [TProcess 文档](<http://lazarus-ccr.sourceforge.net/docs/fcl/process/tprocess.html>) | |
| 996 | + | * [[opendocument|OpenDocument]] | |
| 997 | + | * [OpenUrl](</index.php?title=OpenUrl&action=edit&redlink=1> "OpenUrl \(page does not exist\)") | |
| 998 | + | * [[TProcessUTF8]] | |
| 999 | + | * [[TXMLPropStorage]] | |
| 1000 | + | * [[Webbrowser|网页浏览器]] | |
| 1001 | + | ||
| 1002 | + | ## 贡献者和更改 | |
| 1003 | + | ||
| 1004 | + | * 简体中文版本由 robsean 于 2019-03-07 创建。 | |
| 1005 | + | ||
| 1006 | + | --- | |
| 1007 | + | *From the Free Pascal wiki, page "Executing External Programs/zh CN", as the Internet Archive kept it on 2025-02-07. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).* |
