Run python script at cinema4d opening



  • Hi everyone,

    I'm developing an application that, at some point, has to open cinema4d, import some files (dae, obj...etc) , process them and export them as obj and mtl. I have the script ready, but I need, somehow, to run it when cinema4d starts from the command line.
    How should I do it?
    I've read somewhere that there's "init.py' that gets executed when cinema4d opens, can I get some documentation about it?

    Thanks in advance


  • Global Moderator

    Hi,

    first I'd like to ask you to please add tags to your threads, see Read Before Posting. For example I'm not sure for which version of Cinema 4D you are asking.
    I have moved your thread to the "Cinema 4D Development" category.
    I also changed your thread into a question, see Q&A New Functionality.

    There are actually a few ways to achieve this.

    In all of the following cases, please note, in Script Manager scripts, there are a few predefined global variables (e.g. doc for the active document or op for the active object) you may be using. In the following solutions, these are not available. There even may be no active document (depending on the startup state of Cinema 4D), so you most likely will need load the document via LoadDocument().

    You could write your script as a plugin without an actual plugin... I mean, you'll write your code in a "my_plugin.pyp" (except for the suffix, the name is arbitrary) file inside of Cinema 4D's plugins folder, but instead of registering an actual plugin class (like e.g. CommandData), you can just implement PluginMessage() and have your code run for example on C4DPL_PROGRAM_STARTED.

    A bit elaborate may be to implement a small plugin, that adds a command line option to run a Python script via command line.
    This could roughly look like so:

    import sys, ntpath
    import c4d
    
    # Executes a given Python script
    # Syntax: cinema4d.exe "-runpy script param"
    def CommandRunPy(arg):
    	# Parse arguments
    	argComponents = arg.split(' ')
    	script = argComponents[1]
    	param = argComponents[2]
    
    	# If file exists, execute the script
    	if ntpath.isfile(script) is False:
    		return
    	# NOTE: execfile runs the script in this context,
    	#       all variables available in this scope can be used inside of the script
    	#       In this case, we may use param inside the script
    	execfile(script)
    
    def ParseCommandline(argv):
    	for arg in argv:
    		if arg.find("-runpy") == 0:
    			CommandRunPy(arg)
    
    def PluginMessage(id, data):
    	if id == c4d.C4DPL_COMMANDLINEARGS:
    		# Extend command line parsing, here
    		# This is the last plugin message on Cinema 4D's start process
    		ParseCommandline(sys.argv)
    	return True
    

    A third option may be to add to a Python init script. This has changed in version R20. See R20 Startup script location - python_init.py.

    Cheers,
    Andreas