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