AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / computer / Perguntas / 1675694
Accepted
Io-oI
Io-oI
Asked: 2021-09-12 15:50:38 +0800 CST2021-09-12 15:50:38 +0800 CST 2021-09-12 15:50:38 +0800 CST

Como enviar variável para um processo em segundo plano, que é um loop :label do próprio bat (ou stop loop se a variável estiver definida)

  • 772

Eu tenho um bat com algum rótulo nele, então eu começo meu bat verificando se algum argumento foi passado, caso contrário, a execução fará uma nova chamada do próprio bat passando um argumento, e uma vez feito isso ele continua executando o próximo comandos.

Quando bat inicia por uma chamada recebendo um argumento, sua execução é colocada em loop dentro de um :label (permanentemente)

É um morcego que pode levar muito tempo para ser executado, então a chamada faz com que uma barra de progresso "infinita" apareça no título da janela e permaneça em um loop fazendo isso em segundo plano.

insira a descrição da imagem aqui

Porque é tedioso ver uma linha estática ( "Finding Nemo, Files, etc..." ) na tela ou na barra de título, e um exemplo recente de uma tarefa/script que leva muito tempo é encontrar uma nova executável (versão/data) verificando todos os drivers e comparando os resultados para obter um (mais recente), respondido aqui .

Tomando o código vinculado acima para um exemplo de tarefa demorada e adicionando uma barra de progresso no título, tenho o seguinte código:

@echo off

if "%~1."=="." (call start ".:." /b cmd.exe /v:on /c "%~f0" ? )else goto %:^|
setlocal enabledelayedexpansion && set "_f=" && set "_ff=" && set /a "_cnt=0"

for /f usebackq^tokens^=* %%f in (`%__AppDir__%mountvol.exe^|find.exe /i ":\"
    `)do 2>nul pushd %%~f && (set/a "_cnt+=1" && call %:^) _ff_!_cnt! & popd)

for /f useback^tokens^=1*delims^=^=^ %%i in (`^<nul ^<con: set _ff_ ^|%__AppDir__%sort.exe /r
    `)do <con: <nul call set "_ffprobe=%%~dpnxj" & call set "_ffprob_Path=%%~dpj" & goto %:^V

%:^)
for /f usebackq^tokens^=2^,4* %%i in =;(`2^>nul %__AppDir__%where.exe /r \ ffprobe.exe /t ^|^
    %__AppDir__%sort.exe /r^|^|exit/b`)do set "_f=%%~k" && for /f useback^delims^=. %%G in (`
        ^<con %__AppDir__%wbem\wmic.exe DataFile where name^="!_f:\=\\!" get LastModified ^|^
            %__AppDir__%findstr.exe /rb [0-9]`)do <con: <nul call set "%~1=%%~k" && exit /b 0

%:^|
>nul chcp 65001 & mode 89,5 & set "_title=Looking for your latest ffprob.exe, please wait^!!"

<con: ;color 0a && set^ "_176=░░░░░░░░░░" && set^ "_255=▓▓▓▓▓▓▓▓▓▓" && set^ "_022=▬▬▬▬▬▬▬▬▬▬"
call setlocal enabledelayedexpansion & set "_ping=%__AppDir__%pathping.exe 127.1 -q 1 -p 050"

