How to recreate a stable environment (IPython) [duplicate] - 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 xlwings: EventError: Command failed: Parameter error. (-50)

I wish I could use python to execute the Excel macro, so I tried to use the package xlwings to implement it.
The OS of my laptop is macOS Catalina (ver.: 10.15.7), my compiler is PyCharm (ver.: 2021.2.3), my Python version is 3.8.8, I used Anaconda (Ver.: 22.11.1) as my interpreter, my excel version is 16.66.1 (Microsoft Excel for Mac).
I faced the error "Command Error -1743: The User has declined permission" when I tried to use this package originally, and I solved this issue by installing an old compiler & using the old version of the compiler to run my code. My privacy setting for automation in the app Setting was shown below: (This is NOT the question I want to ask, but I'm not sure if it is also related to the issue I faced, so I still attached it here. I had uninstalled the old version of my compiler already.)
I wish I could implement an existing macro (called Hi) in an existing Excel file (called [StakeOverflow]HelloWorld.xlsm) through Python (represented as MY_PYTHON_FILE.py below), like the snapshot below:
My Excel file and my python code were stored on OneDrive. My macro code was shown below:
Sub Hi()
MsgBox "Good morning!"
End Sub
My python code was shown below:
import xlwings as xw
import time
wb = xw.Book('/Users/<MY NAME>/OneDrive/MY PATH DETAILS/[StakeOverflow]HelloWorld.xlsm')
time.sleep(10)
app = wb.app
macro_vba = app.macro("Hi")
macro_vba()
The code looks really simple, but I still faced the error. My Excel was not opened automatically, and I even could not open the Excel file manually thereafter. The error was shown below:
/Users/.../.conda/envs/Program/bin/python "/Users/.../OneDrive/.../MY_PYTHON_FILE.py"
Traceback (most recent call last):
File "/Users/.../.conda/envs/Program/lib/python3.9/site-packages/xlwings/main.py", line 4914, in open
impl= self.impl(name)
File "/Users/.../.conda/envs/Program/lib/python3.9/site-packages/xlwings/_xlmac.py", line 366, in __call__
raise KeyError(name_or_index)
KeyError: '[stakeoverflow] helloworld.xlsm'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/.../.conda/envs/Program/lib/python3.9/site-packages/aeosa/appscript/reference.py", line 482, in __call___
return self.AS_appdata.target().event (self._code, params, atts, codecs=self.AS_appdata).send(timeout, sendflags)
File "/Users/.../.conda/envs/Program/lib/python3.9/site-packages/aeosa/aem/aemsend.py", line 92, in send
raise EventError(errornum, errormsg, eventresult)
aem.aemsend.EventError: Command failed: Parameter error. (-50)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/.../OneDrive/.../MY_PYTHON_FILE.py", line 18, in <module>
wb = xw.Book('/Users/.../OneDrive/.../[stakeoverflow] helloworld.xlsm')
File "/Users/.../.conda/envs/Program/lib/python3.9/site-packages/xlwings/main.py", line 876, in __init__
impl= app.books.open(
File "/Users/.../.conda/envs/Program/lib/python3.9/site-packages/xlwings/main.py", line 4921, in open
impl = self.impl.open(
File "/Users/.../.conda/envs/Program/lib/python3.9/site-packages/xlwings/ xlmac.py", line 420, in open
self.app.xl.open_workbook(
File "/Users/.../.conda/envs/Program/lib/python3.9/site-packages/aeosa/appscript/reference.py", line 518, in __call__
raise CommandError(self, (args, kargs), e, self.AS_appdata) from e
appscript.reference.CommandError: Command failed:
OSERROR: -50
MESSAGE: Parameter error.
COMMAND: app(pid=1647).open_workbook (workbook_file_name='/users/.../onedrive/.../[stakeoverflow] helloworld.xlsm', update_links=k.do_not_update_links, read_only=None, format=None, password=None, write_reserved_password=None, ignore_read_only_recommended=None, origin=None, delimiter=None, editable=None, notify=None, converter=None, add_to_mru=None, timeout=-1)
Process finished with exit code 1
I tried to use terminal to run my python code, but I could not solve the problem, either.
I tried to open the Excel file manually thereafter, the error was shown below:
Excel cannot open the file ’[StakeOverflow]HelloWorld.xlsm’
because the file format or file extension is not valid. Verify
that the file has not been corrupted and that the file
extension matches the format of the file.
I tried to Google this error, but few solutions was found. It seems that it is related to the issue of external storage location. I tried to create another Excel file with the same name & macro code on my desktop and try again, and the error would disappear. (However, our company stored the files on OneDrive, so I wish I could utilise the file online.)
Just wondering if anyone here faced this situation before?
I found the answer by myself today. The issue is related to the naming issue rather than the permission issue.
As we could see that the error is KeyError: '[stakeoverflow] helloworld.xlsm', which implies that the problem is here. (Maybe because the system could not find the Excel file with this name.)
I tried to change the name from [stakeoverflow] helloworld.xlsm to helloworld.xlsm, and the error was gone. It seems that when xlwings want to open an Excel file, it would check the validity of the file name and change the name into smaller cases. If the file name contains special characters which are not allowed (e.g., "[]"), then the error would occur.
Notice that I could store the Excel file with these special characters in our laptop & OneDrive, but xlwings did not accept them.
Hope it is helpful to those who face this issue when using xlwings!

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

Spyder plots non responding with the Tkinter backend

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