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

如何让Node.js与Python文件共享同一变量值?

Sharing Variables Between Node.js and Python: Single Source of Truth

Great question! When building a Node.js/Express app that works alongside Python scripts, having a single source of truth for shared variables is totally achievable—much like Android’s res directory for centralized resources. Here are a few practical approaches I’ve used in similar projects:

1. Centralized JSON Configuration File

This is the simplest, most straightforward method for static variables that don’t change at runtime. Create a single JSON file both languages can natively read.

Example config.json:

{
  "model_settings": {
    "model_path": "./models/trained_model.pkl",
    "confidence_threshold": 0.85
  },
  "math_constants": {
    "pi_approx": 3.14159265,
    "max_calculation_limit": 1000000
  }
}

Node.js Usage (Express):

// app.js
const express = require('express');
const config = require('./config.json');

const app = express();

// Use the shared variable
app.get('/predict', (req, res) => {
  console.log(`Using threshold: ${config.model_settings.confidence_threshold}`);
  // Call your Python script with this value, or use it directly
  res.send('Prediction in progress');
});

app.listen(3000);

Python Usage:

# ml_script.py
import json

# Load the shared config
with open('./config.json', 'r') as config_file:
    config = json.load(config_file)

# Access the variable
threshold = config['model_settings']['confidence_threshold']
print(f"Confidence threshold set to: {threshold}")

Pros: No extra dependencies, easy to edit, works for most static use cases.

2. Environment Variables (.env File)

Perfect for sensitive variables or values you might want to adjust per environment (dev/prod). Use dotenv libraries to load the same .env file in both languages.

Example .env:

MODEL_PATH=./models/trained_model.pkl
CONFIDENCE_THRESHOLD=0.85
PI_APPROX=3.14159265

Node.js Usage (with dotenv):

First install the package: npm install dotenv

// app.js
require('dotenv').config();
const express = require('express');

const app = express();

// Access the variable (note: env vars are strings by default)
const threshold = parseFloat(process.env.CONFIDENCE_THRESHOLD);
console.log(`Threshold: ${threshold}`);

Python Usage (with python-dotenv):

First install the package: pip install python-dotenv

# ml_script.py
from dotenv import load_dotenv
import os

load_dotenv()

# Access and convert the variable
threshold = float(os.getenv('CONFIDENCE_THRESHOLD'))
print(f"Threshold: {threshold}")

Pros: Keeps sensitive data out of version control, easy to switch environments.

3. Centralized API Endpoint (For Dynamic Variables)

If your variables need to update at runtime (e.g., based on user input or app state), create a simple Express endpoint that serves the shared values, and have your Python script fetch them via HTTP.

Node.js Express Endpoint:

// app.js
const express = require('express');
const app = express();

// Shared variables that can be updated dynamically
let sharedVars = {
  confidence_threshold: 0.85,
  model_path: './models/trained_model.pkl'
};

// Endpoint to get shared vars
app.get('/api/shared-vars', (req, res) => {
  res.json(sharedVars);
});

// Optional: Endpoint to update vars (add auth if needed)
app.post('/api/shared-vars', express.json(), (req, res) => {
  sharedVars = {...sharedVars, ...req.body};
  res.json({success: true});
});

app.listen(3000);

Python Script to Fetch Variables:

# ml_script.py
import requests

def get_shared_vars():
    response = requests.get('http://localhost:3000/api/shared-vars')
    if response.status_code == 200:
        return response.json()
    raise Exception("Failed to fetch shared variables")

shared_vars = get_shared_vars()
threshold = shared_vars['confidence_threshold']
print(f"Current threshold: {threshold}")

Pros: Real-time synchronization, supports dynamic updates. Cons: Requires your Express server to be running, adds minor network overhead.

Key Notes:

  • For static variables, stick with JSON or .env—they’re lightweight and low-effort.
  • Always handle type conversion when using environment variables (they’re stored as strings).
  • If sharing sensitive data, prioritize .env over JSON, and never commit .env to version control.
  • Ensure file paths are consistent between Node.js and Python (use absolute paths if your scripts run from different directories).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:19:35