I'm trying to run the following code:
# To use interactive plots (mouse clicks, zooming, panning) we use the nbagg back end. We want our graphs
# to be embedded in the notebook, inline mode, this combination is defined by the magic "%matplotlib notebook".
%matplotlib notebook
import SimpleITK as sitk
%run update_path_to_download_script
from downloaddata import fetch_data as fdata
import gui
# Using an external viewer (ITK-SNAP or 3D Slicer) we identified a visually appealing window-level setting
T1_WINDOW_LEVEL = (1050,500)
When I run it in spider 3.2.6 I get:
ModuleNotFoundError: No module named 'gui'
Any help would be appreciated.
Code source: http://insightsoftwareconsortium.github.io/SimpleITK-Notebooks/Python_html/30_Segmentation_Region_Growing.html
This isn't a spyder issue.
The gui module is part of the notebooks repository. Either clone the repository or just download this file. Same goes for the downloaddata module.
Related
I'm running a script which imports a module from a file in the same directory. The first time I run the script after starting the cluster the script runs as expected. Any subsequent times I run the script I get the following error: ModuleNotFoundError: No module named 'ex_cls'
How do I get Ray to recognize modules I'm importing after the first run?
I am using Ray 1.11.0 on a redhat Linux cluster.
Here are my scripts. Both are located in the /home/ray_experiment directory:
--ex_main.py
import sys
sys.path.insert(0, '/home/ray_experiment')
from ex_cls import monitor_wrapper
import ray
ray.init(address='auto')
from ray.util.multiprocessing import Pool
def main():
pdu_infos = range(10)
with Pool() as pool:
results = pool.map(monitor_wrapper, [pdu for pdu in pdu_infos])
for pdu_info, result in zip(pdu_infos, results):
print(pdu_info, result)
if __name__ == "__main__":
main()
--ex_cls.py
import sys
from time import time, sleep
from random import randint
import collections
sys.path.insert(0, '/home/ray_experiment')
MonitorResult = collections.namedtuple('MonitorResult', 'key task_time')
def monitor_wrapper(args):
start = time()
rando = randint(0, 200)
lst = []
for i in range(10000 * rando):
lst.append(i)
pause = 1
sleep(pause)
return MonitorResult(args, time() - start)
-- Edit
I've found that by adding these two environment variables I no longer see the ModuleNotFoundError.
export PYTHONPATH="${PYTHONPATH}:/home/ray_experiment/"
export RAY_RUNTIME_ENV_WORKING_DIR_CACHE_SIZE_GB=0
Is there another solution that doesn't require disabling the working environment caching?
The issue here is that Ray's worker processes may be run from different working directories than your driver python script. In fact, on a cluster, they may even be run from different machines. This is coupled by the fact that python looks for the module based on a relative path (to be precise, cloudpickle serializes definitions in other modules by reference).
The "intended" solution to this problem is to use runtime environments.
In particular, you should do ray.init(address='auto', runtime_env={"working_dir": "./"}) when starting Ray to ensure that the module is passed to other processes.
After searching for similar error I found this in Ray docs:
https://docs.ray.io/en/latest/ray-core/handling-dependencies.html#library-development
Adding __init__.py to root of these directories and handing them over with this kwarg solved my issue with ModuleNotFoundError. Another part of solution is to install all requirements to the container the ray is running in and probably starting it in same workdir as app (or passing workdir in runtime kwargs)
To answer OPs problem I would try something like this:
import ex_cls
# it cannot pass classes, just whole module
ray.init(address='auto', runtime_env={"py_modules": [ex_cls]})
I made an executable gui (with tkinter) file using cx_freeze. The executable has several buttons. When the user click the button, the calculation should work and then it will write out an xlsx file.
Everything went good when I make the executable, there was no error. But when I click the button, it seems like the calculation works (since it was loading), but then it does not write out the xlsx file.
I don't know what went wrong. Anyone can help me?
Here's the setup.py file:
import sys
from cx_Freeze import setup, Executable
import os
import tkinter
base = None
if sys.platform == 'win32':
base = "Win32GUI"
executables = [Executable("gui.py", base=base)]
packages = ["tkinter", 'xlsxwriter', 'matplotlib']
options = {
'build_exe': {
'includes': ["os", "tkinter", 'numpy.core._methods', 'numpy.lib.format', 'xlrd', 'scipy', 'pandas'],
'include_files': [r"C:\Users\USERNAME\AppData\Local\Programs\Python\Python36-32\DLLs\tcl86t.dll",
r"C:\Users\USERNAME\AppData\Local\Programs\Python\Python36-32\DLLs\tk86t.dll"]
},
}
os.environ['TCL_LIBRARY'] = r'C:\Users\USERNAME\AppData\Local\Programs\Python\Python36-32\tcl\tcl8.6'
os.environ['TK_LIBRARY'] = r'C:\Users\USERNAME\AppData\Local\Programs\Python\Python36-32\tcl\tk8.6'
setup(
name="Tool",
version="1.0",
description="Tool prototype for calculating",
options=options,
executables=executables
)
I've solved the problem.
What i did was to change the base in setup.py to : base = None
and I installed the xlsxwriter by following this thread: ImportError: No module named 'xlsxwriter': Error in bamboo
After this, I encountered another problem:
No module named: scipy.sparse.csgraph._validation
but I simply add this to the 'includes': ['scipy.sparse.csgraph._validation', ...]
now everything works perfectly.
I hope this helps anyone who has the same problem.
I want to be able to graph using Matplotlib in Jython so that I can use ABAGAIL inside of Python.
ABAGAIL:
https://github.com/pushkar/ABAGAIL
Jython does not seem to support Matplotlib. But I found the following idea on how to call Python inside of Jython:
Invoking Jython from Python (or Vice Versa)
Unfortunately, I can't get the code they suggest to work:
import execnet
gw = execnet.makegateway("popen//python=python")
channel = gw.remote_exec("""
from numpy import *
a = array([2,3,4])
channel.send(a.size)
""")
for item in channel:
print item
The main problem is that python=python doesn't work. What I'm not understanding is how to actually specify the version of python (anaconda, actually) on my Windows 10 system. What do I need to setup?
Also, is there an alternative package besides matplotlib I can use with Jython to create graphs?
I'm currently following this link with a tutorial:
Here is the one I am following. The dude gives you the code. Have included it at the bottom anyway.
Would definitely recommend. But now facing issues:
Using Spyder 2.3.8
Python 3.5
Everything up to date
Have set the backend for Spyder to read matplotlib as 'TkAgg' (also took ages!).
Have hashtagged out the three lines which are causing the issue. Works fine when these lines aren't active. Activating them and running causes my terminal to crash and get the message:
It seems the kernel died unexpectedly. Use 'Restart kernel' to continue using this console.
I have really been looking everywhere for a solution. The objective is to get a chart into a Tkinter GUI without it crashing. Please help!?
Here is the code, nearly identical to the one provided in the link:
import matplotlib
#matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg,NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import tkinter as tk
import pandas as pd
from tkinter import ttk
LARGE_FONT=("Consolas",12)
class SeaofBTCapp(tk.Tk):
def __init__(self,*args,**kwargs):
#
#tk.Tk.wm_title(self,"")
print("")
tk.Tk.__init__(self,*args,**kwargs)
tk.Tk.wm_title(self,"Hold my Hand")
tk.Tk.iconbitmap(self,default="1.ico")
container=tk.Frame(self)
container.pack(side="top", fill="both",expand=True)
container.grid_rowconfigure(0,weight=1)
container.grid_columnconfigure(0,weight=1)
self.frames={}
for F in (StartPage,PageThree):
frame=F(container, self)
self.frames[F]=frame
frame.grid(row=0,column=0,sticky="nsew") #north south east west
self.show_frame(StartPage)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
def qf(stringtoprint):
print(stringtoprint)
class StartPage(tk.Frame):
def __init__(self,parent,controller):
ttk.Frame.__init__(self,parent)
label=ttk.Label(self,text="Testing",font=LARGE_FONT)
label.pack(pady=10,padx=10)
button3=ttk.Button(self, text="Graph page",
command=lambda:controller.show_frame(PageThree))
#lambda:controller.show_frame(PageOne))
button3.pack()
class PageThree(tk.Frame):
def __init__(self, parent, controller):
# app=tk.Tk()
tk.Frame.__init__(self,parent)
label=tk.Label(self,text="Graph Page",font=LARGE_FONT)
label.pack(pady=10,padx=10)
label1=ttk.Button(self, text="Start Page",
command=lambda:controller.show_frame(StartPage))
label1.pack()
label1=ttk.Button(self, text="Back to Home",
command=lambda:controller.show_frame(StartPage))
label1.pack()
# f=Figure(figsize=(5,5))
# a=f.add_subplot(111)
# a.plot([1,2,3,4,5,6,7,8],[5,6,7,8,1,2,2,1])
# canvas=FigureCanvasTkAgg(f,self)
# canvas.show()
# canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH,expand=True)
app=SeaofBTCapp()
app.mainloop()
It's the above three-six lines that cause Spyder to crash.
Uninstalling the conda version and installing it via pip fixes it.
There is an issue about that: https://github.com/ContinuumIO/anaconda-issues/issues/979
I was struggling with the same problem for a couple of days (Python 3.5.2/64-bit, matplotlib 1.5.1, Win 10 Professional). Reinstallation of matplotlib, tkinter and Python didn't help. Tkinter + matplotlib in Anaconda didn't work as well. Since I am not savvy enough to build matplotlib from the source, I just installed Ubuntu + Anaconda and it helped to solve the issue.
There is something wrong with the code you posted (i.e. indention etc.), I didn't try to fix it. But the following code is working on Ubuntu:
import matplotlib
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import tkinter as tk
fig = Figure()
plt = fig.add_subplot(111)
plt.plot([1, 2], [1, 2])
root = tk.Tk()
canvas = FigureCanvasTkAgg(fig, master=root)
canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
root.update()
root.mainloop()
I hope, it helped.
At long last(!) I've compiled Boost::Python and have gotten my XCode project to import a local module. This module starts with the line from xml.dom import minidom, but when it executes, I'm given this error:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "FeedStore.py", line 1, in <module>
from xml.dom import minidom
ImportError: No module named xml.dom
However, I know that I've installed the xml Python module -- when I open Python from my command prompt and type from xml.dom import minidom, everything goes smoothly. Moreover, when I import the module, it behaves as I would expect.
I suspected that there was something wrong with sys.path, so I compared the one I get from the prompt to the one that's being used in my embedded module. The only difference is that the embedded sys.path does not include ''. I've tried appending it, but that didn't change the behavior.
I also suspected that the embedded version was accessing a different version of Python than I was using from the prompt, but sys.prefix matched between both executions.
Here's the code that imports my module and runs it. It's pretty bare-bones at the moment (not even reference counting yet) because at this point I'd just like to make sure I'll be able to embed my module (I'm a total newbie C++ programmer).
Py_Initialize();
//PyRun_SimpleString("import sys");
//PyRun_SimpleString("sys.path.append('')"); //tried this to no avail!
PySys_SetPath("/Users/timoooo/Documents/Code/TestEmbed/"); //this allows me to import my local module
PyRun_SimpleString("import FeedStore as fs"); //here's where it whines about the lack of xml.dom
PyRun_SimpleString("store = fs.feedStore()");
PyRun_SimpleString("print store.next()");
Py_Finalize();
I'm probably misunderstanding something essential about boost::python. Can anyone help me out?
Despite having identical sys.path values, calling
PyRun_SimpleString("sys.path.append(\"<<path>>\")");
with the places I needed fixed the problem.