py2exe single executable file doesn't work - python

I'm trying to generate a single executable file with py2exe, without dependencies. With a standard setup.py file and all dependencies the exe works but when I try to modify setup.py to generate a single exe, the .exe file is generated but when I click it doesn't work.
This is the code of my python script:
# ======== Select a directory:
import Tkinter, tkFileDialog
root = Tkinter.Tk()
dirname = tkFileDialog.askdirectory(parent=root,initialdir="/",title='Please select a directory')
if len(dirname ) > 0:
print "You chose %s" % dirname
# ======== Select a file for opening:
import Tkinter,tkFileDialog
import sys
import ntpath
import os
root = Tkinter.Tk()
file = tkFileDialog.askopenfile(parent=root,mode='rb',title='Choose a file')
if file != None:
reader = file
print type(str(reader.name))
output_name= os.path.splitext(os.path.basename(str(reader.name)))[0]
writer = open(output_name+'_Elaborata.txt','w')
count = 1
countbis = 0
index = 0
c = 0
listaindex = []
firstline = 1
flag = False
a = ''.join([chr(n) for n in range(256)])
b = ''.join([n for n in a if ord(n) >= 32 and ord(n) <= 126])
c = ''.join([n for n in a if ord(n) < 32 or ord(n) > 126])
#print a
arraychar = []
#for n in range(256):
#if(n >= 32 and n <= 126):
# print n, chr(n)
#else:
#arraychar.append(chr(n))
result = "".join([(" " if n in c else n) for n in a if n not in c])
#print a
#print result
#print arraychar
listaelem=[]
with reader as f:
for _ in xrange(3):
next(f)
for line in f:
if('-------' in line):
continue
if(line.strip() != ''):
lista = line.split("|")
if(len(lista) != 10):
pass
#print len(lista), line.strip()
lista2 = []
for elem in lista:
#Pulitura singola linea da caratteri speciali
result = "".join([("" if n in c else n) for n in elem.strip() if n not in c])
lista2.append(result.strip())
if len(lista2) != 10:
#print line.strip()
pass
string = ""
for elem in lista2:
string += elem + "|"
writer.write(string[:-1]+"\n")
reader.close()
writer.close()
Which setup.py could be correct to generate only one .exe file?
this is the setup.py:
from distutils.core import setup
import py2exe, sys, os
sys.argv.append('py2exe')
setup(
options = {'py2exe': {'bundle_files': 1}},
windows = [{'script': "single.py"}],
zipfile = None,
)

Related

append dictionaries from csv file

