8
$\begingroup$

How can I make a script run when I open a file? This to be used with registering an handler every time the file is opened.

$\endgroup$
7
$\begingroup$

You can do this somewhat easily, by naming your text block *.py and checking the Register checkbox.

enter image description here

Then the script contained in it will be run every time you open the .blend file. This is great for registering handlers at the startup of a file.

$\endgroup$
  • $\begingroup$ If I do this, I get "Auto-run disabled: Text.py", see: i.stack.imgur.com/3Ardx.png Do you know why? $\endgroup$ – p2or Jan 15 '15 at 16:10
  • 1
    $\begingroup$ @poor That's because it's disabled by default, for security reasons. You can allow all or files in specific directories to run scripts at the startup. $\endgroup$ – someonewithpc Jan 15 '15 at 16:51
3
$\begingroup$

If the file is a .blend you can use an application handler

import bpy
from bpy.app.handlers import persistent


@persistent
def load_handler(dummy):
    print("Load Handler:", bpy.data.filepath)

bpy.app.handlers.load_post.append(load_handler)

For other file types there is no callback provided, you could iterate over all text files

for t in bpy.data.texts:
    'check for previously created' -> exec if new and add to list.

and check for new entries triggered by a timer.

Related:

$\endgroup$
  • $\begingroup$ I mean the answer you gave in the other question, when opening a specific file, without first having to open another one $\endgroup$ – someonewithpc Jan 15 '15 at 13:30
  • $\begingroup$ @someonewithpc Sorry but I don't get this, about which other question are you talking? $\endgroup$ – stacker Jan 15 '15 at 14:01
  • $\begingroup$ Sorry, I'm confused: it was @sambler who posted a comment to this question: blender.stackexchange.com/a/23166/3078 . I'll post it as another answer, tough $\endgroup$ – someonewithpc Jan 15 '15 at 14:52
  • $\begingroup$ There are two closely related things here. This code sets a python function to be run when any blend file is opened. I think this question is more concerned with running a text block that is saved in the blend file as the blend file is open, this would keep it unique to the one file rather than the handler that applies to every blend file opened. $\endgroup$ – sambler Jan 16 '15 at 9:03
2
$\begingroup$

When you are opening .blend file, then you have to also enable "Trusted source" option. See it in following image:

Option of opening blend file with python script

It is not enabled by default, because there are security reason for that. You can do very bad thing with Python (delete files on your disk, send spam, etc.)

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.