import camelot
import pandas as pd
import matplotlib
file = 'foo.pdf'
tables = camelot.read_pdf(file, pages='all', flavor='stream')
camelot.plot(tables[0], kind='text').show()
The matplot window opens and suddenly closes in a flash without any user input whatsoever.
I want the window to remain open to examine the contents.
Edit: I am using Windows 11 and Python 3.9, running the code on Pycharm and it's the system interpreter rather than a virtual environment.
Not sure if you ever found your answer, but I will attach what I have found from the following answer by swenzel: https://stackoverflow.com/a/33062819
The plot is opening in a non-blocking window which disappears as soon as the script finishes. You can override this by importing matplotlib and using plot.show(block=True) at the end to show the window as a blocking window, which will keep the script from continuing until closed. See his code snippet below.
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("table.csv")
values = df["blah"]
values.plot()
print 1
df['blahblah'].plot()
print 2
plt.show(block=True)
Your code rewritten would look like the following:
import camelot
import pandas as pd
import matplotlib.pyplot as plt
file = 'foo.pdf'
tables = camelot.read_pdf(file, pages='all', flavor='stream')
camelot.plot(tables[0], kind='text')
plt.show(block=True)
For example I am trying to import this function "load_modules() which is in a script called "setup.py" into another script using the code directly below.
def load_modules():
import cv2
import numpy as np
import pandas as pd
from scipy import ndimage
import os
from matplotlib import pyplot as plt
import matplotlib.image as mpimg
import time
import math
import random
from scipy.ndimage.interpolation import map_coordinates
from scipy.ndimage.filters import gaussian_filter
from setup import *
load_modules()
img = cv2.imread("image.jpg", 1)
The first two lines run fine so the files functions have been imported and there appears to be no issue running the load_modules() function however I get an error on the last line saying that cv2 is not defined.
I'm fairly new to python and looking for the best (most preferred) way to handle imports in a project.
I've been given the task to cleanup a python project and noticed there are the same includes in many modules throughout the project. Here is an example of what I am seeing.
File my_main_file.py
import os
import sys
import inspect
...
import gvars
import Common
...
from Tkinter import Menu
from Tkinter import WORD
from Tkinter import END
from Tkinter import Text
...
import menus.config
File gvars.py (also calls Tkinter)
from Tkinter import Text
from Tkinter import Tk
import Tkinter
File Common.py (also calls gvars and os)
import gvars
import tkFileDialog
import os
From Menus/config.py (also calls Common, gvars and Tkinter)
import Common
import gvars
import UIFunctions
import Tkinter
# Imports from Tk
from Tkinter import END
from Tkinter import Toplevel
from Tkinter import Button, Checkbutton
from Tkinter import Label
And on and on it goes... As you can see this is a mess I inherited. I know there are issue here (like "import blah" followed by "from blah import yuck"). I'm just looking for the most pythonic way to handle this.
Do I only need the imports in my_main_file.py? I.e. will Common.py code be able to access os. methods if "import os" is removed from the module and i=is only in the main script.
Is it best to have imports that are only referenced in a module imported in that module even though they are the similar? I.e. "from Tkinter import Text" in one module and "from Tkinter import END" in another.
Side question - which is better?
import Tkinter
or
from Tkinter import Menu
from Tkinter import WORD
from Tkinter import END
from Tkinter import Text
from Tkinter import Scrollbar
from Tkinter import Toplevel
from Tkinter import Button, Checkbutton
from Tkinter import Label
from Tkinter import Entry
from Tkinter import LEFT, RIGHT, TOP, BOTTOM
from Tkinter import DISABLED
from Tkinter import X, Y, BOTH
from Tkinter import VERTICAL, HORIZONTAL
from Tkinter import Listbox
from Tkinter import Frame, LabelFrame
from Tkinter import Entry
from Tkinter import N,S,E,W
from Tkinter import BROWSE, EXTENDED
from Tkinter import DISABLED, NORMAL
According to the PEP8 styleguide (one of the most authoritative sources on what is pythonic) using wildcard imports (from ... import *) should be avoided unless you are republishing an interface, which is not your intent.
My suggestion is to import TKinter as tk and refer to tk.WORD etc.
One of the reasons for doing this is that some of the constants and classes from Tkinter are fairly generically named - N, Button, etc.
By referring to tk.N, tk.Button, etc. it makes your intent in the code much clearer.
If one or two specific things are imported, then:
from Tkinter import END, Toplevel, ...
If pretty much everything in that module is imported, then:
from Tkinter import *
If more than a bunch of functions and classes are imported, then:
import Tkinter
Or more pythonic:
import Tkinter as tk
I am not sure if we can have common file to import all common modules. I think, for all of the files which you mentioned in question, you need to have separate imports.
About your side question, it is better to import specific function, method from class. You should import only those methods, functions which are being used in file. if you just do import Tkinter, then you have to use it like Tkinter.Menu, Tkinter.WORD etc in your code. Then it might be difficult to read if some library or module's functions have been used at lot of places in your file. So its better to import all required methods, functions from module and use them. You can import many functions from same library in one liner.
The way I've solved this in the past is to have an __init__.py file in each folder where the sources exist, then all your imports can go in there
There are even better ways of organizing python files. For more information on how to organize modules, see the official documentation
docs.python.org
stackoverflow
Also checkout importanize
Agree that from Tkinter import * is best avoided.
One way I found to deal with long imports on any given module. Not totally clean, but less wordy than the 1 per line repeats you have.
I would have done it with your TKinter import list, but I don't have it installed, so using sys instead.
#opening a parenthesis allows for implicit line feeds
from sys import (
stderr, stdout, stdin, #could have more...
#dont need this anymore
# maxint,
#maxsize, #dont this need anymore either
argv,
)
print globals().keys()
output:
['stdout', '__builtins__', '__file__', 'stdin', 'argv', '__package__', 'stderr', '__name__', '__doc__']
Is there a way to use and plot with opencv2 with ipython notebook?
I am fairly new to python image analysis. I decided to go with the notebook work flow to make nice record as I process and it has been working out quite well using matplotlib/pylab to plot things.
An initial hurdle I had was how to plot things within the notebook. Easy, just use magic:
%matplotlib inline
Later, I wanted to perform manipulations with interactive plots but plotting in a dedicated window would always freeze. Fine, I learnt again that you need to use magic. Instead of just importing the modules:
%pylab
Now I have moved onto working with opencv. I am now back to the same problem, where I either want to plot inline or use dedicated, interactive windows depending on the task at hand. Is there similar magic to use? Is there another way to get things working? Or am I stuck and need to just go back to running a program from IDLE?
As a side note: I know that opencv has installed correctly. Firstly, because I got no errors either installing or importing the cv2 module. Secondly, because I can read in images with cv2 and then plot them with something else.
This is my empty template:
import cv2
import matplotlib.pyplot as plt
import numpy as np
import sys
%matplotlib inline
im = cv2.imread('IMG_FILENAME',0)
h,w = im.shape[:2]
print(im.shape)
plt.imshow(im,cmap='gray')
plt.show()
See online sample
For a Jupyter notebook running on Python 3.5 I had to modify this to:
import io
import cv2
import numpy as np
from IPython.display import clear_output, Image, display
import PIL.Image
def showarray(a, fmt='jpeg'):
a = np.uint8(np.clip(a, 0, 255))
f = io.BytesIO()
PIL.Image.fromarray(a).save(f, fmt)
display(Image(data=f.getvalue()))
There is also that little function that was used into the Google Deepdream Notebook:
import cv2
import numpy as np
from IPython.display import clear_output, Image, display
from cStringIO import StringIO
import PIL.Image
def showarray(a, fmt='jpeg'):
a = np.uint8(np.clip(a, 0, 255))
f = StringIO()
PIL.Image.fromarray(a).save(f, fmt)
display(Image(data=f.getvalue()))
Then you can do :
img = cv2.imread("an_image.jpg")
And simply :
showarray(img)
Each time you need to render the image in a cell
I am unable to position a chart at a given location on the activesheet in excel from python code shown below. I can produce the chart but cannot control the placement location on the worksheet. I am an absolute beginner and may not have followed all the required conventions in the forum. Apologies. Vas
from __future__ import division
get_ipython().magic(u'matplotlib inline')
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
from sympy import *
from IPython.display import display as dsp
from IPython.display import Math, Latex
import xlwings as xw
plt.plot(psr,dphs)
plot = xw.Plot(fig)
#xlwings.shapes.shape.top = Range('A23') DID NOT WORK
plot.show('Plot1')
Currently, there's only a left and top position implemented in points:
plot.show('Plot1', left=10, top=30)
For xlwings >= v0.6.0, you can do:
plot.show('Plot1', left=Range('A1').left, top=Range('A1').top)
For xlwings <0.6.0, just follow the workarounds as described here:
The following shows the workaround applied to the picture object returned by the show method as alternative to setting it within the show method directly (Windows version):
pic = plot.show('Plot1')
pic.top = Range('A1').xl_range.Top
pic.left = Range('A1').xl_range.Left