Blender auto run python script

How could a single Python script run when Blender is started?

I would like to have a few globally available functions which should not not depend on a .blend file. Is there a place (A setup.py , __init__.py or something like that) where I could put a few lines of code?

$\begingroup$ This video (youtube.com/watch?v=A-BOWF82Er4) explains how to easily create an addon but it ssems not to be working on the 2.92 version. $\endgroup$

2 Answers 2

As documented in the manual, you can save your script in the scripts/startup/ directory with a .py extension and it will be automatically imported on startup.

If it’s for all of your Blender sessions, then you might be best creating a simple add-on with the functions you need.

If it’s per .blend file, then you can use Blender’s Text Editor within that file, store your python commands there, and enable the Register checkbox in the Text Editor’s header. The only caveat to this approach is that you’ll need to start Blender with the -y flag so the embedded script will run on start.

You must log in to answer this question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.21.43541

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Scripting & Security

The ability to include Python scripts within blend-files is valuable for advanced tasks such as rigging and automation. However, it poses a security risk since Python does not restrict what a script can do. Therefore, you should only run scripts from sources you know and trust. Automatic execution is disabled by default; however, some blend-files need this to function properly.

When a blend-file tries to execute a script and is not allowed, a dialog will appear. In it, you can choose to Allow Execution or to Ignore the scripts.

Читайте также:  Libreoffice html to docx

../../_images/advanced_scripting_security_autorun-scripts-dialog.png

Scripts in Blend-Files

Auto Execution

Here are the different ways blend-files may automatically run scripts.

A text data-block can have its Register option enabled which means it will load on start.

Python expressions can be used to Drive values and are often used in more advanced rigs and animations.

Manual Execution

There are other ways scripts in a blend-file may execute that require user interaction (therefore will run even when auto execution is off), but you should be aware that this is the case since it is not necessarily obvious.

  • Running a script in the Text editor.
  • Rendering with Freestyle, because Freestyle uses scripts to control line styles.

Controlling Script Execution

Blender provides a number of ways to control whether scripts from a blend-file are allowed to automatically execute.

First, the File Browser has the option Trusted Source which you can use on a case-by-case basis to control auto execution. Since you may forget to set this, or may open a file without going through the File Browser, you can change the default (described next).

Setting Defaults

In the Preferences, there is the toggle to Auto Run Python Scripts . This means the Trusted Source option in the File Browser will be enabled by default, and scripts can run when blend-files are loaded without using the File Browser. Once enabled you have the option to exclude certain directories; a typical configuration would be to trust all paths except for the download directory.

../../_images/animation_drivers_troubleshooting_autorun-user-preference.png

Command Line

You may want to perform batch rendering or some other task from the command line, running Blender without an interface. In this case, the Preferences are still used but you may want to override them:

Example

To render an animation in background mode, allowing drivers and other scripts to run:

blender --background --enable-autoexec my_movie.blend --render-anim

These command-line arguments can be used to start a regular Blender instance and will still override the Preferences.

© Copyright : This page is licensed under a CC-BY-SA 4.0 Int. License. Last updated on 07/24/2023.

Источник

Save & Load

Asks for confirmation before closing or opening a new blend-file if the current file has unsaved changes.

Select how blend-file preview are generated. These previews are used both in the File Browser and for previews shown in the operating system’s file browser.

Do not generate any blend-file previews.

If there is no camera in the 3D Viewport a preview using a screenshot of the active Workspace is generated. If a camera is in the scene, a preview of the viewport from the camera view is used.

Generate a preview by taking a screenshot of the active Workspace.

Читайте также:  Php открыть файл в новом окне

Generate a preview of a Workbench render from the camera’s point of view.

Default To Relative Paths

Default value for Relative Paths when loading external files such as images, sounds, and linked libraries. It will be ignored if a path is already set.

Default value for Compress file when saving blend-files.

Default value for Load UI when loading blend-files.

Text Files Tabs as Spaces

Entering Tab in the Text Editor adds the appropriate number of spaces instead of using characters.

Number of versions created (for backup) when saving newer versions of a file.

This option keeps saved versions of your file in the same directory, using extensions: .blend1 , .blend2 , etc., with the number increasing to the number of versions you specify.

Older files will be named with a higher number. E.g. with the default setting of 2, you will have three versions of your file:

Number of files displayed in File ‣ Open Recent .

Auto Save

Enables Auto Save . Tells Blender to automatically save a backup copy of your work-in-progress files to the Temporary Directory .

This specifies the number of minutes to wait between each Auto Save . The default value of the Blender installation is 2 minutes. The minimum is 1, and the Maximum is 60 (save every hour).

Auto Run Python Scripts

Python scripts (including driver expressions) are not executed by default for security reasons. You may be working on projects where you only load files from trusted sources, making it more convenient to allow scripts to be executed automatically.

