Thursday, December 29, 2011

Maya os.environ() for windows


In a way, os.environ is similar to setting a list: sys.append( 'D:/data/folder' ). Except that it is a list from a constant environment variable from the operating system instead of writing each data path. Though they do seem to be similar in practice but the os.eviron seem to have more flexible functionality: you can call each folder as a module you can access to. Let's say you have 3 files inside the D:/Data/Path/File system path: "Modules", "Systems" and "Utilities". And inside each of those folders are more files and python files, in this case, in file "Systems" I have a file called “Addons” and a python file called "utility" and I can access that file, and all other files without writing too much code.

For example:
In windows, you can set your environment variable by right-clicking My Computer > Properties > Advanced System Settings > Environment Variables. Click on New. You will get this window:
Variable Name:
Variable Value:

Set it to something like this:
Variable Name: MODULAR_PATH
Variable Value: D:\Data\Path\File
The variable value is your file path, just make sure to invert the slashes from " / " to " \ ."

Now that you have set your environment variable, you can go back to maya and type something like this:
import os
import maya.OpenMaya as om
import sys

try:
    rootPath= os.environ[' MODULAR_PATH ']
except:
    om.MGlobal.displayWarning( ' MODULAR_PATH  is not in environment.' )
    sys.exit()

else:
    import sys
    #print rootPath
    if not  rootPath in sys.path:
        sys.path.append(  rootPath )

    print 'Systems path appended -- >', sys.path

    import Systems.Addon.utility as util
    reload( util )
    util.run()

    import Modules.testPyCode as tpc
    reload( tpc )
    tpc.runAll()

    import Utilities.__init__A as init
    reload(init)
    init.initialize()

And so on and so forth. I believe this way is a much cleaner way to handle modules than by appending each directory to a list. My opinion.

P.S.
When I write python code, I always do 4 spaces for intentation.

No comments:

Post a Comment