Convert .py to .exe including matplotlib code - python

I am trying to convert this code:
import pandas as pd
import matplotlib.pyplot as plt
import readTrc
path = 'C:/filepath/data.trc'
datX, datY, m = readTrc.readTrc(path)
srx, sry = pd.Series(datX * 1000), pd.Series(datY * 1000)
df = pd.concat([srx, sry], axis = 1)
df.set_index(0, inplace = True)
df.plot(grid = 1,
linewidth = 0.5,
figsize = (9,5),
legend = False,
xlim = (df.index[0] , df.index[-1]),
xticks = [-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9])
plt.xlabel('Zeit in ms')
plt.ylabel('Spannung in mV')
plt.savefig('test.png', dpi = 600)
into an executable with cx_Freeze.
Setup.py :
import cx_Freeze
import sys
import matplotlib
base = None
if sys.platform == "win32":
base = "Win32GUI"
executables = [
cx_Freeze.Executable("read_trc.py", base = base),
]
build_exe_options = {"includes":["matplotlib.backends.backend_tkagg"],
"include_files":[(matplotlib.get_data_path(), "mpl-data"),
('C:/filepath', 'data.trc')],
"excludes":[],
}
cx_Freeze.setup(
name = "script",
options = {"build_exe": build_exe_options},
version = "0.0",
description = "A basic example",
executables = executables)
The conversion works but when I try to run the .exe I get this error:
Is there a way to make this work? I am using Python 3.6 on Windows 10.
I have already tried the fixes found on Stackoverflow regarding Numpy import errors but it does not seem to help.
Edit:
Thanks to comments I solved the Error. Unfortunately now I get another Error when I try to execute the converted file:
Edit2:
I tried to include tkinter in my code but it doesn't work. I have a standard python 3.6 distribution installed which should include tkinter. tkinter.test() works. I assume that there is something wrong with the tkinter.ddls import. How would I do that correctly?
import cx_Freeze
import sys
import os
import matplotlib
os.environ['TCL_LIBRARY'] = r"C:\Users\Artur\AppData\Local\Programs\Python\Python36\DLLs\tcl86t.dll"
os.environ['TK_LIBRARY'] = r"C:\Users\Artur\AppData\Local\Programs\Python\Python36\DLLs\tk86t.dll"
base = None
if sys.platform == "win32":
base = "Win32GUI"
executables = [
cx_Freeze.Executable("plt_test.py", base = base),
]
include_files = [(matplotlib.get_data_path(), "mpl-data"),
('C:/Users/Artur/Desktop/Nellingen/Messdaten/20180104_Zyl_NiCr_DCneg_5bar_HSC/20180104_04_Zyl_NiCr_DCneg_5bar_170kV_HSC_Firefly/C220180104_ch2_UHF00000.trc',
'C220180104_ch2_UHF00000.trc'),
(r"C:\Users\Artur\AppData\Local\Programs\Python\Python36\DLLs\tcl86t.dll",
r"C:\Users\Artur\AppData\Local\Programs\Python\Python36\DLLs\tk86t.dll")]
build_exe_options = {"includes":["matplotlib.backends.backend_tkagg"],
"include_files":include_files,
"excludes":[],
"packages":["numpy", "matplotlib", "pandas", 'tkinter', 'os'],
}
cx_Freeze.setup(
name = "script",
options = {"build_exe": build_exe_options},
version = "0.0",
description = "A basic example",
executables = executables)
Output in windows console:

Related

Merge with Rasterio in Python 3.7

I am attempting to run this code:
# -*- coding: utf-8 -*-
"""
Created on Wed May 13 12:43:07 2020
#author: Matthew Farnham
"""
import gdal
import os.path
import rasterio
from rasterio.merge import merge
from rasterio.plot import show
import glob
import os
import numpy as np
with rasterio.Env(GDAL_TIFF_INTERNAL_MASK=True):
PIXELTYPE = 'DEFAULT',
TFW='YES'
directory = r"H:\Projects\Countries\USA\State\Washington_DC\DTM\LIDAR\Datagateway\Unzipped\elevation"
Output = r"E:\Previsico\PERM\Matthew\Previsico\7_Model_Workings\DEM_Mosaic\Data_Testing_Keep_empty\Trial1\Test3.tif"
search_criteria = "*.tif"
q = os.path.join(directory, search_criteria)
print(q)
dem_fps = glob.glob(q)
print(dem_fps)
Mosaic_files = []
for i in dem_fps:
src = rasterio.open(i)
Mosaic_files.append(src)
out_meta = src.meta.copy()
mosaic, out_trans = merge(Mosaic_files)
out_meta = src.meta.copy()
out_meta.update({"driver": "GTiff",
"height": mosaic.shape[1],
"width": mosaic.shape[2],
"transform": out_trans,
"crs":"+proj= unknown",
"BigTIFF" : "yes",
}
)
with rasterio.open(Output, "w", BigTIFF = 'YES', **out_meta) as dest:
dest.write(mosaic)
I am running it in Python 3.7 in a 64-bit environment. The error is:"MemoryError: Unable to allocate 17.4 GiB for an array with shape (1, 70544, 66261) and data type float32"
I am trying to mosaic (merge) raster files (.tif) to create a raster dataset comprising all of the individual raster files. Is there a way to get Python to write it first as opposed to storing everything to memory?
Thank you all for your help!

AttributeError: 'list' object has no attribute 'item' Ask

I am getting an unexpected error. I realize that there are posts with similar errors but either could not understand the answer or could not relate it to my case (dictionary).
I am trying to calculate a similarity score for each line of an input file and at every iteration (i.e for each line of input file) store the top 20 values of the score in a dictionary.
Following is my code:
import sys
from cx_Freeze import setup, Executable
includefiles = ['Arcade Funk.mp3', 'game over.wav', 'FrogTown.wav','pixel ufo.png','introBackground.png','pixel playButton.png','pixel instructionButton.png','pixel playButtonHighlighted.png','pixel instructionButtonHighlighted.png','instructionPage.png','crashBackground.png','space background long.png','pixel earth.png','pixel asteroid.png', 'pixel icon.png','Montserrat-ExtraBold.otf','Montserrat-Bold.otf','arial.ttf']
includes = []
excludes = ['Tkinter']
packages = ['pygame']
build_exe_options = {'includes':[includes],'packages':[packages], 'excludes':[excludes], 'include_files':[includefiles]}
base = None
if sys.platform == 'win64':
base = 'Win64GUI'
elif sys.platform == 'win32':
base = 'Win32GUI'
setup( name = 'Earth Invaders',
version = '0.1',
author = 'redacted',
description = 'Slider Game: Space',
options = {'build_exe': [build_exe_options]},
executables = [Executable('EarthInvaders.py', base=base)]
)
This is the error
Traceback (most recent call last):
File "C:/Users/Vix_Ox/Desktop/Earth Invaders/setup.py", line 21, in <module>
executables = [Executable('EarthInvaders.py', base=base)]
File "C:\Users\----\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\cx_Freeze\dist.py", line 349, in setup
distutils.core.setup(**attrs)
File "C:\Users\----\AppData\Local\Programs\Python\Python36-32\lib\distutils\core.py", line 108, in setup
_setup_distribution = dist = klass(attrs)
File "C:\Users\----\AppData\Local\Programs\Python\Python36-32\lib\site-packages\cx_Freeze\dist.py", line 24, in __init__
distutils.dist.Distribution.__init__(self, attrs)
File "C:\Users\----\AppData\Local\Programs\Python\Python36-32\lib\distutils\dist.py", line 237, in __init__
for (opt, val) in cmd_options.items():
AttributeError: 'list' object has no attribute 'items'
It looks like you've been following the documentation fine.
I think the issue is some extra square braces on line 20: [build_exe_options] should be build_exe_options. That variable is expected to be a dictionary, but it's getting a list, thus the error.
setup( name = 'Earth Invaders',
version = '0.1',
author = 'redacted',
description = 'Slider Game: Space',
options = {'build_exe': build_exe_options},
executables = [Executable('EarthInvaders.py', base=base)]
)
You may also find that you have to apply this retroactively to an earlier line, as they are already encapsulated in lists when they are declared:
build_exe_options = {'includes':includes,'packages':packages, 'excludes':excludes, 'include_files':includefiles}

Python mfc100u.dll error with cx_Freeze

I have made a python file and I want to convert it to an MSI file. Here is my code:
from cx_Freeze import *
includefiles=[]
excludes=[]
packages=["tkinter", "openpyxl"]
base = None
if sys.platform == "win32":
base = "Win32GUI"
shortcut_table = []
company_name = 'Bills Programs'
product_name = 'BananaCell'
msi_data = {"Shortcut": shortcut_table}
bdist_msi_options = { 'upgrade_code': '{Banana-rama-30403344939493}',
'add_to_path': False, 'initial_target_dir': r'[ProgramFilesFolder]\%s\%s' %
(company_name, product_name), }
setup(
version = "0.1",
description = "Lightweight excel comparing program",
author = "Bill",
name = "BananaCell",
options = {'build_exe': {'include_files':includefiles}, "bdist_msi": bdist_msi_options,},
executables = [
Executable(
script="comparing.py",
base=base,
shortcutName="BananaCell",
shortcutDir="DesktopFolder",
icon='icon.ico',
)
]
)
But when I run the following code, the installation completes but I get the following error message
What am I doing wrong? I have full access ti the directory. Any help would be greatly appreciated.

rpy2 zoo unused argument

I've been recently trying to use rpy2 and import zoo library into python.
however, when I run the following sets of code, I receive the following error
from rpy2.robjects.packages import importr
r_zoo = importr("zoo")
r_zoo.rollapply(ddf,FUN = r_func.fun1, width = 10, align = "left",by_column = True)
res = super(Function, self).call(*new_args, **new_kwargs)
rpy2.rinterface.RRuntimeError: Error in FUN(data[posns], ...) : unused
argument (by_column = TRUE)
The equivalent r code is
rollapply(ddf,FUN = r_func.fun1, width = 10, align = "left",by.column = True)
I understand that when we use the importr from rpy2.robjects.packages it automatically converts the '.' in Rlang to '_' in python.
Two ways to get around that problem:
Use a kwargs dict
r_zoo.rollapply(ddf,FUN = r_func.fun1, width = 10, align = "left",**{"by.column":True})
Explicitly specify that by_column is to be translated to by.column
from rpy2.robjects.functions import SignatureTranslatedFunction`
r_zoo.rollapply = SignatureTranslatedFunction(r_zoo.rollapply, init_prm_translate = {'by_column': 'by.column'})
Source

EXE with MatplotLib Crashes

I'm developing an application using Python 3.4 and PyQt4 with LiClipse as the IDE and have an issue with plotting graphs closing the entire program with no error after I've compiled the program into an executable. I've pin-pointed the problem area and know that calling matplotlib.figure.Figure() is the crash culprit but I don't know where to go from here.
import matplotlib
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
class GraphWidget(FigureCanvas):
def __init__(self,parent=None,width = 500, height = 600, dpi = 100):
self.width = width/dpi
self.height = height/dpi
self.dpi = dpi
#================crashes here=============#
self.figure = Figure((self.width,self.height), dpi=self.dpi)
#=========================================#
alert = QMessageBox()
alert.setText("Passed Figure()")
alert.exec_()
FigureCanvas.__init__(self,self.figure)
alert = QMessageBox()
alert.setText("Passed super init")
alert.exec_()
self.canvas = self
self.axis = self.figure.add_subplot(111)
self.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding)
self.parent = parent
def set_new_graph(self,data,labels):
self.layoutVert = QVBoxLayout(self)
size = QSize(self.width*self.dpi,self.height*self.dpi)
self.axis.hold(False)
mined = min(data.totalamount) - round(min(data.totalamount)*.1,0)
if mined > 0: mined = 0
maxed = max(data.totalamount) + round(max(data.totalamount)*.1,0)
if maxed == mined: maxed += 5
data.plot(x = data.totalamount
, ax = self.axis
, kind = 'bar'
, rot=0
, legend = False
, sharex = True
, sharey = True
# , xticks = labels
, ylim = (mined,maxed)
, table = False)
# self.axis.set_ylim(mined,maxed)
self.axis.set_xticklabels(labels, fontsize = 'small')
self.axis.set_title("Sales History over Past Year")
self.canvas.draw()
self.resize(size)
self.layoutVert.addWidget(self.canvas)
My py2exe setup script produces a usable executable for all functions except when a graph is initialized on the page:
mpld = matplotlib.get_py2exe_datafiles()
include = ['sip','pandas','reportlab'
, 'PyQt4'
, 'PyQt4.QtGui'
, 'PyQt4.QtCore'
, 'PyQt4.Qt'
,'reportlab.rl_settings','scipy','win32com'
,'win32com.client'
, 'matplotlib'
, 'matplotlib.backends'
, 'matplotlib.backends.backend_qt4agg'
, 'matplotlib.figure'
]
exclude = ['nbformat','win32com.gen_py',"six.moves.urllib.parse",
'_gtkagg', '_tkagg', '_agg2',
'_cairo', '_cocoaagg',
'_fltkagg', '_gtk', '_gtkcairo']
setup(name="ServiceMgmt",
# console based executables
console=[],
# windows subsystem executables (no console)
windows=['ServiceMgmt.py'],
# py2exe options
#zipfile=None,
options={"py2exe": py2exe_options},
data_files=mpld
)
I am able to run all other functions of my application in the executable but without issue. No visible error is shown, and the application works fine prior to compiling.
Thank you for your help.
My troubleshooting found numpy.core to be the culprit of my issue. I re-installed numpy and the executable runs properly now.

Categories