Spyder plots non responding with the Tkinter backend - python-3.x

plotting under spyder 4 (and also after downgrading with 3) doesn't work. I am just doing:
data=[1,2,3]
plt.plot(data)
The output is a non-responding frame:
After forcing to close it, i get:
An error ocurred while starting the kernel
RROR:tornado.application:Exception in callback functools.partial(.advance_eventloop at 0x000001A802791318>)
Traceback (most recent call last):
File "path\anaconda3\lib\site‑packages\tornado\ioloop.py", line 743, in _run_callback
ret = callback()
File "path\anaconda3\lib\site‑packages\ipykernel\kernelbase.py", line 310, in advance_eventloop
eventloop(self)
File "path\anaconda3\lib\site‑packages\ipykernel\eventloops.py", line 232, in loop_tk
app.tk.createfilehandler(stream.getsockopt(zmq.FD), READABLE, notifier)
AttributeError: '_tkinter.tkapp' object has no attribute 'createfilehandler'
(where is replaced with path)
Any idea why?
(if relevant i am using windows, python3)
Edit
adding plt.show() alone doesn't make a difference to the output (still blank frame), but
thanks to Neven V. and other quests i added
root = tk.Tk()
def on_closing():
if messagebox.askokcancel("Quit", "Do you want to quit?"):
root.destroy()
root.protocol("WM_DELETE_WINDOW", on_closing)
root.mainloop()
then i see a plot where the frame is responding. But after clicking on quit, the process do not quit and i have to restart the kernel (the mainloop is halting it but without it i get the result: no plot), thus i tried:
plt.show(block=False)
plt.pause(0.001) # Pause for interval seconds.
input("hit[enter] to end.")
plt.close('all') # all open plots are correctly closed after each run
and see a plot but it is non responding also after hitting enter.

I was using a standalone Python (3.8.3) within Spyder (IPython 7.15.0), but it resolved when I reverted to the conda installation (Python 3.6.8, IPython 7.6.0). I'm not sure that helps though!

Related

Python "No module named mysql.connector" when running script on Raspberry Pi

I wrote a Python script to test the MariaDB package using Python-3.7.3 running on a Raspberry Pi 3. The script is shown below:
#============================================================================
# Test Snippet #1
import mysql.connector
from mysql.connector
import connect, errorcode, Error
############################################################################
# Begin execution here:
print (">> Program Start >>")
#---------------------------------------------------------------------------
# Connect to the test database:
try:
dbConn=\
connect (user='WebServer', password='$$$$$$$$', host='localhost', \
database='HamRadio')
except Error as err:
print ("! Error #", err.errno, \
" encountered when connecting to test database !")
#---------------------------------------------------------------------------
# Search the test table for certain entries:
curSel=dbConn.cursor ()
strStatement="SELECT * FROM HamRadio.Log WHERE Call_Sign like 'OK%' " + \
"ORDER BY Call_Sign"
try:
curSel.execute (strStatement)
except Error as err:
print ("! Error #", err.errno, " encountered when executing SELECT command !")
#---------------------------------------------------------------------------
# Display the rows selected:
for row in curSel:
print ("Row Contents=", row)
#---------------------------------------------------------------------------
# Close the database table:
curSel.close ()
If I execute this script using the Python3 IDE (Python shell), the script works correctly.
However, if I attempt to execute the same script from the command line:
pi#raspberrypi:~ $ sudo python TestSnippet_1.py
The following error message is displayed:
'''
Traceback (most recent call last):
File "TestSnippet_1.py", line 4, in <module>
import mysql.connector
ImportError: No module named mysql.connector*
'''
I suspect that the issue may be related to some sort of environment path but I lack the experience using Python in a Raspberry Pi environment to fully understand what is happening.
Any help would greatly be appreciated because I am at a standstill at this point.
After many hours of investigation, I determined that the cause of the error was the use of 'sudo' in the command line (which invokes a different set of path variables)!! Typing just: python TestSnippet_1.py instead of sudo python TestSnippet_1.py enables the program to execute with no errors!! Very subtle but very deadly!!

