100% found this document useful (6 votes)
82 views

Instant download Practical Maya Programming with Python 1st Edition Galanakis pdf all chapter

Galanakis

Uploaded by

xenyaomeonu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (6 votes)
82 views

Instant download Practical Maya Programming with Python 1st Edition Galanakis pdf all chapter

Galanakis

Uploaded by

xenyaomeonu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 71

Visit https://ebookgate.

com to download the full version and


explore more ebooks

Practical Maya Programming with Python 1st Edition


Galanakis

_____ Click the link below to download _____


https://ebookgate.com/product/practical-maya-
programming-with-python-1st-edition-galanakis/

Explore and download more ebooks at ebookgate.com


Here are some recommended products that might interest you.
You can download now and explore!

Maya Python for Games and Film A Complete Reference for


Maya Python and the Maya Python API 1st Edition Adam
Mechtley
https://ebookgate.com/product/maya-python-for-games-and-film-a-
complete-reference-for-maya-python-and-the-maya-python-api-1st-
edition-adam-mechtley/
ebookgate.com

Python Programming for Arduino Develop practical Internet


of Things prototypes and applications with Arduino and
Python Pratik Desai
https://ebookgate.com/product/python-programming-for-arduino-develop-
practical-internet-of-things-prototypes-and-applications-with-arduino-
and-python-pratik-desai/
ebookgate.com

Practical programming An introduction to computer science


using Python Jennifer Campbell

https://ebookgate.com/product/practical-programming-an-introduction-
to-computer-science-using-python-jennifer-campbell/

ebookgate.com

Rapid GUI Programming with Python and Qt The Definitive


Guide to PyQt Programming paperback 1st Edition
Summerfield
https://ebookgate.com/product/rapid-gui-programming-with-python-and-
qt-the-definitive-guide-to-pyqt-programming-paperback-1st-edition-
summerfield/
ebookgate.com
Programming the Raspberry Pi Second Edition Getting
Started with Python Simon Monk

https://ebookgate.com/product/programming-the-raspberry-pi-second-
edition-getting-started-with-python-simon-monk/

ebookgate.com

Ultimate Python Programming 1st Edition Deepali Srivastava

https://ebookgate.com/product/ultimate-python-programming-1st-edition-
deepali-srivastava/

ebookgate.com

Expert Python Programming 2nd Edition Jaworski

https://ebookgate.com/product/expert-python-programming-2nd-edition-
jaworski/

ebookgate.com

Python Programming 4th Edition Singh A.

https://ebookgate.com/product/python-programming-4th-edition-singh-a/

ebookgate.com

Black hat Python Python programming for hackers and


pentesters 1st Edition Seitz

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.

First published: July 2014

Production reference: 1180714

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

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

Content Development Editor

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."

A block of code is set as follows:


def spam():
return 'spam!'

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

Any command line input or output is written as follows:


> mayapy --version
Python 2.6.4

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.

Please contact us at <copyright@packtpub.com> with a link to the suspected pirated material.

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.

You can also contact the author, Robert Galanakis, at <rob.galanakis@gmail.com>.


Chapter 1. Introspecting Maya, Python, and PyMEL
Maya and Python are both excellent and elegant tools that can together achieve amazing results. And while it may be
tempting to dive in and start wielding this power, it is prudent to understand some basic things first. Knowledge of
the fundamentals will provide the platform from which we will grow great skills and conquer our obstacles
throughout the rest of this book.

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'>

The following is the equivalent commands on OS X or Linux:


$ export PYTHONPATH=$PYTHONPATH:~/mayapybook/pylib
$ mayapy
>>> import sys
>>> '~/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.
Random documents with unrelated
content Scribd suggests to you:
THE COST OF THE COALITION MINISTRY.

It is probable that ere these pages issue from the press, war will
have been formally declared with Russia, and Great Britain will be
irretrievably engaged in a contest of which it is impossible to see the
termination. Already our choicest troops have left our shores for the
Mediterranean, inspired by the cheers and accompanied by the
blessing of many hundreds of thousands of their fellow-countrymen,
who, for the first time in their lives, have witnessed so solemn yet
exciting a spectacle. Already has a noble fleet sailed for the waters of
the Baltic, to sweep that inland sea, and to launch its thunders
against the foe. Wellnigh forty years have elapsed since such din of
martial preparation has been heard. On the last occasion, Russia and
Britain were combined against France—now, Britain and France are
combined together against Russia. Such a struggle, so commenced,
must be a desperate, but not therefore necessarily a short one. We
cannot yet calculate on the part to be taken by the central powers of
Europe; for, notwithstanding Lord Clarendon’s assurance that
Austria is with us, we have every reason to believe that the
government of that country is so closely leagued with Russia, that
when compelled to throw off its appearance of neutrality, its forces
will be ranged upon her side.[11] We cannot depend upon the cordial
co-operation of Prussia—which power, besides having no direct
interest in the Eastern quarrel, is intimately allied with Russia, and
has always acted, during times of European disturbance, with a view
to its own aggrandisement. It would be folly to underrate the
magnitude of the contest in which we are engaging. The re-
pacification of Europe cannot be achieved without an enormous
expenditure of blood and treasure, and without very considerable
alterations in its territorial adjustment. The war once begun, Russia
will know that she is fighting, not for the occupation of the Danubian
provinces, but for the retention of the territories which she has
absorbed or pillaged from her neighbours. The penalty she must pay
in the event of defeat is dismemberment, and she will resist that to
the uttermost.
We must not, therefore, blind ourselves to consequences, which, in
so far as human judgment can go, appear to be inevitable. We may be
able to disperse or even to annihilate the Russian fleets in the Baltic
and the Black seas—we may be able to prevent the colossal northern
power from crossing the Danube, or even beat it back from the
Principalities—but the contest will not end there. We are on the verge
of a general European embroilment, in which there will not only be
wars, but bloody revolutions; and as we have been the first to enter,
so we must be the last to withdraw. We do not say this for the
purpose of checking enthusiasm—God forbid! We are already
committed to the struggle; and if in the minds of any there has
lingered a doubt as to the propriety of Christian intervention for the
maintenance of a Mahometan power in Europe, that ought to be
dispelled by the revelations recently made of the objects of the
Russian ambition. The Czar is no crusader; nor is he influenced by
any tender regard for the religious liberties of the Christian
population dwelling beneath the government of the Sultan. He has
set his eyes upon Turkey, just as Catherine in 1772 fixed hers upon
Poland, and he has had the astounding effrontery to propose that
Great Britain should take part in the spoliation. Here is his own
proposition, as communicated to Lord John Russell, by Sir G. H.
Seymour, in his despatch of 22d February 1853:—

