# How to make a script run when a file is opened

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.

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

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.

• If I do this, I get "Auto-run disabled: Text.py", see: i.stack.imgur.com/3Ardx.png Do you know why? – p2or Jan 15 '15 at 16:10
• @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. – someonewithpc Jan 15 '15 at 16:51

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

import bpy
from bpy.app.handlers import persistent

@persistent



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:

• I mean the answer you gave in the other question, when opening a specific file, without first having to open another one – someonewithpc Jan 15 '15 at 13:30
• @someonewithpc Sorry but I don't get this, about which other question are you talking? – stacker Jan 15 '15 at 14:01
• 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 – someonewithpc Jan 15 '15 at 14:52
• 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. – sambler Jan 16 '15 at 9:03

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

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