【CMD】运行程序,将log保存在以时间命名的log文件中

一、V1版本:通过bat脚本运行程序,并将log保存成时间命名的log文件中。
代码如下:

@echo off
set "current_path=%~dp0"
set "log_file_name=%date:~0,4%-%date:~5,2%-%date:~8,2%_%time:~0,2%-%time:~3,2%-%time:~6,2%.log" 
if not exist %current_path%\log (mkdir %current_path%\log) 
python -u test_39.py >> %current_path%\log\%log_file_name% 
if %ERRORLEVEL% neq 0 ( 
	echo The command failed with error code %ERRORLEVEL% 
) else ( 
	echo The command succeeded. 
)
pause 

二、V2版本:兼容不同系统编码集(utf-8,中文编码集:936)
系统默认编码集为utf-8,date显示格式如下:
在这里插入图片描述
代码如下:

@echo off
for /F "tokens=2 delims=:" %%a in ('chcp') do set "codepage=%%a"
if %codepage% == 65001 (
    set "log_file_name=%date:~3,4%-%date:~8,2%-%date:~11,2%_%time:~0,2%-%time:~3,2%-%time:~6,2%.log" 
) else (
    set "log_file_name=%date:~0,4%-%date:~5,2%-%date:~8,2%_%time:~0,2%-%time:~3,2%-%time:~6,2%.log" 
)
set "current_path=%~dp0"
if not exist %current_path%\log (mkdir %current_path%\log) 
python -u test_37.py >> %current_path%\log\%log_file_name% 
if %ERRORLEVEL% neq 0 ( 
	echo The command failed with error code %ERRORLEVEL% 
) else ( 
	echo The command succeeded. 
)
pause 

三、V3版本:修改系统时间小于10时,文件命名出错问题
系统变量time,小于10点时会填充空格,导致处理log文件名出错。
修改代码如下:

@echo off
set hour=%time:~0,2%
set hour=%hour: =0%
for /F "tokens=2 delims=:" %%a in ('chcp') do set "codepage=%%a"
if %codepage% == 65001 (
    set "log_file_name=%date:~3,4%-%date:~8,2%-%date:~11,2%_%hour%-%time:~3,2%-%time:~6,2%.log" 
) else (
    set "log_file_name=%date:~0,4%-%date:~5,2%-%date:~8,2%_%hour%-%time:~3,2%-%time:~6,2%.log" 
)
set "current_path=%~dp0"
if not exist %current_path%\log (mkdir %current_path%\log) 
python -u test_37.py >> %current_path%\log\%log_file_name% 
if %ERRORLEVEL% neq 0 ( 
	echo The command failed with error code %ERRORLEVEL% 
) else ( 
	echo The command succeeded. 
)
pause 
  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值