在节点js中设置env变量并在python脚本中使用

时间:2022-01-29 23:29:30

I am setting an env variable in node js app: process.env.data = "data-env";
Acessing the same env variable in my python script using : print(os.environ["data"])

我在node js app中设置了一个env变量:process.env.data =“data-env”;使用以下命令在我的python脚本中访问相同的env变量: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

Using below code from nodeJs to run py script

使用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');
});

am i doing something wrong?

难道我做错了什么?

1 个解决方案

#1


2  

Modifying process.env alters environment variables for the current process and (optionally) child processes.

修改process.env会更改当前进程和(可选)子进程的环境变量。

So, unless you are starting your Python script from the Node.js app, environment variables set in the Node.js app wouldn't be accessible from Python script.

因此,除非您从Node.js应用程序启动Python脚本,否则无法从Python脚本访问Node.js应用程序中设置的环境变量。

EDIT:

编辑:

PythonShell accepts second parameter options, which you can use to propagate environment variables down to the child process.

PythonShell接受第二个参数选项,您可以使用这些选项将环境变量传播到子进程。

var pyshell = new PythonShell(myPythonScriptPath, {
  env: process.env,
});

#1


2  

Modifying process.env alters environment variables for the current process and (optionally) child processes.

修改process.env会更改当前进程和(可选)子进程的环境变量。

So, unless you are starting your Python script from the Node.js app, environment variables set in the Node.js app wouldn't be accessible from Python script.

因此,除非您从Node.js应用程序启动Python脚本,否则无法从Python脚本访问Node.js应用程序中设置的环境变量。

EDIT:

编辑:

PythonShell accepts second parameter options, which you can use to propagate environment variables down to the child process.

PythonShell接受第二个参数选项,您可以使用这些选项将环境变量传播到子进程。

var pyshell = new PythonShell(myPythonScriptPath, {
  env: process.env,
});