我有一个批处理文件,运行几个python脚本,做表修改。

我想让用户注释掉1-2个他们不想运行的python脚本,而不是从批处理文件中删除它们(这样下一个用户就知道这些脚本作为选项存在!) 我还想添加注释,以引起他们的注意,特别是他们在运行批处理文件之前需要更新的变量。我看到我可以使用REM,但它看起来更像是在用户运行后更新进度。

是否有更适当地添加注释的语法?


当前回答

你可以用下面的语法在批处理文件的末尾添加注释:

@echo off
:: Start of code
...
:: End of code

(I am a comment
So I am!
This can be only at the end of batch files

只是要确保不要使用右括号。

署名:Leo Guttirez Ramirez, https://www.robvanderwoude.com/comments.php

其他回答

这是一个古老的话题,我想在这里补充我的理解,扩展这个有趣的话题的知识。

REM和::之间的关键区别是:

REM本身是一个命令,而::不是。

我们可以把::作为一个令牌,只要CMD解析器在一行中遇到第一个非空白空格,它就会跳过整行,读取下一行。这就是为什么REM后面至少应该有一个空格,以便能够作为该行的注释,而::后面不需要任何空格。

REM本身是一个命令,从下面的FOR语法可以更好地理解

基本的FOR语法如下

FOR %v in (set) DO <Command> [command param] 

这里<命令>可以是任何有效的命令 因此,我们可以编写以下有效的命令行,因为rem是一个命令

FOR %i in (1,2,3) DO rem echo %i

然而,我们不能把下面的行写成::不是命令

FOR %i in (1,2,3) DO :: echo %i

将注释与命令:use &:: comment放在同一行

color C          & :: set red font color
echo IMPORTANT INFORMATION
color            & :: reset the color to default

解释:

&分隔了两个命令,因此在本例中,color C是第一个命令,::set红色字体颜色是第二个命令。


重要的是:

这个带有注释的语句直观上看起来是正确的:

goto error1         :: handling the error

但这不是注释的有效使用。它之所以有效,只是因为goto忽略了第一个参数之后的所有参数。证明很简单,这个goto也不会失败:

goto error1 handling the error

但是类似的尝试

color 17            :: grey on blue

原因:::,grey, on, blue 4个参数与color命令不匹配,导致命令执行失败。

它只会工作:

color 17     &      :: grey on blue

所以&是不可避免的。

你可以用下面的语法在批处理文件的末尾添加注释:

@echo off
:: Start of code
...
:: End of code

(I am a comment
So I am!
This can be only at the end of batch files

只是要确保不要使用右括号。

署名:Leo Guttirez Ramirez, https://www.robvanderwoude.com/comments.php

我更喜欢用:

REM评论 &REM内联注释

例子:

@echo off
set parameter1=%1%
REM test if the parameter 1 was received
if defined parameter1 echo The parameter 1 is %parameter1% &REM Display the parameter

多行注释

如果有大量的行你想注释掉,那么如果你能多行注释而不是每一行都注释掉会更好。

看看Rob van der Woude在评论区发布的这篇文章:

The batch language doesn't have comment blocks, though there are ways to accomplish the effect. GOTO EndComment1 This line is comment. And so is this line. And this one... :EndComment1 You can use GOTO Label and :Label for making block comments. Or, If the comment block appears at the end of the batch file, you can write EXIT at end of code and then any number of comments for your understanding. @ECHO OFF REM Do something • • REM End of code; use GOTO:EOF instead of EXIT for Windows NT and later EXIT Start of comment block at end of batch file This line is comment. And so is this line. And this one...