run_code_rmcp 0.0.35

云函数服务,执行JS/TS/Python语言代码,脚本必须有约定的函数名称(handler/main),会调用约定的函数名称结果和日志返回.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
use anyhow::Result;
use log::{debug, info};
use pest::Parser;
use pest_derive::Parser;

#[derive(Parser)]
#[grammar = "python_imports.pest"] // 这里是你的pest语法文件
struct ImportParser;

// Python标准库模块列表,使用静态变量定义
static PYTHON_STDLIB_MODULES: &[&str] = &[
    "abc",
    "argparse",
    "array",
    "ast",
    "asyncio",
    "atexit",
    "base64",
    "bdb",
    "binascii",
    "bisect",
    "builtins",
    "bz2",
    "calendar",
    "cmath",
    "cmd",
    "code",
    "codecs",
    "codeop",
    "collections",
    "colorsys",
    "compileall",
    "concurrent",
    "configparser",
    "contextlib",
    "copy",
    "copyreg",
    "cProfile",
    "csv",
    "ctypes",
    "curses",
    "dataclasses",
    "datetime",
    "dbm",
    "decimal",
    "difflib",
    "dis",
    "doctest",
    "email",
    "encodings",
    "ensurepip",
    "enum",
    "errno",
    "faulthandler",
    "fcntl",
    "filecmp",
    "fileinput",
    "fnmatch",
    "fractions",
    "ftplib",
    "functools",
    "gc",
    "getopt",
    "getpass",
    "gettext",
    "glob",
    "graphlib",
    "grp",
    "gzip",
    "hashlib",
    "heapq",
    "hmac",
    "html",
    "http",
    "idlelib",
    "imaplib",
    "importlib",
    "inspect",
    "io",
    "ipaddress",
    "itertools",
    "json",
    "keyword",
    "linecache",
    "locale",
    "logging",
    "lzma",
    "mailbox",
    "marshal",
    "math",
    "mimetypes",
    "mmap",
    "modulefinder",
    "msvcrt",
    "multiprocessing",
    "netrc",
    "numbers",
    "operator",
    "optparse",
    "os",
    "pathlib",
    "pdb",
    "pickle",
    "pickletools",
    "pkgutil",
    "platform",
    "plistlib",
    "poplib",
    "posix",
    "pprint",
    "profile",
    "pstats",
    "pty",
    "pwd",
    "py_compile",
    "pyclbr",
    "pydoc",
    "queue",
    "quopri",
    "random",
    "re",
    "readline",
    "reprlib",
    "resource",
    "rlcompleter",
    "runpy",
    "sched",
    "secrets",
    "select",
    "selectors",
    "shelve",
    "shlex",
    "shutil",
    "signal",
    "site",
    "smtplib",
    "socket",
    "socketserver",
    "sqlite3",
    "ssl",
    "stat",
    "statistics",
    "string",
    "stringprep",
    "struct",
    "subprocess",
    "sys",
    "sysconfig",
    "syslog",
    "tabnanny",
    "tarfile",
    "tempfile",
    "termios",
    "test",
    "textwrap",
    "threading",
    "time",
    "timeit",
    "tkinter",
    "token",
    "tokenize",
    "tomllib",
    "trace",
    "traceback",
    "tracemalloc",
    "tty",
    "turtle",
    "turtledemo",
    "types",
    "typing",
    "unicodedata",
    "unittest",
    "urllib",
    "uuid",
    "venv",
    "warnings",
    "wave",
    "weakref",
    "webbrowser",
    "winreg",
    "winsound",
    "wsgiref",
    "xml",
    "xmlrpc",
    "zipapp",
    "zipfile",
    "zipimport",
    "zlib",
    "zoneinfo",
];

pub fn parse_import(code: &str) -> Result<Vec<String>> {
    let modules = parse_python_imports(code)?;
    // 在非测试环境中,过滤标准库模块
    let mut imports = Vec::new();
    for module in modules {
        if !is_standard_library(&module) {
            imports.push(module);
        }
    }

    Ok(imports)
}

