Avoiding side effects when running long-running scripts
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report
I have a script that generates 100+ designs in Fusion 360. I'm able to reduce the issue to the following.
import adsk.core, adsk.fusion, adsk.cam, traceback, time
app: adsk.core.Application = None
ui = adsk.core.UserInterface.cast(None)
def run(context):
global app
global ui
try:
app = adsk.core.Application.get()
ui = app.userInterface
project: adsk.core.DataProject = app.data.activeProject
folder = get_folder(project.rootFolder, "Folder1")
for n in range(1,1000):
adsk.doEvents()
name = 'Document{}'.format(n)
app.log(f'Creating document {name}.')
document = app.documents.add(adsk.core.DocumentTypes.FusionDesignDocumentType)
# TODO: Fill the gap
document.saveAs(name, folder, '', '')
wait_until_saved(document)
document.close(False)
except:
if ui:
ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
def wait_until_saved(document):
start_time = time.time()
end_time = start_time + 10
while not document.dataFile.isComplete and time.time() < end_time:
app.log('Waiting for save to finish.')
time.sleep(0.5)
adsk.doEvents()
app.log("Done")
def create_sub_folder(parent: adsk.core.DataFolder, name: str) -> adsk.core.DataFolder:
return parent and parent.dataFolders.add(name) or None
def get_folder(parent: adsk.core.DataFolder, name: str, create=True) -> adsk.core.DataFolder:
folders = parent and parent.dataFolders
folder = folders and folders.itemByName(name)
folder = folder or create and create_sub_folder(parent, name) or None
return folder
The challenge with this approach running Fusion 360 on macOS Monterey 12.1, is that despite Fusion 360 being full screen on one desktop, it will display this on the desktop you're working on, which in turn interferes with say reading this forum in a browser.
I have also found Fusion 360 to become unresponsive, and then subsequently crash even though the script has long been completed. I suspect the application may run out of memory if one doesn't close the documents.
What's the best approach to give Fusion 360 a fighting chance and avoid the display issues while the script is running.
I suspect the "time.Sleep" may block the UI. Perhaps it may be better for Fusion 360 to implement a sleep function on the app [app.Sleep(0.5)], or add some wait methods for long-running operations [e.g. doc.WaitToComplete() or doc.Sync()], or allow a script to run in its own background thread (which is what I did when I wrote software for OS/2 and Windows back in the day). I've coded a bit in .NET and love the await pattern the platform provides for async development.
https://wernerstrydom.com