Unable to log to a file executing infinite loops while polling data from python-telegram-bot
Posted by:
pavan hnk
Date: July 12, 2022 03:21AM
I'm NOT a programmer, but a very enthusiast user :) I've implemented a logger with influxdb, grafana and a connection to a modbus interface via tcp/ip with python. All works well, but i have a big issue, i cannot have LOGS of the activities, maybe for the bad construct i've used. Basically i should have the bot listening, and another infinite thread who pull data from an inverter. Here is a cutted version of the construct i've used:
def start(update: Updater, context: CallbackContext):
update.message.reply_text('Whatever command/action/function i want')
def anothercommand(update: Updater, context: CallbackContext):
update.message.reply_text('Whatever command/action/function i want')
def loop(update: Updater, context: CallbackContext):
print('Starting thread for automations')
def thread1(update: Updater, context: CallbackContext):
while 1:
#loop to collect data into dB and send automated TG Alerts
update.message.reply_text('I am from thread 1. going to sleep now.')
time.sleep(2)
t1 = threading.Thread(target=thread1,args=(update,context))
t1.start()
def main() -> None:
print('bot started..')
updater = Updater(TOKEN,use_context=True)
dispatcher = updater.dispatcher
loop(updater,CallbackContext)
dispatcher.add_handler(CommandHandler('start', start))
dispatcher.add_handler(CommandHandler('anothercommand', anothercommand))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
...forcing the logging to a file :
sys.stdout = open('/the/path/to/your/file', 'w')
or with
file.py > output.txt
or
import logging
logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG)
generate an empty logfile, and nothing appears on the console