// 解析Python代码中的import语句
fn parse_python_imports(python_code: &str) -> Result<Vec<String>> {
    let input = if python_code.ends_with('\n') {
        python_code.to_string()
    } else {
        format!("{python_code}\n")
    };
    debug!("Processing input: {input:?}");

    let pairs = ImportParser::parse(Rule::file, &input)
        .map_err(|e| anyhow::anyhow!("Failed to parse input: {}", e))?;
    debug!("Initial parse successful");

    let mut imported_modules = Vec::new();

    for pair in pairs {
        debug!("Top level rule: {:?}", pair.as_rule());
        for record in pair.into_inner() {
            debug!(
                "Record rule: {:?}, text: {:?}",
                record.as_rule(),
                record.as_str()
            );
            // 遍历 record 的内部规则
            for inner in record.into_inner() {
                debug!(
                    "Inner rule: {:?}, text: {:?}",
                    inner.as_rule(),
                    inner.as_str()
                );
                match inner.as_rule() {
                    Rule::from_import_statement => {
                        for module in inner.into_inner() {
                            if let Rule::module_name = module.as_rule() {
                                imported_modules.push(module.as_str().to_string());
                            }
                        }
                    }
                    Rule::import_statement => {
                        // 遍历 import_statement 的内部规则找到 module_name
                        for module in inner.into_inner() {
                            if let Rule::module_name = module.as_rule() {
                                imported_modules.push(module.as_str().to_string());
                            }
                        }
                    }
                    Rule::importlib_statement => {
                        // 遍历 importlib_statement 的内部规则找到 module_name
                        for module in inner.into_inner() {
                            if let Rule::module_name = module.as_rule() {
                                imported_modules.push(module.as_str().to_string());
                            }
                        }
                    }
                    _ => {
                        info!("Unknown rule: {:?}", inner.as_rule());
                    }
                }
            }
        }
    }

    debug!("Final result: {imported_modules:?}");
    Ok(imported_modules)
}

// 判断是否为Python标准库模块
fn is_standard_library(module: &str) -> bool {
    // 检查模块名是否在标准库列表中
    PYTHON_STDLIB_MODULES.contains(&module)
}

#[cfg(test)]
mod tests {
    use super::parse_import;
    use anyhow::Result;
    use log::{LevelFilter, info};
    use std::sync::Once;

    // 使用 Once 确保 env_logger 只初始化一次
    static INIT: Once = Once::new();

    fn setup() {
        INIT.call_once(|| {
            env_logger::builder()
                .filter_level(LevelFilter::Debug)
                .init();
        });
    }

    #[test]
    fn test_line() -> Result<()> {
        setup();
        let python_code = "
                import pandas as pd\n";
        info!("Testing with input: {python_code:?}");

        let imported_modules = parse_import(python_code)?;
        info!("Parsed modules: {imported_modules:?}");

        assert_eq!(imported_modules, vec!["pandas"]);
        Ok(())
    }

    #[test]
    fn test_line2() -> Result<()> {
        setup();
        let python_code = "
             numpy_alias = importlib.import_module('numpy')";
        info!("Testing with input: {python_code:?}");

        let imported_modules = parse_import(python_code)?;
        info!("Parsed modules: {imported_modules:?}");

        assert_eq!(imported_modules, vec!["numpy"]);
        Ok(())
    }

    #[test]
    fn test_parse_import_bs() -> Result<()> {
        setup();
        let python_code = r#"
import requests
from bs4 import BeautifulSoup

# 发送请求到百度
url = 'https://www.baidu.com'
response = requests.get(url)

# 检查请求是否成功
if response.status_code == 200:
    # 解析网页内容
    soup = BeautifulSoup(response.text, 'html.parser')

    # 提取你想要的信息,例如标题
    title = soup.title.string
    print(f"网页标题: {title}")
else:
    print(f"请求失败,状态码: {response.status_code}")

 "#;
        let imported_modules = parse_import(python_code)?;
        info!("Parsed modules: {imported_modules:?}");
        assert_eq!(imported_modules, vec!["requests", "bs4"]);

        Ok(())
    }

    #[test]
    fn test_parse_import() -> Result<()> {
        setup();
        let python_code = r#"
import pandas as pd
import logging

# 配置日志记录
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

import importlib

# 使用 importlib 动态导入 numpy
numpy = importlib.import_module('numpy')
# 创建一个简单的 numpy 数组
arr = numpy.array([1, 2, 3, 4, 5])
# 记录数组信息
logging.info(f"Created numpy array: {arr}")

# 进行一些简单的操作
sum_arr = numpy.sum(arr)
logging.info(f"Sum of array: {sum_arr}")

# 创建一个简单的 DataFrame
data = {
    'Name': ['Alice', 'Bob', 'Charlie'],
    'Age': [25, 30, 35]
}
df = pd.DataFrame(data)

# 记录 DataFrame 信息
logging.info(f"Created DataFrame:\n{df}")

def main(args: dict) -> dict:
    logging.info(f"input args: {args}")

    params = args.get("params")
    # 构建输出对象
    ret = {
        "key0": params['input'], # 拼接两次入参 input 的值
        "key1": ["hello", "world"],  # 输出一个数组
        "key2": { # 输出一个Object
            "key21": "hi"
        },
    }
    return ret
"#;

        let imported_modules = parse_import(python_code)?;
        info!("Parsed modules: {imported_modules:?}");
        assert_eq!(imported_modules, vec!["pandas", "numpy"]);
        Ok(())
    }
}