【问题标题】:Writing Curl Output to Batch File Variable将卷曲输出写入批处理文件变量
【发布时间】:2014-10-02 09:05:58
【问题描述】:

我正在尝试获取访问页面并使用此命令的总时间:

curl -o NUL -s -w "%%{time_total}" http://stackoverflow.com

我能够得到命令提示符中显示的总时间。

但是,现在我想把它放在这样的 for 循环中:

echo off
SET /a i=0

:loop
IF %i%==10 GOTO END
echo Iteration %i%.
SET /a i=%i%+1
GOTO LOOP
:end

总结我得到的所有时间,用类似的东西替换echo Iteration %i%.

set /a var = curl -o NUL -s -w "%%{time_total}" http://stackoverflow.com
set /a vartotal = var + vartotal

但这当然行不通,我知道它的部分原因是返回的时间是十进制的,而批处理无法处理小数。此外,URL 中可能包含非字母字符,例如 ?、= 和 &。请帮忙

【问题讨论】:

    标签: batch-file curl command-prompt


    【解决方案1】:

    执行此操作的最简单方法是将 curl 命令的结果输出重定向到文件并处理该文件。

    这有点棘手,因为数字包含一个逗号(在您的环境中可能是一个点),并且命令解释器只进行整数计算,并且在我的盒子上它解释了错误的数字。此外,如果它的数字以零开头,它假定它是一个八进制数,所以你也必须去掉它。将所有这些加在一起会给你这个命令批处理脚本:

    set site=http://stackoverflow.com
    set file=so.log
    rem set this to , or . depending on your locale
    set sep=,
    
    set tot=0
    del /Q %file%
    
    rem add 10 values to the so.log file
    for /L %%r in (1,1,10) do curl -o NUL -s -w "%%{time_total}\r\n" %site% >> %file%
    
    rem read each line from the file
    for /F %%a in (%file%) do  call :sum "%%a"
    
    goto :end
    
    rem sum procedure takes a number as first parameter
    :sum
    set milli=%1
    
    IF "%sep%"=="," set val=%milli:,=%
    IF "%sep%"=="." set val=%milli:.=%
    
    set val2=%val:"=%
    
    rem strip 0 if that is the first char
    rem otherwise the number is 
    rem considered to be octal
    set lz=%val2:~0,1%
    if @%lz%==@0 set val2=%val2:~1%
    
    set /a "tot=tot+%val2%"
    
    set milli=
    set val=
    set val2=
    
    goto :EOF
    
    :end
    echo total time: %tot%
    
    rem clean up
    set sep=
    set tot=
    set site=
    set file=
    

    【讨论】:

      猜你喜欢
      • 2018-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-29
      • 1970-01-01
      • 2016-01-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多