用Python

时间:2018-04-27 20:45:52

标签: python python-3.x printing output string-literals

我正在研究一个使用Python 3.6围绕天文学和望远镜位置的课程。我的项目涉及将望远镜的位置打印到控制台并反复更新。我希望将信息打印到控制台并在每个时间步都覆盖,以使用户更新其当前位置。到目前为止,我已经实现了打印当地时间和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秒更新一次输出。我想做的是用多行来实现这一点(因此几行每次都会更新,并被覆盖)。我在其他线程中找到了flush = True和end ='\ r',但将其应用于单独的print语句会覆盖第一行。有没有办法让每个时间步都更新几个独立的行?谢谢!

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

看起来我找到了解决方案!

如果从IPython.display导入“clear_output”,则可以允许控制台在每次迭代后使用更新的信息进行刷新。结果代码:

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和本地时间字段。感谢大家的帮助:))