“The Emperor went on to say that, in the event of the dissolution of the Ottoman
empire, he thought it might be less difficult to arrive at a satisfactory territorial
arrangement than was commonly believed. ‘The Principalities are,’ he said, ‘in fact
an independent state under my protection; this might so continue. Servia might
receive the same form of government. So again with Bulgaria. There seems to be no
reason this province should not form an independent state. As to Egypt, I quite
understand the importance to England of that territory. I can then only say that if,
in the event of a distribution of the Ottoman succession upon the fall of the
empire, you should take possession of Egypt, I shall have no objections to offer. I
would say the same thing of Candia: that island might suit you, and I do not
know why it should not become an English possession.’”
Such was the language used by the Emperor of Russia to the
British minister at the Court of St Petersburg, and we really cannot
imagine anything more absolutely infamous. It was a bribe, tendered
evidently in the belief that it would be accepted; and the offer ought
to have been at once most indignantly repelled. Was it so? We shall
see presently—for the correspondence recently published is far too
remarkable and momentous to be passed over with a single extract
from its contents.
The Government of Lord Aberdeen, it will be remembered,
acceded to office in the latter part of December 1852. On the 9th of
January following, the Emperor Nicholas, at a private meeting in the
palace of the Grand-duchess Helen, thus approached Sir G. H.
Seymour. We shall be as short in quotation as possible; but it is
absolutely necessary that the leading points of such an extraordinary
transaction as this should be kept before the public view. We quote
from Sir Hamilton Seymour’s despatch to Lord John Russell, then
Foreign Secretary, of date 11th January 1853:—

“The Emperor came up to me, in the most gracious manner, to say that he had
heard with great pleasure of Her Majesty’s Government having been definitively
formed, adding that he trusted the Ministry would be of long duration.
“His Imperial Majesty desired me particularly to convey this assurance to the
Earl of Aberdeen, with whom, he said, he had been acquainted for nearly forty
years, and for whom he entertained equal regard and esteem. His Majesty desired
to be brought to the kind recollection of his Lordship.”

Then follows the report of some expressions regarding the close


amity which ought to prevail between the two countries, and their
community of interests, which, being general, we may pass over: but
Nicholas speedily comes to the point—

“In the mean time, the Emperor went on to say—‘I repeat, that it is very essential
that the two Governments—that is, that the English Government and I, and I and
the English Government—should be upon the best terms; and the necessity was
never greater than at present. I beg you to convey these words to Lord John
Russell. When we are agreed (d’accord), I am quite without anxiety to the west of
Europe; it is immaterial what the others may think or do. As to Turkey, that is
another question; that country is in a critical state, and may give us all a great deal
of trouble. And now I will take my leave of you,’ which His Majesty proceeded to do
by shaking hands with me very graciously.”

The Czar probably thought that he had said enough in the first
instance, and that it would be prudent to allow Sir Hamilton
Seymour to chew, for a day or two, the cud of thought. But that active
and astute diplomatist saw that something more than common was
intended, and pressed for a further explanation. The following
conversation is certainly as curious as any which is recorded in the
pages of history:—

“‘Sir,’ I observed, ‘your Majesty has been good enough to charge me with general
assurances as to the identity of views between the two Cabinets, which assuredly
have given me the greatest pleasure, and will be received with equal satisfaction in
England; but I should be particularly glad that your Majesty should add a few
words which may tend to calm the anxiety with regard to the affairs of Turkey,
which passing events are so calculated to excite on the part of Her Majesty’s
Government. Perhaps you will be pleased to charge me with some additional
assurances of this kind.’
“The Emperor’s words and manner, although still very kind, showed that His
Majesty had no intention of speaking to me of the demonstration which he is
about to make in the South. He said, however, at first with a little hesitation, but,
as he proceeded, in an open and unhesitating manner—‘The affairs of Turkey are in
a very disorganised condition; the country itself seems to be falling to pieces
(menace ruine); the fall will be a great misfortune, and it is very important that
England and Russia should come to a perfectly good understanding upon these
affairs, and that neither should take any decisive step of which the other is not
apprised.’
“I observed in a few words, that I rejoiced to hear that His Imperial Majesty held
this language; that this was certainly the view I took of the manner in which
Turkish questions were to be treated.
“‘Tenez,’ the Emperor said, as if proceeding with his remark, ‘tenez; nous avons
sur les bras un homme malade—un homme gravement malade; ce sera, je vous le
dis franchement, un grand malheur si, un de ces jours, il devait nous échapper,
surtout avant que toutes les dispositions nécessaires fussent prises. Mais enfin ce
n’est point le moment de vous parler de cela.’
“It was clear that the Emperor did not intend to prolong the conversation. I
therefore said, ‘Votre Majesté est si gracieuse qu’elle me permettra de lui faire
encore une observation. Votre Majesté dit que l’homme est malade; c’est bien vrai,
mais votre Majesté daignera m’excuser si je lui fais observer, que c’est à l’homme
généreux et fort de ménager l’homme malade et faible.’
“The Emperor then took leave of me in a manner which conveyed the impression
of my having, at least, not given offence, and again expressed his intention of
sending for me on some future day.”

