Maya Get Date and Time

proc string getDateAndTime()
        python("import datetime");
        python("d =");
        return python("d.strftime('%Y-%m-%d-%Hh%Mm%Ss')");
// Result: 2011-08-03-20h24m56s //


Just a quick note about how to get date and time via MEL and Python


Leave a comment

Filed under MEL, Python

Using Mental Ray Textures

Mental Ray can use Maya built-in file textures, but sometimes using Mental Ray Textures have some advantages. Unlike Maya file, Mental Ray Textures cannot be connected to a material directly. They should be connected via some Texture Lookup node:

A mib_texture_filter_lookup node in this case. A mentalrayTexute node is connected to its tex, and a mib_texture_vector node is connected to its coord.

Image file is loaded in the mentalrayTexture node:

A mib_texture_vector produces the coordinate for texture lookup. UV coordinate is used by default. Select appears to be the index number of UV set, so select zero means the first UV set (map1), one is second, two is third, and so on.

Leave a comment

Filed under Mental Ray

Get Maya Version And Bin Location

Sometimes it is important to deduce the version and bin location of the Maya your are working with. Getting the version number is easy:


should be sufficient. But there seems no built-in MEL command to get where the Maya application is installed. I tried to write a procedural to do that trick:

proc string getApplicationLocation()
string $scpt =
"import sys, os\n\
def where_maya_app_resides(path):\n\
    appName = '/Maya'\n\
    if sys.platform == 'win32':\n\
        appName = '/Maya.exe'\n\
    for apath in path:\n\
        if os.path.exists(apath+appName):\n\
            return apath\n\
    return 'maya not found in any path'\n";

        return python("where_maya_app_resides(sys.path)");

Actually, it is done in Python. Calling sys.path in Maya Python will returns a number of module search directories. Usually the first one will be Maya/bin. To make sure it returns the bin directory, I check every directory to find whether Maya(.exe) does exist inside it. On Mac, it returns: /Applications/Autodesk/maya2008/

1 Comment

Filed under MEL, Python

Python Regex Notes

Before you can use Regex, or Regular Expression, in Python, you must:

import re

First useful stuff is re.sub(), replacing parts of a string based on some pattern. For example:

text = 'dog boot. shoot root o hoodie'
text = re.sub('o', 'e', text)
print text'

This will change text to ‘deg beet. sheet reet e heedie’. So every character ‘o’ is replaced by ‘e’. Changed the pattern to:

re.sub('o|s', 'e', text)

Result will be ‘deg beet. eheet reet e heedie’, so both ‘o’ and ‘s’ is replaced by ‘e’. Now try a new pattern:

re.sub('o|s|.', 'e', text)

It returns ‘eeeeeeeeeeeeeeeeeeeeeeeeeeeee’, what’s wrong? Because ‘.’ is a special characters in the expression(pattern), it must be used with escape:

re.sub('o|s|\.', 'e', text)

Now it gets ‘deg beete eheet reet e heedie’. There are a few more special characters, like ‘\’, ‘|’. For example, to replace ‘\’ with ‘/’:

re.sub('\\\\', '/', text)

to insert ‘\’ before ‘\’:

re.sub('\\\\', '\\\\\\\\', text)

to insert ‘\’ before ‘.’:

re.sub('\.', '\\\.', text)

to insert ‘\’ before ‘|’:

re.sub('\|', '\\\|', text)

Inserting escape before those special characters will make sure regex will treat them as regular characters instead of character with special meanings. This will be useful in search(). For example, to find the sub-string right after r’\\\Public’:

text = '\\\\\\Public//abc/foo.txt'
m ='(?<=\\\\\\\\dump\.jianzhang\.fr\\\\Public).+', text)

(?<=something) means matches if the position is preceded by something, so something here is  ‘\\\\\\Public’, which equals r’\\\Public’

.+ means everything from the matched position until it hits a new line, ‘\n’. It returns ‘//abc/foo.txt’.  Now try some more detailed pattern like:

text = r'\\\Public//abc/702/foo.txt'
m ='(?<=\\\\dump\.jianzhang\.fr\\Public)./{1,2}.[a-z]./', text)

It returns ‘//abc/702’. ‘./{1,2}.[a-z]./’ means right after the matched block, there should be one or two ‘/’, followed by a block contains lowercase characters, and followed by another ‘/’. To add one more condition:'(?<=\\\\dump\.jianzhang\.fr\\Public)./{1,2}.[a-z]./\d{1,3}/', text)

