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

咨询:能否在脚本中导入/包含其他脚本?主脚本按需加载需求

当然可以!这种根据用户选择动态加载脚本的需求太常见了,不同脚本语言都有成熟的实现方式,我给你几个主流场景的具体例子:

1. Python实现

Python可以通过importlib模块实现动态导入,也可以用exec()直接读取并执行脚本内容,推荐用更规范的模块导入方式:

import importlib
import os

def load_selected_script():
    print("请选择要加载的脚本:")
    # 筛选当前目录下的Python脚本(排除主脚本自身)
    scripts = [f for f in os.listdir('.') if f.endswith('.py') and f != __file__]
    
    # 列出可选脚本
    for idx, script in enumerate(scripts, 1):
        print(f"{idx}. {script}")
    
    choice = int(input("输入选项编号:")) - 1
    if 0 <= choice < len(scripts):
        script_name = scripts[choice].replace('.py', '')
        # 动态导入目标脚本
        target_module = importlib.import_module(script_name)
        # 假设每个脚本都定义了run()作为入口函数
        if hasattr(target_module, 'run'):
            target_module.run()
        else:
            print(f"提示:脚本 {scripts[choice]} 没有定义统一的run()入口函数")
    else:
        print("无效的选项,请重新输入!")

if __name__ == "__main__":
    load_selected_script()
2. JavaScript(Node.js环境)实现

Node.js里可以用require()(CommonJS)或import()(ES模块)动态加载脚本,这里以CommonJS为例:

const readline = require('readline');
const fs = require('fs');
const path = require('path');

const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

function loadSelectedScript() {
    console.log("请选择要加载的脚本:");
    // 筛选当前目录下的JS脚本(排除主脚本自身)
    const scripts = fs.readdirSync(__dirname).filter(file => 
        file.endsWith('.js') && file !== path.basename(__filename)
    );
    
    // 列出可选脚本
    scripts.forEach((script, idx) => {
        console.log(`${idx + 1}. ${script}`);
    });

    rl.question("输入选项编号:", (choice) => {
        const index = parseInt(choice) - 1;
        if (index >= 0 && index < scripts.length) {
            const scriptPath = path.join(__dirname, scripts[index]);
            // 动态加载目标脚本
            const targetModule = require(scriptPath);
            // 调用统一的入口函数
            if (typeof targetModule.run === 'function') {
                targetModule.run();
            } else {
                console.log(`提示:脚本 ${scripts[index]} 没有导出run()入口函数`);
            }
        } else {
            console.log("无效的选项,请重新输入!");
        }
        rl.close();
    });
}

loadSelectedScript();
3. Bash脚本实现

Bash中可以用source命令(或缩写.)直接加载并执行其他脚本的内容,动态加载只需拼接路径即可:

#!/bin/bash

echo "请选择要加载的脚本:"
# 筛选当前目录下的Shell脚本(排除主脚本自身)
scripts=($(ls *.sh | grep -v "$0"))

# 列出可选脚本
for idx in "${!scripts[@]}"; do
    echo "$((idx+1)). ${scripts[idx]}"
done

read -p "输入选项编号:" choice

index=$((choice-1))
if [[ $index -ge 0 && $index -lt ${#scripts[@]} ]]; then
    # 加载并执行目标脚本
    source "${scripts[index]}"
    # 如果脚本定义了run函数则调用
    if command -v run &> /dev/null; then
        run
    fi
else
    echo "无效的选项,请重新输入!"
fi

核心思路就是根据用户选择动态确定脚本路径/名称,再调用对应语言的导入/加载机制。建议给所有被加载的脚本定义统一的入口(比如run()函数),这样主脚本调用更规范,也能避免变量或函数冲突。

内容的提问来源于stack exchange,提问作者a.lejeune626

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:31:35