Python Maya startup script

The order actually follows sys.path, you can actually find the userSetup.py behavior in maya.app.startup.basic.executeUserSetup, in fact if you need to rerun userSetup for some reason you can call that function and it will do so.

You are correct that this all runs well before the GUI.

However, I would do this a bit differently, instead of passing a string into executeDeferred you can hand it the function object and it will call it for you at the proper time. The nice thing about this is you can pass *args, **kwargs along with it.

import maya

def yourMethodName(standalone=False):
    #do python stuff here once GUIā€™s loaded.
    pass

maya.utils.executeDeferred(yourMethodName, standalone=True)
3 Likes

Thanks! Thatā€™s much cleaner. I was shown passing the method as a string, and assumed from lack of testing time, it was like old mel eval, and never questioned it this entire time.

(also looks like I need to learn how to format my responses on here for legibility)

Any other tricks for testing startup without shutting down maya and reopening it?

The best trick is to make sure that your startup proper is as short and simple as humanly possible. It should only handle making sure the rest of your code is available for import and then kickoff whatever code you need by calling a single function. Then you can test the pieces in isolation

2 Likes

Thanks that was super-useful(!) Iā€™m new to Python (& pipelines - just to pick up some skills on my own time).
I was having connection issues between PyCharm and Maya. It looks like userSetup.py was executing before the Maya interface was launching and therefore not getting the commandPort command. So I modified your code and it seems to work:

import maya
import maya.cmds as cmds

def pycharmConnect(standalone=False):
    
	if not cmds.commandPort(':4434', query=True):
	    cmds.commandPort(name=':4434')

maya.utils.executeDeferred(pycharmConnect, standalone=True)

Iā€™m having the same issue as you, I tried your code but itā€™s not working? Iā€™m using maya 2020, any clues on an updated code? I have the userSetup.py file on documents/maya/scripts and everything. If i launch the script on the console after maya opens it works, but trying to set it up with the userSetup.py code doesnt work, iā€™ve tried with the native one that mayacharm provides and yours.

Have you double checked you are using a compatible version of PyCharm?, many of the latest versions arenā€™t supported since PyCharm made the default Python interpreter become 3.0. (reference thread for information on this topic)