Cannot open Matplotlib figure in new Process on Mac - macos

If I try to launch a process that creates a matplotlib figure, the process hangs when trying to create the figure. Here is some code that reproduces the problem:
from matplotlib import pyplot as plt
from multiprocessing import Process
import numpy as np
def plotit():
data = np.cos(np.linspace(0, 10, 100))
print 'Gets Here'
plt.figure()
print 'But This is never printed.'
plt.plot(data)
plt.show()
def main():
p = Process(target=plotit)
p.start()
print raw_input('Press Enter when Done>>')
if __name__ == '__main__':
main()
The output from this is:
Press Enter when Done>>Gets Here
So it seems to freeze on plt.figure().
Note: The code seems to run fine on linux - it just fails on Mac! (My matplotlib backend is TkAgg in both cases). (Python 2.7.12, matplotlib 2.0.2., OSX Sierra 10.12)
Is there any way around this?

Related

difference between python2 and python3 in terms of multiprocessing?

So I had a paragraph of code "train.py" that goes like
do something
print('log something...')
do something else
and I used pytorch's multiprocessing toolbox
import torch.multiprocessing as mp
to execute multithreads of "train.py", however, the print function works well under python3, but not python2. Why?
so in python 2 multiprocessing, new process creation is by default fork() method and forking a multithreaded process could be problematic.
Pytorch uses multithreaded process and to do it safely they use the below-mentioned functionality of python 3
import multiprocessing as mp
def foo(q):
q.put('hello')
if __name__ == '__main__':
mp.set_start_method('spawn')
Note that above snippet will only work with python 3. They use method "set_start_method" and ask python interpreter to start a new process by using 'spawn' rather than 'fork'
As I said the above method only works in python 3's multiprocessing module and because python 2's multiprocessing module does not have "set_start_method", your code
import torch.multiprocessing as mp
might not work as expected. It does not give you an error but the results of the computation are not reliable
Although there are more differences, one of the main differences is the use of the with statement. An easy way to understand the difference is to see how to use multiprocessing using with for both Python 2 and Python 3. If you add (in Python 2 or 3):
# For python 2/3 compatibility, define pool context manager
# to support the 'with' statement in Python 2
if sys.version_info[0] == 2:
from contextlib import contextmanager
#contextmanager
def multiprocessing_context(*args, **kwargs):
pool = multiprocessing.Pool(*args, **kwargs)
yield pool
pool.terminate()
else:
multiprocessing_context = multiprocessing.Pool
After that, you can use multiprocessing the regular Python 3 way, regardless of which version of Python you are using. For example:
def _function_to_run_for_each(x):
return x.lower()
with multiprocessing_context(processes=3) as pool:
results = pool.map(_function_to_run_for_each, ['Bob', 'Sue', 'Tim']) print(results)
will work in Python 2 or Python 3.

How to open an image in Python

I am new to python. I am learning how to add images to my Tkinter file. However, when I try to run the following code, the interpreter returns the error: FileNotFoundError: [Errno 2] No such file or directory: lee.jpg
I hypothesize that I need a more specific path and have already ensured that both the file and image are in the same folder. Any explanations would be appreciated.
from tkinter import *
from PIL import ImageTk, Image
#Main Window
window = Tk()
window.title("Join")
window.geometry("800x600")
window.configure(background='white')
path = "lee.jpg" # I believe this is causing issues
#Makes image Tkinter-compatible
img = ImageTk.PhotoImage(Image.open(path))
panel = Label(window, image=img)
panel.pack(side="bottom", fill="both", expand="yes")
#Start
window.mainloop()
This is actually pretty simple and can be achieved with the below:
from tkinter import * #imports tkinter
root = Tk() #establishes root as the Tk window
image = PhotoImage(file="lee.jpg") #imports image from file
label = Label(root, image=image) #creates a Label object containing the image
label.pack() #packs the Label into the Tk window
root.mainloop() #starts event loop
This is probably the simplest way to achieve the desired result.
If you're new to Python I would suggest a free tutorial rather than Stack Overflow, and if you're new to tKinter then http://effbot.org/tkinterbook is your friend.
you can use pillow module
from PIL import Image
img = Image.open(r'path/to/file.png')
img.show()
i hope this helps....

Not able to get output with Pythons multiprocessing

so I am trying to delve into multiprocessing with python. I went to the python 3 website, to see some example code, and they have this:
from multiprocessing import Process
def f(name):
print('hello', name)
if __name__ == '__main__':
p = Process(target=f, args=('bob',))
p.start()
p.join()
I put it in my IDE and ran it, but nothing happens. If I run the debugger, it takes me to the process, and I see that everything happens, but just running it does nothing. Can someone help me?
Same code is working here :http://ideone.com/9kcQru
from multiprocessing import Process
def f(name):
print('hello', name)
if __name__ == '__main__':
p = Process(target=f, args=('bob',))
p.start()
p.join()
output : hello bob
There is something wrong with your environment

why pool.map in python doesn't work

import multiprocessing as mul
def f(x):
return x**2
pool = mul.Pool(5)
rel = pool.map(f,[1,2,3,4,5,6,7,8,9,10])
print(rel)
When I run the program above, the application is stuck in a loop and can't stop.
I am using python 3.5 in windows, is there something wrong?
This is what I see on my screen:
I am new to finance data analysis; and I am trying to find out a way to solve the big data problem with parallel computing.
Its not working because you are typing the commands in a shell; try saving the code in a file and running it directly.
Don't forget to copy the code correctly, you were missing a very important if statement (see the documentation).
Save this to a file, for example example.py on the desktop:
import multiprocessing as mul
def f(x):
return x**2
if __name__ == '__main__':
pool = mul.Pool(5)
rel = pool.map(f,[1,2,3,4,5,6,7,8,9,10])
print(rel)
Then, open a command prompt and type:
python %USERPROFILE%\Desktop\example.py

Inserting Image using Class in Python 3.3.1

I am trying to insert an image(logo) in GIUs to display it in top left corner using grid and preferable in frame.
When I do this code without demonstrator then it works perfectly but as soon I put it in Demonstrator the image disappears. Any Suggestion?
class TaskGUI():
def __init__(self,master):
header = Frame(master, )
header.grid(row=2,column=1,sticky=W)
canvas= Canvas(header, bg= 'pink')
Label(header, bg= 'blue' ).grid(row=1)
canvas.grid(row=1,column=1)
imgLogo = PhotoImage(file = 'logo.gif' )
canvas.create_image(10,10, image= imgLogo, ancho= NW)
if __name__ == "__main__":
top =Tk()
top.geometry('10920x1080')
top.title("Stel")
top.grid()
app = TaskGUI(top)
top.mainloop()
I tried to use PIL libary but could not find any solution on this on either, I get this error:
from PIL import Image,ImageTk
File "C:\Program Files\Python\PIL\Image.py", line 57
except ImportError, v:
^
SyntaxError: invalid syntax
You are trying to run the code using Python 3 but PIL is only compatible with Python 2.
In Python 3 the syntax to catch an exception is except ImportError as v while it used to be except ImportError, v in Python 2. Note that changing this most likely won't help since there will be many other incompatible things within PIL.
However, Pillow is a compatible fork of PIL that is compatible with Python 3.

Resources