Practical Maya Programming with Python 1st Edition Galanakis - Read the ebook online or download it to own the complete version
Practical Maya Programming with Python 1st Edition Galanakis - Read the ebook online or download it to own the complete version
com
https://ebookgate.com/product/practical-maya-programming-
with-python-1st-edition-galanakis/
OR CLICK BUTTON
DOWLOAD EBOOK
https://ebookgate.com/product/practical-programming-an-introduction-
to-computer-science-using-python-jennifer-campbell/
ebookgate.com
https://ebookgate.com/product/programming-the-raspberry-pi-second-
edition-getting-started-with-python-simon-monk/
ebookgate.com
https://ebookgate.com/product/ultimate-python-programming-1st-edition-
deepali-srivastava/
ebookgate.com
https://ebookgate.com/product/expert-python-programming-2nd-edition-
jaworski/
ebookgate.com
https://ebookgate.com/product/python-programming-4th-edition-singh-a/
ebookgate.com
https://ebookgate.com/product/black-hat-python-python-programming-for-
hackers-and-pentesters-1st-edition-seitz/
ebookgate.com
Practical Maya Programming with Python
Table of Contents
Practical Maya Programming with Python
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers and more
Why Subscribe?
Free Access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Introspecting Maya, Python, and PyMEL
Creating your library
Using the interpreter
Finding a place for our library
Choosing a development root
Creating a function in your IDE
Reloading code changes
Exploring Maya and PyMEL
Creating an introspection function
Understanding Python and MEL types
Using the method resolution order
PyNodes all the way down
Understanding PyMEL data and math types
Leveraging the REPL
Building the pmhelp function
Creating a query string for a PyMEL object
Creating more tests
Adding support for modules
Adding support for types
Adding support for methods
Adding support for functions
Adding support for non-PyMEL objects
Designing with EAFP versus LBYL
Code is never complete
Opening help in a web browser
Summary
2. Writing Composable Code
Defining composability
Identifying anti-patterns of composability
Avoiding the use of Boolean flags
Evolving legacy code into composable code
Rewriting code for composability
Getting the first item in a sequence
Writing head and tail functions
Learning to use list comprehensions
Implementing is_exact_type
Saying goodbye to map and filter
Writing a skeleton converter library
Writing the docstring and pseudocode
Understanding docstrings and reStructured Text
Writing the first implementation
Breaking the first implementation
Understanding interface contracts
Extracting the safe_setparent utility function
Learning how to refactor
Simplifying the node to joint conversion
Learning how to use closures
Dealing with node connections
Dealing with namespaces
Wrapping up the skeleton converter
Writing a character creator
Stubbing out the character creator
Implementing convert_hierarchies_main
Implementing convert_hierarchies
Decomposing into composable functions
Implementing convert_hierarchy
Supporting inevitable modifications
Improving the performance of PyMEL
Defining performance
Refactoring for performance
Rewriting inner loops to use maya.cmds
Summary
3. Dealing with Errors
Understanding exceptions
Introducing exception types
Explaining try/catch/finally flow control
Explaining traceback objects
Explaining the exc_info tuple
Living with unhandled exceptions
Handling exceptions at the application level
Golden rules of error handling
Focus on the critical path
Keep the end user in mind
Only catch errors you can handle
Avoid partial mutations
Practical error handling in Maya
Dealing with expensive and mutable state
Leveraging undo blocks
Dealing with Maya's poor exception design
Leveraging the Maya application
Dealing with the Maya application
Leveraging Python, which is better than MEL
Building a high-level error handler
Understanding sys.excepthook
Using sys.excepthook in Maya
Creating an error handler
Improving the error handler
Inspecting Python code objects
Adding filtering based on filename
Assembling the contents of an error e-mail
Sending the error e-mail
Installing the error handler
Obeying the What If Two Programs Did This rule
Improving the error handler
Adding a user interface
Using a background thread to send the e-mail
Moving beyond e-mail
Capturing locals
Attaching log files
Summary
4. Leveraging Context Managers and Decorators in Maya
Inverting the subroutine
Introducing decorators
Explaining decorators
Wrapping an exporter with a decorator
Introducing context managers
Writing the undo_chunk context manager
Writing the undo_on_error context manager
Contrasting decorators and context managers
Context managers for changing scene state
Building the set_file_prompt context manager
Building the at_time context manager
Building the with_unit context manager
Building the set_renderlayer_active context manager
Building the set_namespace_active context manager
Improving on future versions of Maya
Creating the denormalized_skin context manager
Safely swapping vertex influences
Addressing performance concerns
Creating a decorator to record metrics
Getting a unique key
Recording duration
Reporting duration
Handling errors
Advanced decorator topics
Defining decorators with arguments
Decorating PyMEL attributes and methods
Stacking decorators
Using Python's decorator library
Doing decorators the right way
Summary
5. Building Graphical User Interfaces for Maya
Introducing Qt, PyQt, and PySide
Introducing Qt widgets
Introducing Qt layouts
Understanding Qt main windows and sorting
Introducing Qt signals
Establishing rules for crafting a GUI
Prefer pure PySide GUIs where possible
Use command-style UI building where necessary
Avoid the use of .ui files
Installing PySide
Supporting PySide and PyQt
Creating the hierarchy converter GUI
Creating the window
Running a Python file as a script
Introducing the QApplication class
Understanding the event loop
Running your GUI
Designing and building your GUI
Defining control, container, and window widgets
Adding the rest of the widgets
Hooking up the application to be effected by the GUI
Hooking up the GUI to be effected by the application
Simulating application events
Considering alternative implementations
Integrating the tool GUI with Maya
Opening the tool GUI from Maya
Getting the main Maya window as a QMainWindow
Making a Qt window the child of Maya's window
Using Python's reload function with GUIs
Emitting a signal from Maya
Connecting Maya to a signal
Verifying the hierarchy converter works
Working with menus
Creating a top-level menu
Getting the Qt object from a Maya path
Changing the font of a widget
Marking menus as new
Creating a test case
Adding a persistence registry
Verifying the new menu marker works
Using alternative methods to style widgets
Working with Maya shelves
Summary
6. Automating Maya from the Outside
Controlling Maya through request-reply
Using a Python client and Maya server
Controlling Python through exec and eval
Handling problems with IPC
Installing ZeroMQ
Demonstrating request-reply with ZeroMQ
Explaining connection strings, ports, bind, and connect
Designing the automation system
Pairing one client and one server
Bootstrapping the server from the client
The client-server handshake
Defining the server loop
Serializing requests and responses
Choosing what the server does
Handling exceptions between client and server
Understanding the Maya startup routine
Using batch mode versus GUI mode
Choosing a startup configuration mechanism
Using command line options
Using environment variables
Building the request-reply automation system
Creating a Python package
Launching Maya from Python
Automatically killing the server
Creating a basic Maya server
Running code at Maya startup
Understanding eval and exec
Adding support for eval and exec
Adding support for exception handling
Adding support for timeouts
Adding support for the client-server handshake
Practical uses and improvements
Batch processing using Maya
Running a server in a Maya GUI session
Running automated tests in Maya
Adding support for logging
Supporting multiple languages and applications
Supporting control from a remote computer
Designing an object-oriented system
Evaluating other RPC frameworks
Summary
7. Taming the Maya API
Explaining types
Dicts all the way down
Using custom types to simplify code
Introducing inheritance by drawing shapes
Introducing Maya's API and architecture
Understanding the OpenMaya bindings
Navigating the Maya API Reference
Understanding MObjects and function sets
Learning the Maya Python API by example
Converting a name to an MObject node
Getting the name of an MObject
Getting the hash of a node
Building a mesh
Setting mesh normals
Using MScriptUtil to call a method
Using OpenMaya for callbacks
Comparing Maya Python API and PyMEL
Creating a Maya Python plugin
The life of a Python plugin
Creating the sound player library
Creating the plugin file
Reloading plugins
Adding a command flag
Comparing the OpenMaya and scripting solutions
Using PyMEL in a plugin that loads during startup
Summary
8. Unleashing the Maya API through Python
Understanding Dependency Graph plugins
Building a simple node plugin
Understanding plugin type IDs
Defining inputs, outputs, and the initializer
Creating the compute method
Taming the non-Pythonic Maya API
Demystifying Python metaprogramming
Rethinking type creation
Exploring the type function
The importance of being declarative
Designing the node factory
Designing plugin nodes
Designing the attribute specification
Designing the node type specification
Building the node factory
Specifying attributes
Creating attributes
Specifying a node
Using partial application to create attributes
Creating a node
Slaying the compute method
Extending the node factory
Supporting string and color attributes
Supporting enum attributes
Supporting transform nodes
Overriding MPxNode methods
Summary
9. Becoming a Part of the Python Community
Understanding Open Source Software
Differentiating OSS from script download sites
Defining what a third-party module is
Creating a site directory for third-party modules
Explaining the site directory
Creating a new site directory for Maya
Establishing the site directory at startup
Working with Python distributions in Maya
Using the Python Package Index
Adding a source distribution to Maya
Adding an egg or wheel to Maya
Using binary distributions on Windows
Using pip to install third-party modules
Contributing to the open source community
Designing Maya Python code for open source
Starting an open source project
Distributing your project
Engaging with the wider community
Summary
A. Python Best Practices
The args and kwargs parameters
String formatting
String concatenation
Raw strings and string literals
Path building and manipulation
Unicode strings
Using the doctest module
Adopting Test-Driven Development
Using the GitHub repository for this book
Index
Practical Maya Programming with Python
Practical Maya Programming with Python
Copyright © 2014 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a
retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher,
except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented.
However, the information contained in this book is sold without warranty, either express or implied. Neither the
author nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged
to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products
mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy
of this information.
Livery Place
35 Livery Street
ISBN 978-1-84969-472-8
www.packtpub.com
Cover image by Andrei Cosmin Cristea (<Andrei@undoz.com>)
Credits
Author
Robert Galanakis
Reviewers
Harry Boltz
Brian Escribano
Michael Tsai
Commissioning Editor
Akram Hussain
Acquisition Editor
Subho Gupta
Dayan Hyames
Technical Editors
Krishnaveni Haridas
Manal Pednekar
Copy Editors
Aditya Nair
Stuti Srivastava
Project Coordinator
Leena Purkait
Proofreaders
Stephen Copestake
Maria Gould
Paul Hindle
Indexers
Mariammal Chettiyar
Tejal Soni
Priya Subramani
Graphics
Sheetal Aute
Yuvraj Mannari
Abhinash Sahu
Production Coordinator
Pooja Chiplunkar
Cover Work
Pooja Chiplunkar
About the Author
Robert Galanakis is a technical artist cum programmer who has worked in various areas of game development. He
is the Technical Director of EVE Online at CCP Games, Iceland, where he focuses on Python, Lean, and Agile
training and evangelism. In 2008, Rob founded tech-artists.org, which is the largest and the most active community
focused on tech art on the Internet. He has spoken at Game Developers Conference several times and has also
written many articles about tools, pipelines, and culture. His blog can be found at www.robg3d.com. He lives in
Reykjavík, Iceland, with his wife Casady and their son Marcus.
About the Reviewers
Brian Escribano has over 11 years of experience working in the fields of education, TV, and games. He builds
world-class character rigs and animation pipelines for companies such as Nickelodeon, Mirada, and Spark
Unlimited. With his deep scripting knowledge in Python and MEL, Brian brings a wealth of expertise and
experience to any team he works with.
Michael Tsai attended the Academy of Art University at San Francisco to study Visual Effects. After college, he
worked on Fantastic Four 2 – Rise of the Silver Surfer, Red Cliff 2 – The Battle of Red Cliff, and the stereoscopic
version of G-Force. In 2012, Michael received his Master of Entertainment Technology degree (MET) from the
Entertainment Technology Center of Carnegie Mellon University. Elysium was another feature film he worked on
before he joined Schell Games in Pittsburgh as a full-time game artist.
www.PacktPub.com
Support files, eBooks, discount offers and more
You might want to visit www.PacktPub.com for support files and downloads related to your book.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You
can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount
on the eBook copy. Get in touch with us at <service@packtpub.com> for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free
newsletters and receive exclusive discounts and offers on Packt books and eBooks.
http://PacktLib.PacktPub.com
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can
access, read and search across Packt's entire library of books.
Why Subscribe?
Fully searchable across every book published by Packt
Copy and paste, print and bookmark content
On demand and accessible via web browser
Free Access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine
entirely free books. Simply use your login credentials for immediate access.
Preface
When Autodesk added support for Python into Maya 8.5, few people understood the implications. It was a decision
that has fundamentally changed the way 3D art gets done. Now, years later, we stand on the edge of realizing its
promise.
The promise of Python in Maya goes beyond just a familiar language with a great syntax. Any language could have
been chosen to bind to Maya; and most would have been more familiar, and with a better syntax than MEL, and
easier to use than C++. So, why Python?
The promise goes beyond a powerful language with lots of built-in features. Python is said to have batteries
included, but so do other languages, and Autodesk certainly has lots of batteries in Maya that now also exist in
Python. So, again, why Python?
The promise goes beyond having a single language for scripting, API use, and plugins. It goes beyond the endless
third-party libraries maintained by a large community. It goes beyond having powerful development tools.
The promise of Python in Maya is all of these things and more. You can learn how to use the language by leveraging
a wide variety of resources that have nothing to do with Maya. You can easily translate what you know of MEL and
the C++ API and use it in Python, but with an improved development velocity and maintainability of code. You can
use your favorite standard Python editor and tools. You can learn about the language from a technical and design
perspective and apply that to improve your programming in Maya. You can be part of a large, vibrant, diverse
community of developers on the forefront of multiple areas of technology.
Join me as we explore topics that will allow you to unleash the power of Maya through Python. Together, we'll
learn how Python works both under the hood and over it, how Maya integrates with Python, and how the elegant
PyMEL builds on that integration. We will drill down into what makes Python code beautiful and idiomatic, and
how we can use these concepts and Python's language features to make our Maya Python code expressive and
elegant. We will leverage third-party solutions for networking and user interfaces, to compliment and extend what is
included with Maya and Python. We will decouple Python code from Maya dependencies, making our work go
smoother and faster
This book is not a reference. It is not a cookbook, and it is not a comprehensive guide to Maya's Python API. It is a
book that will teach you how to write better Python code for use inside of Maya. It will unearth interesting ways of
using Maya and Python to create amazing things that wouldn't be possible otherwise. While there is plenty of code
in this book that I encourage you to copy and adapt, this book is not about providing recipes. It is a book to teach
skills and enable.
This is a book which, I hope, helps realize the promise of Python in Maya.
What this book covers
Chapter 1, Introspecting Maya, Python, and PyMEL, explores how Maya and Python work individually and
together to create a powerful programming and scripting environment. It covers some of the key technical
underpinnings for the rest of the book.
Chapter 2, Writing Composable Code, introduces the practice of writing code that can be reused in many places.
Composable code is a fundamental concept for the rest of the skills taught in this book.
Chapter 3, Dealing with Errors, teaches you all about exceptions and errors in Maya and Python. We explore
several strategies for handling them effectively.
Chapter 4, Leveraging Context Managers and Decorators in Maya, covers context managers and decorators,
which are two powerful features of Python, and how they can be used to simplify your code.
Chapter 5, Building Graphical User Interfaces for Maya, demonstrates the PySide and PyQt frameworks, how to
abstract your user interface code from underlying logic, and a strategy of building GUIs to maximize maintainability
and productivity.
Chapter 6, Automating Maya from the Outside, shows how Maya can be controlled from another process, explains
how request-reply systems work, and builds a fully featured automation system on these principles.
Chapter 7, Taming the Maya API, introduces the Maya Python API and how types and classes work in Python and
Maya. It contains a number of examples to demonstrate the API, as well as a Maya command plugin.
Chapter 8, Unleashing the Maya API through Python, covers the creation of a library to easily create Maya plugin
nodes, demonstrating how to map the Maya API onto Pythonic idioms using metaprogramming.
Chapter 9, Becoming a Part of the Python Community, goes over the concepts behind open source software,
demonstrates how to find and use third-party modules, explains how to create your own open source project, and
tours the Python and Maya programming communities.
Appendix, Python Best Practices, explains in detail various Python language features and miscellaneous, but very
relevant, topics.
What you need for this book
You will need a copy of Autodesk Maya 2013 for this book. Newer versions are fine, and older versions that use
Python 2.6 (2011, 2012) should be acceptable as well. Any operating system capable of running Maya (Windows,
OS X, Linux) should work, though you will need to translate things such as file paths to what is appropriate on your
system.
I would also suggest having an install of Python 2.6 or 2.7 outside Maya for exploring and running some of the
samples that can be run from the interactive interpreter prompt. You can download Python 2.6 or 2.7 from
http://www.python.org/download, or it may be installed on your Mac or Linux OS already!
Finally, I strongly suggest installing both a powerful text editor and an Integrated Development Environment
(IDE). Python is a real programming language, and you should use the powerful tools available. If you are an
experienced Python user already happy with vim, I don't expect to convert you. But if you are a converted MEL
scripter playing around in Notepad, it is time to embrace your good fortune!
For a text editor, Sublime Text (http://www.sublimetext.com) is popular, cross-platform, and free to use on an
unlimited trial. Notepad++ (http://notepad-plus-plus.org) is excellent if you are on Windows and prefer free and
open source. There are dozens of other good text editors, and if the two editors mentioned here do not tickle your
fancy, you should keep trying until you find one that does.
Finally, the choice of IDE is usually a contentious topic. For Python, however, I can confidently say PyCharm
(http://www.jetbrains.com/pycharm/) by JetBrains is the premiere IDE, and my personal favorite. It has a free and
quite powerful Community Edition as well. Other popular options are Wing IDE (http://www.wingware.com) and
Eclipse with PyDev (http://pydev.org). Experiment with a few different programs, but whatever you do, move past
IDLE, the IDE bundled with Python!
Who this book is for
Do you currently use Python with Maya and ask yourself: "Can I do better?"
Are you a MEL scripter who has started using Python and want to know what all the fuss is about?
Are you a Python programmer who is starting with Maya and believes there must be a better way?
Have you been using Python in Maya for a while but work hard to continuously improve?
Some basic experience with Python and Maya is expected. This book does not cover those most primitive topics
that are inevitably learned through introductory Maya and Python use.
Even more than experience, this book requires a willingness to learn. Some of the more advanced or unfamiliar
topics may feel a bit like learning how to ride a bicycle, but keep peddling and you'll get the hang of things in no
time.
Conventions
In this book, you will find a number of styles of text that distinguish between different kinds of information. Here
are some examples of these styles, and an explanation of their meaning.
Code words in text are shown as follows: "We can include other modules through the use of the import statement."
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
def more_spam():
spams = ' '.join([spam()] * 5)
return spams
Code meant to be entered by the Python interactive interpreter uses its familiar conventions. Input lines are prefixed
with ">>>". Continuations for multiline statements are prefixed with "...". Output from the interpreter has no
prefix:
>>> 'This is input'.replace('in', 'out')
'This is output'
>>> if True:
... print 'Hello!'
Hello
New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for
example, appear in the text like this: "Clicking on the Next button moves you to the next screen".
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may
have disliked. Reader feedback is important for us to develop titles that you really get the most out of.
To send us general feedback, simply send an e-mail to <feedback@packtpub.com>, and mention the book title via
the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see
our author guide on www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your
purchase.
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at
http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support
and register to have the files emailed directly to you.
The code for this book is also available on GitHub, at https://github.com/rgalanakis/practicalmayapython. See the
Appendix, Python Best Practices, for more information about the GitHub repository.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake
in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us.
By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If
you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book,
clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified,
your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing
errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from
http://www.packtpub.com/support.
Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection
of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the
Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
We appreciate your help in protecting our authors, and our ability to bring you valuable content.
Questions
You can contact us at <questions@packtpub.com> if you are having a problem with any aspect of the book, and
we will do our best to address it.
In this chapter, we will look at Python as a language, Maya as a program, and PyMEL as a framework. We will
begin by briefly going over how to use the standard Python interpreter, the Maya Python interpreter, the Script
Editor in Maya, and your Integrated Development Environment (IDE) or text editor in which you will do the
majority of your development. Our goal for the chapter is to build a small library that can easily link us to
documentation about Python and PyMEL objects. Building this library will illuminate how Maya, Python and
PyMEL are designed, and demonstrate why PyMEL is superior to maya.cmds. We will use the powerful technique
of type introspection to teach us more about Maya's node-based design than any Hypergraph or static
documentation can. Along the way we will explore some core concepts that will reoccur throughout later chapters.
Creating your library
There are generally three different modes you will be developing in while programming Python in Maya: using the
mayapy interpreter to evaluate short bits of code and explore ideas, using your Integrated Development
Environment to work on the bulk of the code, and using Maya's Script Editor to help iterate and test your work. In
this section, we'll start learning how to use all three tools to create a very simple library.
Using the interpreter
The first thing we must do is find your mayapy interpreter. It should be next to your Maya executable, named
mayapy or mayapy.exe. It is a Python interpreter that can run Python code as if it were being run in a normal Maya
session. When you launch it, it will start up the interpreter in interactive mode, which means you enter commands
and it gives you results, interactively. The >>> and ... characters in code blocks indicate something you should
enter at the interactive prompt; the code listing in the book and your prompt should look basically the same. In later
listings, long output lines will be elided with ... to save on space.
Note
Most of the interactive samples can be run as code through doctest. See Appendix, Python Best Practices, for
more information.
Start a mayapy process by double clicking or calling it from the command line, and enter the following code:
>>> print 'Hello, Maya!'
Hello, Maya!
>>> def hello():
... return 'Hello, Maya!'
...
>>> hello()
'Hello, Maya!'
The first statement prints a string, which shows up under the prompting line. The second statement is a multiline
function definition. The ... indicates the line is part of the preceding line. The blank line following the ...
indicates the end of the function. For brevity, we will leave out empty ... lines in other code listings. After we
define our hello function, we invoke it. It returns the string "Hello, Maya!", which is printed out beneath the
invocation.
Finding a place for our library
Now, we need to find a place to put our library file. In order for Python to load the file as a module, it needs to be
on some path where Python can find it. We can see all available paths by looking at the path list on the sys module.
>>> import sys
>>> for p in sys.path:
... print p
C:\Program Files\Autodesk\Maya2013\bin\python26.zip
C:\Program Files\Autodesk\Maya2013\Python\DLLs
C:\Program Files\Autodesk\Maya2013\Python\lib
C:\Program Files\Autodesk\Maya2013\Python\lib\plat-win
C:\Program Files\Autodesk\Maya2013\Python\lib\lib-tk
C:\Program Files\Autodesk\Maya2013\bin
C:\Program Files\Autodesk\Maya2013\Python
C:\Program Files\Autodesk\Maya2013\Python\lib\site-packages
A number of paths will print out; I've replicated what's on my Windows system, but yours will almost definitely be
different. Unfortunately, the default paths don't give us a place to put custom code. They are application installation
directories, which we should not modify. Instead, we should be doing our coding outside of all the application
installation directories. In fact, it's a good practice to avoid editing anything in the application installation
directories entirely.
Choosing a development root
Let's decide where we will do our coding. We'll call this location the development root for the rest of the book. To
be concise, I'll choose C:\mayapybook\pylib to house all of our Python code, but it can be anywhere. You'll need
to choose something appropriate if you are on OS X or Linux; we will use ~/mayapybook/pylib as our path on
these systems, but I'll refer only to the Windows path except where more clarity is needed. Create the development
root folder, and inside of it create an empty file named minspect.py.
Now, we need to get C:\mayapybook\pylib onto Python's sys.path so it can be imported. The easiest way to do
this is to use the PYTHONPATH environment variable. From a Windows command line you can run the following to
add the path, and ensure it worked:
> set PYTHONPATH=%PYTHONPATH%;C:\mayapybook\pylib
> mayapy.exe
>>> import sys
>>> 'C:\\mayapybook\\pylib' in sys.path
True
>>> import minspect
>>> minspect
<module 'minspect' from '...\minspect.py'>
There are actually a number of ways to get your development root onto Maya's path. The option presented here
(using environment variables before starting Maya or mayapy) is just one of the more straightforward choices, and
it works for mayapy as well as normal Maya. Calling sys.path.append('C:\\mayapybook\\pylib') inside
your userSetup.py file, for example, would work for Maya but not mayapy (you would need to use
maya.standalone.initialize to register user paths, as we will do later).
Using set or export to set environment variables only works for the current process and any new children. If you
want it to work for unrelated processes, you may need to modify your global or user environment. Each OS is
different, so you should refer to your operating system's documentation or a Google search. Some possibilities are
setx from the Windows command line, editing etcenvironment in Linux, or editing etclaunchd.conf on OS X.
If you are in a studio environment and don't want to make changes to people's machines, you should consider an
alternative such as using a script to launch Maya which will set up the PYTHONPATH, instead of launching the maya
executable directly.
Other documents randomly have
different content
pagato romani ufficiali affinché distruggessero le statue di Teodorico
per vendicar l'uccisione del padre Simmaco e del marito Boezio. Ma
Totila non concesse che le si facesse ingiuria e salvò da oltraggio lei e
tutte l'altre donne, della qual temperanza ei ricevette gran lode.»
Mentre Procopio in questo episodio commovente tributa onore a Totila
e alle ultime reliquie del patriziato romano, ci dà prova insieme di
possedere una grande serenità di giudizio e quella qualità eccellente in
uno storico del saper cogliere la vera luce dei fatti ed esporli in guisa
che dal complesso loro appariscano le condizioni generali dei tempi
descritti. Del resto le migliori qualità sue di scrittore mi par che si
mostrino tutte in questa descrizione dell'estrema battaglia combattuta
tra Bizantini e Goti, colla quale Procopio conclude la sua narrazione:
«A pie' del monte Vesuvio sono sorgenti di pura acqua e ne deriva un
fiume chiamato Draco (Sarno) che passa assai prossimo alla città di
Nocera, e i due eserciti s'erano accampati a' due lati del fiume. Ma il
Draco ancorché contenga poca acqua, non può guadarsi da cavalieri
nè da fanti perché stringe il suo letto in breve spazio e solca d'ambo i
lati la terra a molta profondità talché le sponde divengono ripide
molto. Se ciò avvenga per la qualità del suolo o dell'acqua io non so. E
i Goti occupato il ponte e accampativisi presso, posero in quello torri
di legno e macchine diverse, e tra esse quella che chiamano balista,
per modo ch'essi potevano dall'alto ferire e tormentar l'inimico.
Imperocché, come ho detto, per cagion del fiume che si frapponeva,
era impossibile combatter petto a petto e per lo più ciascuna parte
attaccava l'altra con missili avvicinandosi per quanto poteva sulla sua
sponda. Pochi certami singolari avean luogo quando qualche Goto
varcava il ponte recando una sfida. E così i due eserciti passarono lo
spazio di due mesi. Ma quinci i Goti eran padroni del mare presso a cui
s'accampavano, e potevan reggere finché le lor navi recavan per essi
le provviste occorrenti. Poi i Romani [27] preser le navi nemiche per
tradimento del Goto che comandava l'armata, ed anche navi
innumerevoli da Sicilia e dal rimanente Impero vennero a loro
soccorso. Nel tempo stesso Narsete ponendo torri di legno sulla
sponda del fiume riuscì interamente ad abbatter l'animo dei suoi
avversari. I Goti scorati e stretti dal difetto di cibo si rifugiarono ad
una montagna vicina chiamata dai Romani in latino Mons Lactarius.
Quivi non potevano inseguirli i Romani per cagione del cattivo terreno.
Ma presto i barbari incominciarono a pentirsi d'esserci andati ché le
provviste si fecero anche più scarse tanto che in nessun modo
potevano più mantener sé stessi e i cavalli loro. Di che, stimando
meglio accettevole morire in ordine di battaglia che per lenta fame,
calaron giù quando il nemico men li aspettava facendo contro esso
impeto improvviso. I Romani li fronteggiarono così com'erano senza
ordinarsi secondo lor capitani, o compagnie, o posizioni, nè collocarsi
in alcuna maniera d'ordine tra loro, ma difendendosi contro il nemico
ciascuno come gli accadde trovarsi. Allora i Goti lasciati i cavalli
composero una profonda falange tutti colla faccia rivolta al nemico e
anch'essi i Romani vedendo questo lasciarono i cavalli e tutti si
strinsero insieme nello stesso ordine.
«E qui io narrerò una battaglia assai memorabile per sé stessa e per la
chiara virtù spiegata da Teia che non si mostrò minore ad alcuno di
quelli a cui diamo nome d'eroi. E il disperato partito a cui erano ridotti
i Goti accresceva in essi prodezza, mentre i Romani li confrontavano
con ogni possa vergognosi di cedere a coloro che già eran vinti, sicché
d'ambe parti s'attaccavano i più vicini nemici, gli uni cercando la morte
gli altri la gloria. E cominciando la battaglia per tempo al mattino, Teia
riparato dallo scudo e imbrandita la lancia stava in luogo cospicuo
innanzi alla falange. Quando i Romani lo videro, pensarono che s'egli
cedesse sarebbe più facile romper tutta la linea di battaglia, onde
quanti pretendevano d'aver coraggio, ed eran molti, s'adunarono
insieme contro di lui, alquanti appuntando in lui le lancie altri
scagliandogliele addosso. Ma egli celato dallo scudo, in questo
riceveva i dardi e poi a un tratto gettandosi sui nemici, molti ne
uccideva. E quando vedeva che lo scudo era carico di dardi, ei lo dava
ad uno de' suoi scudieri e prendevane un altro. Così continuò a
combattere per una terza parte del giorno, quando essendo il suo
scudo trapassato da dodici dardi ei non poteva più muoverlo a posta
sua nè respingere i suoi assalitori. Ma egli soltanto chiamò in fretta
uno dei suoi scudieri, senza lasciar suo posto o dare indietro un pollice
o lasciare il nemico avanzarsi, e senza rivolgersi o coprirsi le spalle con
lo scudo o mettersi da lato; ma egli stava con lo scudo come piantato
in terra, menando colpi mortali colla destra, tenendo tutti a distanza
colla manca, e chiamando per nome il suo scudiero. E allorché questi
gli portò lo scudo, ei subito lo cambiò con quel che aveva greve per
gl'infissi dardi. In quella avvenne che gli rimase il petto scoperto un
momento e un giavellotto colselo e l'uccise di colpo. E alcuni Romani
infissero una picca al capo suo e questo portarono attorno
mostrandolo ai due eserciti; ai Romani per incorarli, ai Goti affinché,
sparita ogni speranza, cessassero la guerra. Pure nemmen per questo
i Goti lasciarono il combattere, ancora che per certo sapessero ch'era
morto il re loro. Ma quando fu scuro, gli uni e gli altri separandosi
passaron la notte entro l'arme, e sorgendo presto il mattino appresso
venner fuori di nuovo nell'ordine medesimo e combatterono fino a
notte, gli uni non cedendo agli altri nè rivolgendosi o lasciando presa
un momento, avvegnaché molti restassero morti d'ambo i lati, ma
ostinandosi nel contrasto e infuriati a vicenda. Imperocché i Goti bene
sapevano di combattere la battaglia suprema e i Romani stimavano
troppo da meno di loro l'essere vinti. Da ultimo i barbari spedirono
alcuni di lor capi a Narsete dicendo d'essere omai persuasi ch'eglino
contendevano con Dio perché sentivano che il poter suo stava
contr'essi. Perciò considerando questa verità al paragone di quanto
era accaduto, desideravano mutar d'avviso e cessare la lotta non già
per obbedire all'imperatore ma per vivere liberamente con altri
barbari. E chiesero che i Romani li lasciassero ritirarsi in pace e non
contrastassero a loro un trattamento ragionevole, ma concedessero
loro come mantenimento pel viaggio tutta la moneta ch'essi tenevan
raccolta in lor castella in Italia. E mentre Narsete stava deliberando,
Giovanni figlio di Vitaliano lo consigliò di acconsentire alla domanda, e
che non era da seguitare a combatter con uomini disposti a morire, nè
porre più oltre a prova una virtù che veniva da disperazione e del pari
era funesta a chi la mostrava e a chi l'opponeva. ‘Imperocché, egli
disse, all'uom saggio dovrebbe bastare il vincere, e il voler troppo
rischia d'essere in pregiudizio d'ambe le parti’. Questo consiglio
piacque a Narsete, e combinarono che quanti rimanevano dei barbari,
raccolti i lor beni tosto se n'andassero fuori d'Italia, e per nessuna
ragione combattessero più contro i Romani. Frattanto circa mille dei
Goti, lasciato il campo s'erano recati alla città di Pavia e alle contrade
di là dal Po; e quell'Indulfo che abbiam già menzionato era tra coloro
che li conducevano. Ma tutti gli altri confermarono per giuramento
quanto s'era combinato. Così i Romani presero Cuma e tutti gli altri
luoghi, e questo fu il termine del decimottavo anno della guerra coi
Goti che fu scritta da Procopio.»
In Cassiodoro e Procopio si riassume tutta la storia di questa età, ma
v'hanno insieme alcuni scrittori minori degni di menzione. Agatia
continuò, anch'egli in greco, la storia di Procopio narrando le imprese
di Narsete, e può essere consultato con frutto circa le ultime vicende
della guerra gotica dopo la morte di Teia [28]. Un'arida cronaca latina è
quella di Marcellino Conte, la quale dai tempi di Teodosio va fino a
quelli di Giustiniano (A. D. 379-558), ma pur malgrado l'aridità sua ha
valore specialmente per la cronologia di alcuni fatti. Lo stesso può dirsi
per la cronaca di Mario Aventicense [29]. Assai superiore a costoro per
interesse e per pregio è Magno Felice Ennodio vescovo di Pavia. Di
stirpe indubbiamente gallo-romana e nobile, nacque per quanto pare a
Pavia e certo v'ebbe dimora fanciullo. Fu legato di parentela e
d'amicizia coi primi uomini del suo tempo e più segnalati per sapere e
per nascita. Ebbe moglie ed un figlio, ma più tardi egli e la sposa
lasciato il secolo si consacrarono alla Chiesa. Nominato diacono,
Ennodio rimase lungamente in tal grado finché fu chiamato alla dignità
di vescovo di Pavia dove morì verso il 521. Godè riputazione grande
come retore a' suoi tempi, e scrisse in nome suo e d'altrui moltissime
orazioni, lettere ed epitaffi per cui fu celebrato largamente. Ma la fama
maggiore gli venne da un panegirico di Teodorico e da un libro
apologetico in favore di papa Simmaco. Il panegirico fu scritto nei
primi anni del sesto secolo. Non è ben certo in quale città fosse
recitato a Teodorico, e taluno reca valide ragioni per credere che esso
non sia stato recitato mai [30]. È scrittura di pessimo gusto,
abbondante in tutti i difetti dello stile di Cassiodoro, scarsa nei pregi.
La povertà di migliori documenti le dà qualche importanza storica ma
non certo paragonabile alla importanza delle sue lettere e della vita di
Santo Epifanio vescovo di Pavia. Le lettere dirette quasi sempre a
personaggi cospicui, contengono molte notizie preziose per gli studiosi
del secolo quinto e del sesto. La vita di Santo Epifanio poi non pure
dipinge l'accesa carità d'un santo tutto rivolto a riscattar coloro che i
barbari nelle loro incursioni trascinavano schiavi fuor della patria, ma è
una pittura viva della torbida età che precedette immediatamente i
tempi gotici, torbidi anch'essi e sovra i quali purtroppo incombono
oramai tempi di maggior dolore [31].
Capitolo II
ebookgate.com