The following code applies one update to my project.
tagPath = ["Package_PLC/Tags/CCN_CNV01_MX001_A_FLT"]
alarmConfig = {"BLD_CHN01_VS001_A_FLT_C":[["enabled","Value","0"]]}
system.tag.editAlarmConfig(tagPaths, alarmConfig)
I need to do this hundreds of times.
I am trying to build tagPath and alarmConfig dictionaries from a csv file.
Sample csv:
Equipment,Item Name,Alarm Tag,Alarm Name,Cluster Name,Category,Alarm Desc,Delay,Help,Comment,Variable Tag A,Variable Tag B,Custom 1,Custom 2,Custom 3,Custom 4,Custom 5,Custom 6,Custom 7,Custom 8,Paging,Paging Group,Area,Privilege,Historize,Project,SEQUENCE,TAGGENLINK,EDITCODE,LINKED
"","","BLD_CHN01_VS001_A_FLT_C","BLD_CHN01_VS001_A_FLT_C","","","Catch-up Conveyor / Chain Comms Fault","00:00:00","","BLD_CHN01_VS001_A_FLT_C","BLD_CHN01_VS001_A_FLT_C","KFS_ZNE02_WRM","STUN","","","","","","","","","","1","","","","","","",""
"","","BLD_CHN01_VS001_A_FLT_V","BLD_CHN01_VS001_A_FLT_V","","","Catch-up Conveyor / Chain VSD Fault","00:00:00","","BLD_CHN01_VS001_A_FLT_V","BLD_CHN01_VS001_A_FLT_V","","STUN","","","","","","","","","","1","","","","","","",""
"","","BLD_CHN01_VS001_S_HTY","BLD_CHN01_VS001_S_HTY","","","Catch-up Conveyor / Chain Cicuit Breaker","00:00:00","","BLD_CHN01_VS001_S_HTY","NOT BLD_CHN01_VS001_S_HTY","KFS_ZNE02_WRM","STUN","","","","","","","","","","1","","","","","","",""
This is what I have so far:
import system
import csv
path = system.file.openFile('csv')
if path != None:
print "path found"
f=open(path)
reader = csv.DictReader(f)
path1 = "Package_PLC/Tags/"
tagpath = []
alarmConfig = []
state = 0
comment = ""
for i in reader:
if row['Alarm Tag'] == 'ECN*' || 'FCN*' || 'PAC*':
tagpath.append(path1 + int(row['Alarm Tag']))
alarmname = row[Alarm Tag]
if row[Variable Tag A] == "NOT*":
state = 0
else:
state = 1
comment = row[Alarm Desc]
alarmConfig.append({alarmname: [["setpointA","Value",state],
["displayPath","Value","Packing"],
["notes","Value",comment]]
})
system.tag.editAlarmConfig(tagPaths, alarmConfig)
f.close()
The following error gets thrown.
Traceback (most recent call last):
File "<buffer>", line 28, in <module>
TypeError: list indices must be integers
This worked.
import string
import system
import csv
path = system.file.openFile('csv')
if path != None:
print "path found"
f=open(path)
reader = csv.DictReader(f)
path1 = "Package_PLC/Tags/"
tagpath = []
alarmConfig = {}
state = 0
readerlist = list(reader)
for stuff in readerlist:
if "PAC" in stuff['Alarm Tag'] or "ECN" in stuff['Alarm Tag'] or "CCN" in stuff['Alarm Tag'] or "FCN" in stuff['Alarm Tag'] :
tagpath = []
tagpath.append(str( path1 + stuff['Alarm Tag']))
if "NOT" in stuff['Variable Tag A']:
state = 0
else :
state = 1
display = ['displayPath','Value','Packing']
notes = ['notes','Value',str(stuff['Alarm Desc'])]
setpointA =['setpointA','Value', str(state)]
alarmConfig = {}
alarmConfig[stuff['Alarm Tag']] = [display,notes,setpointA]
system.tag.editAlarmConfig(tagpath, alarmConfig)
f.close()
It's difficult to help you because:
The sample file doesn't trigger anything
You didn't provide the system module
But still here's my attempt:
import os.path
import csv
input_file_name = 'Sample.csv'
if os.path.exists(input_file_name):
with open(input_file_name, newline='') as input_file:
events = csv.DictReader(input_file)
data_extracted = [
(
current_event['Alarm Tag'],
0 if current_event['Variable Tag A'].startswith('NOT') else 1,
current_event['Alarm Desc']
)
for current_event in events
if current_event['Alarm Tag'][:3] in ('ECN', 'FCN', 'PAC')
]
tag_paths = [f'Package_PLC/Tags/{x[0]}' for x in data_extracted]
alarm_config = {
alarm_name: [
['setpointA', 'Value', state],
['displayPath', 'Value', 'Packing'],
['notes', 'value', comment]
]
for (alarm_name, state, comment) in data_extracted
}
system.tag.editAlarmConfig(tag_paths, alarm_config)

Pyinstaller executable closes instantly

I need to create a one file portable executable. I wrote a python program for word suggestions and I wanted to build a one file executable for the program. I ran pyinstaller --F prog.py
However, the exe file built from this does not run and instead just shows a blank screen. My program:
import pandas as pd
import csv
import timeit
import copy
dictionary = {}
with open('EnglishDictionary.csv', mode='r') as infile:
reader = csv.reader(infile)
for rows in reader:
dictionary[rows[0]] = int(rows[1])
dictionary = dict(sorted(dictionary.items(), key=lambda x: x[1], reverse=True))
a = sorted(dictionary, key=dictionary.get, reverse=True)
def recommend(word):
global a
count = 0
num = len(word)
res = []
a = [i for i in a if i[:num]==word]
if len(a)>5:
return a[:5]
elif len(a)==0:
return ['No match found!']
else:
return a
word = ''
char = ''
while(1):
char = input("Enter character: ")[0]
if char=='#':
break
start_time = timeit.default_timer()
word+=char
x = recommend(word)
time = str(int((timeit.default_timer() - start_time)*(10**6)))+' microseconds'
for i in x:
if i!=x[-1]:
i+=','
print("{0: <10}".format(i),end=' ')
print(time)
if x[0]=='No match found!':
print("Exiting")
break
I'm new to building executables from python files. So if any other way to build that works would also be very helpful!
Link to CSV file: https://drive.google.com/file/d/12UJl_TjV_JlMVS9XCGLEXfboPXO4lMi3/view?usp=sharing

