0

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"])

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

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 Answer 1

3

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

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.

EDIT:

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

var pyshell = new PythonShell(myPythonScriptPath, {
  env: process.env,
});
Sign up to request clarification or add additional context in comments.

1 Comment

i am running py script from nodejs module only...please check the updated code in the question...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.