Запуск асинхронной функции в файле сценария FUSIONPython

Программы на Python
Ответить
Anonymous
 Запуск асинхронной функции в файле сценария FUSION

Сообщение Anonymous »

Я создаю файл сценария для использования в fusion 360, и когда я пытаюсь выполнить асинхронную функцию, обязательно возникают некоторые или другие ошибки.
Ниже приведена более простая версия одной из моих проблем:

Код: Выделить всё

`
# import Client.Client
import adsk.core, adsk.fusion, traceback
import asyncio
import math
import bleak

# Command properties
commandId = 'SetCameraAutoRotateCommand'
commandName = 'Auto Rotate Camera'
commandDescription = 'Automatically rotate the camera around all angles.'

app = adsk.core.Application.get()
ui = app.userInterface if app else None

# Global handlers to maintain references
eventHandlers = []

async def fu():
l = await bleak.BleakScanner.discover()
ui.messageBox("List of Devices: ")
s=repr(l)
# ui.messageBox("List of Devices: ")
ui.messageBox(s)

def auto_rotate_camera():
asyncio.run(fu())

# Command event handlers
class AutoRotateCommandExecuteHandler(adsk.core.CommandEventHandler):
def init(self):
super().init()

def notify(self, args):
try:
auto_rotate_camera()
except:
if ui:
ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

class AutoRotateCommandDestroyHandler(adsk.core.CommandEventHandler):
def init(self):
super().init()

def notify(self, args):
try:
adsk.terminate()
except:
if ui:
ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

class AutoRotateCommandCreatedHandler(adsk.core.CommandCreatedEventHandler):
def init(self):
super().init()

def notify(self, args):
try:
cmd = args.command
cmd.isRepeatable = False

# Event handlers
onExecute = AutoRotateCommandExecuteHandler()
cmd.execute.add(onExecute)
eventHandlers.append(onExecute)

onDestroy = AutoRotateCommandDestroyHandler()
cmd.destroy.add(onDestroy)
eventHandlers.append(onDestroy)

except:
if ui:
ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

def run(context):
try:
ui.messageBox("File #1")
cmdDef = ui.commandDefinitions.itemById(commandId)
if not cmdDef:
cmdDef = ui.commandDefinitions.addButtonDefinition(
commandId, commandName, commandDescription)

onCommandCreated = AutoRotateCommandCreatedHandler()
cmdDef.commandCreated.add(onCommandCreated)
eventHandlers.append(onCommandCreated)

inputs = adsk.core.NamedValues.create()
cmdDef.execute(inputs)

adsk.autoTerminate(False)

except:
if ui:
ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))`
Вот сообщение об ошибке

Код: Выделить всё

`bleak.exc.BleakError:  Thread is configured for Windows GUI but callbacks are not working.`
Вот полный журнал ошибок:

Код: Выделить всё

`Failed:
Traceback (most recent call last):
File "C:\Users\HOST_USER\AppData\Local\Autodesk\webdeploy\production\bce2902bbfcb27678033cbb9e17a3529631b97a7\Python\lib\site-packages\bleak\backends\winrt\util.py", line 166, in assert_mta
await event.wait()
File "C:\Users\HOST_USER\AppData\Local\Autodesk\webdeploy\production\bce2902bbfcb27678033cbb9e17a3529631b97a7\Python\lib\asyncio\locks.py", line 212, in wait
await fut
asyncio.exceptions.CancelledError

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "C:\Users\HOST_USER\AppData\Local\Autodesk\webdeploy\production\bce2902bbfcb27678033cbb9e17a3529631b97a7\Python\lib\site-packages\bleak\backends\winrt\util.py", line 165, in assert_mta
async with async_timeout(0.5):
File "C:\Users\HOST_USER\AppData\Local\Autodesk\webdeploy\production\bce2902bbfcb27678033cbb9e17a3529631b97a7\Python\lib\asyncio\timeouts.py", line 115, in __aexit__
raise TimeoutError from exc_val
TimeoutError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:/Users/HOST_USER/AppData/Roaming/Autodesk/Autodesk Fusion 360/API/Scripts/file1/file1.py", line 37, in notify
auto_rotate_camera()
File "C:/Users/HOST_USER/AppData/Roaming/Autodesk/Autodesk Fusion 360/API/Scripts/file1/file1.py", line 28, in auto_rotate_camera
asyncio.run(fu())
File "C:\Users\HOST_USER\AppData\Local\Autodesk\webdeploy\production\bce2902bbfcb27678033cbb9e17a3529631b97a7\Python\lib\asyncio\runners.py", line 194, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\HOST_USER\AppData\Local\Autodesk\webdeploy\production\bce2902bbfcb27678033cbb9e17a3529631b97a7\Python\lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\HOST_USER\AppData\Local\Autodesk\webdeploy\production\bce2902bbfcb27678033cbb9e17a3529631b97a7\Python\lib\asyncio\base_events.py", line 687, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "C:/Users/HOST_USER/AppData/Roaming/Autodesk/Autodesk Fusion 360/API/Scripts/file1/file1.py", line 21, in fu
l = await bleak.BleakScanner.discover()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\HOST_USER\AppData\Local\Autodesk\webdeploy\production\bce2902bbfcb27678033cbb9e17a3529631b97a7\Python\lib\site-packages\bleak\__init__.py", line 320, in discover
async with cls(**kwargs) as scanner:
File "C:\Users\HOST_USER\AppData\Local\Autodesk\webdeploy\production\bce2902bbfcb27678033cbb9e17a3529631b97a7\Python\lib\site-packages\bleak\__init__.py", line 158, in __aenter__
await self._backend.start()
File "C:\Users\HOST_USER\AppData\Local\Autodesk\webdeploy\production\bce2902bbfcb27678033cbb9e17a3529631b97a7\Python\lib\site-packages\bleak\backends\winrt\scanner.py", line 225, in start
await assert_mta()
File "C:\Users\HOST_USER\AppData\Local\Autodesk\webdeploy\production\bce2902bbfcb27678033cbb9e17a3529631b97a7\Python\lib\site-packages\bleak\backends\winrt\util.py", line 168, in assert_mta
raise BleakError(
bleak.exc.BleakError: Thread is configured for Windows GUI but callbacks are not working.
`
Код asyncio правильно работает автономно, если он не запускается в файле сценария Fusion.

Подробнее здесь: https://stackoverflow.com/questions/793 ... cript-file
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»