No such file or directory error in python - python-2.7

In my python study,I meet a problem like this:
File "wfdbtools.py", line 418, in _getheaderlines
all_lines = open(hfile, 'r').readlines()
IOError: [Errno 2] No such file or directory: 'C:\\Users\\liujiankang\\Desktop\\\xe7\xa8\x8b\xe5\xba\x8f-1\\datafile\x03908522m\x03908522m_ECG.txt.hea'
the Corresponding code:
def check_qrs_detection():
from wfdbtools import rdsamp, rdann
import subprocess
test_record = 'C:\Users\liujiankang\Desktop\程序-1\datafile\3908522m\3908522m_ECG.txt'
qrslead = 2
data, info = rdsamp(test_record)
qrsdetector = QRSDetector(data, info['samp_freq'])
qrspeaks = qrsdetector.qrs_detect(qrslead)
print 'Found %s QRS complexes' %(len(qrspeaks))
qrsdetector.write_ann(os.path.abspath(test_record) + '.test')
ref_qrs = rdann(os.path.abspath(test_record), 'atr')
print ref_qrs.shape
print qrspeaks[:10]
print ref_qrs[:10, :1]
sigdata = data[:, qrslead]
pylab.plot(sigdata)
for r in qrspeaks:
pylab.plot(r, sigdata[r], 'xr')
for r in ref_qrs[:, 1]:
pylab.plot(r*info['samp_freq'], sigdata[r*info['samp_freq']], 'ob')
pylab.show()
if __name__ == '__main__':
check_qrs_detection()
test()
Since the code is copied from someone else,the original path which I suspected is follows:
test_record = '../samples/format212/100'`
What may be the problem?Thanks!

Related

Multiple time "Init failure" error witth attribute error "__dict__"

I have a bunch of code, Program is written in python2 and used old version of pymc. probably version2.x .
When i run
python run.py
the error i am facing
Init failure
Init failure
Init failure
Init failure
Init failure
Init failure
Init failure
Init failure
No previous MCMC data found.
Traceback (most recent call last):
File "run.py", line 106, in <module>
M=run_MCMC(ms)
File "run.py", line 94, in run_MCMC
mcmc = pm.MCMC(model, db=db, name=name)
File "/home/divyadeep/miniconda3/envs/detrital/lib/python2.7/site-packages/pymc/MCMC.py", line 90, in init
**kwds)
File "/home/divyadeep/miniconda3/envs/detrital/lib/python2.7/site-packages/pymc/Model.py", line 191, in init
Model.init(self, input, name, verbose)
File "/home/divyadeep/miniconda3/envs/detrital/lib/python2.7/site-packages/pymc/Model.py", line 92, in init
ObjectContainer.init(self, input)
File "/home/divyadeep/miniconda3/envs/detrital/lib/python2.7/site-packages/pymc/Container.py", line 605, in init
input_to_file = input.dict
AttributeError: 'NoneType' object has no attribute 'dict'`
I have tried to comment out some of 'init' in the program. but still not able to run.
the run.py is as
def InitExhumation(settings):
"""Initialize piece-wise linear exhumation model"""
#Check that erosion and age break priors are meaningful
if (settings.erate_prior[0] >= settings.erate_prior[1]):
print "\nInvalid range for erate_prior."
sys.exit()
if (settings.abr_prior[0] >= settings.abr_prior[1]):
print "\nInvalid range for abr_prior."
sys.exit()
#Create erosion rate parameters (e1, e2, ...)
e = []
for i in range(1,settings.breaks+2):
e.append(pm.Uniform("e%i" % i, settings.erate_prior[0], settings.erate_prior[1]))
#Create age break parameters (abr1, ...)
abr_i = settings.abr_prior[0]
abr = []
for i in range(1,settings.breaks+1):
abr_i = pm.Uniform("abr%i" % i, abr_i, settings.abr_prior[1])
abr.append(abr_i)
return e, abr
def ExhumationModel(settings):
"""Set up the exhumation model"""
#Check that error rate priors are meaningful
if (settings.error_prior[0] >= settings.error_prior[1]):
print "\nInvalid range for error_prior."
sys.exit()
err = pm.Uniform('RelErr',settings.error_prior[0],settings.error_prior[1])
#Closure elevation priors
hc_parms={'AFT':[3.7, 0.8, 6.0, 2.9], 'AHe':[2.2, 0.5, 3.7, 1.6]}
e, abr = InitExhumation(settings)
nodes = [err, e, abr]
hc = {}
for sample in settings.samples:
parms = e[:]
h_mu = np.mean(sample.catchment.z)
if sample.tc_type not in hc.keys():
hc[sample.tc_type] = pm.TruncatedNormal("hc_%s"%sample.tc_type, h_mu-hc_parms[sample.tc_type][0],
1/hc_parms[sample.tc_type][1]**2,
h_mu-hc_parms[sample.tc_type][2],
h_mu-hc_parms[sample.tc_type][3])
nodes.append(hc[sample.tc_type])
parms.append(hc[sample.tc_type])
parms.extend(abr)
if isinstance(sample, DetritalSample):
idx_i = pm.Categorical("Index_" + sample.sample_name, p = sample.catchment.bins['w'], size=len(sample.dt_ages))
nodes.extend([idx_i])
exp_i = pm.Lambda("ExpAge_" + sample.sample_name, lambda parm=parms, idx=idx_i: ba.h2a(sample.catchment.bins['h'][idx],parm))
value = sample.dt_ages
else:
idx_i = None
exp_i = pm.Lambda("ExpAge_" + sample.sample_name, lambda parm=parms: ba.h2a(sample.br_elevation,parm), plot=False)
value = sample.br_ages
obs_i = pm.Normal("ObsAge_" + sample.sample_name, mu = exp_i, tau = 1./(err*exp_i)**2, value = value, observed=True)
sim_i = pm.Lambda("SimAge_" + sample.sample_name, lambda ta=exp_i, err=err: pm.rnormal(mu = ta, tau = 1./(err*ta)**2))
nodes.extend([exp_i, obs_i, sim_i])
return nodes
def run_MCMC(settings):
"""Run MCMC algorithm"""
burn = settings.iterations/2
thin = (settings.iterations-burn) / settings.finalChainSize
name = "%s" % settings.model_name + "_%ibrk" % settings.breaks
attempt = 0
model=None
while attempt<5000:
try:
model = ExhumationModel(settings)
break
except pm.ZeroProbability, ValueError:
attempt+=1
#print "Init failure %i" % attemp
print "Init failure "
try:
#The following creates text files for the chains rather than hdf5
db = pm.database.txt.load(name + '.txt')
#db = pm.database.hdf5.load(name + '.hdf5')
print "\nExisting MCMC data loaded.\n"
except AttributeError:
print "\nNo previous MCMC data found.\n"
db='txt'
mcmc = pm.MCMC(model, db=db, name=name)
#mcmc.use_step_method(pm.AdaptiveMetropolis, M.parm)
if settings.iterations > 1:
mcmc.sample(settings.iterations,burn=burn,thin=thin)
return mcmc
if __name__ == '__main__':
sys.path[0:0] = './' # Puts current directory at the start of path
import model_setup as ms
if len(sys.argv)>1: ms.iterations = int(sys.argv[1])
M=run_MCMC(ms)
#import pdb; pdb.set_trace()
#Output and diagnostics
try:
ba.statistics(M, ms.samples)
except TypeError:
print "\nCannot compute stats without resampling (PyMC bug?).\n"
ps.chains(M, ms.finalChainSize, ms.iterations, ms.samples, ms.output_format)
ps.summary(M, ms.samples, ms.output_format)
ps.ks_gof(M, ms.samples, ms.output_format)
ps.histograms(ms.samples, ms.show_histogram, ms.output_format)
ps.discrepancy(M, ms.samples, ms.output_format)
## ps.unorthodox_ks(M, ms.output_format)
## try:
## ps.catchment(M.catchment_dem, format=ms.output_format)
## except KeyError:
## print "\nUnable to generate catchment plot."
M.db.close()
`

how to play background music in Asterisk AGI while some process is Going on in background to remove the silence during execution

I am using python 2 in asterisk 2 there is a section where code listen to callers audio and process the audio. During the process there is a silence of 15 sec before the audio is played. I want to add a music during the processing of audio. Is there a way to do this.
the extension.config is like this
[autoattendant2]
exten => 5555,1,same=>n,Answer()
same=> n, AGI(/root/code_base/Queue/code2.py)
same=>n,hangup()
Below is the python code
#!/usr/bin/env python2
import sys
import re
import time
import random
import subprocess
import requests
import json
from datetime import datetime
env = {}
tests = 0;
while 1:
line = sys.stdin.readline().strip()
if line == '':
break
key,data = line.split(':')
if key[:4] <> 'agi_':
#skip input that doesn't begin with agi_
sys.stderr.write("Did not work!\n");
sys.stderr.flush()
continue
key = key.strip()
data = data.strip()
if key <> '':
env[key] = data
sys.stderr.write("AGI Environment Dump:\n");
sys.stderr.flush()
for key in env.keys():
sys.stderr.write(" -- %s = %s\n" % (key, env[key]))
sys.stderr.flush()
def checkresult (params):
params = params.rstrip()
if re.search('^200',params):
result = re.search('result=(\d+)',params)
if (not result):
sys.stderr.write("FAIL ('%s')\n" % params)
sys.stderr.flush()
return -1
else:
result = result.group(1)
#debug("Result:%s Params:%s" % (result, params))
sys.stderr.write("PASS (%s)\n" % result)
sys.stderr.flush()
return result
else:
sys.stderr.write("FAIL (unexpected result '%s')\n" % params)
sys.stderr.flush()
return -2
def change_file(path, cid):
# one of the process example
filename = 'complain{0}'.format(cid)
#filename =
input_file = path + '/' + filename + '.gsm'
output_file = path + '/' + filename + '.wav'
#command = "sox {} -r 8000 -c 1 {}".format(input_file, output_file)
command = "sox {} -b 16 -r 44100 -c 1 {} trim 0 7 vol 2".format(input_file, output_file)
subprocess.call(command, shell=True)
pbcheck = requests.get("http://127.0.0.1:8000/STT_complaint/", params = {"address" : output_file, "lang" : language, "cid":cid, "phone":callerid, "start_time":now})
res = pbcheck.content
res2 = res.replace('"', "")
return res2
def run_cmd(cmd):
#This runs the general command
sys.stderr.write(cmd)
sys.stderr.flush()
sys.stdout.write(cmd)
sys.stdout.flush()
result = sys.stdin.readline().strip()
checkresult(result)
#language = "ben"
# asking problem recorded audio
cmd_streaming = "STREAM FILE /root/code_base/recorded_voices/{0}/plz_tell_problem \"\"\n".format(language, language)
run_cmd(cmd_streaming)
# listening to caller / recording caller voice
cmd_record = "RECORD FILE {0}/complain{1} gsm 1234 {2} s=3 \"\"\n".format(fixed_path, cid, 15)
run_cmd(cmd_record)
#processing audio
processed_output = change_file(path , cid) # while this is executing ad giving output i want to play wait_music and then stop to run
# while processing play this
cmd_streaming = "STREAM FILE /root/code_base/recorded_voices/wait_music \"\"\n".format(language, language)
run_cmd(cmd_streaming)
# once output received (processed_output) play next audio
cmd_streaming = "STREAM FILE /root/code_base/recorded_voices/next_instruction \"\"\n")
run_cmd(cmd_streaming)
For that asterisk AGI have the special command "SET MUSIC ON"
https://wiki.asterisk.org/wiki/display/AST/Asterisk+18+AGICommand_set+music
Set waiting tone for asterisk agi function processing

python - ZeroDivisionError

I created a script which copy data to specific location. What i tried to do is print a results via progress-bar. I tried to use package : -> https://pypi.python.org/pypi/progressbar2
Here is my code:
src = raw_input("Enter source disk location: ")
src = os.path.abspath(src)
dst = raw_input("Enter first destination to copy: ")
dst = os.path.abspath(dst)
dest = raw_input("Enter second destination to move : ")
dest = os.path.abspath(dest)
for dir, dirs, files in os.walk(src):
if any(f.endswith('.mdi') for f in files):
dirs[:] = [] # do not recurse into subdirectories
continue # ignore this directory
files = [os.path.join(dir, f) for f in files]
progress, progress_maxval = 0, len(files) pbar = ProgressBar(widgets=['Progress ', Percentage(), Bar(), ' ', ETA(), ],maxval=progress_maxval).start()
debug_status = ''
for list in files:
part1 = os.path.dirname(list)
part2 = os.path.dirname(os.path.dirname(part1))
part3 = os.path.split(part1)[1]
path_miss1 = os.path.join(dst, "missing_mdi")
# ---------first location-------------------#
path_miss = os.path.join(path_miss1, part3)
# ---------second location-------------------#
path_missing = os.path.join(dest, "missing_mdi")
try:
# ---------first location-------------------#
if not os.path.exists(path_miss):
os.makedirs(path_miss)
else:
pass
if os.path.exists(path_miss):
distutils.dir_util.copy_tree(part1, path_miss)
else:
debug_status += "missing_file\n"
pass
if (get_size(path_miss)) == 0:
os.rmdir(path_miss)
else:
pass
# ---------second location-------------------#
if not os.path.exists(path_missing):
os.makedirs(path_missing)
else:
pass
if os.path.exists(path_missing):
shutil.move(part1, path_missing)
else:
debug_status += "missing_file\n"
if (get_size(path_missing)) == 0:
os.rmdir(path_missing)
else:
pass
except Exception:
pass
finally:
progress += 1
pbar.update(progress)
pbar.finish()
print debug_status
When i tried to execute it i got error and My Traceback is below:
Traceback (most recent call last):
File "<string>", line 254, in run_nodebug
File "C:\Users\kostrzew\Desktop\REPORTS\ClassCopy\CopyClass.py", in <module>
pbar = ProgressBar(widgets=['Progress ', Percentage(), Bar(), ' ', ETA(),],maxval=progress_maxval).start()
File "C:\Users\kostrzew\Desktop\REPORTS\ClassCopy\progressbar\__init__.py", in start
self.update(0)
File "C:\Users\kostrzew\Desktop\REPORTS\ClassCopy\progressbar\__init__.py", line 283, in update
self.fd.write(self._format_line() + '\r')
File "C:\Users\kostrzew\Desktop\REPORTS\ClassCopy\progressbar\__init__.py", line 243, in _format_line
widgets = ''.join(self._format_widgets())
File "C:\Users\kostrzew\Desktop\REPORTS\ClassCopy\progressbar\__init__.py", line 223, in _format_widgets
widget = format_updatable(widget, self)
File "C:\Users\kostrzew\Desktop\REPORTS\ClassCopy\progressbar\widgets.py", in format_updatable
if hasattr(updatable, 'update'): return updatable.update(pbar)
File "C:\Users\kostrzew\Desktop\REPORTS\ClassCopy\progressbar\widgets.py", in update
return '%3d%%' % pbar.percentage()
File "C:\Users\kostrzew\Desktop\REPORTS\ClassCopy\progressbar\__init__.py", line 208, in percentage
return self.currval * 100.0 / self.maxval
ZeroDivisionError: float division by zero
I know that there is a problem with "maxval=progress_maxval" because it can't be devided by zero.
My qestion is ,how to change it? Should i create exception to ignore zero ? How to do it ?
I think inside the ProgressBar its trying divide to zero. It calculates like this:
max_value - 100%
progress_value - x and from this formula if we find x? will be this:
x = (100 * progress_value) / max_value
for this solution set 1 instead of 0 for max_value.

replacing specific lines in a text file using python

First of all I am pretty new at python, so bear with me. I am attempting to read from one file, retrieve specific values and overwrite old values in another file with a similar format. The format is 'text value=xxx' in both files. I have the first half of the program working, I can extract the values I want and have placed them into a dict named 'params{}'. The part I haven't figured out is how to just write the specific value into the target file without it showing up at the end of the file or just writing garbage or only half of the file. Here is my source code so far:
import os, os.path, re, fileinput, sys
#set the path to the resource files
#res_files_path = r'C:\Users\n518013\Documents\203-104 WA My MRT Files\CIA Data\pelzer_settings'
tst_res_files_path = r'C:\resource'
# Set path to target files.
#tar_files_path = r'C:\Users\n518013\Documents\203-104 WA My MRT Files\CIA Data\CIA3 Settings-G4'
tst_tar_files_path = r'C:\target'
#test dir.
test_files_path = r'C:\Users\n518013\Documents\MRT Equipment - BY 740-104 WA\CIA - AS\Setting Files\305_70R_22_5 setting files\CIA 1 Standard'
# function1 to find word index and point to value
def f_index(lst, item):
ind = lst.index(item)
val = lst[ind + 3]
print val
return val
# function 2 for values only 1 away from search term
def f_index_1(lst, item):
ind = lst.index(item)
val = lst[ind + 1]
return val
# Create file list.
file_lst = os.listdir(tst_res_files_path)
# Traverse the file list and read in dim settings files.
# Set up dict.
params = {}
#print params
for fname in file_lst:
file_loc = os.path.join(tst_res_files_path, fname)
with open(file_loc, 'r') as f:
if re.search('ms\.', fname):
print fname
break
line = f.read()
word = re.split('\W+', line)
print word
for w in word:
if w == 'Number':
print w
params['sectors'] = f_index(word, w)
elif w == 'Lid':
params['lid_dly'] = f_index(word, w)
elif w == 'Head':
params['rotation_dly'] = f_index(word, w)
elif w == 'Horizontal':
tmp = f_index_1(word, w)
param = int(tmp) + 72
params['horizontal'] = str(param)
elif w == 'Vertical':
tmp = f_index_1(word, w)
param = int(tmp) - 65
params['vertical'] = str(param)
elif w == 'Tilt':
params['tilt'] = f_index_1(word, w)
else:
print 'next...'
print params #this is just for debugging
file_tar = os.path.join(tst_tar_files_path, fname)
for lines in fileinput.input(file_tar, inplace=True):
print lines.rstrip()
if lines.startswith('Number'):
if lines[-2:-1] != params['sectors']:
repl = params['sectors']
lines = lines.replace(lines[-2:-1], repl)
sys.stdout.write(lines)
else:
continue
Sample text files:
[ADMINISTRATIVE SETTINGS]
SettingsType=SingleScan
DimensionCode=
Operator=
Description=rev.1 4sept03
TireDimClass=Crown
TireWidth=400mm
[TEST PARAMETERS]
Number Of Sectors=9
Vacuum=50
[DELAY SETTINGS]
Lid Close Delay=3
Head Rotation Delay=3
[HEAD POSITION]
Horizontal=140
Vertical=460
Tilt=0
[CALIBRATION]
UseConvFactors=0
LengthUnit=0
ConvMMX=1
ConvPixelX=1
CorrFactorX=1
ConvMMY=1
ConvPixelY=1
CorrFactorY=1
end sample txt.
The code I have only writes about half of the file back, and I don't understand why? I am trying to replace the line 'Number of Sectors=9' with 'Number of Sectors=8' if I could get this to work, the rest of the replacements can be done using if statements.
Please help! I've spent hours on google looking for answers and info and everything I find gets me close but no cigar!
Thank you all in advance!
your file has the '.ini' format. python supports reading and writing those with the ConfigParser module. you could do this:
# py3: from pathlib import Path
import os.path
import configparser
# py3: IN_PATH = Path(__file__).parent / '../data/sample.ini'
# py3: OUT_PATH = Path(__file__).parent / '../data/sample_out.ini'
HERE = os.path.dirname(__file__)
IN_PATH = os.path.join(HERE, '../data/sample.ini')
OUT_PATH = os.path.join(HERE, '../data/sample_out.ini')
config = configparser.ConfigParser()
# py3: config.read(str(IN_PATH))
config.read(IN_PATH)
print(config['CALIBRATION']['LengthUnit'])
config['CALIBRATION']['LengthUnit'] = '27'
# py3: with OUT_PATH.open('w') as fle:
with open(OUT_PATH, 'w') as fle:
config.write(fle)

Cannot Pool.map() function because of UnpickleableError?

So I am trying to multi process function F. Which is accessed by a button press with tkinter.
def f(x):
global doom,results,info
doom = doom + 1
if check(x) == True:
results.add(x)
info.append(get_column_number(x))
j.step(1)
texx = "1/"+doom
s.configure(text=texx)
root.update()
The function is called within a function like so:
def dojob():
index = ['URLS'...]
pool = Pool(processes=4)
s.configure(text="Shifting Workload to cores..")
root.update()
pool.map(f, index)
The button is inside root window.
I get the following error:
Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Python27\lib\threading.py", line 808, in __bootstrap_inner
self.run()
File "C:\Python27\lib\threading.py", line 761, in run
self.__target(*self.__args, **self.__kwargs)
File "C:\Python27\lib\multiprocessing\pool.py", line 342, in _handle_tasks
put(task)
UnpickleableError: Cannot pickle <type 'tkapp'> objects
I do not even know what a pickle does? Help?
Here is the complete code:
from Tkinter import *
from ttk import *
from tkMessageBox import showinfo
from multiprocessing import Pool
import random
emails = set()
import urllib2
import urllib2 as urllib
########
CONSTANT_PAGECOUNT = 20
######
def f(x):
global doom,emails,info
doom = doom + 1
if check(x) == True:
print "",
emails.add(x)
info.append(get_column_number(x))
j.step(1)
texx = "Sk1nn1n "+str(doom)+'/'+str(CONSTANT_PAGECOUNT)+""
s.configure(text=texx)
root.update()
return 0
def f(x):
print ""
def showFile(site,info):
top = Toplevel()
top.title('Sites')
x = Text(top)
x.pack()
i=0
for site_url in site:
x.insert(END,site_url)
i=i+1
def get_column_number(url):
return True
def check(url):
return True
def getgoogleurl(search,siteurl=False,startr=0):
if siteurl==False:
return 'http://www.google.com/search?q='+urllib2.quote(search)+'&start='+str(startr)+'&oq='+urllib2.quote(search)
else:
return 'http://www.google.com/search?q=site:'+urllib2.quote(siteurl)+'%20'+urllib2.quote(search)+'&oq=site:'+urllib2.quote(siteurl)+'%20'+urllib2.quote(search)
def getgooglelinks(search,siteurl=False,startr=0):
#google returns 403 without user agent
headers = {'User-agent':'Mozilla/11.0'}
req = urllib2.Request(getgoogleurl(search,siteurl,startr),None,headers)
site = urllib2.urlopen(req)
data = site.read()
site.close()
#no beatifulsoup because google html is generated with javascript
start = data.find('<div id="res">')
end = data.find('<div id="foot">')
if data[start:end]=='':
#error, no links to find
return False
else:
links =[]
data = data[start:end]
start = 0
end = 0
while start>-1 and end>-1:
#get only results of the provided site
if siteurl==False:
start = data.find('<a href="/url?q=')
else:
start = data.find('<a href="/url?q='+str(siteurl))
data = data[start+len('<a href="/url?q='):]
end = data.find('&sa=U&ei=')
if start>-1 and end>-1:
link = urllib2.unquote(data[0:end])
data = data[end:len(data)]
if link.find('http')==0:
links.append(link)
return links
def rip(results=15,accuracy=16):
global e
keyword = ''+str(e.get())
if keyword.strip()=="":
s.configure(text="Please enter a keyword")
root.update()
return 0
linklist = []
counter = 0
doom = 0
while counter < results:
links = getgooglelinks(keyword,startr=counter)
for link in links:
if len(linklist) > CONSTANT_PAGECOUNT:
s.configure(text="Proccessing..")
root.update()
return linklist
else:
doom = doom + 1
linklist.append(link)
texx = str(doom)+"/"+str(CONSTANT_PAGECOUNT)
s.configure(text=texx)
root.update()
root.update()
counter = counter+accuracy
return linklist
def flip():
global e
emails = set()
info = []
keyword = ''+str(e.get())
if keyword.strip()=="":
s.configure(text="Please enter a keyword")
root.update()
return 0
s.configure(text="Generating index..")
root.update()
doom = -1
index = rip(CONSTANT_PAGECOUNT,10)
if 1:
try:
pool = Pool(processes=4)
#s.configure(text="Shifting Workload to cores..")
#root.update()
pool.map(f, index)
pool.close()
except:
print "The errors there.."
j.config(value=CONSTANT_PAGECOUNT)
if len(emails) > 0:
filepath='relavant_list_'+str(random.randint(1,9999))+'.emList.txt'
#print len(emails),
#print "emails found."
ggg = open(filepath,'a+')
for x in emails:
ggg.write(x+"\n")
showinfo(
str(len(emails))+" key word related sites found!",
" sites are saved in "+str(filepath)
)
showFile(emails,info)
s.configure(text=filepath)
else:
s.configure(text='No related sites found : (')
if __name__ == '__main__':
### CONSTANTS
version = '1.0'
### END CONSTANTS
root = Tk()
root.title('Program v'+version)
s = Style()
s.theme_use('default')
#print s.theme_names()
s.configure("black.Horizontal.TProgressbar", foreground='blue', background='blue')
j = Progressbar(root, style="black.Horizontal.TProgressbar", orient="vertical", length=200, mode="determinate", maximum=CONSTANT_PAGECOUNT, value=0)
j.pack(side='right',fill='y')
f = Frame(root)
x = Frame(f)
e = Entry(x,width=51)
s = Label(x,width=50,anchor='center',text='Waiting for task..')
Button(f,text='Generate List!',width=50,command=flip).pack(fill='both',expand=True)
s.pack(side='bottom',fill='y',expand=True)
e.pack(side='top',fill='both',expand=True)
x.pack(side='top',fill='y',expand=True)
f.pack(side='left',expand=True,fill="both")
root.mainloop()
You are leaking a tkinter object. Most likely because you are trying to update the interface from another process with the last line of f()
Update based on code
You have a name collision between your function f() and a variable f in your __main__ which gets assigned to your main window and causes the tkapp pickle error. Rename the function to def myfunc() or something. Also need to call pool.join() after pool.close()