Sign in Join
Wiki copytemporary

Command line parameters and environment variables/zh CN: what changed

Revision 1 to 2. Removed lines have a minus sign; added lines have a plus sign.

OldNewLine
11在大多数(交互式)操作系统中,可以通过[[Command-line interface|命令行界面]](CLI)启动[[Program|程序]],并允许向程序提供附带的数据。[[System unit|system]]单元(以及[[Object Pascal|`objPas`]])单元提供了一些基本的[[Function|函数]],用于访问这些通过命令行给出的数据。
22
33## Contents
44
55 * 1 概述
66 * 1.1 术语
77 * 1.2 底层函数
88 * 2 命令行参数
99 * 2.1 基本用法
1010 * 2.2 用户友好性
1111 * 2.2.1 检测某个参数
1212 * 2.2.2 读取参数值
1313 * 2.2.3 校验参数
1414 * 3 环境变量
1515
1616## 概述
1717
1818尽管这里介绍的是“命令行”参数和环境变量,但使用传给程序的数据,以及这里提及的例程和术语,都不需要实际用到命令行界面(CLI)。只是命令行界面更为直观,因此以下内容主要考虑 shell 用户的体验。
1919
2020### 术语
2121
2222选项(Option)
2323 选项就是“是/否”。通常假定为如下形式
2424
2525`‑‑dryrun`/`‑‑no‑dryrun` (分别为启用和禁用 dryrun 选项)。 选项也被称为“开关”。
2626
2727参数(Parameter)
2828 参数是键值元组。在命令行中的形式如下:
2929
3030`‑‑processors 4`。
3131
3232实参(Argument)
3333 实参就是一些简单的单词。在命令行中通常以空格分隔(某些 shell 中可由 IFS 变量定义)。从狭义上讲, _实参_ 指既非选项也不属于参数的所有单词。而从广义上讲,实参是指命令行中未以任何方式解释的所有单词。
3434
3535环境变量(Environment variable)
3636 环境变量是指运行环境中打了标签的一块存储空间,都是“名称/值”对。
3737
3838请注意,命令行界面操作系统向程序传递的参数会先进行处理:比如转义后的换行符、文件重定向(管道或重定向文件)、对环境变量的赋值,都不会传给程序。
3939
4040### 底层函数
4141
4242“选项”和“参数”的概念抽象程度已经较高,且存在不同的风格(如短选项和长选项),而 system 单元的目标是提供较为 _底层_ 的工作方式,因此只把全部命令行参数视为从零开始的枚举类型,未做任何解释处理。
4343
4444函数 [`paramStr`](<https://www.freepascal.org/docs-html/rtl/system/paramstr.html>) 用于返回第 n 个命令行参数。 `ParamStr(0)` 尝试返回可执行程序文件名,以及完整路径。
4545
4646## 命令行参数
4747
4848### 基本用法
4949
5050Pascal 程序可以将 `paramStr` [[Function|函数]] 和 [`paramCount`](<https://www.freepascal.org/docs-html/rtl/system/paramcount.html>) 结合起来,以便访问命令行参数。
5151
5252`ParamCount` 将返回给出的参数个数。
5353```
5454program listArguments(input, output, stdErr);
5555 {$mode objFPC}
5656 var
5757 i: integer;
5858 begin
5959 writeLn({$ifDef Darwin}
6060 // Mac OS X 中的返回值依赖于调用方法
6161 'This program was invoked via: ',
6262 {$else}
6363 // 兼容 Turbo Pascal 的 paramStr(0) 返回程序所在位置
6464 'This program is/was stored at: ',
6565 {$endIf}
6666 paramStr(0));
6767
6868 for i := 1 to paramCount() do
6969 begin
7070 writeLn(i:2, '. argument: ', paramStr(i));
7171 end;
7272 end.
7373```
7474
7575在非 Mac OS X 系统中,上述程序的运行结果可能如下:
7676```
7777$ ./listArguments foo bar able
7878 This program is/was stored at: /tmp/listArguments
7979 1. argument: foo
8080 2. argument: bar
8181 3. argument: able
8282```
8383
8484RTL 的 system 单元提供了一个 `paramStr`,返回的是[[Shortstring|`shortString`]] 类型的字符串。`shortString` 类型的实现方式限制了其长度在255个字符以内。 但是用户可能会给出长度超限的命令行参数。 为了访问全部命令行参数,[`objPas` 单元](<https://www.freepascal.org/docs-html/rtl/objpas/index.html>) 重新定义了 `paramStr`,返回类型换成了 [[Ansistring|`ansiString`]],这样长度就不受限了。在 [[Mode ObjFPC|`{$mode objFPC}`]](第2行)和 [[Mode Delphi|`{$mode Delphi}`]] 编译模式下,会自动包含 `objPas` 单元。
8585
8686提供 `paramStr` 函数是为了与 Turbo Pascal 保持兼容。在 Turbo Pascal 中,`paramStr(0)` 返回程序的所在位置。但这需要操作系统的支持。尤其值得注意的是,在 Mac OS X 系统中,`paramStr(0)` 的返回值取决于调用方法,即应用程序的启动方式。
8787
8888![Light bulb](https://upload.wikimedia.org/wikipedia/commons/d/d8/Nuvola_apps_ktip.png) **Note:** 由于 `paramStr(0)` 依赖于操作系统的支持,所以并不适用于 [[Multiplatform Programming Guide|跨平台应用]]。
8989
9090![Light bulb](https://upload.wikimedia.org/wikipedia/commons/d/d8/Nuvola_apps_ktip.png) **Note:** 在类 Unix 系统中,只用字符串不可能确定文件的位置。可能有多个硬链接指向同一个i节点,文件可能已删除,文件路径可能已有部分改动,以及其他细节问题。
9191
9292因此,在类 Unix 系统中 `paramStr(0)` 无效。
9393
9494[`getOpts` 单元](<https://www.freepascal.org/docs-html/rtl/getopts/index.html>)提供了其他一些函数,在以特定格式调用程序时可用于解析命令行参数。
9595
9696### 用户友好性
9797
9898设计良好的程序在收到错误参数时应能给出帮助信息,并且应该遵循一种通用的参数传递方式。 FPC 的 [unit `custApp`](<https://www.freepascal.org/docs-html/fcl/custapp/index.html>) 单元提供了一个 [`TCustomApplication`](<https://www.freepascal.org/docs-html/fcl/custapp/tcustomapplication.html>) 类,可用于轻松检查和读取命令行参数。当然,用 `paramStr` 和 `paramCount` 直接访问也没问题。
9999
100100[[LCL]] 应用程序都会自动使用 TCustomApplication。Application 对象就是 TCustomApplication 的实例。
101101
102102若要编写非 LCL 程序,那么先在 [[Lazarus]] 中新建“控制台应用程序”类型的项目。这会创建一个包含某些实用功能的 project1.lpr,这些功能几乎所有程序都需要用到。接下来,请定位到 `doRun` 方法。
103103
104104#### 检测某个参数
105105
106106TCustomApplication 可以通过名称访问命令行参数。 比如用户给出通用的求助参数 _-h_ 时,程序应该打印出一条帮助文字。 _-h_ 是个短选项。 长选项则为 _\--help_ 。 若要测试用户在调用程序时是否带有 _-h_ 或 _\--help_ 参数,可以使用如下代码:
107107```
108108if hasOption('h', 'help') then
109109 begin
110110 writeHelp;
111111 halt;
112112 end;
113113```
114114
115115![Light bulb](https://upload.wikimedia.org/wikipedia/commons/d/d8/Nuvola_apps_ktip.png) **Note:** 在 LCL 窗体中,必须在 `hasOption` 前面加上 `application.`。
116116
117117例如:
118118```
119119if application.hasOption('h', 'help') then
120120 begin
121121 writeHelp;
122122 halt;
123123 end;
124124```
125125
126126如果只支持短选项,请用以下代码:
127127```
128128if hasOption('h', '') then
129129```
130130
131131若只支持长选项,则用:
132132```
133133if hasOption('help') then
134134```
135135
136136#### 读取参数值
137137
138138每个命令行参数可以给定一个值。 例如:
139139```
140140$ project1 -f filename
141141```
142142
143143或者长格式:
144144```
145145$ project1 --file=filename
146146```
147147
148148读取 `filename` :
149149```
150150writeLn('f=', getOptionValue('f', 'file'));
151151```
152152
153153注意:如果报错“`Option at position 1 needs an argument : f.`”,则是在调用
154154```
155155[checkOptions](<https://www.freepascal.org/docs-html/fcl/custapp/tcustomapplication.checkoptions.html>) 时忘记加入该选项了。
156156```
157157
158158#### 校验参数
159159
160160命令行参数就是一条内容随意的文本,因此用户输入很容易出错。 因此,必须对命令行参数作语法检查。用 [CheckOptions](<http://lazarus-ccr.sourceforge.net/docs/fcl/custapp/tcustomapplication.checkoptions.html> "doc:fcl/custapp/tcustomapplication.checkoptions.html") 方法即可完成检查。
161161
162162可定义允许哪些参数及哪些参数需要有值,在发生语法错误时可获取错误消息和出错的选项,以便打印出帮助信息和错误细节。
163163
164164示例:
165165```
166166errorMsg := checkOptions('hf:', 'help file:');
167167```
168168
169169上述代码允许传递短选项 `‑f value` 和 `‑h`, 还允许 `‑‑help` 或 `‑‑file=filename`。 但不允许 `‑‑help` 带有值,也不允许 `‑‑file` 没有值。
170170
171171参数示例:
172172```
173173procedure TMainForm.FormShow(Sender: TObject);
174174 var
175175 I: Integer;
176176 Params : TStringList
177177 LongOpts : array [1..2] of string = ('debug-sync', 'config-dir:');
178178 begin
179179 Params := TStringList.Create;
180180 try
181181 Application.GetNonOptions('hgo:', LongOpts, Params);
182182 for I := 0 to Params.Count -1 do
183183 debugln('Extra Param ' + inttostr(I) + ' is ' + Params[I]); }
184184 finally
185185 FreeAndNil(Params);
186186 end;
187187 end;
188188```
189189
190190以上例程会查找参数,且不会和命令行开关或选项混淆。 应用程序还接受 --debug-sync 和 --config-dir=somedir 开关,只是没有打印出来。
191191
192192请注意,Application.GetNonOptions() 方法以数组类型的长选项为参数,而 Application.CheckOptions 方法的参数数据相同却只认字符串。 有点遗憾!
193193
194194## 环境变量
195195
196196[[sysutils|`sysUtils`]] 单元定义了3个读取环境变量的基本函数。
197197
198198 * [`getEnvironmentVariableCount`](<https://www.freepascal.org/docs-html/rtl/sysutils/getenvironmentvariablecount.html>) 返回全部环境变量的数量。
199199 * [`getEnvironmentString`](<https://www.freepascal.org/docs-html/rtl/sysutils/getenvironmentstring.html>) 按索引编号返回某个环境变量。
200200 * [`getEnvironmentVariable`](<https://www.freepascal.org/docs-html/rtl/sysutils/getenvironmentvariable.html>) 按键值返回某个环境变量。
201201
202202示例:
203203```
204204program environmentVariablesList(input, output, stdErr);
205205 uses
206206 sysUtils;
207207 var
208208 i: integer;
209209 begin
210210 for i := 0 to getEnvironmentVariableCount() - 1 do
211211 begin
212212 writeLn(getEnvironmentString(i));
213213 end;
214214 end.
215215```
216216
217217另外还有一种可能的方式,就是将所有环境变量载入 [`tStringList`](<https://www.freepascal.org/docs-html/rtl/classes/tstringlist.html>)对象,以便访问键值对。 字符串列表会自动处理分隔符,默认为[[=|等号 (`'='`)]]。
218218```
219219program environmentVariablesSorted(input, output, stdErr);
220220 {$mode objFPC}
221221 uses
222222 classes, sysUtils;
223223 var
224224 i: integer;
225225 environmentVariables: tStringList;
226226 begin
227227 environmentVariables := tStringList.create();
228228
229229 try
230230 // load all variables to string list
231231 for i := 0 to getEnvironmentVariableCount() - 1 do
232232 begin
233233 environmentVariables.append(getEnvironmentString(i));
234234 end;
235235
236236 environmentVariables.sort;
237237 for i := 0 to environmentVariables.count - 1 do
238238 begin
239239 writeLn(environmentVariables.names[i]:20,
240240 ' = ',
241241 environmentVariables.valueFromIndex[i]);
242242 end;
243243 finally
244244 environmentVariables.free;
245245 end;
246246 end.
247247```
248248
249249还可以采用 `tCustomApplication` 的 [[Method|方法]],可一次性将全部环境变量读取为一个[[TStringList|`tStringList`]]。大致如下所示:
250250```
251251var
252252 environmentVariables: tStringList;
253253 begin
254254 environmentVariables := tStringList.create();
255255 try
256256 application.getEnvironmentList(environmentVariables);
257257 …
258258 finally
259259 environmentVariables.free;
260260 end;
261261 end;
262262```
263263 *[IFS]: internal field separator
264264
265265---
266-*From the Free Pascal wiki, page "Command line parameters and environment variables/zh CN", as the Internet Archive kept it on 2025-01-13. 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).*
266+*From the Free Pascal wiki, page "Command line parameters and environment variables/zh CN", as the Internet Archive kept it on 2025-01-13, last changed on 2024-12-09. 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).*

Back to history