jsarbour
jsarbour

Reputation: 1148

Escape sequences and Node.js child process spawning

I am trying to run some python code inside of a node.js server.

I am running the python as:

//handler.js

const spawn = require("child_process").spawn

module.exports = (parameter) => {
  return new Promise((resolve, reject) => {
    //***vvv***
    const pythonProcess = spawn('python', [filepath/to/main.py, '--option', 'argument1', 'parameter', 'multiple\ word\ argument', 'argument2']).
    //***^^^***


    //and the functions that go with it for now
    pythonProcess.stdout.on('data', function(data) {
      consolde.log("data: ", data.toString())
    })    

    pythonProcess.on('exit', function(code) {
      console.log("EXIT: ", code.toString())
    })

  }
}

And am having issues with the script. I believe I am having issues with the multiple\ word\ argument. I don't know if it is escaping the spaces correctly when calling it in the shell. Is there any way to check that? Is there a certain way to do this?

This is inside a Linux environment.

Thanks

Upvotes: 1

Views: 944

Answers (2)

Dan D.
Dan D.

Reputation: 74645

You don't need to escape here as the library does it for you on platforms where it is needed.

 const pythonProcess = spawn('python', ['filepath/to/main.py', '--option', 'argument1', 'parameter', 'multiple word argument', 'argument2']).

Upvotes: 2

guzmonne
guzmonne

Reputation: 2540

One thing I see in your code is that you are returning a promise, but you are never calling resolve or reject on its implementation.

Try doing something like this:

function callPython(parameter) {
  return new Promise((resolve, reject) => {
    const pythonProcess = spawn('python', [
      path.resolve(__dirname, 'print_arguments.py'),
      '--option',
      'argument1',
      'parameter',
      parameter,
      'multiple \word \argument',
      'argument2'
    ]);

    pythonProcess.stdout.on('data', data => {
      console.log("data:", data.toString());
    });

    pythonProcess.stdout.on('exit', code => {
      console.log("EXIT:", code.toString());
      resolve();
    });

    pythonProcess.stdout.on('error', error => {
      console.log('ERROR:', error.toString());
      reject();
    });
  });
}

I don't think that there is a problem with how you are escaping the spaces on the string parameters. I tried it with this Python script, and it worked fine:

import sys

if __name__ == '__main__':
    for argument in sys.argv:
        print(str(argument))

It just prints the arguments.

Look at this link for more information regarding JavaScript promise interface:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

I hope it helps

Upvotes: 1

Related Questions