在Python中重复打印几行

2024-04-24 07:12:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个关于天文学和望远镜位置的项目,使用python3.6。我的项目包括将望远镜的位置打印到控制台上,并反复更新。我想有信息打印到控制台,并覆盖每一个timestep,让用户更新其当前位置。到目前为止,我已经实现了打印本地时间和UTC:

import time
from datetime import datetime
from numpy import array
import sys

#Initial conditions
longitude= 83.6123 #W
latitude= 41.6624 #N
tstep=1/24 #timestep between time calculations
zero_angle=latitude #when telescope is directly up, the angle between telescope and horizon is the latitude.


while stop!=1:
    utc_time,loc_time=datetime.utcnow(),time.ctime()
    print('UTC       :',utc_time,'Local time:',loc_time,flush=True,end='\r')
    #print('Coordinates: ', latitude, ' N',longitude, ' W')
    time.sleep(tstep)

上面的一些东西是供以后使用的,现在还不相关。此代码当前打印出来:

UTC       : 2018-04-27 20:41:41.981367 Local time: Fri Apr 27 16:41:41 2018

每1/24秒更新一次输出。我想做的是用多行实现这一点(因此每一个timestep都有几行更新,并被覆盖)。我在其他线程中发现flush=True和end='\r',但将其应用于单独的print语句会覆盖第一行。有没有一种方法可以让每个时间步都更新几个独立的行?谢谢!你知道吗


Tags: 项目fromimportdatetimetime时间betweenutc
2条回答

查找curses模块。它是经典curses库的接口,用于在终端上进行光标移动。你知道吗

看来我找到解决办法了!你知道吗

如果从导入“清除输出”IPython.display显示您可以允许控制台在每次迭代后使用更新的信息进行刷新。生成的代码:

while im_still_presenting==True:
    utc_time,loc_time=datetime.utcnow(),time.ctime()
    print('UTC        :',utc_time,'Julian Day:',JD(utc_time),flush=True)
    print('Local time :',loc_time,flush=True)
    print('Coordinates: ', latitude, ' N',longitude, ' E',flush=True)

    time.sleep(tstep)
    clear_output(wait=True)

将打印到控制台:

UTC        : 2018-04-29 15:17:30.667045 Julian Day: 2458237.5
Local time : Sun Apr 29 11:17:30 2018
Coordinates:  41.6624  N -83.6123  E

并在每个时间步更新UTC和本地时间字段。谢谢大家的帮助:)

相关问题 更多 >