python - 在节点 js 中设置环境变量并在 python 脚本中使用
问题描述
我在节点 js 应用程序中设置一个环境变量:
process.env.data = "data-env";
在我的 python 脚本中使用相同的环境变量:print(os.environ["data"])
but getting error throw err;
^
Error: KeyError: 'data'
at PythonShell.parseError (H:\NodeJS\node_modules\python-shell\index.js:184:17)
at terminateIfNeeded (H:\NodeJS\node_modules\python-shell\index.js:98:28)
at ChildProcess.<anonymous> (H:\NodeJS\node_modules\python-shell\index.js:89:9)
at emitTwo (events.js:126:13)
at ChildProcess.emit (events.js:214:7)
at Process.ChildProcess._handle.onexit (internal/child_process.js:198:12)
----- Python Traceback -----
File "script.py", line 5, in <module>
print(os.environ["data"])
File "C:\Program Files\Anaconda3\lib\os.py", line 725, in __getitem__
raise KeyError(key) from None
使用 nodeJs 中的以下代码运行 py 脚本
var PythonShell = require('python-shell');
var myPythonScriptPath = './script.py';
var pyshell = new PythonShell(myPythonScriptPath);
pyshell.on('message', function (message) {
// received a message sent from the Python script (a simple "print" statement)
console.log(message);
});
// end the input stream and allow the process to exit
pyshell.end(function (err) {
if (err){
throw err;
};
console.log('finished');
});
难道我做错了什么?
解决方案
修改process.env
会更改当前进程和(可选)子进程的环境变量。
因此,除非您从 Node.js 应用程序启动 Python 脚本,否则无法从 Python 脚本访问 Node.js 应用程序中设置的环境变量。
编辑:
PythonShell
接受第二个参数options
,您可以使用该参数将环境变量向下传播到子进程。
var pyshell = new PythonShell(myPythonScriptPath, {
env: process.env,
});
推荐阅读
- android - 相当于 AAB 的 APK Editor Studio
- python - 尝试使用动态变量更新 Django 模型
- python - 我怎样才能实现这个模型?
- keyword - Roogle 视觉包
- javascript - 反应状态不会随着 axios 响应而更新
- email - 如何在 Mantis Bug Tracker 中启用电子邮件通知?
- python - 如何从电报会话中保存数据 - django
- git - Git克隆到现有分支(覆盖现有分支)
- python - 为什么当我使用 OR 布尔运算符时,while 循环会一直持续到两个变量都达到目标而不是一个
- python - 当有两个接受字符串输入的 django 路径时,为什么我会收到 NoReverseError 消息?(我正在研究 CS50 项目 1。)