Scripting in Maya through Python? Get used to a lot of string operations.

loocas | 3ds Max,maxscript,Maya,Python,technical | Wednesday, May 14th, 2008

Maya hypergraph banner

I find myself scripting in Maya more and more often. As I’ve expressed many times already, I really love and appretiate Python’s way of dealing with things, so having this language available in Maya is a blessing. The most beautiful part is when software actually does all the hard and annoying work for you ;) Scripting in Maya using Python hadn’t been designed the way it should be. Unfortunately, Python only serves as a “wrapper” around MEL commands and MEL architecture. Fortunately there are attempts at simplifying Python scripting in Maya, such as PyMEL from Luma Pictures (which is a studio I feel honored to cooperate with on The Nutcracker: The Untold Story), which is a fantastic “plug-in” for any Maya TD! which was, not surprisingly, done solely through Python itself :) A fantastic demonstration of Python’s power. However, PyMEL isn’t the topic for this short post, maybe later, when I get more familiar with it and gain more experience using it.

The main reason for getting used to working and parsing a lot of string data is, as stated above, because, by default, Python acts as sort of a “wrapper” around Maya’s native MEL language. You’ll be passing tons of string arguments and parameters to Maya’s Python interpreter, so knowing how to deal with long strings is a must. Today I was solving a trivial issue of assigning numerous texture inputs to quite a few tripleShadingSwitch objects for some complex material and shader definition. The whole, manual, procedure would have been very straight forward, but extremely tedious and time consuming. So, as a TD, I was asked to write a little script that’d do the trick with a very limited user input, which basically meant no UI, which is a good thing for a scripter. If you’ve done some UI coding, you know what I’m talking about, especially in connection to Maya ;)

In the end, I dealt with a lot of string variables that were passed throughout the script in Python. It’d have been a pain in the ass doing this sort of thing in MAXScript, as MAXScript isn’t very “string friendly”. I mean, of course there are various string functions available, but they don’t come even close to waht Python has to offer! A single Python module, called “string”, did all and much more I needed. For example, after importing the module, I was able to, very effectively, break a string down based on a keyword argument and separate individual words. While this concrete example is very easily doable in MAXScript, not so easily doable in MEL, there are many other examples that aren’t so easy to do in MAXScript or MEL in comparison to Python. One example for all. Let’s say you have to deal with namespaces. They usually occur in applications like Maya or MotionBuilder which preven users from naming individual objects the same name under the same level in a hierarchy. When you have multiple hierarchies, you may bump into objects with the same name. Maya will return the shortest namespace possible, so instead of returning a “Sphere1” it’ll return a “myHierarchy|secondLevel|thirdLeve|Sphere1” if multiple objects with this particular name exist in the scene. So, for whatever reason, what if you need to replace the specific namespace separator with something else? Here’s an example of a very long string of several words separated with a colon (as it’s a common character for identifyingnamespaces) that you want to replace by an underscore character, let’s say for compatibility reasons (say you want to pass this string to Max). Here’s how to do it in Python (including Python in Maya):

from string import *
aVeryLongString = "a:very:very:very:very:long:string:with:namespaces"
aNewString = replace(aVeryLongString,":","_")

the result: a_very_very_very_very_long_string_with_namespaces

Great! Only three lines of code and very little brain usage was actually needed to perform this task :) How about MAXscript? Well, MAXscript has a function called replace(), the problem is, it expects a string, a start position, a number of characters it should replace and an actual new string that’ll replace the old ones. Certainly usable, but very inconvenient, especially for casual or beginner scripters. How do you go about this limitation? You can’t import a “string” module or anything like that in MAXScript, so you have to write your own, custom, function to do that for you, which would be one of many ways to solve this little issue. For this example, I wrote a custom function that mimics Python’s replace() functino behavior including the number and nature of arguments it requires.

aVeryLongString = "a:very:very:very:very:long:string:with:namespaces"
fn replaceAll str old kwrd =
(
    while findString str old != undefined do
    (
        str = replace str (findString str old) kwrd.count kwrd
    )
    return str
)
replaceAll aVeryLongString ":" "_"

the result: a_very_very_very_very_long_string_with_namespaces

Basic break down: the function takes three arguments, the actual string you want to work with, and old character you want to replace (it supports more than one character) and a new, keyword (kwrd) to replace with. When invoked, it goes through a while loop to search for the old character string and replaces it with the new kwrd character string. After it’s all done it returns the new string.

Even though this took only a few more lines of code, I used two string specific functions and a loop clause all wrapped up in a custom function to do the trick for me. Besides, as I already mentioned, this method is much more complex and hard to code for an inexperienced scripter who just wants to perform a simple character replacement function. These are the tiny little differences that may cause a lot of trouble and headaches when developing really complex and large scripts or, for example, when you have a Junior TD at the studio who should help you out with simpler, smaller tasks and they bump into some similar problem like this one, which it’s as if they weren’t there since you end up doing the work yourself anyways.

