在pycharm中,在a.py文件中调用code.js并进行执行的方法

第一种情况:a.py不需要给code.js传参,但是需要从code.js拿回结果

最终可用代码(无传参,只拿结果)

1. 你的 code.js(只负责计算,返回结果)

javascript
// code.js
// 这里写你的 JS 逻辑
function calculate() {
    // 示例:你真正的业务逻辑
    let result = 100 + 200;
    return result; // 必须 return 结果
}

// 把结果打印出来,Python 就能拿到
console.log(calculate());
 

2. 你的 a.py(调用 JS,只拿返回值)

python
import subprocess

def get_result_from_js():
    # 执行 code.js
    result = subprocess.run(
        ["node", "code.js"],
        capture_output=True,
        text=True,
        encoding="utf-8"
    )
    
    # 拿到 JS 返回的结果(纯结果,干净无多余)
    js_result = result.stdout.strip()
    
    # 你可以直接用这个结果
    print("从 JS 拿到的结果:", js_result)
    return js_result

# 调用
if __name__ == "__main__":
    get_result_from_js()
 

运行效果

从 JS 拿到的结果:300
 

核心说明(你只需要记住这 2 点)

  1. JS 里必须用 console.log(结果)Python 才能读到返回值
  2. Python 用 result.stdout.strip()就能拿到纯结果字符串,可直接使用

支持任意复杂 JS 逻辑

不管你的 JS 是计算、接口请求、加密、解析……
 
只要最后 console.log (最终结果),Python 就能稳稳拿到。
 
再来看个简单的案例,熟悉一下

最简单(调用系统 node 命令)

纯 Python 标准库,不用装任何包,直接执行 JS 文件并获取输出。

a.py 代码

python
import subprocess
import sys

# 调用 node 执行 code.js
def run_js_file():
    try:
        # 核心命令:node 你的JS文件路径
        result = subprocess.run(
            ["node", "code.js"],
            capture_output=True,
            text=True,
            encoding="utf-8"
        )
        
        # 打印 JS 执行结果
        print("JS 标准输出:", result.stdout)
        print("JS 错误信息:", result.stderr)
        
        return result.stdout
    
    except Exception as e:
        print("调用失败:", e)

# 测试调用
if __name__ == "__main__":
    run_js_file()
 

配套 code.js 示例

javascript
// code.js
console.log("我是JS文件,被Python调用成功啦!");

// 你可以写任意JS代码
let a = 10;
let b = 20;
console.log("计算结果:", a + b);
 

运行效果

JS 标准输出:我是JS文件,被Python调用成功啦!
计算结果: 30
第二种情况:a.py需要给code.js传参,还要从code.js拿回结果
日常开发最常用:Python 给 JS 传数据 → JS 处理 → 返回结果
(注意:要在同级目录中)

a.py(传参给 JS)

python
import subprocess

def run_js_with_params():
    # Python 要传给 JS 的数据
    name = "小明"
    age = 20
    
    # 命令:node code.js 参数1 参数2
    result = subprocess.run(
        ["node", "code.js", name, str(age)],
        capture_output=True,
        text=True,
        encoding="utf-8"
    )
    
    print("JS 返回结果:", result.stdout.strip())

if __name__ == "__main__":
    run_js_with_params()
 

code.js(接收参数)

javascript
// process.argv 会接收 Python 传过来的参数
const args = process.argv.slice(2); // 去掉前2个默认参数
const name = args[0];
const age = args[1];

console.log(`姓名:${name},年龄:${age}`);
console.log("10年后年龄:", Number(age) + 10);

image

posted @ 2026-05-25 14:01  chenlight  阅读(14)  评论(0)    收藏  举报