Is there a way of printing the time output on one line instead of scrolling down the page.
while True:
import datetime
import pytz
T = datetime.datetime.now()
print(T)
in python 2, do below, i try on my python2.7, its also working even without the sys.stdout.flush()
while True:
import datetime
T = datetime.datetime.now()
print "{}\r".format(T), ;sys.stdout.flush()
in python 3
while True:
import datetime
T = datetime.datetime.now()
print(T, end='\r', flush=True)
import datetime
import sys
import os
os.system('setterm -cursor off')
while True:
T = datetime.datetime.now()
sys.stdout.write(str(T))
sys.stdout.write('\b' * 50)
you can import print from python 3 and do:
from __future__ import print_function
import time
import sys
import datetime
while True:
T = datetime.datetime.now()
print(T, end="\r")
sys.stdout.flush()
time.sleep(.4)
This solution is based on the following gist
Related
I would like to have a timer above an input, then end the timer once the player inputs anything.
So far I've tried using threading and sys.flush, and multithreading to terminate the thread, but I wasn't able to input anything since the timer just followed the cursor.
My Code:
def DisplayTime():
import sys
while True:
sys.stdout.write('\r'+str(format_time))
sys.stdout.flush()
displayTime = threading.Thread(name='DisplayTime', target=DisplayTime)
Somewhere else:
displayTime.start()
What happened:
>>> Text Here
>>> Timer: 0:00:00(Wait for input)
I was expecting something like this:
>>> Timer: 0:00:00
>>> Text Here
>>> (Wait for input)
>>> Timer: 0:00:01
>>> Text Here
>>> (Wait for input)
The following code prints a timer followed by a line of text followed by an empty line on which the cursor is displayed. start_time lets us calculate the elapsed time, and last_printed keeps track of the last printed time so we don't have to print on every iteration. The important parts are taken from other StackOverflow answers:
Move cursor up one line
Non-blocking console input
import sys
import time
import msvcrt
import datetime
start_time = time.time()
last_printed = -1
print('\n')
while True:
elapsed_time = time.time() - start_time
int_elapsed = int(elapsed_time)
if int_elapsed > last_printed:
elapsed_td = datetime.timedelta(seconds=int_elapsed)
# Go up one line: https://stackoverflow.com/a/11474509/20103413
sys.stdout.write('\033[F'*2 + str(elapsed_td) + '\nText here\n')
sys.stdout.flush()
last_printed = int_elapsed
# Non-blocking input: https://stackoverflow.com/a/2409034/20103413
if msvcrt.kbhit():
print(msvcrt.getch().decode())
break
#!/usr/bin/env python
from urllib import request
import requests
from urllib.request import urlopen
import threading # import threadding
import json # import json
READ_API_KEY= "ZG0YZXYKP9LOMMB9"
CHANNEL_ID= "1370649"
while True:
TS = urllib3.urlopen("http://api.thingspeak.com/channels/%s/feeds/last.json?api_key=%s" \
% (CHANNEL_ID,READ_API_KEY))
response = TS.read()
data=json.loads(response)
b = data['field1']
c = data['field2']
print (b)
print (c)
time.sleep(15)
TS.close()
I uploaded the data from raspberry pi to thingspeak, but in order to use it in the follium map, I need to access these data instantly. The code here seems to work but I keep getting errors. Can you help me?
I would recommend you research a bit more about python imports.
In the meantime, this change should fix the issue:
import time # you forgot to import
TS = urllib3.urlopen(#url)
# should be
TS = urlopen(#url)
while True:
TS = urllib3.urlopen(#"http://api.thingspeak.com/channels/1370649/feeds/last.json?api_key=ZG0YZXYKP9LOMMB9")
response = TS.read()
data=json.loads(response)
b = data['field1']
c = data['field2']
print (b)
print (c)
time.sleep(15)
TS.close()
data=json.loads(response)
^
SyntaxError: invalid syntax
I'm searching, but I haven't found much.
I have a large number of import statements (with prints for debug...) for my code:
from __future__ import absolute_import, division, print_function, unicode_literals
import os, sys, struct, json, time, socket
print("start import BS")
from BS import run_BS # custom library
print("end import BS")
print("Import 1")
print("Import 2")
import numpy as np
print("Import 3")
import platform
import datetime
from posixpath import join as pjoin
print("Import 4")
from multiprocessing import Process, Queue
import matplotlib
import tkinter
print("Import 5")
print("Import 6")
print("Import 7")
from send_tune_request import tune
print("Import 8")
print("Import 9")
and the code structure is roughly:
class ed_bs:
def __init__(self, check=False, test_mode=False):
curr_BS_proc = Process(target=run_BS, args=(a, b, c))
def main_loop(self):
while 1:
pass # run forever...
if __name__ == '__main__':
e_d = ed_bs(check=True)
test_mode = True
if test_mode:
test_start_thread = Process(target=tune)
test_start_thread.setDaemon = True
test_start_thread.start()
The print statements look like as follows:
start import BS
end import BS
Import 1
Import 2
Import 3
Import 4
Import 5
Import 6
Import 7
Import 8
Import 9
start import BS
end import BS
Import 1
Import 2
Import 3
Import 4
Import 5
Import 6
Import 7
Import 8
Import 9
start import BS
end import BS
Import 1
Import 2
Import 3
Import 4
Import 5
Import 6
Import 7
Import 8
Import 9
I'm guessing that it's printing three times because there's 3 processes in this flow (the __main__ process, tune, and run_BS), but neither BS nor send_tune_request import the __file__ file so I am a little confused. The imports take a long time (run_BS has Tensforflow trace compiling) and use a lot of memory to import everything thrice over three processors so I'd like to limit imports more appropriately.
Why are the import taking a long time and how do I make everything import only once?
Thanks for the help.
EDIT: BS.py looks something like the below:
from __future__ import absolute_import, division, print_function, unicode_literals
import os, sys, struct, json, time
from posixpath import join as pjoin
from termcolor import colored
import numpy as np
import scipy.signal as sig
import tensorflow as tf
import platform
import tensorflow_probability as tfp
def run_BS():
bs = BS()
while 1:
bs.process_data()
class BS:
def process_data(self):
self.tf_process_1()
self.tf_process_2()
self.non_tf_process()
#tf.function
def tf_process_1(self):
tf.cast()
...
#tf.function
def tf_process_2(self):
tf.cast()
...
def non_tf_process(self):
x = np.zeros(100)
x = x+1
...
I would like to change my lcd 24 hours time format to 12 hours
import lcddriver
import time
import datetime
display = lcddriver.lcd()
try:
print("Writing to display")
display.lcd_display_string("Time", 1)
while True:
display.lcd_display_string(str(datetime.datetime.now().time()), 2)
except KeyboardInterrupt:
print("Cleaning up!")
display.lcd_clear()
You could use datetime module in python like this:
import lcddriver
import time
import datetime
display = lcddriver.lcd()
try:
print("Writing to display")
display.lcd_display_string("Time", 1)
while True:
datestr = datetime.datetime.now().strftime("%I:%M:%S %p")
display.lcd_display_string(datestr, 2)
except KeyboardInterrupt:
print("Cleaning up!")
display.lcd_clear()
For example, if current time is 15:40:50 then datetime.datetime.now().strftime("%I:%M:%S %p") outputs 03:40:50 PM
Hope it helps you!
I am running below scripts it taking almost 35 sec for all stocks. Is there any lib to run faster for all stocks at a time
import schedule
import time
from kiteconnect import KiteConnect
import CSV
import JSON
import requests
import pandas_datareader.data as pdr
import pandas as pd
import matplotlib.pyplot as plt
import time
import subprocess
Def job():
api_key='YOUR_API'
api_secret='YOUR_SECRETKEY'
api_token='YOUR_ACESSTOKEN'
kite=KiteConnect(api_key=api_key)
kite.set_access_token('YOUR_ACCESStoken')
Stocks = ['BANKINDIA','CAPF','CHENNPETRO','DLF',
'EQUITAS','ESCORTS','FORTIS','HEXAWARE',
'IDBI','IDFCBANK','IOC','IRB','ITC','JUBLFOOD',
'KPIT','OFSS','ONGC','PFC','PNB',
'RPOWER','TATAPOWER','VGUARD','WOCKPHARMA']
for testst in Stocks:
print(testst)
Kite_TODAY="https://api.kite.trade/instruments/NSE/%s?api_key='YOUR_API'&access_token='ACCESS_TOKEN'"
print(Kite_TODAY % testst)
r = requests.get(Kite_TODAY % testst)
rjson=r.json()
r1=rjson['data']['last_price']
Open = rjson['data']['ohlc']['open']
High = rjson['data']['ohlc']['high']
Low = rjson['data']['ohlc']['low']
Close = rjson['data']['ohlc']['close']
print(" Stock %s Open %s High %s Low %s Close %s",testst,Open,High,Low,Close)
if ( Open == High ):
testkite = (("kite.order_place(tradingsymbol='%s',exchange='NSE',quantity=1,price=%s,squareoff_value=1,stoploss_value=5,variety='bo',transaction_type='SELL',order_type='LIMIT',product='MIS',validity='DAY')") % (testst,Open))
order1=testkite
order2=exec(order1)
print(order2)
print (" working...")
return
schedule.every().day.at ("09:15").do (job)
While True:
schedule.run_pending()
time.sleep (1)