21 Comments »

  1. hi,duber。

    This article is helpful for me, thank you man!

    I am learning python now, although mel can do almost all the work, python gives the flexibility for programming. Combining both is the direction. I hate maxscript like most guys!

    In your post you said:

    ” If you’ve done some UI coding, you know what I’m talking about, especially in connection to Maya ;)

    Did you mean that you can access mayaUI from exturnal editor? If the answer is “Yes”, that would be great! So I don’t need to write python script in exturnal editor(because they have sytax highlighting) and degug in maya’s script editor.

    In maya help file it mentioned that from exturnal editor maya will be in batch mode,and mayaUI cann’t be accessed, so how could you do that?

    Comment by Ross — May 24, 2008 @ 11:45

  2. Hi Ross,

    the UI note was meant as in scripting UI controls, like sliders, pick buttons, lists, drobdown menus etc… is a pain in MEL (Maya), but thankfully, through Python and some very cool modules, you can do a lot of stuff in this regard.

    As for connecting an external script editor with syntax highlights with Maya, take a look at Mapy (http://rodmena.com/mapy/), it’s really great for this kind of stuff, I love it.

    cheers,

    – loocas

    Comment by loocas — May 24, 2008 @ 18:08

  3. Thank you for the quick reply, man.

    I searched the internet and find some cool result. You can check it out(http://cgkit.sourceforge.net/download.html).

    It’s amazing that they treat txPythonUI as subframe of maya’s mainUI, so we can use wxPython’s colorful UI in maya. I will give it a try .

    this link : http://rodmena.com/mapy/ cann’t work in my computer.

    Comment by Ross — May 25, 2008 @ 09:37

  4. cool tutorial, but i have a question

    as a python newbie , actually indeed i am, should i choose the default “Autodesk” way coming with maya , or the “pymel” way? pymel is still young , and will be constantly evolving, i mean what if the author drop development, or he changed the syntax quite a bit. then i would have to relearn the nitty gritty grammar?

    hope you shed some light on me.

    Comment by oglop — June 25, 2008 @ 02:50

  5. oglop, I’d recommend you briefly learning MEL in this case. It helped me tremendously, because Python in Maya acts more as a wrapper than a native language, which is fine, if you ask me (some people dislike this behavior).

    So, again, briefly jump into MEL, give it a week, learn the basic syntax needed to communicate with Maya, don’t bother with loops, structs, procedures etc… (of course, if you’re interested in it, go for it) and once you’re familiar how MEL works, go for default Python to, once again, get familiar with it.

    After a few weeks (or if you’re a skilled scripter/programmer, it’ll only take you a few days) you’ll be able to script virtually anything in Maya and thus installing PyMel and reading through the documentation, you’ll immediately recognize what’s going on. ;) PyMel is just Python with “nicer” syntax, you won’t have to learn anything new once you know MEL and Python, you’ll only be accessing the MEL commands through PyMel, not through “maya.cmds” ;)

    Comment by loocas — June 25, 2008 @ 09:13

  6. thanks for you answer. I’m trying to learn it by myself, but the learning curve seems fairly sharp for me about the API and class @#%%^. MEL for me is not a problem, i’ve written 3000 more lines of submission script in mel, combined with vbscript.

    the problem for me is i don’t see the big pictures, various jargons float around the web, although there are many tutorials, but you can be easily confused. say i want to write xml in my next asset management script. after spending half an hour on a “python XML introduction ” site, only to find that the xml.dom.ext package didn’t work because it’s not contained in the standard python distribution , but in a deprecated module pyxml… ahhh (my fault , i didn’t read the beginning of the tutorial carefully enough)

    and for the gui development , pyqt tkinter wxpython, which makes my brain more messy…
    anyway , i’ll keep it on, thanks for your advice

    Comment by oglop — June 26, 2008 @ 07:27

  7. Well, in this case, just read about modules in Python, copy the needed modules you want into maya’s Python lib directory and add the path through sys.os.path to the module you want.

    I extended Maya’s standard Python library this way (I’m sure there are other ways) very easily and it works for me.

    For example, I use IronPython, PyXML, PyMath etc… in Maya without problems. The only thing is, Maya 8.5 uses Python 2.4, while Maya 2008 uses Python 2.5.

    Comment by loocas — June 26, 2008 @ 09:13

  8. hello sir
    if i want to right mel scripts and python script, what is the basic scripting knowledge.

    i have little bit knowledge in c,c++.

    what should i study and how should i prepare?

    plz help me to get eminence

    Comment by narmatha — October 23, 2008 @ 11:47

  9. namatha, it’s hard to say, but I’d guess the bit of knowledge of C, C++ should be enough for you to get started. In this case, I’d recommend you starting with MEL as it’s a bit more similar to C, C++ as opposed to Python, which is way more comfortable for the kind of scripters like myself as I don’t have no knowledge of C or C++ and I script because I need to get things done and not be dragged behind by counting the number of curly braces or semicolons. But guys with the knowledge of C or C++ don’t have any problems with that, so, go for it. Open up the MEL documentation, read about the basic syntax and you’re good to go.

    Comment by loocas — October 23, 2008 @ 12:19

  10. hi.,
    Im SRAVAN From India.,
    Im learning python for Maya.
    can u suggest any good tutorials..?

    Im aquainted with C, C++, Java

    ThanQ>

    Comment by sravan — October 8, 2009 @ 13:38

  11. Hi Sravan,

    a few good training DVDs has DigitalTutors on this topic, these I highly recommend. Other than that, just learn Python as is and you’ll be all good ;)

    Comment by loocas — October 8, 2009 @ 14:35

  12. hi
    I ambhaskarachari
    I want to learn pythan for maya .But don’t know c ,c++ .is it possible to learn pythan without c c++ .If so how .
    thanQ

    Comment by bhaskara — February 26, 2010 @ 03:06

  13. Don’t worry, bhaskara, I don’t know C, C++ at all, yet I know Python and MAXScript quite well, so, it absolutely is possible ;)

    Comment by loocas — February 26, 2010 @ 11:14

  14. respected sir
    thanks for you answer.how can i learn.
    Is any sites are there for good tutorials about pythan .
    no teaching centers are hear for pythan for maya .if hear suggest me good one.
    this is bhaskara chary from INDIA, AP , HYD.

    Comment by bhaskaracharivfx — February 27, 2010 @ 01:31

  15. For learning Python, I’d suggest buying a Python book. For example, Learn Python from Lutz & Ascher. Then look at Digital Tutors’ site for any Maya, Python, related tutorials. These were surprisingly very good. But then, it’s all about Python. So learn it in general and apply it in a concrete example.

    Comment by loocas — February 27, 2010 @ 23:52

  16. THANKS FOR YOUR EXPLANATION LOOCA (SIR / MADAM ).BUT WHAT IS LUTZ &ASCHER .THESE R RELATED TO SOFT WARE OR ANY THING ELSE .COULD YOU PLEASE ME .& ALS
    YOURS FAITH FULL CHARI VFX

    Comment by BHASKARACHARIVFX — March 1, 2010 @ 01:13

  17. sorry after searching i came to know the names are authors of the PYTHAN Books .which book is the better one ,which one i have to start first.

    Comment by BHASKARACHARIVFX — March 1, 2010 @ 01:30

  18. hey !
    Ma slf arpan. U can call me nix..
    I’m lrning MEL and Python frm digital tutorial’s tutorials.
    I jst wanted to know tht is python is difficult thn MEL ?
    Caz i’m lrning MEL nw.. N it is so simple as i ancountrd !. Caz i’ve a bit knowledge of C,C++,java,vb….. Ya thts all language.
    So let me knw tht python is esy or vice verca !
    Thnx budy !

    Comment by arpan — December 10, 2011 @ 21:07

  19. Well, it’s certainly a bit harder than proper English grammar. So, once you get that right, you shouldn’t have too many issues with either Python or MEL.

    Comment by loocas — December 11, 2011 @ 16:06

  20. Hello Lukas,

    I have been working as vfx artist but recently decided to go get a technical job like that of a TD. Now that I have taken a brake I am preparing myself by studying python, in 2008 when I graduated in VFX program I wrote few scripts in mel, but my past desire to be a compositor suppressed(actually killed my time) that I could have done lot by staying into technical field since I have a programming background(Masters in Comp Sci) , and now when I have taken a brake I do not have enough time and I am getting old and have lots of responsibilities. How should I jump into a technical job or what do companies\senior TD’s expect when they hire a technical person?

    So while I was learning python (reading python docs and lots of video tutorials) I have made some tools(http://www.creativecrash.com/users/san–2/contributions?tab=free_downloads) for maya mostly can you judge by looking at the tools if I have something to jump in to apply for?

    I have been exploring the maya python wrappers for mel but some guys have suggested me to learn Pymel would it be any beneficial skill to get?

    now since PyQt is gaining popularity for UI development I am thinking to learn few basics of it to jump into the first job of TD if I get.

    in the end I want say you probably a great person how nicely you have answered to question people asked who are like freshers… you probably are kind of person I would really like to work with !!!

    Comment by Sanjeev Kumar — October 15, 2012 @ 08:13

  21. Thanks man. :)
    As for how to get a TD job, well, it really isn’t about what programming language you know, but more about how resourceful and independent you can be when dealing with problems. If you know some programming stuff and you know your way around IT and technical shit, then you’re half way there. The rest is just you and you alone figuring out whatever the challenge is and whatever the artistic team throws at you.

    So, if you don’t mind starting as a Jr. TD, then go for it. Apply anywhere you’d like to work and work your way up. That’s how I got my Lead TD job at UPP on a major Hollywood project. I just worked my way up from small script fragments here and there to leading a team of artists and providing them with tools and solutions to do their job. :)

    Comment by loocas — November 27, 2012 @ 23:00

RSS feed for comments on this post. TrackBack URI

Leave a comment

Powered by WordPress | Theme by Roy Tanck