Maya Python API: Hello world!

Write a custom Maya command that print “Hello world!” in Maya console.
There are Python API 1.0 and 2.0. The syntax would be different.
We will integrate with API 2.0 in this example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import sys
import maya.api.OpenMaya as api

# Must include to use Maya API 2.0
def maya_useNewAPI():
pass

class HelloWorldCmd(api.MPxCommand):
kCmdName = 'helloWorld'

def __init__(self):
api.MPxCommand.__init__(self)

@staticmethod
def creator():
return HelloWorldCmd()

def doIt(self, arg_list):
print('Hello world!')

# initialize and uninitialize functions are
# needed to be loaded by Maya Plug-in Manager
def initializePlugin(mobject):
fn_plugin = api.MFnPlugin(mobject)
try:
fn_plugin.registerCommand(
HelloWorldCmd.kCmdName,
HelloWorldCmd.creator
)
except:
sys.stderr.write("Fail to register plugin: " + HelloWorldCmd.kCmdName)

def uninitializePlugin(mobject):
fn_plugin = api.MFnPlugin(mobject)
try:
fn_plugin.deregisterCommand(
HelloWorldCmd.kCmdName
)
except:
sys.stderr.write("Fail to deregister plugin: " + HelloWorldCmd.kCmdName)

Open Maya Plug-in Manager, and hit “Browse” to load our command.

Then we can run our command

1
helloworld;

We can also call it in Python:

1
2
from maya import cmds
cmds.helloWorld