It is proper to subjoin Sir Hamilton Seymour’s own impressions of


this interview, as communicated to Lord John Russell.

“Your Lordship will pardon me if I remark that, after reflecting attentively upon
my conversation with the Emperor, it appears to me that this, and any overture of
the kind which may be made, tends to establish a dilemma by which it is very
desirable that Her Majesty’s Government should not allow themselves to be
fettered. The dilemma seems to be this:—If her Majesty’s Government do not come
to an understanding with Russia as to what is to happen in the event of the sudden
downfall of Turkey, they will have the less reason for complaining if results
displeasing to England should be prepared. If, on the contrary, Her Majesty’s
Government should enter into the consideration of such eventualities, they make
themselves in some degree consenting parties to a catastrophe which they have so
much interest in warding off as long as possible.
The sum is probably this:—That England has to desire a close concert with
Russia, with a view to preventing the downfall of Turkey; while Russia would be
well pleased that the concert should apply to the events by which this downfall is to
be followed.”

In a postscript to this despatch, we learn that the Emperor had


communicated to the Austrian Minister the tenor of the above
conversation. That circumstance is, to say the least of it, significant.
Five days afterwards, Sir Hamilton Seymour waited upon the
Emperor, at the request of the latter, and was favoured from the
imperial lips with a remarkably choice specimen of what our Irish
friends denominate blarney. The Czar began by asseverating that he
had not the least intention of increasing the extent of his territorial
dominions. The only danger, he said, which he could foresee to
Russia would arise from an extension given to an empire already too
large. From this general statement he presently condescended to
particulars.

“Close to us lies Turkey, and, in our present condition, nothing better for our
interests can be desired; the times have gone by when we had anything to fear from
the fanatical spirit or the military enterprise of the Turks, and yet the country is
strong enough, or has hitherto been strong enough, to preserve its independence,
and to insure respectful treatment from other countries.”

These were, we venture to think, injudicious premises on the part


of the Emperor, for they are tantamount to an admission that
Turkey, if left alone, was quite able to maintain its own position. We
are not quite sure that the same could be said of Austria, which, but a
few years ago, owed its integrity to the intervention of Russian
bayonets. Be that as it may, the Emperor went on to state that he had
the right of surveillance over some millions of Christians in the
Ottoman empire—a right which he regarded as a duty, but used
sparingly, because it was “attended with obligations occasionally very
inconvenient.” And then we arrive at a statement, quite inconsistent,
we think, with what had gone before.

“Now, Turkey, in the condition which I have described, has by degrees fallen into
such a state of decrepitude, that, as I told you the other night, eager as we all are
for the prolonged existence of the man (and that I am as desirous as you can be for
the continuance of his life, I beg you to believe), he may suddenly die upon our
hands (nous rester sur les bras); we cannot resuscitate what is dead: if the Turkish
empire falls, it falls to rise no more; and I put it to you, therefore, whether it is not
better to be provided beforehand for a contingency, than to incur the chaos,
confusion, and the certainty of a European war, all of which must attend the
catastrophe if it should occur unexpectedly, and before some ulterior system has
been sketched? This is the point to which I am desirous that you should call the
attention of your Government.”

We had better give in extenso the conversation which immediately


followed; because we think that Sir Hamilton Seymour might,
without any breach of propriety, have used more decided language
than he did employ, with regard to the view likely to be taken by the
British Cabinet. We are quite aware of the difficulties of an
ambassador in such a situation; still we cannot avoid the conclusion
that Sir H. Seymour was unnecessarily timid, and not nearly decided
enough in the tone which he assumed. He objected, indeed, but the
objection was rather feeble; which was unfortunate, as his principal
in England immediately adopted the like inconclusive tone.
“‘Sir,’ I replied, ‘your Majesty is so frank with me that I am sure you will have the
goodness to permit me to speak with the same openness. I would then observe
that, deplorable as is the condition of Turkey, it is a country which has long been
plunged in difficulties supposed by many to be insurmountable. With regard to
contingent arrangements, her Majesty’s Government, as your Majesty is well
aware, objects, as a general rule to taking engagements upon possible eventualities,
and would, perhaps, be particularly disinclined to doing so in this instance. If I
may be allowed to say so, a great disinclination (répugnance) might be expected in
England to disposing by anticipation (d’escompter) of the succession of an old
friend and ally.’
“‘The rule is a good one,’ the Emperor replied, ‘good at all times, especially in
times of uncertainty and change, like the present: still it is of the greatest
importance that we should understand one an other, and not allow events to take
us by surprise; maintenant je désire vous parler en ami et en gentleman; si nous
arrivons à nous entendre sur cette affaire, l’Angleterre et moi, pour le reste peu
m’importe; il m’est indifferent ce que font ou pensent les autres. Usant donc de
franchise, je vous dis nettement, que si l’Angleterre songe à s’établir un de ces jours
à Constantinople, je ne le permettrai pas; je ne vous prête point ces intentions,
mais il vaut mieux dans ces occasions parler clairement; de mon côté, je suis
également disposé de prendre l’engagement de ne pas m’y établir, en propriétaire
il s’entend, car en dépositaire je ne dis pas; il pourrait se faire que les
circonstances me misent dans le cas d’occuper Constantinople, si rien ne se trouve
prévu, si l’on doit tout laisser aller au hazard.’
“I thanked his Majesty for the frankness of his declarations, and for the desire
which he had expressed of acting cordially and openly with her Majesty’s
Government, observing at the same time that such an understanding appeared the
best security against the sudden danger to which his Majesty had alluded. I added
that, although unprepared to give a decided opinion upon questions of such
magnitude and delicacy, it appeared to me possible that some such arrangement
might be made between her Majesty’s Government and his Majesty as might
guard, if not for, at least against certain contingencies.
“To render my meaning more clear,” I said, further, “I can only repeat, Sir, that
in my opinion her Majesty’s Government will be indisposed to make certain
arrangements connected with the downfall of Turkey, but it is possible that they
may be ready to pledge themselves against certain arrangements which might, in
that event, be attempted.”

