2014-02-11 7 views
1

스크립트가 잠자기 시간 동안 카운트 다운 타이머를 인쇄해야합니다.Tcl 타이머 스 니펫

화면 출력은 다음과 같습니다 -

 
Started Script 

Script will Sleep for 100 seconds 

Time left 100 
Time left 99 
Time left 98 

내가 남아있는 시간을 인쇄 싶지만 이전 항목을 삭제하여. 당시

0

 
Started Script 

Script will Sleep for 100 seconds 

Time left 100 

번에 1

 
Started Script 

Script will Sleep for 100 seconds 

Time left 99 

시간에서 2

 
Started Script 

Script will Sleep for 100 seconds 

Time left 98 

어떻게이 내가 할 수 있습니다 n tcl?

답변

1

가장 간단한 방법은 일부 터미널 트릭입니다. 핵심 요령은 캐리지 리턴 (\u000d 또는 \r)을 인쇄하면 커서를 현재 줄의 시작 부분으로 되돌려 보내는 것입니다.

puts "Started Script\n" 

# Turn off output buffering; important! 
fconfigure stdout -buffering none 

puts "Script will sleep for 100 seconds\n" 

set deadline [expr {[clock seconds] + 100}] 
while 1 { 
    set now [clock seconds] 
    if {$deadline <= $now} { 
     break 
    } 

    # Tricky; the CR is critical to making this work... 
    puts -nonewline "\rTime left [expr {$deadline - $now}] " 

    # Sleep *half* a second for accuracy 
    after 500 
} 

# Blank the countdown line and put a finished message with a cheap hack 
puts -nonewline "[string repeat " " 15]\rDone!" 

할 수 있습니다 타이밍 소스로 clock milliseconds을 사용하고 after에서 잠을 단축하여보다 정확한 카운트 다운을 얻을; 이 경우 남은 시간을 초로 변환하려면 약간의 (약간의) 추가 작업이 필요합니다.