P4D101 – Getting started with Python in Cinema 4D

2 January 2011

The Python integration into Cinema 4D is quite thorough. There are several places where you can use Python to script and Python is integrated as a first class citizen with the same level of access like Cinema 4D’s internal scripting language COFFEE as well as the C++ API.

There are different places in which you can use Python:

  • as Python Script
  • as Python Generator
  • as Python Tag
  • as Python Xpresso Node
  • as Python Plugin

As you can see, there are plenty of options to use Python in Cinema 4D. For a start let us focus on using a Python script – ignoring the other possibilities for now.

Python Script

Python scripts are probably the most immediate way to perform automated tasks. To create a script open the Script Manager (Python) from the Python menu. Also open the Console (Python) from the same menu. The console will show you error messages and output from print statements in your Python script.

When you have not done something in Cinema 4D before the Script Manager should already contain this code:

import c4d
from c4d import gui
#Welcome to the world of Python

def main():
    gui.MessageDialog(‘Hello World!’)

if __name__==‘__main__’:
    main()

The executed part

Now let us examine this a bit closer. For a start let us ignore the first few statements and look at the parts that actually do something:

if __name__==‘__main__’:
    main()

This is the part that get’s executed when Cinema 4D runs the Python script. When a Python program is loaded as script, Python sets the variable __name__ to the value of “__main__”. This way a Python script knows it has been called as script rather than having been imported.

This brings us to the first statements – the import:

Imports

import c4d
from c4d import gui

The import statement loads existing Python code from another file – a module. The Python binding to Cinema 4D is defined by the c4d module. By importing the c4d module you gain access to Cinema 4D’s functions through the API (Application Programming Interface). Within the c4d module there are several specialized packages that handle different parts of the API. One of those packages is c4d.gui that deals with the graphical user interface functions and classes.

from c4d import gui

This statements imports the gui package from the c4d module. This is an optional step that makes the gui functions available without the need to prefix them with the c4d module name (the namespace). Without the above statement you would have to explicitly prefix the gui.MessageDialog() function with c4d.

import c4d
c4d.gui.MessageDialog("Hello World!");

Condition and Code Block

Back to the actual code:

if __name__== ‘__main__’:
    main()

The conditional if statement checks the __name__ variable for the value of ‘__main__’. If this is true – so the program was loaded as script – the code block in the if statement is executed. Here, the previously defined function main() is called.


In Python a code block (=scope) like within a if statement or a function is defined by indenting the code rather than having curly brackets { } like eg. in COFFEE. You need to pay attention to have the identical number of whitespace characters when indenting. Different levels indicate different code blocks. Generally I would advise you to use spaces and no tab characters. Indenting by four spaces is a widely used format.

Print

Instead of defining a function first and then calling it when the script is executed you can also write your code here:

if __name__ ==  "__main__" :
    print "Hello World!"

This would output the text “Hello World!” into the Python console rather than popping up a dialog window like MessageDialog() does. The advantage of print is that it does not interrupt the execution of the script like the dialog window that requires the user to press the OK button. So print is a great way of outputting debugging data to the console that can show you what is happening in your script. This makes it easier to find errors when something goes wrong. The disadvantage of print is that is only shows in the console which a normal user generally does not have open when using scripts. So avoid print for displaying data that is important to the user.

Functions

In the example code there is definition of the function main() that is being called from the script rather than immediate code:

def main():
    gui.MessageDialog(‘Hello World!’)

This def statement defines a function named main(). The code following the definition is indented to contain the code block for the function. In this case a popup window with the text “Hello World!” is shown. This function only contains this one statement and does not have parameters or return values. We will have a look on how to use those in a later article.

In the example the function main() is called below using the statement main().

Summary

This was a very brief introduction into Python scripting in Cinema 4D by looking at the default script that is generated when opening the Script Manager.

What we have learned is:

  • how Python scripts are executed in Cinema 4D (it defines __name__ as “__main__” conforming to general Python scripts)
  • how Python can access Cinema 4D’s API through the c4d module and how to use import to use the c4d module and its packages
  • how to use the print statement to output text to the Python console
  • how to define a basic function using the def statement and how to call it

In future articles we actually will have a look at how to do something meaningful in a Python script like working with the current scene and how to use variables to store values and how to save your scripts so you can reuse them.

For further information have a look at the Python 2.6.4 documentation and Maxon’s documentation on their Python integration.

Do you have a question or want to learn something specific? Leave a reply below or use the contact form from the top of the page!

Tags: , ,

Top

