This is a problem I've ran into several times, but never found a good way around it.
Let's say you have a script that does "stuff". Half way though the script, certail calls are made that generate nodes in the scene. After those nodes are generated, the scrip goes on to modify them. However, the nodes take some time to generate (3-10 seconds), and while they're being generated, the script keeps running, and then errors, since it's trying to act upon nodes that have yet to be made.
Solutions that don't work:
making a "sleep" system call before the nodes are made. This hangs the whole system, node generation included, so when the system comes back awake, it then starts to build the nodes and runing the rest of the script, resulting in the above mentioned problem.
using the mel timerX comand to actually compute a delay and make the script "pause". This has the exact same result as the sleep call, it pauses the whole system.
What to do? How can I make a script "wait" for part of it to finish before continuing on? I've added if(objExists) loops to test for whether or not the objects exist, but this puts the machine into an infinite loop, never actully allowing it to build the nodes.
In my current case, all via mel I'm opening a new scene, switching the renderer to mentalRay, and then assigning some mentalRay variables to the new MR nodes. MR nodes don't exist in a default scene upon open, but are built automatically when making Maya switch to the MR renderer.... but, generating those nodes can take 5 seconds or so, while the rest of the script that tries to change their attrs fails, since they don't exist yet. The whole thing has to be done without user input, since this will be batched over hundreds of files.