How can I open a file with its correct program (e.g. ".blend" with Blender and ".webloc" with Chrome) inside a Python program?

I'm working with IDLE on Mac and I'm trying to make a small program that opens a random file from a folder (it is actually a test for a bigger project). In the folder, I have many types of files like ".blend", ".m4a", ".py" and ".webloc" but I expect to have even more in the future. I would like my code to open a random one with their respective program (Blender, QuickTime Player, IDLE, Chrome...) but so far I have not found any way to do it. Is it possible? The most I've been able to do is open Google Chrome from my Windows computer. It doesn't work on my Mac (maybe because it is .app instead of .exe?) and I can only open programs, but not files. Here's the code I used for that:
import subprocess
subprocess.Popen(['C:\Program Files (x86)\Google\Chrome\Application\\chrome.exe', '-new-tab'])
When I enter that on Mac (but with the correct file path for Mac):
import subprocess
subprocess.Popen(['/Applications/Google Chrome.app', '-new-tab'])
It gives me this error (could it be because the file path is written incorrectly? I copied it with right-click on the Chrome file and clicking "copy as path"):
>>>
=============== RESTART: /Users/jaimewalter/Desktop/Test/Test3.py ==============
Traceback (most recent call last):
File "/Users/jaimewalter/Desktop/Test/Test3.py", line 3, in <module>
subprocess.Popen(['/Applications/Google Chrome.app', '-new-tab'])
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/subprocess.py", line 854, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/subprocess.py", line 1702, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
PermissionError: [Errno 13] Permission denied: '/Applications/Google Chrome.app'
>>>
And here's my code for the random file selector:
import random
files = ["Test1.blend", "Test2.m4a", "Test3.py", "Test4.webloc"]
open_this = random.choice (files)
print(open_this)
if open_this == "Test1.blend":
print("Opening Test1.blend")
#now it should open Test1.blend on a new Blender window (/Users/jaimewalter/Desktop/Test/Test1.blend)
elif open_this == "Test2.m4a":
print("Opening Test2.m4a")
#now it should open Test2.m4a on a new QuickTime Player window (/Users/jaimewalter/Desktop/Test/Test2.m4a)
elif open_this == "Test3.py":
print("Opening Test3.py")
#now it should open Test3.py on a new IDLE window or preferably runs the code inside directly it if that's possible (/Users/jaimewalter/Desktop/Test/Test3.py)
elif open_this == "Test4.webloc":
print("Opening Test4.webloc")
#now it should open Test4.webloc on a new Chrome or Safari window (/Users/jaimewalter/Desktop/Test/Test4.webloc)
What should I use to open the files inside the code? Thanks in advance
I already solved it. I used
import subprocess
subprocess.call(["open", "Test1.blend"])
I think with Linux it's xdg-open

How to recreate a stable environment (IPython) [duplicate]

plotting under spyder 4 (and also after downgrading with 3) doesn't work. I am just doing:
data=[1,2,3]
plt.plot(data)
The output is a non-responding frame:
After forcing to close it, i get:
An error ocurred while starting the kernel
RROR:tornado.application:Exception in callback functools.partial(.advance_eventloop at 0x000001A802791318>)
Traceback (most recent call last):
File "path\anaconda3\lib\site‑packages\tornado\ioloop.py", line 743, in _run_callback
ret = callback()
File "path\anaconda3\lib\site‑packages\ipykernel\kernelbase.py", line 310, in advance_eventloop
eventloop(self)
File "path\anaconda3\lib\site‑packages\ipykernel\eventloops.py", line 232, in loop_tk
app.tk.createfilehandler(stream.getsockopt(zmq.FD), READABLE, notifier)
AttributeError: '_tkinter.tkapp' object has no attribute 'createfilehandler'
(where is replaced with path)
Any idea why?
(if relevant i am using windows, python3)
Edit
adding plt.show() alone doesn't make a difference to the output (still blank frame), but
thanks to Neven V. and other quests i added
root = tk.Tk()
def on_closing():
if messagebox.askokcancel("Quit", "Do you want to quit?"):
root.destroy()
root.protocol("WM_DELETE_WINDOW", on_closing)
root.mainloop()
then i see a plot where the frame is responding. But after clicking on quit, the process do not quit and i have to restart the kernel (the mainloop is halting it but without it i get the result: no plot), thus i tried:
plt.show(block=False)
plt.pause(0.001) # Pause for interval seconds.
input("hit[enter] to end.")
plt.close('all') # all open plots are correctly closed after each run
and see a plot but it is non responding also after hitting enter.
I was using a standalone Python (3.8.3) within Spyder (IPython 7.15.0), but it resolved when I reverted to the conda installation (Python 3.6.8, IPython 7.6.0). I'm not sure that helps though!

