Hey I am trying to set up a logger for python3.9 for an entire project, with multiple files. I want to just define the logger in main.py using command line arguments to define log file name.
logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s', level='INFO')
logger = logging.getLogger(__name__)
def main():
file_name = sys.argv[1]
lookback_minutes = int(sys.argv[2])
file_handler = logging.FileHandler(f'log/{file_name}.log')
logger.addHandler(file_handler)
logger.info(f'Running processing chain for: {file_name}')
processing_chain.run(lookback_minutes)
processing_chain file:
import logging
def run(lookback_minutes):
logging.info(lookback_minutes)
Which works for main, I get the info statement printed to the log file. However I do not understand how to import it into the files that main calls. How do I bring the file handler into processing_chain file? Currently from what I could understand from other places on stackoverflow, I just import logging and then use logging.info or any other level and it should follow. But it does not log to file, just to console.
import configparser
from tkinter import *
from tkinter import filedialog,messagebox
from tkinter.filedialog import asksaveasfile
from customtkinter import *
import os
import time
import wikipedia
config=configparser.ConfigParser()
config.read("config.ini")
def change_config():
messagebox.showinfo("Information","App is going to restart in few seconds")
print(mode.get())
print(color.get())
global location
config.set("THEME","mode",str(mode.get()))
config.set("VOICE","voice",str(gender.get()))
if color.get() =="pink":
location="C:/Users/DELL/Documents/python programs/notepad/custom_theme.json"
config.set("THEME","color",location)
else :
config.set("THEME","color",color.get())
with open("config.ini","w") as configfile:
config.write(configfile)
restart()
def main():
global root,label,frame1,config_color,config_mode,config_gender
root=CTk()
root.geometry("700x600")
root.resizable(0,0)
root.title("Notepad")
frame1=CTkFrame(root,width=150,height=580)
frame1.pack_propagate(False)
frame1.place(x=10,y=10)
config_color=config.get("THEME","color")
config_mode=config.get("THEME","mode")
config_gender=config.get("VOICE","voice")
set_appearance_mode(config_mode)
set_default_color_theme(config_color)
label=CTkLabel(root,text="File",width=520,height=40,font=("Algerian",30))
label.place(x=170,y=10)
global S
global text_area
text_area=CTkTextbox(root,height=580,width=520,)
text_area.place(x=170,y=60)
global button,commands,button_text
button_text="Settings"
commands=settings
button=CTkButton(frame1,text=button_text,command=settings)
button.pack(padx=10,pady=10)
root.mainloop()
def settings():
global submit,mode,color,config_color,config_mode,gender
window=CTkToplevel(root)
window.title("Settings")
window.geometry("200x300")
label1=CTkLabel(window,text="Mode").pack(pady=5)
mode=CTkOptionMenu(window,values=["light","dark"])
mode.pack(pady=5,padx=5,anchor=CENTER)
label2=CTkLabel(window,text="Color").pack(pady=5)
color=CTkOptionMenu(window,values=["pink","blue","green","dark-blue"])
color.pack(pady=5)
label3=CTkLabel(window,text="speech-gender").pack(pady=5)
gender=CTkOptionMenu(window,values=["male","female"])
gender.pack(pady=5)
submit=CTkButton(window,text="Submit",command=change_config)
submit.pack(pady=20)
window.mainloop()
if __name__=="__main__":
def restart():
time.sleep(5)
root.destroy()
main()
main()
I want to create a notepad , where we can change themes and colors.
I have made config.ini file where i save the current mode, color and the voice type for the notepad ( voicetype is for text-to-speech functionality that i have added here ) becuase while using customtkinter we can set default color theme and cannot change it once initialized in a program.
The program now save the selected preferences in config.ini file and grab it when run again.
I want the program to run again itself without having the need to explicitly run it again.
Though program is running i am still getting this error at backend:
invalid command name "2912423726080check_dpi_scaling"
while executing
"2912423726080check_dpi_scaling"
("after" script)
invalid command name "2912423728512update"
while executing
"2912423728512update"
("after" script)
invalid command name "2912423728448<lambda>"
while executing
"2912423728448<lambda>"
("after" script)
I want to know what this error means so that the users might not face problem in future while using this app.
Thanks in advance for helping.
Since JupyterLab 3.x jupyter-server is used instead of the classic notebook server, and the following code does not list servers served with jupyter_server:
from notebook import notebookapp
notebookapp.list_running_servers()
None
What still works for the file/notebook name is:
from time import sleep
from IPython.display import display, Javascript
import subprocess
import os
import uuid
def get_notebook_path_and_save():
magic = str(uuid.uuid1()).replace('-', '')
print(magic)
# saves it (ctrl+S)
# display(Javascript('IPython.notebook.save_checkpoint();')) # Javascript Error: IPython is not defined
nb_name = None
while nb_name is None:
try:
sleep(0.1)
nb_name = subprocess.check_output(f'grep -l {magic} *.ipynb', shell=True).decode().strip()
except:
pass
return os.path.join(os.getcwd(), nb_name)
But it's not pythonic nor fast
How to get the current running server instances - and so e.g. the current notebook file?
Migration to jupyter_server should be as easy as changing notebook to jupyter_server, notebookapp to serverapp and changing the appropriate configuration files - the server-related codebase is largely unchanged. In the case of listing servers simply use:
from jupyter_server import serverapp
serverapp.list_running_servers()
I am using python 3.7.6. and abseil module for logging messages with absl-py 0.9.0. I am using this piece of code for my tests.
from absl import logging
from absl import app
def main(argv):
#logging.set_stderrthreshold(logging.ERROR)
#logging._warn_preinit_stderr = False
logging.set_verbosity(logging.DEBUG)
print(' 0 -----')
logging.debug(' 1 logging-debug-test')
logging.info(' 2 logging-info-test')
logging.warning(' 3 logging-warning-test')
logging.error('4 logging-error-test')
print(' 5 -----')
if __name__ == '__main__':
app.run(main)
When testing it in a Jupyter notebook, it is clear from the color code of the background that abseil messages are in the stderr stream.
Same things when executing the python code in a shell:
I tried few things with different values like:
logging.set_stderrthreshold(logging.DEBUG)
logging._warn_preinit_stderr = True
but I still see 100% the same output.
How can I redirect output abseil logging messages to stdout instead of stderr ?
Is it expected to have the logging output messages redirect to stderr and not stdout? I am probably missing something with the logging logic and I want to better understand it.
I was told that this is the standard behavior and what Python's standard logging module does. In my case adding the following line redirect the logging messages to stdout:
logging.get_absl_handler().python_handler.stream = sys.stdout
Now in my Jupyter notebook it looks like that:
This did NOT work for me for some reason:
from absl import logging
import sys
logging.get_absl_handler().python_handler.stream = sys.stdout
But this did:
import logging
import sys
logging.basicConfig(stream=sys.stdout)
This python code file works perfectly. But when I add either of the commented imports, the vscode test feature gives "No tests discovered, please check the configuration settings for the tests." No other errors.
# import boto3
# import pymysql
import decimal
import datetime
def increment(x):
return x + 1
def decrement(x):
return x - 1
What is it that I don't understand about imports and the test feature that explains why these would break the test explorer?