python webbrowser - python

I've been using this module without problems by calling it as:
webbrowser.open("http link...")
now, however, I wanted to select a different browser, and according to the docs (http://docs.python.org/library/webbrowser.html#webbrowser.get) I wrote this
controller = webbrowser.get('firefox')
controller("http link...")
... and I get an error I'm unable to get rid of:
Exception in Tkinter callback
Traceback (most recent call last):
....
TypeError: 'Mozilla' object is not callable
any idea about it???

A Controller object is not callable. Do this:
controller.open(url)

Related

tkintermapview PhotoImage object has no attribute '_PhotoImage__photo'

I am making a project based on tkintermapview, but it throws the error when the following code is run.
import tkintermapview as tkmap
self.map = tkmap.TkinterMapView(self.__map_frame, width=self.__map_width,
height=self.__height, corner_radius=0)
# google normal tile server
self.map.set_tile_server("https://mt0.google.com/vt/lyrs=m&hl=en&x={x}&y={y}&z={z}&s=Ga", max_zoom=22)
# google satellite tile server
# self.map.set_tile_server("https://mt0.google.com/vt/lyrs=s&hl=en&x={x}&y={y}&z={z}&s=Ga", max_zoom=22)
# self.map.set_tile_server("http://c.tile.stamen.com/watercolor/{z}/{x}/{y}.png") # painting style
self.map.pack(fill=tk.BOTH)
self.map.set_address("kathmandu")
if the last line i.e. set_address() is removed then it runs fine otherwise it throws the error.
following is the error message:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/PIL/ImageTk.py", line 118, in __del__
name = self.__photo.name
AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'
Exception ignored in: <function PhotoImage.__del__ at 0x7fa9e10ed510>
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/PIL/ImageTk.py", line 118, in __del__
name = self.__photo.name
AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'
Process finished with exit code 0
I tried the following code as well to reproduce the error
from tkintermapview import TkinterMapView
root_tk = tkinter.Tk()
root_tk.geometry(f"{600}x{400}")
root_tk.title("map_view_simple_example.py")
# create map widget
map_widget = TkinterMapView(root_tk, width=600, height=400, corner_radius=0)
map_widget.pack(fill="both", expand=True)
# google normal tile server
map_widget.set_tile_server("https://mt0.google.com/vt/lyrs=m&hl=en&x={x}&y={y}&z={z}&s=Ga", max_zoom=22)
map_widget.set_address("chyasal")
root_tk.mainloop()
But this time the error is shown for the first time only. After that the program works correctly.
But again when I change the place to new location say set_address("Manang") again for the first launch, the same error is occured.
But this is not the case with all the places, I tried many different places inside the set_address() method, but only some of them caused the error.
I have one more question
My project should enable a user to pick the pick up and drop off location on the map and the map should calculate the shortest road and its distance(length of road) between the two locations.
Is tkintermapview good choice or is there a better way to display google map and implement this requirement in tkinter...?

Can I make Python output exceptions in one line / via logging?

I am using AWS and use AWS cloudwatch to view logs. While things should not break on AWS, they could. I just had such a case. Then I searched for Traceback and just got the lines
Traceback (most recent call last):
without the actual traceback. I have a working structured logging setup (see other question) and I would like to get tracebacks in a similar way.
So instead of:
Traceback (most recent call last):
File "/home/math/Desktop/test.py", line 32, in <module>
adf
NameError: name 'adf' is not defined
something like
{"message": "Traceback (most recent call last):\n File \"/home/math/Desktop/test.py\", line 32, in <module>\n adf\n NameError: name 'adf' is not defined", "lineno": 35, "pathname": "/home/math/Desktop/test.py"}
or even better also with the string in a JSON format.
The only way to achieve this I can think of is a giant try-except block. Pokemon-style. Is there a better solution?
You can use sys.excepthook. It is invoked whenever an exception occurs in your script.
import logging
import sys
import traceback
def exception_logging(exctype, value, tb):
"""
Log exception by using the root logger.
Parameters
----------
exctype : type
value : NameError
tb : traceback
"""
write_val = {'exception_type': str(exctype),
'message': str(traceback.format_tb(tb, 10))}
logging.exception(str(write_val))
Then in your script you have to override the value of sys.excepthook.
sys.excepthook = exception_logging
Now whenever an exception occurs it will be logged with your logger handler.
Note: Don't forget to setup logger before running this
In case somebody wants the exception logged in its default format, but in one line (for any reason), based on the accepted answer:
def exception_logging(exctype, value, tb):
"""
Log exception in one line by using the root logger.
Parameters
----------
exctype : exception type
value : seems to be the Exception object (with its message)
tb : traceback
"""
logging.error(''.join(traceback.format_exception(exctype, value, tb)))
Please also note, that it uses logging.error() instead of logging.exception() which also printed some extra "NoneType: None" line.
Also note that it only seems to work with uncaught exceptions.
For logging caught exceptions, visit How do I can format exception stacktraces in Python logging? and see also my answer.
A slight variation: If you run a Flask application, you can do this:
#app.errorhandler(Exception)
def exception_logger(error):
"""Log the exception."""
logger.exception(str(error))
return str(error)

How can I get the traceback object ( sys.exc_info()[2] , same as sys.exc_traceback ) as a string?

I have a function which catches all exceptions, and I want to be able to get the traceback as a string within this function.
So far this is not working:
def handle_errors(error_type, error_message, error_traceback):
"""catch errors"""
import traceback
error = {}
error['type'] = error_type.__name__
error['message'] = str(error_message)
error['file'] = os.path.split(error_traceback.tb_frame.f_code.co_filename)[1]
error['line'] = error_traceback.tb_lineno
error['traceback'] = repr(traceback.print_tb(error_traceback))
### finalise error handling and exit ###
sys.excepthook = handle_errors
It's the error['traceback'] line which is wrong. Do i even need to use the traceback module?
As per this other vaguely similar question, I have tried:
error['traceback'] = repr(error_traceback.print_exc())
...but this gives an error:
Error in sys.excepthook:
Traceback (most recent call last):
File "xxxxxxxxxxx", line 54, in handle_errors
error['traceback'] = repr(error_traceback.print_exc())
AttributeError: 'traceback' object has no attribute 'print_exc'
Use traceback.format_tb() instead of print_tb() to get the formatted stack trace (as a list of lines):
error['traceback'] = ''.join(traceback.format_tb(error_traceback))
print_tb() directly prints the traceback, that's why you get None as a result (that's the default for any Python function that doesn't return anything explicitely).
traceback.format_exc([limit])
This is like print_exc(limit) but
returns a string instead of printing to a file.
New in version 2.4.
error['traceback'] = traceback.format_exc(error_traceback)

renderContents in beautifulsoup (python)

The code I'm trying to get working is:
h = str(heading)
# '<h1>Heading</h1>'
heading.renderContents()
I get this error:
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
print h.renderContents()
AttributeError: 'str' object has no attribute 'renderContents'
Any ideas?
I have a string with html tags and i need to clean it if there is a different way of doing that please suggest it.
Your error message and your code sample don't line up. You say you're calling:
heading.renderContents()
But your error message says you're calling:
print h.renderContents()
Which suggests that perhaps you have a bug in your code, trying to call renderContents() on a string object that doesn't define that method.
In any case, it would help if you checked what type of object heading is to make sure it's really a BeautifulSoup instance. This works for me with BeautifulSoup 3.2.0:
from BeautifulSoup import BeautifulSoup
heading = BeautifulSoup('<h1>heading</h1>')
repr(heading)
# '<h1>heading</h1>'
print heading.renderContents()
# <h1>heading</h1>
print str(heading)
# '<h1>heading</h1>'
h = str(heading)
print h
# <h1>heading</h1>

Python: TypeError: 'float' object is not callable

I am trying to join 2 strings using this code:
def __get_temp(self):
return float(self.ask('RS'))
def __set_temp(self, temp):
set = ('SS' + repr(temp))
stat = self.ask(set)
return self.check(stat)
temp = property(__get_temp, __set_temp)
Once together, I then send a signal over a serial bus using PyVisa. However, when I try to call the function, I get
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
chil.temp(13)
TypeError: 'float' object is not callable
I've tried looking around for explanation of this error, but none of them make any sense. Anyone know what is going on?
It looks like you are trying to set the property temp, but what you're actually doing is getting the property and then trying to call it as function with the parameter 13. The syntax for setting is:
chil.temp = 13

Categories