We have no desire whatever to reflect upon the conduct of the


prudence of Sir Hamilton Seymour, but we cannot help saying that
he seems to have missed one very material point—that being a
distinct explanation of the quarter from which the anticipated
danger to Turkey was to arise. Sir Hamilton was perfectly justified
in intimating that Britain did not intend to subvert the integrity of
Turkey, and that she would not be passive if France were to manifest
such a design. There was no earthly danger from either quarter; and
certainly Austria, whatever she may wish to have or is ready to
receive, would not have dared, under existing circumstances, to
disturb the peace of Europe. Turkey itself was in a far better position
than it ever had been. “L’homme gravement malade,” was exhibiting
every symptom of convalescence, and the only danger to be
apprehended was from the Muscovite doctor, who, without being
summoned, was preparing to administer his pills. Therefore, we
think that the rejoinder to the Emperor’s confidences—subject, of
course, to the official Cabinet approval—should have been in the
shape of a query as to the nature of the apprehended danger. The
Czar had protested, in the most emphatic language, that he was
“eager for the prolonged existence of the man;” and, if that were the
case, his dissolution was an event much less likely than that of many
a dynasty of Christian Europe. With Russia and Britain as
determined protectors, who was to give him the coup-de-grace?
Surely Sir Hamilton Seymour erred in not putting that point more
forcibly and distinctly in his confidential conversations with the
Emperor.
We say this, because the last paragraph in Sir Hamilton Seymour’s
despatch, of 22d January 1853, to Lord John Russell shows that he
was not altogether uninfluenced by the Imperial blandishments and
affectation of perfect sincerity.

“A noble triumph would be obtained by the civilisation of the nineteenth century


if the void left by the extinction of Mahommedan rule in Europe could be filled up
without an interruption of the general peace, in consequence of the precautions
adopted by the two principal Governments the most interested in the destinies of
Turkey.”

Precautions indeed! Precautions which would have made Russia,


without assuming the name of proprietor, the virtual and absolute
occupier of Constantinople, with the power of the keys of the
Bosphorus! It is marvellous that so acute a minister as Sir Hamilton
Seymour—who otherwise deserves great praise for his lucid
exposition of the designs and motives of the Czar—did not perceive
that any approach to an arrangement for disposing of the
inheritance, was tantamount to a declaration of the immediate
dissolution of Turkey.
In answer to these communications, Lord John Russell, on the 9th
February, forwarded a despatch, of the wisdom of which it is for the
public to form their own opinion. It commences with an
acknowledgment of “the moderation, the frankness, and the friendly
disposition of his Imperial Majesty.” Why the first of these terms
should have been employed, we really do not comprehend. Then
Lord John, adverting to the indirect proposal of the Emperor,
observes that—“In considering this grave question, the first reflection
which occurs to Her Majesty’s Government is, that no actual crisis
has occurred which renders necessary a solution of this vast
European problem”—that “there is no sufficient cause for intimating
to the Sultan that he cannot keep peace at home, or preserve friendly
relations with his neighbours”—and that “it occurs further to her
Majesty’s Government to remark that the event which is
contemplated is not definitely fixed in point of time.” After pointing
out the impropriety as well as the impolicy of devising a partition for
providing for a settlement under such circumstances, Lord John
intimates, in tolerably distinct terms, that “neither England nor
France, nor probably Austria, would be content to see
Constantinople permanently in the hands of Russia.” He then draws
the following conclusions:—

“Upon the whole, then, Her Majesty’s Government are persuaded that no course
of policy can be adopted more wise, more disinterested, more beneficial to Europe,
than that which His Imperial Majesty has so long followed, and which will render
his name more illustrious than that of the most famous sovereigns who have
sought immortality by unprovoked conquest and ephemeral glory.
“With a view to the success of this policy, it is desirable that the utmost
forbearance should be manifested towards Turkey; that any demands which the
Great Powers of Europe may have to make should be made matter of friendly
negotiation rather than of peremptory demand; that military and naval
demonstrations to coerce the Sultan should as much as possible be avoided; that
differences with respect to matters affecting Turkey, within the competence of the
Sublime Porte, should be decided after mutual concert between the great powers,
and not be forced upon the weakness of the Turkish Government.”
To this succeeds a passage which we cannot help considering as
unfortunate, because it gives decided colour to the Russian pretext,
that a protectorate over Turkey was necessary for securing the rights
of the Christian inhabitants. There was no occasion whatever for its
introduction, especially as the Emperor had not thought it necessary
to ask advice upon the subject:—

