I'm very new to working on MacOS, but I need to make an app that Mac users can utilize. It's supposed to be a simple plug-and-play app, that is to say that I want to make sure that all they need to do is download the Mac executable file and then they can use the app freely. My app currently seems to be working perfectly fine, that is at least while I'm running the program using the PyCharm IDE, which is also where I compiled my code. This app works through the IDE on the original machine, as well as any other device that I can install the IDE and the other required packages (wand). However, when creating an app through py2app and running it, I get the following error:
avery#averys-MacBook-Air-2 Patents %
./dist/PatDrawDemo.app/Contents/MacOS/PatDrawDemo
Exception in Tkinter callback
Traceback (most recent call last):
File
"/usr/local/opt/python#3.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/tkinter/init.py",
line 1892, in call
return self.func(*args)
File "/Users/avery/Documents/Patents/PatDrawDemo.py", line
165, in get_input
fig_one(txt, int(ct))
File "/Users/avery/Documents/Patents/PatDrawDemo.py", line
105, in fig_one
fig1.save(filename='PatDrawFig1.png')
File
"/usr/local/opt/python#3.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/wand/image.py",
line 9892, in save
self.raise_exception()
File
"/usr/local/opt/python#3.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/wand/resource.py",
line 222, in raise_exception
raise e
wand.exceptions.CoderError: WriteBlob Failed `PatDrawFig1.png' #
error/png.c/MagickPNGErrorHandler/1713
I imagine that the error I'm getting is due to the path to which it's supposed to save to is invalid or unreachable or something of the sort, but then again I honestly don't know what the problem is. Any help would be greatly appreciated. If there's anything that is needed in addition to what I've posted, please let me know. Below is just a snippet of the code where 'PatDrawFig1.png' is saving.
def fig_one(full_text, ct):
target_width = 375
y_offset = 0
y_padding = 5
x_padding = 7
with Image(width=2000, height=5000, pseudo='xc:white') as fig1:
for match in find_matches(text=full_text):
with Drawing() as ctx:
ctx.font_size = 20
ctx.text_alignment = 'center'
words = match.split(" ")
word_count = len(words)
while True:
temp_text = rebuild_text(words, word_count, str(ct))
metrics = ctx.get_font_metrics(fig1, temp_text, multiline=True)
if metrics.text_width > target_width:
word_count -= 1
else:
text = temp_text
target_height = int(metrics.text_height + 1)
break
ctx.push()
ctx.fill_color = 'white'
ctx.stroke_width = 3
ctx.stroke_color = 'black'
ctx.rectangle(2, y_offset + y_padding, width=2*x_padding+target_width,
height=2*y_padding+target_height)
ctx.pop()
ctx.text(x_padding+3 + (target_width // 2), 10 + 4*y_padding+y_offset, text)
ctx(fig1)
y_offset += target_height + 4*y_padding - 2
ct += 2
fig1.trim()
fig1.save(filename='PatDrawFig1.png')
open_image('PatDrawFig1.png')
exit()
Also let me know if there's any other sort of clarification needed.
Related
Oh my python guys, please help me.
One of my python projects suddenly stopped working for no reason.
I'm using pytube module and when i try to run the code i get this error:
Traceback (most recent call last):
File "C:\Users\giova\AppData\Local\Programs\Python\Python39\lib\site-packages\pytube\contrib\search.py", line 94, in fetch_and_parse
sections = raw_results['contents']['twoColumnSearchResultsRenderer'][
KeyError: 'twoColumnSearchResultsRenderer' fetch_and_parse
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\giova\OneDrive\Desktop\Coding\Python\youtubeapp.py", line 38, in <module>
videoSearch()
File "C:\Users\giova\OneDrive\Desktop\Coding\Python\youtubeapp.py", line 21, in videoSearch
availableResults = len(vid.results)
File "C:\Users\giova\AppData\Local\Programs\Python\Python39\lib\site-packages\pytube\contrib\search.py", line 62, in results
videos, continuation = self.fetch_and_parse() results
File "C:\Users\giova\AppData\Local\Programs\Python\Python39\lib\site-packages\pytube\contrib\search.py", line 97, in fetch_and_parse fetch_and_parse
sections = raw_results['onResponseReceivedCommands'][0][
KeyError: 'onResponseReceivedCommands'
This is not even the only error i get, sometimes i got "http error 410: gone" error or some like this. I haven't changed the code for about two weeks (it was working two weeks ago) and it stopped working. I don't know what is happening to my code.
This is the full code:
from pytube import Search, YouTube
print("================================\n What do you want to do?: ")
availableChoose = [
'1 Search videos',
'...',
'================================'
]
for choose in availableChoose:
print(choose)
userChoose = input()
userChoose = userChoose.lower()
def videoSearch():
userSearch = input("Enter the title of the video you want to search: ")
vid = Search(userSearch)
availableResults = len(vid.results)
strAvailableResults = str(availableResults)
print("The available results are " + strAvailableResults)
vidResultsList = vid.results
vidResultsList = str(vidResultsList)
vidResultsList = vidResultsList.replace("<pytube.__main__.YouTube object: videoId=", "")
vidResultsList = vidResultsList.replace(">", "")
vidResultsList = vidResultsList.replace("[", "")
vidResultsList = vidResultsList.replace("]", "")
vidResultsList = vidResultsList.replace(" ", "")
vidResultsList = vidResultsList.split(',')
for vidResultsObject in vidResultsList:
vidLink = ("https://www.youtube.com/watch?v=" + vidResultsObject)
vidTempObject = YouTube(vidLink)
print(vidTempObject.title + " - " + vidLink)
if(userChoose == "search" or userChoose == "search video" or userChoose == "search videos" or userChoose == "1"):
videoSearch()
pytube's 11.0.0 API docs list the Search.fetch_and_parse() method.
The corresponding source-code shows that it internally handles a KeyError for onResponseReceivedCommands:
# Initial result is handled by try block, continuations by except block
try:
sections = raw_results['contents']['twoColumnSearchResultsRenderer'][
'primaryContents']['sectionListRenderer']['contents']
except KeyError:
sections = raw_results['onResponseReceivedCommands'][0][
'appendContinuationItemsAction']['continuationItems']
This method is an inner one, that is used by your vid.results call.
Might be, that the Youtube API has changed there response and your version of pytube is not fitting anymore.
Bug already filed
See pytube issue #1082 and issue #1106.
Meanwhile use another branch
tfdahlin's fork has a bugfixed version. It was already proposed as Pull-Request to the project:
PR #1090, opened on 2021-08-13 (currently waiting for approval).
I am also struggling to get around the search results provided by pytube Search module. Since search results are looking like objects, I was thinking (lazily) that I cannot convert the object list in to strings.
After modifying your function as below, the results are printed as youtube links.
'''
def videoSearch(search_list): #provide the search.results list as input
for result in search_list: #Begin video id extraction
result = str(result)
temp = result.replace("<pytube.__main__.YouTube object: videoId=", "")
temp = temp.split(',')[0] #get the correct video id
vidLink = ("https://www.youtube.com/watch?v=" + temp)
print(vidLink)
'''
Try it out.
I'm having a hard time here on processing GIS data in Python, using library ArcPy.
I've been trying to generate independent features from a feature class based on a field of the attribute table which is a unique code representing productive forest units, but I can't get it done.
I've already done this in other situations, but this time I don't know what I am missing.
Here is the code and the error I get:
# coding utf-8
import arcpy
arcpy.env.overwriteOutput = True
ws = r'D:\Projeto_VANT\SIG\proc_parc.gdb'
arcpy.env.workspace = ws
talhoes = r'copy_talhoes'
estados = ('SP', 'MG')
florestas = ('PROPRIA', 'PARCERIA')
arcpy.MakeFeatureLayer_management(talhoes,
'talhoes_layer',
""" "ESTADO" IN {} AND "FLORESTA" IN {} """.format(estados, florestas),
ws)
arcpy.FeatureClassToFeatureClass_conversion(in_features = 'talhoes_layer',
out_path = ws,
out_name = 'talhoes1')
talhoes1 = r'talhoes1'
arcpy.AddField_management(talhoes1, 'CONCAT_T', 'TEXT')
arcpy.CalculateField_management(talhoes1, 'CONCAT_T', """ [ESTADO] & "_" & [CODIGO] & "_" & [TALHAO] """, 'VB')
with arcpy.da.SearchCursor(talhoes1, ['CONCAT_T', 'AREA']) as tal_cursor:
for x in tal_cursor:
print(x[0] + " " + str(x[1])) # This print is just to check if the cursor works and it does!
arcpy.MakeFeatureLayer_management(x,
'teste',
""" CONCAT_T = '{}' """.format(str(x[0]))) # Apparently the problem is here!
arcpy.CopyFeatures_management('teste',
'Layer{}'.format(x[0]))
Here is the error:
Traceback (most recent call last):
File "D:/ArcPy_Classes/Scripts/sampling_sig.py", line 32, in <module>
""" CONCAT_T = '{}' """.format(str(x[0])))
File "C:\Program Files (x86)\ArcGIS\Desktop10.5\ArcPy\arcpy\management.py", line 6965, in MakeFeatureLayer
raise e
RuntimeError: Object: Error in executing tool
I think the issue is with your In feature. you will want your in feature to be talhoes1 since x is the cursor object and not a feature.
arcpy.MakeFeatureLayer_management(talhoes1,'teste',""" CONCAT_T =
'{}'""".format(str(x[0])))
I'm working on an excel/xlwings tool to practice my mental math, using old python scripts I used to run off a command line. When trying to run my VBA macro, I get the following error:
Traceback (most recent call last):
File "<string>", line 1, in <module>
ModuleNotFoundError: No module named 'Training_factoring'
I'll offer something of a checklist to give this request some context:
I'm using Anaconda3 and the spyder IDE
My PYTHONPATH is C:\Users\benms\Anaconda3, and my Interpreter path
is C:\Users\benms\Anaconda3\python.exe
My excel file is located in the same directory as my python module
I have imported the xlwings bas file
My RunPython call does follow the syntax guidelines from the docs, and my python module has the xw.Book.caller() piece per the docs
Here are my code samples:
VBA macro
Sub PracticeStart()
Dim i As Integer
Dim Response As Long
Do While True
RunPython ("import Training_factoring; Training_factoring.DistributionTwoDigit()")
Response = InputBox("Answer? ")
ActiveWorkbook.Worksheets("practice").Range(i + 2, 1).Value = Response
i = i + 2
Loop
End Sub
Python module
def DistributionTwoDigit():
wb = xw.Book.caller()
x = random.randrange(10, 99, 1)
y = random.randrange(10, 99, 1)
i = 0
i =+ 2
wb.sheets[0].range("A1").value = "Distribution (Two-Digit)"
wb.sheets[0].range(i+1,1).value = '{}*{}'.format(x, y)
RunAnswer()
wb.sheets[0].range(i+3,1).value = (x*y)
wb.sheets[0].range(i+4,1).value = '-------------------------------'
x = random.randrange(10, 90, 1)
y = random.randrange(10, 90, 1)
I had a Progress class that was working fine in 2.8.12.1 unicode:
class Progress(bolt.Progress):
"""Progress as progress dialog."""
def __init__(self,title=_(u'Progress'),message=u' '*60,parent=None,
style=wx.PD_APP_MODAL|wx.PD_ELAPSED_TIME|wx.PD_AUTO_HIDE|wx.PD_SMOOTH,
abort=False, onAbort=None):
if abort:
style |= wx.PD_CAN_ABORT
self.fnAbort = onAbort
self.dialog = wx.ProgressDialog(title,message,100,parent,style)
self.dialog.SetFocus() #### line 1295 in the traceback is here ####
bolt.Progress.__init__(self)
self.message = message
self.isDestroyed = False
self.prevMessage = u''
self.prevState = -1
self.prevTime = 0
(bolt.Progress has no wx in it)
In 3.02 however blows with:
Traceback (most recent call last):
...
File "bash\basher\__init__.py", line 2670, in _refresh_installers_if_needed
with balt.Progress(_(u'Refreshing Installers...'),u'\n'+u' '*60, abort=canCancel) as progress:
File "bash\balt.py", line 1295, in __init__
self.dialog.SetFocus()
File "C:\_\Python27\lib\site-packages\wx-3.0-msw\wx\_core.py", line 10129, in SetFocus
return _core_.Window_SetFocus(*args, **kwargs)
wx._core.PyAssertionError: C++ assertion "hWnd" failed at ..\..\src\msw\window.cpp(562) in wxWindow::SetFocus(): can't set focus to invalid window
Now can anyone spot what is invalid about this window ? As seen the Progress is instantiated in:
with balt.Progress(_(u'Refreshing Installers...'),u'\n'+u' '*60, abort=canCancel) as progress:
so parent is None - is it because of that ? However why the change in behavior in 3.0.2 ? EDIT: well no - passing a non None parent in makes no difference
Incidentally if I remove the SetFocus call it goes on to blow in another setFocus call later on:
def doProgress(self,state,message):
if not self.dialog:
raise StateError(u'Dialog already destroyed.')
elif (state == 0 or state == 1 or (message != self.prevMessage) or
(state - self.prevState) > 0.05 or (time.time() - self.prevTime) > 0.5):
self.dialog.SetFocus() #### blows here, this self.dialog is really, really invalid ####
if message != self.prevMessage:
ret = self.dialog.Update(int(state*100),message)
if not ret[0]:
if self.onAbort():
raise CancelError
else:
ret = self.dialog.Update(int(state*100))
if not ret[0]:
if self.onAbort():
raise CancelError
self.prevMessage = message
self.prevState = state
self.prevTime = time.time()
Not sure if all this hocus pocus is needed or if it could be simplified, but my immediate concern is why the window is invalid.
On Windows the ProgressDialog is now a stock common control (like MessageDialog, FileDialog, etc.) instead of a generic dialog implemented in wx like it used to be. So it is not a real native window any longer but just a wrapper around a platform API. So this means that it has no native window handle, and most non-ProgressDialog-specific APIs like SetFocus will not work.
I'm bukkit jython/python plugin programmer. Last few days, I'm struggling with this problem. I have to add an potion effect to an user, it's not problem if I enter effect name, duration and amplifier manually in code, but when I want to get them from config, I get this error:
13:38:20 [SEVERE] Could not pass event PlayerInteractEvent to ItemEffect v1.0
Traceback (most recent call last):
File "<iostream>", line 126, in onPlayerInteractEvent
TypeError: addPotionEffect(): 1st arg can't be coerced to org.bukkit.potion.Poti
onEffect
Here's that part of code:
effectname = section.getString("%s.effect"%currentKey)
duration = section.getInt("%s.duration"%currentKey)
durationinticks = duration * 20
geteffectname = "PotionEffectType.%s"%effectname
getpotioneffect = "PotionEffect(%s, %i, 1)"%(geteffectname, durationinticks)
geteffectname = "PotionEffectType.%s"%effectname
if iteminhand == currentKey:
event.getPlayer().addPotionEffect(getpotioneffect)
When I print getpotioneffect out, I get:
13:38:20 [INFO] PotionEffect(PotionEffectType.SPEED, 600, 1)
which is okay, and should work. I tested it without getting informations from config, and it works perfectly... To sum up, code above is not working, but below one works:
getpotioneffect = PotionEffect(PotionEffectType.SPEED, 600, 1)
if iteminhand == currentKey:
event.getPlayer().addPotionEffect(getpotioneffect)
Link to javadocs of this event!
http://jd.bukkit.org/rb/apidocs/org/bukkit/entity/LivingEntity.html#addPotionEffect(org.bukkit.potion.PotionEffect)
Thanks!
In your first snippet, getpotioneffect is a string. You can check it adding print type(getpotioneffect) somewhere.
What you want is to replace this :
geteffectname = "PotionEffectType.%s"%effectname
getpotioneffect = "PotionEffect(%s, %i, 1)"%(geteffectname, durationinticks)
with this:
effect_type = getattr(PotionEffectType, effectname)
potion_effect = PotionEffect(effect_type, durationinticks, 1)