I cant read the image file in the particular directory

I took some images in my camera and tried to resize them using opencv library but i think that i can't read the images I don't know the reason why.Thank you for the help in advance.
I have a python 3.8 version and the updated opencv library version.Not much of a background I guess.
import os,cv2
count=0
for file in os.listdir('E:\Projects\Python\Resixing images\Images'):
if file.endswith('.jpg'):
print(file)
img=cv2.imread(file)
img2=img.copy()
img2=cv2.resize(img2,(700,700))
name="resize"+str(count)+".jpg"
cv2.imwrite(name,img2)
count+=1
I receive an error message
P_20191107_214848_SRES.jpg
Traceback (most recent call last):
File "E:\Projects\Python\Resixing images\image changing res.py", line 7, in
img2=img.copy()
AttributeError: 'NoneType' object has no attribute 'copy'
[Finished in 9.7s]
Try this:
img=cv2.imread('E:\Projects\Python\Resixing images\Images' + '\' + file)
The problem was that you were sending only the name of the file to the python program, so the program tried to look for the image in the current directory and not at your specified path. The above change should fix the problem.
also, a good idea would be to have 2 // instead of 1 /, just to avoid any format specifier in the middle of things, or you could just use r to mention the path to be raw string
img=cv2.imread('E:\\Projects\\Python\\Resixing images\\Images' + '\\' + file)
img=cv2.imread(r'E:\Projects\Python\Resixing images\Images\' + file)

AttributeError: 'Timer' object has no attribute '_seed'

This is the code I used. I found this code on https://github.com/openai/universe#breaking-down-the-example . As I'm getting error on remote manager so I have to copy this code to run it. But it still giving me error as below
import gym
import universe # register the universe environments
env = gym.make('flashgames.DuskDrive-v0')
env.configure(remotes=1) # automatically creates a local docker container
observation_n = env.reset()
while True:
action_n = [[('KeyEvent', 'ArrowUp', True)] for ob in observation_n] # your agent here
observation_n, reward_n, done_n, info = env.step(action_n)
env.render()
I'm getting this when try to run above script. I tried every possible way to solve it, but it still causing the same error. There is not even one thread about this. I don't know what to do now please tell me if anyone of you solved it.
I'm using Ubuntu 18.04 LTS on virtual box which is running on Windows 10
WARN: Environment '<class 'universe.wrappers.timer.Timer'>' has deprecated methods '_step' and '_reset' rather than 'step' and 'reset'. Compatibility code invoked. Set _gym_disable_underscore_compat = True to disable this behavior.
Traceback (most recent call last):
File "gymtest1.py", line 4, in <module>
env = gym.make("flashgames.CoasterRacer-v0")
File "/home/mystery/.local/lib/python3.6/site-packages/gym/envs/registration.py", line 167, in make
return registry.make(id)
File "/home/mystery/.local/lib/python3.6/site-packages/gym/envs/registration.py", line 125, in make
patch_deprecated_methods(env)
File "/home/mystery/.local/lib/python3.6/site-packages/gym/envs/registration.py", line 185, in patch_deprecated_methods
env.seed = env._seed
AttributeError: 'Timer' object has no attribute '_seed'
So I think what you need to do add a few lines in the Timer module because the code checks whether the code implements certain functions (_step, _reset, _seed, etc...)
So all you need to do (I think) is add at the end of the Timer class:
def _seed(self, seed_num=0): # this is so that you can get consistent results
pass # optionally, you could add: random.seed(random_num)
return

Resources