“To these cautions Her Majesty’s Government wish to add, that in their view it is
essential that the Sultan should be advised to treat his Christian subjects in
conformity with the principles of equity and religious freedom which prevail
generally among the enlightened nations of Europe. The more the Turkish
Government adopts the rules of impartial law and equal administration, the less
will the Emperor of Russia find it necessary to apply that exceptional protection
which his Imperial Majesty has found so burdensome and inconvenient, though no
doubt prescribed by duty and sanctioned by treaty.

We observe that the Times, notwithstanding its notorious


ministerial leaning, has declined awarding praise to this state
document, and we are not surprised at it. It is dissuasive and
declinatory, but it is altogether feeble. We should have expected to
find in it, not hypocritical acknowledgments of Imperial moderation
and so forth, but a distinct, firm, and energetic protest against any
attempt to disturb the peace, or to violate the integrity of Turkey. The
infamous proposals made to Britain—for they were infamous not
only as regarded Turkey but other European powers—should have
been rejected in a manner that could have left no doubt in the mind
of the Czar as to the part which the British Government was prepared
to take in the event of his entering into hostilities with the Sultan.
From the beginning to the end of this despatch there is not a single
word which can be construed into a plain warning to the Czar, that
any attempt made by him upon Turkey would provoke the hostility of
Britain. On the contrary, the declinature to participate in the scheme
is mainly founded on the fact that no “actual crisis” has yet arrived;
but there is nothing said to indicate that Britain would oppose the
forcing on of such a crisis, if Russia thought proper to precipitate it;
and a more unlucky expression than “that the event which was
contemplated is not definitely fixed in point of time” it is utterly
impossible to conceive. The perusal of this despatch could leave no
other impression upon the mind of the Czar, than that the British
Ministry were afraid to commit themselves by entering into any
secret or separate treaty with Russia for the disposal of the Turkish
dominions, until a crisis actually should occur. That they would have
preferred the maintenance of the status quo to a disturbance of it,
was tolerably clear; but it was not in the least degree clear that they
would take umbrage at an act of aggression, or be indisposed to treat
with Russia after the aggression was made, and the weakness of the
Ottoman empire exhibited by its being forced to succumb to the
attack of the northern Colossus. The despatch, in short, was not
couched in such manly, distinct, and positive terms as a British
Secretary of State for foreign affairs should have employed on such
an occasion. It is weak, timid, and almost subservient; and we are
not in the least degree surprised to find that the Czar considered that
it gave him sufficient encouragement again to renew his attack. Here
is an extract from his next conversation with the British envoy, Sir
Hamilton Seymour.

“‘I think your Government does not well understand my object. I am not so eager
about what shall be done when the sick man dies, as I am to determine with
England what shall not be done upon that event taking place.’
“‘But, sir,’ I replied, ‘allow me to observe, that we have no reason to think that
the sick man (to use your Majesty’s expression) is dying. We are as much
interested as we believe your Majesty to be in his continuing to live; while, for
myself, I will venture to remark that experience shows me that countries do not die
in such a hurry. Turkey will remain for many a year, unless some unforeseen crisis
should occur. It is precisely, sir, for the avoidance of all circumstances likely to
produce such a crisis that Her Majesty’s Government reckons upon your generous
assistance.’
“‘Then,’ rejoined the Emperor, ‘I will tell you that, if your Government has been
led to believe that Turkey retains any elements of existence, your Government
must have received incorrect information. I repeat to you, that the sick man is
dying; and we can never allow such an event to take us by surprise. We must come
to some understanding; and this we should do, I am convinced, if I could hold but
ten minutes’ conversation with your Ministers—with Lord Aberdeen, for instance,
who knows me so well, who has full confidence in me, as I have in him. And,
remember, I do not ask for a treaty or a protocol; a general understanding is all I
require—that between gentlemen is sufficient; and in this case I am certain that the
confidence would be as great on the side of the Queen’s Ministers as on mine.’”
The despatch, containing the report of this conversation, was
written on the 21st February, and received at the Foreign Office on
6th March 1853; so that the Emperor Nicholas, whatever may be
thought of his conduct otherwise, cannot be justly charged with
deliberate perfidy in concealing his views from our Government.
Indeed, Sir Hamilton Seymour, in this very document, gave Lord
John Russell a distinct intimation of the real objects of the Czar.

“It can hardly be otherwise but that the Sovereign, who insists with such
pertinacity upon the impending fall of a neighbouring state, must have settled in
his own mind that the hour, if not of its dissolution, at all events for its dissolution,
must be at hand.
“Then, as now, I reflected that this assumption would hardly be ventured upon
unless some, perhaps general, but at all events intimate understanding, existed
between Russia and Austria.
“Supposing my suspicion to be well founded, the Emperor’s object is to engage
Her Majesty’s Government, in conjunction with his own Cabinet and that of
Vienna, in some scheme for the ultimate partition of Turkey, and for the exclusion
of France from the arrangement.”

On the following day a more particular, and, if possible, more


interesting, conversation took place between the Czar and the British
envoy. We regret extremely that our limits will not allow us to detail
this so fully as we could wish, but we shall advert to the principal
points, which were in the form of a commentary upon Lord John
Russell’s despatch. The Emperor began by saying,—

“That he was, perhaps, even more interested than England could be in