%:^/
set "_title=I'm doing something that takes a while, please wait^!!"
for %%G in =;(1,2,3,4,5,6,0)do if "!_ffprob_Path!\." == "\." =;( if ".\%%~G\." == ".\1\." =;(
     for /l %%L in (0 01 10)do %_ping% |title !_title! [!_255:~0,%%~L!!_022:~%%L!] !time:~,8! 
    )else if "%%G\" == "2\" =;(if "!_ffprob_Path!\." == "\." =;(
     for /l %%L in (10 -1 0)do %_ping% |title !_title! [!_255:~0,%%~L!!_176:~%%L!] !time:~,8! 
   ))else if "%%G\" == "3\" =;(if "!_ffprob_Path!\." == "\." =;(
     for /l %%L in (0 01 10)do %_ping% |title !_title! [!_022:~0,%%~L!!_176:~%%L!] !time:~,8! 
   ))else if "%%G\" == "4\" =;(if "!_ffprob_Path!\." == "\." =;(
     for /l %%L in (10 -1 0)do %_ping% |title !_title! [!_022:~0,%%~L!!_255:~%%L!] !time:~,8! 
   ))else if "%%G\" == "5\" =;(if "!_ffprob_Path!\." == "\." =;(
     for /l %%L in (0 01 10)do %_ping% |title !_title! [!_176:~0,%%~L!!_255:~%%L!] !time:~,8! 
   ))else if "%%G\" == "6\" =;(if "!_ffprob_Path!\." == "\." =;(
     for /l %%L in (10 -1 1)do %_ping% |title !_title! [!_176:~0,%%~L!!_022:~%%L!] !time:~,8! 
   ))else if "%%G\" == "0\" =;(if "!_ffprob_Path!\." == "\." =;(
    goto %:^/
   )));= 

%:^V
rem./ your code continues at this point using: / & echo+!_ffprob_Path! & echo+!_ffprobe!

O resultado é que a barra de progresso "infinita" inicia e não para, mesmo após a variável ser definida, onde deveria sinalizar o fim do loop no rótulo da barra de progresso, mas não funciona...

insira a descrição da imagem aqui

Foram feitas várias tentativas com enable/disable setlocal, invertendo a ordem da chamada do label, e coisas que nem lembro, mas houve várias tentativas de finalizar o loop e sem sucesso...

Como terminar o loop de um rótulo rodando em segundo plano do mesmo morcego?

Estou neste ponto há tanto tempo que não vejo nada.

Qualquer ideia?


O mesmo código no layout convencional...

@echo off

if "%~1." == "." (
     call start ".:." /b cmd.exe /v:on /c "%~f0" ? 
    ) else (
     goto %:^p
    )
    
setlocal enabledelayedexpansion

set "_f="
set "_ff="
set /a "_cnt=0"

for /f "usebackq tokens=*" %%f in (`%__AppDir__%mountvol.exe ^| %__AppDir__%find.exe /i ":\"`) do 2>nul (
     pushd %%~f && (
         set /a "_cnt+=1"
         call %:^) _ff_!_cnt!
         popd
        )
    )
    
for /f "usebackq tokens=1* delims==" %%i in (`set _ff_ ^| %__AppDir__%sort.exe /r`) do (
     call set "_ffprobe=%%~dpnxj"
     call set "_ffprob_Path=%%~dpj"
     goto %:^V
    )
 
%:^)
for /f "usebackq tokens=2,4*" %%i in  (`2^>nul %__AppDir__%where.exe /r \ ffprobe.exe /t ^| %__AppDir__%sort.exe /r ^|^| exit /b`) do (
     set "_f=%%~k"
     for /f "usebackq delims=." %%G in (`^<con: call %__AppDir__%wbem\wmic.exe DataFile where name^="!_f:\=\\!" get LastModified ^| %__AppDir__%findstr.exe /rb [0-9]`)do (
         call set "%~1=%%~k"
         exit /b 0
        )
    )

%:^p
>nul chcp 65001
%__AppDir__%mode.com con: cols=89 lines=5

set "_title=Looking for your latest ffprob.exe, please wait^!!"

color 0a
set "_176=░░░░░░░░░░"
set "_255=▓▓▓▓▓▓▓▓▓▓"
set "_022=▬▬▬▬▬▬▬▬▬▬"

setlocal enabledelayedexpansion
set "_ping=%__AppDir__%pathping.exe 127.1 -q 1 -p 050"

