我有一个以厘米为单位的while
循环,并始终在同一行上打印current_step
var。
例如,我想跑步
x = True
while x is True:
pass #printing timer to CLI here
print('this is more code running while the timer is still running')
input('Press enter to stop the timer')
x = False
#When x becomes False, I want the while loop to terminate
我知道这必须涉及子流程或类似的事物,但我不知道要为解决该问题而学习的方向。
这里是供参考的功能:
def timer(stawt, stahp, step, time_step):
from time import sleep
stawt = int(stawt)
stahp = int(stahp)
if stahp < 1:
stahp = 1
elif stahp > 1000:
stahp = 1000
stahp = stahp * 100 + 1
titerator = iter(range(stawt, stahp, step))
while True:
try:
current_step = str(next(titerator))
if int(current_step) < 99:
final_time = '0' + current_step[:0] + '.' + current_step[0:] + 's'
print('\r' + final_time, end='')
elif int(current_step) < 999:
final_time = current_step[:1] + '.' + current_step[1:] + 's'
print('\r' + final_time, end='')
elif int(current_step) < 9999:
final_time = current_step[:2] + '.' + current_step[2:] + 's'
print('\r' + final_time, end='')
else:
final_time = current_step[:3] + '.' + current_step[3:] + 's'
print('\r' + final_time, end='')
sleep(time_step)
except:
print(); break
seconds = int((int(current_step) / 100) % 60)
minutes = int((int(current_step) / 100) // 60)
if minutes < 1:
return ''
else:
final_time_human = str(minutes) + 'm ' + str(round(seconds)) + 's'
print(final_time_human + '\n')
def MAIN():
count_to = float(input('Enter max number of seconds to count:\n'))
print()
timer(0, count_to, 1, 0.01)
MAIN()
您需要使用线程。
import threading
x = True
def thread_function():
while x is True:
pass #printing timer to CLI here
threading.Thread(target=thread_function).start()
# Continue with the other steps you want to take
# ...
# This will terminate the timer loop
x = False
Python线程文档:https://docs.python.org/3/library/threading.html
如果要始终在同一行上打印时间,则需要控制终端光标。欲了解更多信息,请结帐:How can move terminal cursor in Python?