杰瑞科技汇

After Effects Python 怎么用?

Of course! Here is a comprehensive guide to using Python with Adobe After Effects, covering everything from the basics to advanced techniques and best practices.

After Effects Python 怎么用?-图1
(图片来源网络,侵删)

What is Python in After Effects?

Python is a powerful, general-purpose programming language that you can use to automate, extend, and control Adobe After Effects. It's not the native language for After Effects (which is ExtendScript, based on JavaScript), but Python's extensive libraries and ease of use make it an incredibly popular and powerful choice for automation.

You can use Python to:

  • Automate repetitive tasks: Render compositions, import files, apply effects, and organize projects.
  • Create custom tools: Build complex UIs with tools like PySide or PyQt to streamline your workflow.
  • Process data: Read and write data from external sources (like CSV files or APIs) to drive animations.
  • Integrate with other software: Connect After Effects to a web server, a database, or other creative applications.

How to Run Python in After Effects

There are two primary methods for running Python code inside After Effects:

Method 1: The ae Module (Recommended for Automation)

This is the most common and powerful method. It involves using a special Python module called ae that acts as a bridge, allowing you to call After Effects' native ExtendScript functions directly from your Python script.

After Effects Python 怎么用?-图2
(图片来源网络,侵删)

How it works:

  1. You write a Python script.
  2. The ae module uses Adobe's ExtendScript Toolkit (or a similar bridge) to execute ExtendScript code within the running After Effects application.
  3. The results are passed back to your Python script.

Prerequisites:

  1. Python 3: Make sure you have Python 3 installed.
  2. ae Python Module: Install it using pip:
    pip install ae
  3. ExtendScript Toolkit (Optional but Recommended): This free tool from Adobe helps you understand the ExtendScript API (the functions and objects you can control). You can download it from the Adobe Developer website.

Example: Get the active project's name

import ae
# Connect to a running instance of After Effects
ae.connect()
# Get the active project
project = ae.app.project
# Get the project's name
project_name = project.name
print(f"The active project is named: {project_name}")
# Close the connection
ae.disconnect()

Method 2: The jsx File Method (Simpler for one-off scripts)

This method is simpler for running a single script but is less flexible for complex workflows.

After Effects Python 怎么用?-图3
(图片来源网络,侵删)

How it works:

  1. You write your After Effects logic in a .jsx (ExtendScript) file.
  2. You write a Python script that executes this .jsx file using the subprocess module.
  3. The Python script can pass arguments to the .jsx file and read its output.

Prerequisites:

  1. ExtendScript Toolkit: You need this to run .jsx files.
  2. Python: Standard installation is fine.

Example:

  1. Create a file named get_project_name.jsx:

    // get_project_name.jsx
    var project = app.project;
    var project_name = project.name;
    $.writeln(project_name); // Output to the console
  2. Create a Python script to run it (run_ae_script.py):

    import subprocess
    import os
    # Path to the ExtendScript Toolkit
    # NOTE: This path can vary depending on your OS and installation.
    # You might need to find it on your system.
    estk_path = "C:/Program Files/Common Files/Adobe/CEP/extensions/ExtendScript Toolkit 4/ExtendScript Toolkit.exe"
    # Path to your JSX file
    jsx_path = os.path.join(os.getcwd(), "get_project_name.jsx")
    # Command to run the script
    # The -r flag runs the script.
    command = f'"{estk_path}" -r "{jsx_path}"'
    try:
        # Execute the command
        result = subprocess.run(command, check=True, capture_output=True, text=True, shell=True)
        print("Output from After Effects:")
        print(result.stdout)
    except subprocess.CalledProcessError as e:
        print(f"An error occurred: {e}")
        print(f"Stderr: {e.stderr}")

The ExtendScript API (Your Toolbox)

Whether you use the ae module or the jsx file method, you are ultimately using ExtendScript. The key is learning the ExtendScript API, which is the object model that represents After Effects.

The most important objects in the API are:

  • app: The root object, representing the After Effects application itself.
  • app.project: Represents the current After Effects project (the .aep file).
  • app.project.activeItem: The currently selected item (a composition, a solid, a footage layer, etc.).
  • app.project.activeItem.layers: A collection of layers in the active composition.
  • comp.layers.addSolid(): A method to create a new solid layer.
  • layer.property("Transform").property("Position"): A way to access a specific property of a layer.

Key Resource: The ExtendScript Toolkit has a "JavaScript" reference panel that lists all these objects, methods, and properties. This is your best friend.


Practical Examples

Example 1: Automating a Render Queue (using ae module)

This script creates a new render queue item, sets its output module, and starts the render.

import ae
import os
# --- CONFIGURATION ---
comp_name_to_render = "My Comp" # Name of the composition to render
output_file_path = r"C:\Renders\My_Comp.mp4" # IMPORTANT: Use raw string (r"...") for Windows paths
format_name = "H.264" # The format in the Output Module settings
# --- SCRIPT ---
ae.connect()
try:
    # Find the composition by name
    comp = None
    for item in ae.app.project.items:
        if item.name == comp_name_to_render and item.type == ae.CompItemType.COMP:
            comp = item
            break
    if not comp:
        raise ValueError(f"Composition '{comp_name_to_render}' not found.")
    # Add the composition to the render queue
    render_queue_item = ae.app.project.renderQueue.items.add(comp)
    # Set the output file
    render_queue_item.outputModule(1).file = output_file_path
    # Set the output module (find it by name)
    output_modules = ae.app.project.renderQueue.outputModules
    for om in output_modules:
        if om.name == format_name:
            render_queue_item.outputModule(1).applyTemplate(om.name)
            break
    print(f"Starting render for '{comp_name_to_render}' to '{output_file_path}'...")
    # Start rendering (use False to prevent the dialog box from showing)
    ae.app.project.renderQueue.render(False)
    print("Render complete.")
finally:
    ae.disconnect()

Example 2: Creating a Composition and Adding Layers (using ae module)

This script creates a new composition, adds a solid layer, and changes its color.

import ae
import time
ae.connect()
try:
    # --- Create a new composition ---
    comp_width = 1920
    comp_height = 1080
    comp_duration = 10 # in seconds
    comp_fps = 30
    new_comp = ae.app.project.items.addComp(
        "Python Created Comp",
        comp_width,
        comp_height,
        1, # pixel aspect ratio
        comp_duration,
        comp_fps
    )
    # --- Add a solid layer ---
    solid_color = [1, 0, 0] # RGB Red (values from 0 to 1)
    solid_layer = new_comp.layers.addSolid(solid_color, "My Red Solid", comp_width, comp_height, 1)
    # --- Modify a property ---
    # The property path is hierarchical: "Transform" -> "Opacity"
    opacity_property = solid_layer.property("Transform").property("Opacity")
    opacity_property.setValue(50) # Set opacity to 50%
    print(f"Successfully created composition: '{new_comp.name}' and added a layer.")
    # Optional: Open the composition in the viewer
    # new_comp.openInViewer()
finally:
    ae.disconnect()

Best Practices and Tips

  1. Error Handling is Crucial: After Effects can be unpredictable. Always wrap your ae module calls in try...except blocks to catch errors gracefully.

    try:
        # ... some ae operation ...
    except ae.ae.Error as e:
        print(f"After Effects Error: {e}")
    except Exception as e:
        print(f"General Python Error: {e}")
  2. Use Logging: For complex scripts, use Python's logging module instead of print(). It's more powerful and allows you to control the verbosity of your output.

    import logging
    logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
    logging.info("Script started.")
  3. Performance:

分享:
扫描分享到社交APP
上一篇
下一篇