You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3中如何从example2.py向example.py原样导入MIDI音符块代码?

How to Import Note Blocks from example2.py into example.py

Since your existing code in example.py parses comment lines starting with #Note block to generate MIDI files, the key is to read example2.py, extract those lines, and parse them just like you would with the ones in example.py. Here's a step-by-step implementation that keeps the note structure intact:

Step 1: Extract Note Blocks from example2.py

First, write a helper function to pull all note block lines from the target file:

def extract_note_blocks(file_path):
    note_blocks = []
    with open(file_path, 'r', encoding='utf-8') as f:
        for line in f:
            stripped_line = line.strip()
            if stripped_line.startswith('#Note block'):
                # Remove the comment prefix to get just the parameter string
                params_section = stripped_line[len('#Note block '):]
                note_blocks.append(params_section)
    return note_blocks

Step 2: Parse Blocks into Structured, Accessible Data

To keep the original parameter structure easy to work with, use a dataclass to represent each note block. This lets you access values like note.track or note.pitch cleanly:

from dataclasses import dataclass

@dataclass
class NoteBlock:
    track: int
    channel: int
    pitch: int
    time: int
    duration: int
    volume: int

def parse_note_block(param_string):
    # Split the parameter string into key-value pairs
    param_dict = {}
    for pair in param_string.split():
        key, value = pair.split('=')
        param_dict[key.strip()] = int(value.strip())
    # Return a structured NoteBlock instance
    return NoteBlock(**param_dict)

Step 3: Integrate with Your Existing MIDI Logic

Now, in example.py, load and process the imported note blocks, then combine them with any local blocks (if needed) for MIDI generation:

# Assume your existing MIDI generation function is called generate_midi
# and accepts a list of NoteBlock objects

# Load and parse note blocks from example2.py
imported_note_lines = extract_note_blocks('example2.py')
imported_notes = [parse_note_block(line) for line in imported_note_lines]

# Optional: Load local note blocks from example.py too
local_note_lines = extract_note_blocks('example.py')
local_notes = [parse_note_block(line) for line in local_note_lines]

# Combine all notes and generate MIDI
all_notes = local_notes + imported_notes
generate_midi(all_notes)

Alternative: If You Need Variables in Scope (Use with Caution)

If your original code relies on individual variables (like track, channel) being present in the scope for each note block, you can execute the parsed lines as code. Note: This is less secure if example2.py contains untrusted content:

def load_notes_as_scope_vars(file_path):
    note_var_sets = []
    with open(file_path, 'r', encoding='utf-8') as f:
        for line in f:
            stripped_line = line.strip()
            if stripped_line.startswith('#Note block'):
                # Convert comment to executable code
                code_line = stripped_line[1:]  # Remove leading #
                temp_vars = {}
                exec(code_line, globals(), temp_vars)
                note_var_sets.append(temp_vars)
    return note_var_sets

# Usage: each item is a dict with keys like 'track', 'channel'
imported_note_vars = load_notes_as_scope_vars('example2.py')

内容的提问来源于stack exchange,提问作者Tabor18

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:15:35