preventing a Turkish catastrophe, but that it was constantly impending; that it
might be brought about at any moment, either by an external war, or by a feud
between the old Turkish party and that of the ‘new superficial French reforms,’ or
again, by a rising of the Christians, already known to be very impatient of shaking
off the Mussulman yoke. As regards the first cause, the Emperor said that he had a
good right to advert to it, inasmuch as, if he had not stopped the victorious
progress of General Diebitch in 1829, the Sultan’s authority would have been at an
end.”
Next he descanted upon what could not be permitted in the event
of a break-up of the Ottoman empire. This is perhaps the most
curious passage of the whole.

“‘Well, there are several things which I never will tolerate; I will begin by
ourselves. I will not tolerate the permanent occupation of Constantinople by the
Russians; having said this, I will say that it never shall be held by the English, or
French, or any other great nation. Again, I never will permit an attempt at the
reconstruction of a Byzantine empire, or such an extension of Greece as would
render her a powerful state; still less will I permit the breaking up of Turkey into
little republics, asylums for the Kossuths and Mazzinis, and other revolutionists of
Europe; rather than submit any of these arrangements I would go to war, and as
long as I have a man and a musket left would carry it on. These,’ the Emperor said,
‘are at once some ideas; now give me some in return.’”

This was an awkward demand, but Sir H. Seymour seems to have


acquitted himself with sufficient adroitness. He put the following
case: “How would it be if, in the event of any catastrophe occurring
in Turkey, Russia and England were to declare that no Power should
be allowed to take possession of its provinces; that the property
should remain, as it were, under seals, until amicable arrangements
could be made as to its adjudication?” Of course this notion could
not be countenanced; and the Emperor’s reply allowed Sir Hamilton
the opportunity of making the following remark:—

“‘Sir,’ I then observed, ‘if your Majesty will allow me to speak plainly, I would say
that the great difference between us is this—that you continue to dwell upon the
fall of Turkey, and the arrangements requisite before and after the fall; and that
we, on the contrary, look to Turkey remaining where she is, and to the precautions
which are necessary for preventing her condition from becoming worse.’ ‘Ah!’
replied the Emperor, ‘that is what the Chancellor is perpetually telling me; but the
catastrophe will occur some day, and will take us all unawares.’”

Then follows a passage of very great interest at the present


moment, when the course which Austria may adopt is still matter of
speculation. Our impression has been, and is, that she will ultimately
co-operate with Russia.
“Being desirous, if possible, of ascertaining whether there was any
understanding between the Cabinets of St Petersburg and Vienna, I added, ‘But
your Majesty has forgotten Austria; now all these Eastern questions affect her very
nearly; she, of course, would expect to be consulted.’ ‘Oh!’ replied the Emperor,
greatly to my surprise, ‘but you must understand that when I speak of Russia I
speak of Austria as well: what suits the one suits the other; our interests as regards
Turkey are perfectly identical.’ I should have been glad to make another inquiry or
two upon this subject, but I did not venture to do so.”

Next comes the bribe—for we can call it nothing else—implied in


the Emperor’s statement, already quoted, that he saw no reason why,
in the event of the dissolution of the Ottoman empire, Great Britain
should not obtain possession of Egypt and Candia! And so
completely does he seem to have considered that point settled, that a
few days afterwards, and without any further intercourse with
Britain (for so we are given to understand), a confidential
memorandum, dictated by the Czar, and containing the following
passage, was placed in the hands of Sir Hamilton Seymour:—

“In short, the Emperor cannot but congratulate himself at having given occasion
for this intimate interchange of confidential communications between Her Majesty
and himself. He has found therein valuable assurances, of which he takes note with
a lively satisfaction. The two Sovereigns have frankly explained to each other, what
in the extreme case of which they have been treating, their respective interests
cannot endure. England understands that Russia cannot suffer the establishment
at Constantinople of a Christian Power sufficiently strong to control and disquiet
her. She declares, that for herself she renounces any intention or desire to possess
Constantinople. The Emperor equally disclaims any wish or design of establishing
himself there. England promises that she will enter into no arrangement for
determining the measures to be taken in the event of the fall of the Turkish empire,
without a previous understanding with the Emperor. The Emperor, on his side,
willingly contracts the same engagement. As he is aware that in such a case he can
equally reckon upon Austria, who is bound by her promises to concert with him, he
regards with less apprehension the catastrophe which he still desires to prevent,
and avert as much as it shall depend on him to do so.”

This is, perhaps, the most extraordinary note that was ever issued.
If founded upon nothing else than Lord John Russell’s single
despatch of 9th February 1853, it is an attempt to make a
memorandum supply the place of a treaty, and that not with regard
to existing circumstances, but to a contingency involving the
destruction of an ally. The Emperor must, indeed, have had great
faith in the subserviency of the British Cabinet to his views, before he
could have ventured on such a step. Lord Clarendon now comes into
action, as the successor of Lord John Russell in the Home Office; but
we need not pursue the correspondence further than to say, that it
was conducted on the same principle of remonstrance, though very
feeble on the part of the British Minister, against the assumption that
Turkey was absolutely in a critical state, and of assertion to the
contrary on the part of the Czar. His object was to alienate Britain
from France—to keep the latter power out of any arrangement which
might be made for the partition of the Turkish territories—and to
hasten the crisis as fast as possible, in order that Britain might be
compelled to come to definite terms. Lord Clarendon’s despatches
are couched in terms quite unworthy of his position. Lord John
Russell, who had primarily to state the views of the British Cabinet,
may be excused for a certain weakness of expression; but no such
apology can be made for Lord Clarendon, who was bound
emphatically to have informed the Czar that this country disdained
his proposals, and was prepared, at any hazard, to maintain the
integrity of Turkey. We say that he was bound to have done so, on
the supposition that the Aberdeen Ministry disapproved of the
partition of Turkey, and were prepared, by force of arms, to oppose
it. Disapproval is of two kinds: There is the faint remonstrance,
which is usually considered to imply reluctant consent; and there is
strong distinct denial, which cannot possibly be misinterpreted. We
find no such strong distinct denial in Lord Clarendon’s despatches.
They are filled with almost fulsome adulation of the Czar, who had
previously tendered a bribe. Thus, in the despatch of 23d March, we
find the following passage:—

