目前我正在编写第一个批处理文件,用于部署 asp.net 解决方案。 我一直在谷歌一点一般的错误处理方法,找不到任何真正有用的东西。
基本上,如果有什么地方出了问题,我希望停下来,把出错的地方打印出来。
有人能给我点建议吗?
除了 ERRORLEVEL,批处理文件没有错误处理。你会希望看到一个更强大的脚本语言。我一直在把代码移到 PowerShell。
易于使用的能力。Net 程序集和方法是我开始使用 PowerShell 的主要原因之一。改进的错误处理是另一个问题。事实上,微软现在要求其所有的服务器程序(Exchange、 SQLServer 等)都是 PowerShell 驱动的,这纯粹是锦上添花。
现在看来,任何投入在学习和使用 PowerShell 上的时间都是值得的。
我通常发现条件命令连接操作符比 ERRORLEVEL 更方便。
yourCommand && ( echo yourCommand was successful ) || ( echo yourCommand failed )
有一个复杂的情况你应该知道。如果成功分支中的最后一个命令引发错误,则错误分支将触发。
yourCommand && ( someCommandThatMayFail ) || ( echo This will fire if yourCommand or someCommandThatMayFail raises an error )
修复方法是插入一个无害的命令,该命令保证在成功分支结束时成功。我喜欢使用 (call ),它除了将错误级别设置为0之外什么也不做。推论 (call)除了将错误级别设置为1之外什么也不做。
(call )
(call)
yourCommand && ( someCommandThatMayFail (call ) ) || ( echo This can only fire if yourCommand raises an error )
有关使用 ERRORLEVEL 检测错误时所需的复杂性示例,请参见 在 Windows 批处理文件中检查非零(错误)返回代码的简单方法。
使用 ERRORLEVEL可以捕获对本地网络的成功 ping。
ERRORLEVEL
@ECHO OFF PING 10.0.0.123 IF ERRORLEVEL 1 GOTO NOT-THERE ECHO IP ADDRESS EXISTS PAUSE EXIT :NOT-THERE ECHO IP ADDRESS NOT NOT EXIST PAUSE EXIT
当 ERRORLEVEL 可用时,使用 ERRORLEVEL 是最简单的选择。但是,如果您调用一个外部程序来执行某项任务,而它没有返回正确的代码,那么您可以通过管道将输出发送到“ find”,并从中检查错误级别。
c:\mypath\myexe.exe | find "ERROR" >nul2>nul if not ERRORLEVEL 1 ( echo. Uh oh, something bad happened exit /b 1 )
或者提供更多关于发生了什么的信息
c:\mypath\myexe.exe 2&1> myexe.log find "Invalid File" "myexe.log" >nul2>nul && echo.Invalid File error in Myexe.exe && exit /b 1 find "Error 0x12345678" "myexe.log" >nul2>nul && echo.Myexe.exe was unable to contact server x && exit /b 1
我猜测这个特性是在 OP 之后添加的,但是对于将来在命令窗口中输出的引用错误,可以重定向到独立于标准输出的文件
Command 1 > file-将命令的标准输出写入 file
Command 2 > file-将命令的标准错误写入 file
非常简单! 创建包含以下内容的文件:
call <filename> // the file you made cls echo An error occured! <Your commands> pause
所以当你启动它的时候,它会像往常一样启动你的程序。但是当出现任何错误时,它将退出并在第一个文件中继续执行脚本。现在你可以把你自己的命令放进去了。
Python Unittest,Bat process 错误代码:
if __name__ == "__main__": test_suite = unittest.TestSuite() test_suite.addTest(RunTestCases("test_aggregationCount_001")) runner = unittest.TextTestRunner() result = runner.run(test_suite) # result = unittest.TextTestRunner().run(test_suite) if result.wasSuccessful(): print("############### Test Successful! ###############") sys.exit(1) else: print("############### Test Failed! ###############") sys.exit()
蝙蝠密码:
@echo off for /l %%a in (1,1,2) do ( testcase_test.py && ( echo Error found. Waiting here... pause ) || ( echo This time of test is ok. ) )