我正在使用批处理文件,我定期编写时间用于性能监视。这很好但最近我在该批处理文件中调用了一个Python脚本,时间测量似乎不再起作用了:
我的批处理文件如下所示:
echo [%TIME%] -- task 1
<perform task 1>
echo [%TIME%] -- task 2
<perform task 2>
echo [%TIME%] -- finished
,给出以下结果:
[14:51:32.97] -- task 1
[14:51:34.32] -- task 2
[14:51:39.07] -- finished
现在我已经用Python脚本替换了(至少花了几分钟),但我的%TIME%变量似乎不再更新了:
echo [%TIME%] -- task 1
<perform task 1>
echo [%TIME%] -- task 2
python task2.py
echo [%TIME%] -- finished
给出以下结果:
[14:51:40.02] -- task 1
[14:51:44.32] -- task 2
[14:51:44.32] -- finished
有人知道可能导致此问题的原因以及解决方法吗? 为了您的信息,我正在使用虚拟Windows 7系统,我的Python安装版本为3.5.0。
答案 0 :(得分:0)
我认为这个问题不是'与python有关'。例如脚本
@echo off
echo [%TIME%] ---
echo [%TIME%] ping1
ping 8.8.8.8 >nul
echo [%TIME%] ping1 done
if not exist 123 (
echo [%TIME%] ping2
ping 8.8.8.8 >nul
echo [%TIME%] ping2 done
)
echo [%TIME%] ping3
ping 8.8.8.8 >nul
echo [%TIME%] ping3 done
echo [%TIME%] ---
将输出
[20:33:32,00] ---
[20:33:32,00] ping1
[20:33:35,04] ping1 done
[20:33:35,04] ping2
[20:33:35,04] ping2 done
[20:33:38,12] ping3
[20:33:41,16] ping3 done
[20:33:41,16] ---
如您所见,ping2
和ping2 done
具有相同的时间戳。当使用括号(
)
时,CMD shell将扩展[读取]代码块开头的所有变量,并使用这些值,即使在代码块中更改了变量值。
所以在这种情况下解决方案是
if not exist 123 (
call echo [%%TIME%%] ping2
ping 8.8.8.8 >nul
call echo [%%TIME%%] ping2 done
)
或
@echo off
Setlocal EnableDelayedExpansion
...
if not exist 123 (
echo [!TIME!] ping2
ping 8.8.8.8 >nul
echo [!TIME!] ping2 done
)
,输出
[20:45:28,45] ---
[20:45:28,45] ping1
[20:45:31,49] ping1 done
[20:45:31,49] ping2
[20:45:34,53] ping2 done
[20:45:34,54] ping3
[20:45:37,59] ping3 done
[20:45:37,59] ---