“The generous confidence exhibited by the Emperor entitles His Imperial


Majesty to the most cordial declaration of opinion on the part of Her Majesty’s
Government, who are fully aware that, in the event of any understanding with
reference to future contingencies being expedient, or indeed possible, the word of
His Imperial Majesty would be preferable to any convention that could be framed.”
Scarce less miserably sycophantish are the terms of the despatch of
April 5th. “My despatch of the 23d ult. will have furnished you with
answers upon all the principal points alluded to in the memorandum
which Count Nesselrode placed in your hands; but it is my duty to
inform you that that important and remarkable document was
received by her Majesty’s Government with feelings of sincere
satisfaction, as a renewed proof of the Emperor’s confidence and
friendly feelings; and her Majesty’s Government desire to convey
their acknowledgments to his Imperial Majesty for having thus
placed on record the opinions he expressed at the interview with
which you were honoured by his Imperial Majesty.”
We do not profess to know much about the language of diplomacy;
but if these are the sort of terms to be addressed to an avowed
disturber of the peace of Europe, who has attempted to engage us in
a conspiracy by offer of a bribe, we are at a loss to know what
language can afford by way of adequate encomium to a really honest
ally. The excuse of sincere belief in the sincerity of the Czar is entirely
precluded by the terms of the previous communications from Sir
Hamilton Seymour, which not only indicate but demonstrate the
game which the Autocrat was playing. It is certainly remarkable to
observe the extreme cordiality with which the Emperor greeted the
accession of his old friend, Lord Aberdeen, to power, and the
fervency of his wishes for his long continuance in office. Immediately
thereafter—or rather on the same occasion—he begins to develop his
designs upon Turkey, states his prognosis of the condition of the sick
gentleman, and requests to be informed what are our views as to the
partition of his property. Our Ministers demur as to the fact of the
sickness; but the Imperial Doctor assures them that it is so, or shall
immediately be so, and states that he will be contented with a
temporary occupation of the dying man’s domicile—the catastrophe
to be hastened by a bolus of his own administration—but that we are
perfectly welcome to seize upon certain outlying hereditaments! And
in return to such proposals, which, if agreed to, would have made us
deservedly infamous throughout Europe, the Ministers of Queen
Victoria think fit to beslaver the Czar! Since the days of Charles II.
England has seen no similar instance of adulation to a foreign
potentate.
The correspondence is now before the world, and the public must
decide whether it is such as to justify Lord Aberdeen’s assertion, in
reply to Lord Derby, “that if he thought it would be found to contain
anything on which a charge could be founded against the
Government, he would find himself egregiously mistaken.”
Undoubtedly they are not chargeable with connivance—but they are
chargeable with incapacity and misconduct so gross, that even
connivance could not have produced effects more disastrous. If they
did not play directly into the hands of the Czar, they failed to make
him aware of the part which they were bound to take should he
persist in his nefarious designs. They manifested no kind of
honourable indignation at his offers; they received his cajolements
with complacency, and paid him back with compliments and
assurances not one whit more sincere than his own. If this really is
the style in which our diplomatic intercourse is usually conducted,
there is ample room for a reform. They cannot with justice assert that
the Emperor was keeping them in the dark as to the nature of his
own projects. He was, on the contrary, particularly frank. He
insisted, over and over again, that Turkey was on the eve of
dissolution; he even indicated that he might himself be the agent to
force on that catastrophe—and yet Lord Aberdeen and his colleagues
are now maintaining that he had deceived them! How, where, and
when were they deceived? He showed them the victim, prophesied
his immediate death, intimated that the fatal deathblow might be
given by his hand, told them that he was in accord with Austria,
invited them to declare their wishes as to the subsequent partition,
and emphatically assured them that there was no time to be lost. Let
us call things by their proper names. Stigmatise the conduct of the
Czar, if you will, as ambitious, tyrannical, unprincipled, or nefarious
—but do not accuse him of having concealed his purpose from the
British Ministry.
Were the Ministers then so blind that they failed to perceive his
purpose? Of course they were not. The Cabinet which contained
Lords Aberdeen and Palmerston, both of them experienced in
foreign affairs, could be at no loss to divine his meaning, even if that
had been more obscurely expressed; and consequently we must
conclude that so early as March 1853 they were put thoroughly on
their guard. They were aware that the Czar meditated the destruction
of the Ottoman empire, and having that knowledge, every movement
of his in the East, whether diplomatic or military, could only be
regarded as progressive means towards the end proposed.
Now there were two courses open to Ministers. The one was to
have intimated at once, without any circumlocution or compliment,
that Great Britain would not submit to any invasion of the Turkish
territories on the part of a European power, but would be prepared,
by force of arms, to resist any such attempt. That would have been a
manly and honourable course; and we are satisfied that, if adopted,
the Czar would not have had the temerity to provoke a crisis.
Unfortunately no declaration was made. A faint dissuasive,
accompanied by an immense deal of complimentary sugar, was all
that our Ministers ventured to tender; and the Czar was accordingly
allowed to proceed, under the evident impression that Great Britain
would not actively interfere to prevent his designs upon Turkey, any
more than she interfered to prevent those of his ancestress upon
Poland.
The other course was to have maintained a strict neutrality, and to
have treated the Eastern question as an affair entirely between
Russia and Turkey. To that, however, it is more than doubtful
whether the people of this country would have submitted. The
appetite of Russia for territorial aggrandisement is so insatiable, and
her advances have been pushed so far, that the virtual cession to her
of so fair and fertile a country as Turkey, and the entire command of
the entrance to the Black Sea, would, very justly, have been deemed
an act of culpable cowardice. Setting aside the position of India, and
the facilities which the occupation of Turkey would afford for any
hostile demonstration upon that part of our dominions, we have
now, in consequence of Free Trade, a direct interest in the Danubian
Principalities, as so many granaries for our home consumption.
Since we ceased to act upon the principle of growing corn for our
own population, and made ourselves dependent upon foreign
supplies, it would be suicidal to give Russia the power of cutting us
short both in the north and on the south—in the Baltic and the Black
Seas. Still that was the only other course which Ministers could
consistently have adopted, if they wished to avoid or postpone the
terrible calamity of a war.
They followed neither the one course nor the other. They did not
tell the Czar that, if he persisted in the schemes which he had
disclosed to them, he must be prepared to meet Britain in the field;
nor did they tell him that, in so far as they were concerned, he might
do what he pleased with Turkey. They halted between two
opinions. In full knowledge of his designs, they allowed him to
commit himself—to pick a quarrel with Turkey about some rubbish
relating to the keys of the Holy Places—to march his forces across the
Pruth—to occupy the Principalities,—to do, in short, the work of one
effective campaign. They never intimated to the country that the
religious questions,—on which Russia, with scandalous hypocrisy,
rested her justification of invasion,—were mere pretexts to mask the
avowed intentions of Nicholas. They did not even send a fleet at once
to Constantinople, but kept it hovering between Malta and Besika
Bay, in the attitude of observation, long after the Russian guns were
roaring upon the Danube. Is it fair to suppose that Nicholas,—after
having frankly communicated to them his intentions more than a
twelvemonth ago; after having told them that the sick gentleman was
sure to die immediately; and after having taken measures to secure
the fulfilment of that prophecy,—could consider their late hesitating
and dilatory movement as otherwise than a convenient sham? It
must have appeared to him that if the British Government was
determined to oppose his project, they would at once have said so,
with the same openness which he manifested in his communications
to them. They said nothing of the kind. They gave him fulsome
compliments. Of course he went farther, and marched into the sick
man’s territory. What did our Ministers then? They concealed what
they knew, and entered into negotiations about the Russian
Protectorate of Christian subjects in Turkey, as if that were the sole
point which had occasioned the disturbance! What, under such
circumstances, could the Czar conceive, but that they were playing
into his hands? He had apprised them, in almost as many words, that
he intended to take possession of Turkey, so that they knew perfectly
well that the question involved was not one of religion, but of
political aggrandisement. It was, however, his policy to make it
appear to the uninitiated that religion was his paramount motive;
and when the British Cabinet began to negotiate and issue notes
upon that footing, he was, after the confidential correspondence
which had taken place, fairly entitled to believe that they were not in
earnest. The Czar is a remarkably able man—we question whether,
politically speaking, he is not the ablest man in Europe—but his own
extraordinary position precludes him from understanding the effect
of public opinion in such a country as our own. He is accustomed to
deal with Cabinets, not with nations or parliaments; and he
attributes more power to the former than they possess, at least
according to the constitution of Great Britain. The British Cabinet
cannot, like that of Prussia or Austria, commit the country to a
course which is inconsistent with or derogatory to its honour.
In consequence of this irresolution on the part of our rulers, we are
now precipitated into war, and are already beginning to feel some of
its inconveniences. Let us now endeavour to ascertain the causes
which have led to so very serious a denouement as the disruption of
the peace of Europe. It is important that we should do so now, and
not leave the question entirely to the future speculation of historians.
During Lord Derby’s short tenure of office, relations of peculiar
amity had been established between Britain and France. Lord
Malmesbury, than whom no more able or judicious minister ever
held the seals of the Foreign Office, saw that the interests of
civilisation not only in the west, but throughout the whole of Europe,
could only be maintained by a close and permanent co-operation,
and mutual good understanding between these two countries; and he
addressed himself to the task with equal discretion and success. It is
not too much to say that Britain and France never were more
cordially united and confidentially allied than during the period we
refer to. This, of course, was anything but agreeable to the Czar,
whose opportunity lay in a separation of the interests of the two great
powers of the West.
The dissolution of Lord Derby’s Government and the accession of
the Aberdeen Ministry effected a material alteration. The new
Premier, Lord Aberdeen, had been for a great many years on the
most intimate footing with the despotic Courts and Cabinets. He had
not, it was true, the ability of the Nesselrodes or Metternichs; but he
was considered in the highest diplomatic circles as a person who
might easily be led, and upon whom a certain show of deference
would not be thrown away. It was supposed, also, that he regarded
with particular dislike the recent changes in France, and was not
favourable to the re-establishment of the Empire under the rule of
Napoleon III. This veteran ally of the despotic powers was now
associated with men whose former political opinions had differed
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookgate.com

You might also like