Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
Maya Programming with Python Cookbook

You're reading from   Maya Programming with Python Cookbook Master complex workflows and conquer the world with Python and Maya

Arrow left icon
Product type Paperback
Published in Jul 2016
Publisher Packt
ISBN-13 9781785283987
Length 266 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Pankaj K P Singh Pankaj K P Singh
Author Profile Icon Pankaj K P Singh
Pankaj K P Singh
 Herbez Herbez
Author Profile Icon Herbez
Herbez
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

Preface 1. Getting Started with Maya 2. Creating User Interfaces FREE CHAPTER 3. Working with Geometry 4. Giving Things a Coat of Paint – UVs and Materials 5. Adding Controls – Scripting for Rigging 6. Making Things Move – Scripting for Animation 7. Scripting for Rendering 8. Working with File Input/Output 9. Communicating with the Web 10. Advanced Topics Index

Writing and running an external script

In this recipe, we'll be writing and running our first actual script as an external Python file.

Getting ready

The Script Editor window is a bit of a misnomer. Although it's a great way to test out short snippets of code, it's awkward to use for any kind of real script development. For this, you'll want to have a programmer-friendly text editor setup. There are a ton of options out there, and if you're reading this book, you likely already have one that you like to use. Whatever it is, make sure that it's geared towards writing code, and it saves files in plain text.

How to do it...

First off, we'll need a script. Create a new file in your editor and add the following code:

import maya.cmds as cmds

print("Imported the script!")
def makeObject():
    cmds.polyCube()
    print("Made a cube!")

Now save the script as myScript.py. Once you've done that, switch back to Maya and run the following from either the script editor or the command line:

import myScript

This will cause Maya to read in the file, and you'll see the following in the script editor output:

Imported the script!

What you will not see, however, is a new cube. That's because the real functionality of our (simple) script is defined within a function named "makeObject".

Maya treats each Python file that you import as its own module, with the name of the file providing the name of the module. Once we've imported a file, we can invoke functions within it by calling [moduleName].[function name]. For the earlier-mentioned example, this would mean:

myScript.makeObject()

Run it, and you should see a newly minted cube show up, and "Made a cube!" in the output of the Script Editor.

Now, let's try changing our script. First, delete the cube we just made, then switch over to your text editor, and change the script to the following:

import maya.cmds as cmds

def makeObject():
    cmds.polySphere()
    print("Made a sphere!")

Switch back to Maya and run the script again with:

myScript.makeObject()

You'll see that rather than having a nice sphere, we still ended up with a cube. That's because when you ask Maya to execute a script that it has already executed, it will default to rerunning the same code that it ran previously. In order to ensure that we get the latest, greatest version of our script, we'll need to first run the following:

reload(myScript)

This will force Maya to reload the file. Note that the argument to reload isn't the file name itself (myScript.py in this case), but rather the name of the module that the file defines ("myScript").

Once you've done this, you can once again try:

myScript.makeObject()

This time, you'll see a proper polygonal sphere, just as we intended.

How it works...

It may seem like an unnecessary extra step to both import the script and call one of its functions, and you can indeed have the script automatically execute code (as demonstrated by the call to print("Imported Script!"). However, it's much better practice to wrap all of your functionality in functions, as it makes large scripts much easier to work with.

If you have functionality that you want to execute every time the script is run, it is best to define a function with a name like "main" and have the last line of your script invoke it. Take a look at the following example:

import maya.cmds as cmds

def makeObject():
    cmds.polyCube()
    print("Made a cube!")

makeObject()

This would define the makeObject() function, then (on the last line of the script) cause it to be executed.

When working on a script, it can get really tedious to reload, import, and run the script each time. An easy way to get around that is to enter the following into the script editor:

import myScript
reload(myScript)
myScript.myCommand()

Once you've done that, use File | Save Script to Shelf... to give yourself a button to easily rerun the latest version of your script. Note that the preceding code contains both import and reload. That's to make sure that the code will work both the first time you run it as well as successive times. The "import" command is there to ensure the module has been loaded at least once (necessary for a new script, or upon restarting Maya), and the "reload" command is there to ensure that what we're running is the latest version (necessary if we've made changes to the script with Maya still up).

There's more...

If you have a script that defines a lot of functionality, and you don't want to constantly type out the module name, you can use the same trick we used with maya.cmds to shorten things a bit. Namely, you can use the "as" syntax to provide a shorter name. For example, I could have done the following:

import myScript as ms
ms.makeObject()

This would have exactly the same effect.

lock icon The rest of the chapter is locked
Visually different images
CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
Maya Programming with Python Cookbook
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Modal Close icon
Modal Close icon