it returns ‘//abc/702/’, means after that ‘/’, there must be 1,2, or 3 numbers, followed by another ‘/’.  We can extract that integer by named group:

m ='(?<=\\\\dump\.jianzhang\.fr\\Public)./{1,2}.[a-z]./(?P<foo_loc>\d{1,3})/', text)

it returns 702.

Regex is quite a complex topic. There are still a lot unknowns, so maybe I can clear a few more points next time.




Leave a comment

Filed under Python

PyQt MenuBar Outside MainWindow

import sys, os
from PyQt4 import QtCore, QtGui
class AddressBook(QtGui.QWidget):
    def __init__(self, parent=None):
        super(AddressBook, self).__init__(parent)
        mainLayout = QtGui.QVBoxLayout()
        toolBar = QtGui.QToolBar()
        simpleButton = QtGui.QToolButton()
        fileButton = QtGui.QToolButton()
        editButton = QtGui.QToolButton()
        self.setWindowTitle("Menu By Tool Bar")
    def pop_file_menu(self):
        aMenu = QtGui.QMenu(self)
        return aMenu
    def pop_edit_menu(self):
        aMenu = QtGui.QMenu(self)
        return aMenu
    def create_actions(self):
        self.simpleAct = QtGui.QAction('Simple', self, triggered=self.do_nothing)
        self.fileOpenAct = QtGui.QAction('Open', self, triggered=self.do_nothing)
        self.fileCloseAct = QtGui.QAction('Close', self, triggered=self.do_nothing)
        self.editCopyAct = QtGui.QAction('Copy', self, triggered=self.do_nothing)
        self.filePasteAct = QtGui.QAction('Paste', self, triggered=self.do_nothing)
    def do_nothing(self):
        print 'do nothing'
if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    addressBook = AddressBook()
    addressBook.setGeometry(100, 100, 640, 480)

How to add a QMenuBar to a QWidget instead of QMainWindow? I have no idea. But I really need a menu bar floating above all those small windows! Fortunately, QToolBar comes to save the day. A QToolButton can have a nice popup menu as well. This is a simple example.

Leave a comment

Filed under Python, Qt

Python Socket Server Example

We already know how to check host availability by ping, but that is not good enough. The file returned by popen() is often unreadable. And we need actual communication between client and server side. This is about how to create a simple server with Python socket.

First the class of server. It is a open-ended thread can run forever.  It always listens and waits for a client to contact. Once a connection is established, it tries to receive any message sent by client, then reply a ‘roger’. As soon as the current connection is severed, it comes back to listening again.

import socket, datetime, threading, os

class AServer(threading.Thread):
    def __init__(self, port):
        self.port = port

    def now(self):
        d =
        return d.strftime("%d/%m/%y %H:%M:%S")

    def run(self):
        host = ''
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind((host, self.port))
        print 'server started successfully, waiting...'
        conn, addr = s.accept()
        print 'contact', addr, 'on',

        while 1:
                data = conn.recv(1024)
            except socket.error:
                print 'lost', addr, 'waiting..'
                conn, addr = s.accept()
                print 'contact', addr, 'on',

            if not data:
                print 'lost', addr, 'waiting..'
                conn, addr = s.accept()
                print 'contact', addr, 'on',
                print "received msg:", data

To start the server on local host at a given port:

 t = AServer(31944)

Now write a simple client to contact the server, make sure the host address and port is set correctly:

import socket, time, threading, sys

host = ''
port = 31944

s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
except socket.error:
    print host ,'is offline, stop '

    data = s.recv(1024)
    print host, 'says:', data
except socket.error:
    print host,'is offline, stop '


As long as the server side is running, this will always get a ‘roger’. Because the client exit() right after receiving the first message from server. It will immediately be lost on the server side.

Leave a comment

Filed under Python

Google Reverse Image Search

Google seems to pull out another new trick: reverse image search. You can drop an image into the search bar, wait for a while, and get supposed relevant results. I have been playing with it for a while. Following two images, snapshots from news podcast. One is Ronald Reagan, the other is JFK. Both search returns good result:

The icon of VLC player leads to the site of VLC

And this blue figure actually leads todoctor manhattan!

Man, this is crazy. How does it work?

Leave a comment

Filed under Uncategorized