15 Responses to “P4D101 – Getting started with Python in Cinema 4D”

  1. Martin,

    Nice little intro, I was looking for a heads up on Python scripting in C4D today, and look what popped up :) I’ll be looking forward to future posts.

  2. Thanks Mal! I am glad this is helpful.

    I have to do some catching up right now but I definitely will continue. Let me know if there is something specific you want to learn and I can see to incorporate that in future articles.

    Cheers,
    -Martin

  3. i’m very interesting in this stuff! nice tut!

  4. it’s strange but “Error in line 5, col 48: gui.MessageDialog(‘Hello World!’)”

  5. sorry
    my fault
    it’s all about ‘’

  6. Yeah, sorry. The template for the blog is doing some clever stuff with typography. Too clever so it mixes up ”. I am glad you figured it out yourself.

  7. First things first: Thumbs UP for making this blog. Pythoning in C4D is very hard to learn with those crapy documentations from maxon. So thanx alot for this tuts..

    I have some question: I really dont understand those if __name__ == statements.. why “__”signs before and after?, why name?, its not declared before, how it knows it is equal to that particular function?

    Sorry for so beginner questoin, but i feel this is mantra no1 needed to dive into the world of Py4D :)

  8. Hi Robert,

    the __name__ variable is defined by Python and not particular to Cinema 4D. It holds the name of the function. It is standard Python procedure to test for the __name__ value in the script to see if it has been called to run as script (in this case, __name__ has the value of “__main__”). This is in contrast to a situation where a .py file is imported into another script. In this case __name__ is not “__main__” and you do not want to run the that part of the script. This is necessary as Python actually executed the code when it loads the file and running some parts of the Python script is not wanted in case of an import.

    The underscores __ are just a simple matter of making sure that you do not accidentally define your own variables with the same name as a couple of internal ones.

    The documentation from Maxon actually is not that bad but it assumes that you have a basic understanding of Python and also use the other parts of the documentation, in particular their C++ and COFFEE docs as well as the general Python documentation. It definitely is – at this stage – not aimed at users but rather developers.

  9. This is really excellent thank you.

    I also have trouble with the documentation.
    But I am brand new to Python.

    I have my head around simple scripting (the java-script documentation with After Effects is excellent). I also did the general python 101 from lynda but there is something about the sdk with cinema that I just don’t get yet. I would like a tutorial on how to read an sdk.

    Also if find looking at how someone else’s simple scripts work is very helpful. But there aren’t tons of examples.

    Here is the real question.
    I’m thinking about buying tutorials for python scripting in maya or blender. Do you think this would provide insight on maneuvering through python in Cinema?

    I don’t know how to use Maya or Blender but I am pretty good with Cinema. Do you think the sdk will be similar enough for this to be beneficial?

    I will continue to follow this thread for sure.
    Thanks.

  10. Hi Josh,

    I also learn quickest when looking at examples from other developers. While the documentation for the Python SDK in Cinema lacks examples within the documentation there are quite a few scripts that come with the documentation in the examples folder. Have a look at them.

    Tutorials for Maya or Blender won’t get you far with Cinema as the SDKs are where the differences lay. It’s pretty much like learning how to program for Windows while you actually use Linux. The language (Python) itself is only a minor part to learn. The major part is to learn the inner workings of the host application and how the Python bindings are implemented. That still makes it great to have Python across applications but unfortunately that’s only about the first 10% you’ll need.

  11. Niklas Rosenstein September 3, 2011 at 10:09

    This doesn’t have much to do with Cinema 4D, it’s actually nothing more than a little introduction to Python.
    Beginner should definately start with The Python Tutorial, which can be found here: http://docs.python.org/tutorial/index.html

    After reading it at least to chapter 9, you are ready to go and should even understand most of the Py4D Documentation and how to use it.

    Cheers,
    Niklas

  12. Niklas, I was trying to get artists to understand the basics. I linked the Python documentation and Maxon’s documentation in the article. This is the very first step to understanding how Python works in Cinema 4D – assuming you never have used Python. Any coder can use Maxon’s documentation an be fine with it. I would also suggest to look at the COFFEE and C++ documentation as well as many things are ommited in the Python documentation.

  13. Ah, finally found some usefull tutorial..
    Thanks a lot.

  14. Martin,
    Many thanks for putting this together. Like a lot of others commenting here, I’d like to learn some coding to support my graphics and illustration work, but getting started is difficult – so posts like this are really appreciated.

    I’m taking a similar route to Josh (above) – working through the Python 101 course at Lynda.com. I’ll also aim to work through the Python tutorial on the official site.

    Maxon could really improve their approach in this area. Most docs seem to start ‘just out of reach’ of the absolute beginner. I’d agree with Josh that some help in understanding the SDK / docs would be good – it’s hard to progress when you’re even struggling to understand the instruction manual : )

Trackbacks/Pingbacks

  1. [...] http://cgrebel.com/2011/01/p4d101-starting/ Tweet Add your comment 0 Responses to this post Add your comment [...]

Leave a Reply