%:^/
for %%G in =;(1,2,3,4,5,6,0)do (
     if "!_ffprob_Path!\." == "\." ( 
        if ".\%%~G\." == ".\1\." (
             for /l %%L in (0 01 10) do %_ping% |  title !_title! [!_255:~0,%%~L!!_022:~%%L!] !time:~,8! 
        )else if "%%G\" == "2\" (
             if "!_ffprob_Path!\." == "\." (
                 for /l %%L in (10 -1 0) do %_ping% | title !_title! [!_255:~0,%%~L!!_176:~%%L!] !time:~,8! 
                )
        )else if "%%G\" == "3\" (
             if "!_ffprob_Path!\." == "\." (
                 for /l %%L in (0 01 10) do %_ping% | title !_title! [!_022:~0,%%~L!!_176:~%%L!] !time:~,8! 
                )
        )else if "%%G\" == "4\" (
             if "!_ffprob_Path!\." == "\." (
                 for /l %%L in (10 -1 0) do %_ping% | title !_title! [!_022:~0,%%~L!!_255:~%%L!] !time:~,8!
                )
        )else if "%%G\" == "5\"  (
             if "!_ffprob_Path!\." == "\." (
                 for /l %%L in (0 01 10) do %_ping% | title !_title! [!_176:~0,%%~L!!_255:~%%L!] !time:~,8! 
            )
        )else if "%%G\" == "6\"  (
             if "!_ffprob_Path!\." == "\." (
                 for /l %%L in (10 -1 1) do %_ping% | title !_title! [!_176:~0,%%~L!!_022:~%%L!] !time:~,8! 
            )
        )else if "%%G\" == "0\"  (
            if "!_ffprob_Path!\." == "\." (
                 goto %:^/
                )
            )
        )
    ) 
   
%:^V
rem./ your code continues at this point using: / 
echo+!_ffprob_Path!
echo+!_ffprobe!
powershell batch
  • 1 1 respostas
  • 103 Views