Blend-files in these folders will not automatically run Python scripts. This can be used to define where blend-files from untrusted sources are kept.

File Browser

Hide the Recent panel of the File Browser which displays recently accessed folders.

Hide System Bookmarks in the File Browser.

By activating this, the file region in the File Browser will only show appropriate files (i.e. blend-files when loading a complete Blender setting). The selection of file types may be changed in the file region.

Show Hidden Files/Data-Blocks

Hide files which start with . in File Browsers and data IDs.

Data-blocks beginning with a . can be selected by typing in the . characters. When explicitly written, the setting to hide these data-blocks is ignored.

© Copyright : This page is licensed under a CC-BY-SA 4.0 Int. License. Last updated on 07/24/2023.

Источник

How to auto-run a simple script? [duplicate]

I’m trying to auto-load a script when the user opens the .blend file (I want the user to have a specific panel available when he opens the .blend file). In this case a simple panel to modify the text. I have already activated the «Auto Run Python Scripts» and the «Register» checkbox, but it is not working. Why is this not working?

import bpy def addText (context): bpy.ops.object.editmode_toggle() bpy.ops.font.delete(type='ALL') bpy.ops.font.text_insert(text = context.scene.my_string_prop) bpy.ops.object.editmode_toggle() class SimpleOperator(bpy.types.Operator): """Tooltip""" bl_idname = "object.simple_operator" bl_label = "Simple Object Operator" @classmethod def poll(cls, context): return context.active_object is not None def execute(self, context): addText(context) return class Title (bpy.types.Panel): """Creates a Panel in the Object properties window""" bl_label = "TEXT CONTENT" bl_idname = "OBJECT_PT_title" bl_space_type = 'PROPERTIES' bl_region_type = 'WINDOW' bl_context = "data" def draw(self, context): layout = self.layout obj = context.scene row = layout.row() row.prop(obj,"my_string_prop") row = layout.row() row.operator("object.simple_operator" , text = "Insert Text") def register(): bpy.utils.register_class(SimpleOperator) bpy.utils.register_class(Title) bpy.types.Scene.my_string_prop = bpy.props.StringProperty \ ( name = "3D Text", description = "Insert your text here", default = "TEXT HERE" ) def unregister(): bpy.utils.unregister_class(SimpleOperator) bpy.utils.unregister_class(Title) del bpy.types.Scene.my_string_prop register() 

Источник

Читайте также:  Python dict get key default

How To Run Python Script When Blender Starts

To run Python script when Blender starts only once or every time.

Environment

Method

I created a simple Python script “Documents\blenderPython\test\spheres.py” to add spheres as below

import bpy for i in range(3): bpy.ops.mesh.primitive_uv_sphere_add(radius=1, location=((i-1)*3, 0, 3))

Only once

Start Blender with command

Start blender in command prompt with an argument -P or –python.
Reference: Python Options in Blender 2.91 Manual

blender -P Documents\blenderPython\test\spheres.py

The following is the result of startup scene.

Every time

Method 1. Create bat file.

Create batch file and start Blender with it. Save the command above as “blender_start.bat” and execute it.

Method 2. Hook the function to handler

To run script every time, use handler to execute functions when blender starts. This method can be used in your Addon.
Reference: Application Handlers (bpy.app.handlers) in Blender2.91 Manual

startup_sphere.py

import bpy from bpy.app.handlers import persistent @persistent def add_sphere(dummy): for i in range(3): bpy.ops.mesh.primitive_uv_sphere_add(radius=1, location=((i - 1) * 3, 0, 3)) def register(): bpy.app.handlers.load_post.append(add_sphere) def unregister(): pass if __name__ == "__main__": register()

Put the file startup_sphere.py in the user startup directory such as C:\Users\\AppData\Roaming\Blender Foundation\Blender\2.83\scripts\startup. The files in the start up directory are executed when blender starts.
Reference: Script Loading in Blender Python API document

The following is the result of startup scene.

Wrong Example

You can’t put the python file that has operations of bpy.ops as below in user startup directory.

import bpy for i in range(3): bpy.ops.mesh.primitive_uv_sphere_add(radius=1, location=((i - 1) * 3, 0, 3))
import bpy from bpy.app.handlers import persistent def add_sphere(): for i in range(3): bpy.ops.mesh.primitive_uv_sphere_add(radius=1, location=((i - 1) * 3, 0, 3)) def register(): add_sphere() def unregister(): pass if __name__ == "__main__": register()

The error “AttributeError: ‘_RestrictContext’ object has no attribute ‘view_layer’” will occurs when the addon is activated. Check “[Blender Error] AttributeError: ‘_RestrictContext’ object has no attribute ‘view_layer’” for details.

Источник

Оцените статью