read multiple file and compare with the fixed files

I have 50 files in a directory that are suppose to compare with one file, e.g., original.txt. I have the following code. It works well when I give the file name one-by-one, manually. I want to automate it for this I used 'glob.blog'
folder = "files/"
path = '*.rbd'
path = folder + path
files=sorted(glob.glob(path))
Here the complete code:
import glob
from itertools import islice
import linecache
num_lines_nonbram = 1891427
bits_perline = 32
total_bit_flips = 0
num_bit_diff_flip_zero = 0
num_bit_diff_flip_ones = 0
folder = "files/"
path = '*.rbd'
path = folder + path
files=sorted(glob.glob(path))
original=open('files/mull-original-readback.rbd','r')
#source1 = open(file1, "r")
for filename in files:
del_lines = 101
with open(filename,'r') as f:
i=1
while i <= del_lines:
line1 = f.readline()
lineoriginal=original.readline()
i+=1
i=0
num_bit_diff_flip_zero = 0
num_bit_diff_flip_ones = 0
num_lines_diff =0
i=0
j=0
k=0
a_write2 = ""
while i < (num_lines_nonbram-del_lines):
line1 = f.readline()
lineoriginal = original.readline()
while k < bits_perline:
if ((lineoriginal[k] == line1[k])):
a_write2 += " "
else:
if (lineoriginal[k]=="0"):
#if ((line1[k]=="0" and line1[k]=="1")):
num_bit_diff_flip_zero += 1
if (lineoriginal[k]=="1"):
#if ((line1[k]=="0" and line1[k]=="1")):
num_bit_diff_flip_ones += 1
#if ((line1[k]==1 and line1[k]==0)):
#a_write_file2 = str(i+1) + " " + str(31-k) + "\n" + a_write_file2
#a_write2 += "^"
#num_bit_diff_flip_one += 1
# else:
# a_write2 += " "
k+=1
total_bit_flips=num_bit_diff_flip_zero+num_bit_diff_flip_ones
i+=1
k=0
i = 0
print files
print "Number of bits flip zero= %d" %num_bit_diff_flip_zero +"\n" +"Number of bits flip one= %d" %num_bit_diff_flip_ones +"\n" "Total bit flips = %d " %total_bit_flips
f.close()
original.close()
I got the error:
Traceback (most recent call last):
File "random-ones-zeros.py", line 65, in <module>
if ((lineoriginal[k] == line1[k])):
IndexError: string index out of range
I guess there is some issue with the reading the file automatically, instead giving name manually. But, didn't able to find the solution.
For this the string index is out of range because the value k is iterated once more than intended so the value of the variable exceeds the scope of the program. This should be able to be fixed by using substituting it to
if ((lineoriginal[k-1] == line1[k-1])):
Hope this helps, but I can't access Python right now so I can't test it out :-)

python scripts showing different result( with one error ) in two similar input files