1 respostas

  • Voted
  1. Best Answer
    T3RR0R
    2021-09-13T00:55:08+08:002021-09-13T00:55:08+08:00

    Minha abordagem para isso é usar um loop infinito para /l em um rótulo que é iniciado como um encadeamento separado. Eu uso um ADS do arquivo para me comunicar com o thread do arquivo principal quando parar, depois uma saída difícil para sair do thread.

    :# Author: T3RRY Created: 03/06/2021
    :# Purpose: RGB Spinner animation for load / waiting indication while script continues to run.
    :# Utilises a second thread to display animation while the main script continues executing.
    :# Execution and termination of the thread is controlled using a value stored in an alternate data
    :# stream of this file:. 1 = run ; 0 = stop
    
    @Echo off & CD /D "%~dp0"
    
    :# thread label structure by Jeb - https://stackoverflow.com/a/68636825/12343998
     for /F "tokens=3 delims=:" %%L in ("%~0") do goto %%L
    
     Call :defMacros
     %= Quit if not NTFS =% If Errorlevel 1 Exit /b
     Cls
    
    ===:# Usage Examples.
                   
     %Start.Thread:MSG=Example 1%
      For /l %%i in (1 1 100000)Do Set "var=%%i"
     %End.Thread%
     Echo([%var%] iterations actioned.
    
     %Start.Thread:MSG=Example 2%
      For /l %%i in (1 1 10000)Do Set "var=%%i"
     %End.Thread%
     Echo([%var%] iterations actioned.
    
     %Start.Thread:MSG=Example 3%
     Set "var=1"
     %End.Thread%
     Echo([%var%] iterations actioned.
    
    :# End script cleanup
     Powershell -c "remove-item -path '%~nx0' -Stream '*'"
     CHCP %active.cp% > nul
     @Pause
    
    Goto :Eof
    
    ===========================================================
    :AnimThread - Animation; RGB or BW spinner
    :# Animation sequence. Symbols will not display correctly with certain fonts
    :# Recommended font: Lucida Console
    :# Alt 205 ═ 186 ║ 187 ╗ 200 ╚ 188 ╝ 201 ╔
    :# ╔═╗╔═╗╔═╗╔═╗
    :# ║/║║-║║\║║|║
    :# ╚═╝╚═╝╚═╝╚═╝
    :#
    :# Framerate: ~ 25 fps. ('Delay' assigned as 4/100ths of a second.)
    :# NOTE - Multiple instances of this thread can not be run in parallel;
    :#        as Virtual terminal Cursor save operation will overide information stored by parallel threads
    
     Setlocal EnableDelayedExpansion
     CHCP 65001 > nul
     If "%_Param%"=="MSG" Set "_Param=Executing"
     If defined Win10 <nul set /p "=%\E%[1E%_Param%.%\E%[?25l%\E%[1E%\E%7"
     Set "title.i=-1"
     Set "T2[L]=0"         %= Rem Spinner Loop count    =%
     Set "T2[chars]= |/-\" %= Rem Spinner characters    =%
     Set "Delay=4"         %= Framerate in Centiseconds =%
    
    :# frame control via elapsed time by Dave Benham - https://www.dostips.com/forum/viewtopic.php?f=3&t=4741
    
     If defined Win10 For /l %%. in ()Do (
      %= Check completion status flagged in status stream of this file; =%
      (For /F "UsebackQ Delims=" %%G in ("%~f0:Stream")Do if %%G EQU 0 (
       <nul Set /P "=%\E%[?25h%\E%8%\E[K%"                  %= restore cursor    =%
       %restore.CP% > nul                                   %= restore codepage  =%
       <nul Set /P "=%\E%[7;32mCompleted.%\E%[0m%\E%[1E%\E%[M%\E%[K" %= notify completion; Emit newline; Delete last line of animation =%
       (TITLE )
       Exit                                                 %= exit thread       =%
      ))2> nul
    
      %= Calculate time elapsed =%
      for /f "tokens=1-4 delims=:.," %%a in ("!time: =0!") do set /a "t2=(((1%%a*60)+1%%b)*60+1%%c)*100+1%%d-36610100, tDiff=t2-t1"
      if !tDiff! lss 0 set /a tDiff+=24*60*60*100
    
      if !tDiff! geq !delay! (
       Set /A title.i+=1
       If !title.i! GTR 9 Set "title.i=0"
       Set "Bar=║0123456789║"
       For /l %%v in (0 1 9)Do If %%v NEQ !title.i! (Set "Bar=!Bar:%%v=░!")Else Set "Bar=!Bar:%%v=▬!"
       Title Processing... !BAR! !Time!
       %= delay has expired ; display frame =%
       Set /A "T2[L]+=1"        %= Increment index point of spinner string =%
       %= Output Spinner frame. Overwites previous output using saved cursor position =%
       For /f "Delims=" %%v in ("!T2[L]!")Do <nul Set /p "=%\E%8%\E%[38;2;20;20;20;7m%\E%[48;2;150;;150m╔═╗╔═╗╔═╗%\E%[0;38;2;150;;150m%\E%[K%\E%[E║%\E%[38;2;20;20;20;7m%\E%[48;2;255;;m!T2[chars]:~%%v,1!%\E%[0m%\E%[38;2;20;20;20;7m%\E%[48;2;150;;150m║║%\E%[38;2;20;20;20;7m%\E%[48;2;;255;m!T2[chars]:~%%v,1!%\E%[0m%\E%[38;2;20;20;20;7m%\E%[48;2;150;;150m║║%\E%[38;2;20;20;20;7m%\E%[48;2;;100;255m!T2[chars]:~%%v,1!%\E%[0m%\E%[38;2;20;20;20;7m%\E%[48;2;150;;150m║%\E%[0m%\E%[K%\E%[E%\E%[38;2;20;20;20;7m%\E%[48;2;150;;150m╚═╝╚═╝╚═╝%\E%[0m%\E%[K%\E%[1G%\E%[2A%\E%7"
       If !T2[L]! EQU 4 Set "T2[L]=0" %= Reset index point of spinner string =%
       set /a t1=t2
      )
     )
    
     %= If not defined Win10 [ No Virtual Terminal support ] =%
     For /l %%. in ()Do (
      (For /F "UsebackQ Delims=" %%G in ("%~f0:Stream")Do if %%G EQU 0 (
       %restore.CP% > nul
       Cls
       Echo(Complete.
       (TITLE )
       Exit
      ))2> nul
    
      for /f "tokens=1-4 delims=:.," %%a in ("!time: =0!") do set /a "t2=(((1%%a*60)+1%%b)*60+1%%c)*100+1%%d-36610100, tDiff=t2-t1"
      if !tDiff! lss 0 set /a tDiff+=24*60*60*100
    
      if !tDiff! geq !delay! (
       Set /A title.i+=1
       If !title.i! GTR 9 Set "title.i=0"
       Set "Bar=║0123456789║"
       For /l %%v in (0 1 9)Do If %%v NEQ !title.i! (Set "Bar=!Bar:%%v=░!")Else Set "Bar=!Bar:%%v=▬!"
       Title Processing... !BAR! !Time!
       Set /A "T2[L]+=1"
       For /f "Delims=" %%v in ("!T2[L]!")Do (
        Cls
        Echo(%_Param%.
        Echo(╔═╗╔═╗╔═╗╔═╗╔═╗╔═╗
        Echo(║!T2[chars]:~%%v,1!║║!T2[chars]:~%%v,1!║║!T2[chars]:~%%v,1!║║!T2[chars]:~%%v,1!║║!T2[chars]:~%%v,1!║║!T2[chars]:~%%v,1!║
        Echo(╚═╝╚═╝╚═╝╚═╝╚═╝╚═╝
       )
       If !T2[L]! EQU 4 Set "T2[L]=0"
       set /a t1=t2
      )
     )
    
    :defMacros
    :# OS Requirement tests
    
    :# Verify NTFS drive
     (Echo(verify.NTFS >"%~f0:Status") || (
      Echo(This file must be located on an NTFS drive as it utilises alternate data streams.
      Timeout /t 5
      Exit /B 1
     )
    
    :# Windows Version control. Assigns flag true if system is windows 10 build GTR 10586
    :# https://en.wikipedia.org/wiki/ANSI_escape_code#DOS,_OS/2,_and_Windows
    :# Version 1511 build number = 10.0.10586
     Set "Win10="
     For /f "tokens=3 delims=." %%v in ('Ver')Do if %%v GTR 10586 Set "Win10=True"
    
    :# If Win10 true ; Test if virtual terminal codes enabled ; enable if false
    :# removes win10 flag definition if version does not support Virtual Terminal sequences
     If defined Win10 (
      Reg Query HKCU\Console | %SystemRoot%\System32\findstr.exe /LIC:"VirtualTerminalLevel    REG_DWORD    0x1" > nul || (
        Reg Add HKCU\Console /f /v VirtualTerminalLevel /t REG_DWORD /d 1
      ) > Nul || Set "Win10="
     )
    
    
    =====:# Store codepage to restore on script completion
     For /f "tokens=4 Delims=: " %%1 in ('CHCP')Do Set "active.cp=%%1"
    
    =====:# Define Escape character for Virtual terminal sequences 
    If Defined Win10 For /f "Delims=" %%e in ('Echo(Prompt $E^|Cmd')Do Set "\E=%%e"
    
    ==================:# macros start and stop Thread via t/f flag written to alternate data stream.
    :# Start.Thread - Save current Codepage;
    :#                Remove status thread from this file if present;
    :#                Notify command has started;
    :#                Flag status 1 in Stream :status;
    :#                Use start /b with params to relaunch this script and execute second thread
    :#                executes infinite loop in AnimThread1 based on win10 virtual terminal support
    
     Set "Start.Thread=Set "_param=MSG"& (For /F "tokens=2 Delims=:" %%G in ('CHCP')Do Set "restore.CP=CHCP %%G")&((Echo(1)>"%~f0:Stream") & Start /AboveNormal /b "" "%~d0\:AnimThread:\..%~pnx0""
    
    :# End.Thread  - Flag status 0 in Stream :Status;
    :#               Execute a small delay to ensure thread has time to enable cursor display and clear animation.
    :#               [Delay of approx. 1/66th of a second]
    
     Set "End.Thread=((Echo(0)>"%~f0:Stream")&For /L %%i in (1 1 750)Do ((Call ))"
    
    Exit /b 0
    
    • 2

relate perguntas

  • Powershell e regex: lista de arquivos "backup ao salvar" do Notepad ++. Editar nome, classificar por lastwritetime

  • Adicionando cor de primeiro plano ao perfil do Powershell?

  • Qual seria o equivalente em lote do argumento "pass" do Python?

  • Não é possível ativar o Microsoft Print to PDF depois de desativado

  • Posso fazer com que este script do PowerShell aceite vírgulas?

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Como posso reduzir o consumo do processo `vmmem`?

    • 11 respostas
  • Marko Smith

    Baixar vídeo do Microsoft Stream

    • 4 respostas
  • Marko Smith

    O Google Chrome DevTools falhou ao analisar o SourceMap: chrome-extension

    • 6 respostas
  • Marko Smith

    O visualizador de fotos do Windows não pode ser executado porque não há memória suficiente?

    • 5 respostas
  • Marko Smith

    Como faço para ativar o WindowsXP agora que o suporte acabou?

    • 6 respostas
  • Marko Smith

    Área de trabalho remota congelando intermitentemente

    • 7 respostas
  • Marko Smith

    O que significa ter uma máscara de sub-rede /32?

    • 6 respostas
  • Marko Smith

    Ponteiro do mouse movendo-se nas teclas de seta pressionadas no Windows?

    • 1 respostas
  • Marko Smith

    O VirtualBox falha ao iniciar com VERR_NEM_VM_CREATE_FAILED

    • 8 respostas
  • Marko Smith

    Os aplicativos não aparecem nas configurações de privacidade da câmera e do microfone no MacBook

    • 5 respostas
  • Martin Hope
    Saaru Lindestøkke Por que os arquivos tar.xz são 15x menores ao usar a biblioteca tar do Python em comparação com o tar do macOS? 2021-03-14 09:37:48 +0800 CST
  • Martin Hope
    CiaranWelsh Como posso reduzir o consumo do processo `vmmem`? 2020-06-10 02:06:58 +0800 CST
  • Martin Hope
    Jim Pesquisa do Windows 10 não está carregando, mostrando janela em branco 2020-02-06 03:28:26 +0800 CST
  • Martin Hope
    v15 Por que uma conexão de Internet gigabit/s via cabo (coaxial) não oferece velocidades simétricas como fibra? 2020-01-25 08:53:31 +0800 CST
  • Martin Hope
    andre_ss6 Área de trabalho remota congelando intermitentemente 2019-09-11 12:56:40 +0800 CST
  • Martin Hope
    Riley Carney Por que colocar um ponto após o URL remove as informações de login? 2019-08-06 10:59:24 +0800 CST
  • Martin Hope
    zdimension Ponteiro do mouse movendo-se nas teclas de seta pressionadas no Windows? 2019-08-04 06:39:57 +0800 CST
  • Martin Hope
    jonsca Todos os meus complementos do Firefox foram desativados repentinamente, como posso reativá-los? 2019-05-04 17:58:52 +0800 CST
  • Martin Hope
    MCK É possível criar um código QR usando texto? 2019-04-02 06:32:14 +0800 CST
  • Martin Hope
    SoniEx2 Altere o nome da ramificação padrão do git init 2019-04-01 06:16:56 +0800 CST

Hot tag

windows-10 linux windows microsoft-excel networking ubuntu worksheet-function bash command-line hard-drive

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve