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