The script, originally taken and modified from (http://globplot.embl.de/):
#!/usr/bin/env python
# Copyright (C) 2003 Rune Linding - EMBL
# GlobPlot TM
# GlobPlot is licensed under the Academic Free license
from string import *
from sys import argv
from Bio import File
from Bio import SeqIO
import fpformat
import sys
import tempfile
import os
from os import system,popen3
import math
# Russell/Linding
RL = {'N':0.229885057471264,'P':0.552316012226663,'Q':-0.187676577424997,'A':-0.261538461538462,'R':-0.176592654077609, \
'S':0.142883029808825,'C':-0.0151515151515152,'T':0.00887797506611258,'D':0.227629796839729,'E':-0.204684629516228, \
'V':-0.386174834235195,'F':-0.225572305974316,'W':-0.243375458622095,'G':0.433225711769886,'H':-0.00121743364986608, \
'Y':-0.20750516775322,'I':-0.422234699606962,'K':-0.100092289621613,'L':-0.337933495925287,'M':-0.225903614457831}
def Sum(seq,par_dict):
sum = 0
results = []
raws = []
sums = []
p = 1
for residue in seq:
try:
parameter = par_dict[residue]
except:
parameter = 0
if p == 1:
sum = parameter
else:
sum = sum + parameter#*math.log10(p)
ssum = float(fpformat.fix(sum,10))
sums.append(ssum)
p +=1
return sums
def getSlices(dydx_data, DOM_join_frame, DOM_peak_frame, DIS_join_frame, DIS_peak_frame):
DOMslices = []
DISslices = []
in_DOMslice = 0
in_DISslice = 0
beginDOMslice = 0
endDOMslice = 0
beginDISslice = 0
endDISslice = 0
for i in range( len(dydx_data) ):
#close dom slice
if in_DOMslice and dydx_data[i] > 0:
DOMslices.append([beginDOMslice, endDOMslice])
in_DOMslice = 0
#close dis slice
elif in_DISslice and dydx_data[i] < 0:
DISslices.append([beginDISslice, endDISslice])
in_DISslice = 0
# elseif inSlice expandslice
elif in_DOMslice:
endDOMslice += 1
elif in_DISslice:
endDISslice += 1
# if not in slice and dydx !== 0 start slice
if dydx_data[i] > 0 and not in_DISslice:
beginDISslice = i
endDISslice = i
in_DISslice = 1
elif dydx_data[i] < 0 and not in_DOMslice:
beginDOMslice = i
endDOMslice = i
in_DOMslice = 1
#last slice
if in_DOMslice:
DOMslices.append([beginDOMslice, endDOMslice])
if in_DISslice:
DISslices.append([beginDISslice,endDISslice])
k = 0
l = 0
while k < len(DOMslices):
if k+1 < len(DOMslices) and DOMslices[k+1][0]-DOMslices[k][1] < DOM_join_frame:
DOMslices[k] = [ DOMslices[k][0], DOMslices[k+1][1] ]
del DOMslices[k+1]
elif DOMslices[k][1]-DOMslices[k][0]+1 < DOM_peak_frame:
del DOMslices[k]
else:
k += 1
while l < len(DISslices):
if l+1 < len(DISslices) and DISslices[l+1][0]-DISslices[l][1] < DIS_join_frame:
DISslices[l] = [ DISslices[l][0], DISslices[l+1][1] ]
del DISslices[l+1]
elif DISslices[l][1]-DISslices[l][0]+1 < DIS_peak_frame:
del DISslices[l]
else:
l += 1
return DOMslices, DISslices
def SavitzkyGolay(window,derivative,datalist):
SG_bin = 'sav_gol'
stdin, stdout, stderr = popen3(SG_bin + '-D' + str(derivative) + ' -n' + str(window)+','+str(window))
for data in datalist:
stdin.write(`data`+'\n')
try:
stdin.close()
except:
print stderr.readlines()
results = stdout.readlines()
stdout.close()
SG_results = []
for result in results:
SG_results.append(float(fpformat.fix(result,6)))
return SG_results
def reportSlicesTXT(slices, sequence, maskFlag):
if maskFlag == 'DOM':
coordstr = '|GlobDoms:'
elif maskFlag == 'DIS':
coordstr = '|Disorder:'
else:
raise SystemExit
if slices == []:
#by default the sequence is in uppercase which is our search space
s = sequence
else:
# insert seq before first slide
if slices[0][0] > 0:
s = sequence[0:slices[0][0]]
else:
s = ''
for i in range(len(slices)):
#skip first slice
if i > 0:
coordstr = coordstr + ', '
coordstr = coordstr + str(slices[i][0]+1) + '-' + str(slices[i][1]+1)
#insert the actual slice
if maskFlag == 'DOM':
s = s + lower(sequence[slices[i][0]:(slices[i][1]+1)])
if i < len(slices)-1:
s = s + upper(sequence[(slices[i][1]+1):(slices[i+1][0])])
#last slice
elif slices[i][1] < len(sequence)-1:
s = s + lower(sequence[(slices[i][1]+1):(len(sequence))])
elif maskFlag == 'DIS':
s = s + upper(sequence[slices[i][0]:(slices[i][1]+1)])
#insert untouched seq between disorder segments, 2-run labelling
if i < len(slices)-1:
s = s + sequence[(slices[i][1]+1):(slices[i+1][0])]
#last slice
elif slices[i][1] < len(sequence)-1:
s = s + sequence[(slices[i][1]+1):(len(sequence))]
return s,coordstr
def runGlobPlot():
try:
smoothFrame = int(sys.argv[1])
DOM_joinFrame = int(sys.argv[2])
DOM_peakFrame = int(sys.argv[3])
DIS_joinFrame = int(sys.argv[4])
DIS_peakFrame = int(sys.argv[5])
file = str(sys.argv[6])
db = open(file,'r')
except:
print 'Usage:'
print ' ./GlobPipe.py SmoothFrame DOMjoinFrame DOMpeakFrame DISjoinFrame DISpeakFrame FASTAfile'
print ' Optimised for ELM: ./GlobPlot.py 10 8 75 8 8 sequence_file'
print ' Webserver settings: ./GlobPlot.py 10 15 74 4 5 sequence_file'
raise SystemExit
for cur_record in SeqIO.parse(db, "fasta"):
#uppercase is searchspace
seq = upper(str(cur_record.seq))
# sum function
sum_vector = Sum(seq,RL)
# Run Savitzky-Golay
smooth = SavitzkyGolay('smoothFrame',0, sum_vector)
dydx_vector = SavitzkyGolay('smoothFrame',1, sum_vector)
#test
sumHEAD = sum_vector[:smoothFrame]
sumTAIL = sum_vector[len(sum_vector)-smoothFrame:]
newHEAD = []
newTAIL = []
for i in range(len(sumHEAD)):
try:
dHEAD = (sumHEAD[i+1]-sumHEAD[i])/2
except:
dHEAD = (sumHEAD[i]-sumHEAD[i-1])/2
try:
dTAIL = (sumTAIL[i+1]-sumTAIL[i])/2
except:
dTAIL = (sumTAIL[i]-sumTAIL[i-1])/2
newHEAD.append(dHEAD)
newTAIL.append(dTAIL)
dydx_vector[:smoothFrame] = newHEAD
dydx_vector[len(dydx_vector)-smoothFrame:] = newTAIL
globdoms, globdis = getSlices(dydx_vector, DOM_joinFrame, DOM_peakFrame, DIS_joinFrame, DIS_peakFrame)
s_domMask, coordstrDOM = reportSlicesTXT(globdoms, seq, 'DOM')
s_final, coordstrDIS = reportSlicesTXT(globdis, s_domMask, 'DIS')
sys.stdout.write('>'+cur_record.id+coordstrDOM+coordstrDIS+'\n')
print s_final
print '\n'
return
runGlobPlot()
My input and output files are here: link
This script takes a input (input1.fa) and gives following output output1.txt
But when I try to run this script with similar type but larger input file (input2.fa) .. It shows following error:
Traceback (most recent call last):
File "final_script_globpipe.py", line 207, in <module>
runGlobPlot()
File "final_script_globpipe.py", line 179, in runGlobPlot
smooth = SavitzkyGolay('smoothFrame',0, sum_vector)
File "final_script_globpipe.py", line 105, in SavitzkyGolay
stdin.write(`data`+'\n')
IOError: [Errno 22] Invalid argument
I have no idea where the problem is. Any type of suggestion is appriciated.
I am using python 2.7 in windows 7 machine. I have also attached the Savitzky Golay module which is needed to run the script.
Thanks
UPDATE:
After trying to reproduce the error on linux it's showing a similar behavior, working fine with the first file but with the second is returning Errno32.
Traceback:
Traceback (most recent call last):
File "Glob.py", line 207, in <module>
runGlobPlot()
File "Glob.py", line 179, in runGlobPlot
smooth = SavitzkyGolay('smoothFrame',0, sum_vector)
File "Glob.py", line 105, in SavitzkyGolay
stdin.write(`data`+'\n')
IOError: [Errno 32] Broken pipe
Update:
Some calls of the SG_bin return that the -n parameter is the wrong type.
Wrong type of parameter for flag -n. Has to be unsigned,unsigned
This parameter comes from the window variable that is passed to the SavitzkyGolay function.
Surrounding the stdin.write with a trycatch block reveals that it breaks a hadnfull of times.
try:
for data in datalist:
stdin.write(repr(data)+'\n')
except:
print "It broke"

PyInstaller fails to find fonts.json

I want to make a word cloud in Korean. My OS is Windows. I want to make the Python code into an exe file that can run at any desktop. I'm trying to use PyInstaller to make the exe file.
pyinstaller.exe --onefile --icon=Pikachu.ico wordcloud.py
But I get this error:
Traceback (most recent call last):
File "wordcloud.py", line 6, in <module>
File "C:\Users\Myungho Lee\Downloads\pyinstaller-develop\pyinstaller-develop\PyInstaller\loader\pyimod03_importers.py", line 389, in load_module
File "site-packages\pytagcloud\__init__.py", line 26, in <module>
IOError: [Errno 2] No such file or directory: 'C:\\Users\\Myungho Lee\\AppData\\Local\\Temp\\_MEI67722\\pytagcloud\\fonts\\fonts.json'
Failed to execute script wordcloud
This is my code: (wordcloud.py)
#-*- coding: utf-8 -*-
import fnmatch
import os
import random
from PyInstaller.utils.hooks import collect_data_files
import pytagcloud
import simplejson
from pytagcloud import LAYOUT_HORIZONTAL
# requires Korean font support
import csv
import pygame
def draw_cloud(tags, filename, fontname, size):
pytagcloud.create_tag_image(tags, filename, fontname = fontname, size = size, rectangular=True, layout=LAYOUT_HORIZONTAL)
r = lambda: random.randint(0,255)
color = lambda: (r(), r(), r())
fonts = pygame.font.get_fonts()
#datas = collect_data_files('fonts')
current_dir = os.path.dirname(os.path.abspath(__file__))
current_dir = current_dir.replace('\\', '/')
csv_dir = current_dir+"/csv/"
font_path = current_dir + "/fonts/"
print font_path
FONT_CACHE = simplejson.load(open(os.path.join(font_path, 'fonts.json'), 'r'))
print FONT_CACHE
path = csv_dir
file_list = [os.path.join(dirpath, f)
for dirpath, dirnames, files in os.walk(path)
for f in fnmatch.filter(files, '*.csv')]
for i in range(0, len(file_list)):
file_list[i] = file_list[i].replace('\\', '/')
file_list[i] = file_list[i].decode('cp949').encode('utf-8')
file_list[i] = unicode(file_list[i], 'utf-8')
tmp_str = file_list[i].split("/")
file_len = len(tmp_str)
for fileName in file_list:
with open(fileName, 'rb') as csvfile:
dic = []
count = False
reader = csv.reader(csvfile, delimiter = ',', quotechar = '|')
for row in reader:
try:
if(int(row[2]) > 500):
freq = int(int(row[2]) * 0.4)
count = True
elif(int(row[2]) > 400):
freq = int(int(row[2])*0.5)
count = True
elif(int(row[2])> 300):
freq = int(int(row[2]) * 0.6)
count = False
elif(int(row[2]) > 200):
freq = int(int(row[2])* 0.65)
count = False
elif(int(row[2]) > 100):
freq = int(int(row[2]) * 0.7)
count = False
else:
freq = int(int(row[2])* 0.75)
count = False
if(count):
sizediv = 3
else:
sizediv = 2
dic.append({'color': color(), 'tag': unicode(row[1], 'cp949'), 'size': freq/sizediv})
except:
continue
tags = dic
if (dic[0]['size'] > 70):
size = (600, 600)
elif (dic[0]['size'] > 60):
size = (550, 550)
elif (dic[0]['size'] > 50):
size = (450, 450)
elif (dic[0]['size'] > 40):
size = (400, 400)
elif (dic[0]['size'] > 30):
size = (350, 350)
cloudName = fileName.split('/csv/')[1]
cloudName = cloudName.split('.csv')[0]
dirName = fileName.split('/csv/')[0]
draw_cloud(tags, dirName + '/word_cloud/'+cloudName+ '.png', FONT_CACHE[0]['name'], size)

Categories