Skip to content
Advertisement

Calling python script with config file from node.js as a child process

I am calling a python script as a child process from node.js, the python script uses a config.ini file for some reason the python script does not call the config file when its called as a child process, but when I launch the python script ‘using python script.py’ it works, and when a replace the value from the config.ini file with an actual value inside the script.py it works also, how do I fix this?

from configparser import ConfigParser
import sys
import re
import json
file = 'config.ini'
config = ConfigParser()
config.read(file)

rCARD_NUMBER = r"number:s(d+*+d+).*?"
regex = rCARD_NUMBER*int(config['atm']['bCARD_NUMBER'])
# re.DOTALL to match any characters including newline
input = open(sys.argv[1], "r")
# print(input.read())
matches = re.findall(regex, input.read(), re.DOTALL)
print(json.dumps(matches))

config.ini

[atm]
bCARD_NUMBER = 1

Here is how I call the python script as a child process from node :

 var largeDataSet = [];
    // spawn new child process to call the python script
    // pass the python script the uploaded file as an argument
    const python = spawn("python", [
      "./config/script.py",
      req.file.path,
    ]);

    // collect data from script
    python.stdout.on("data", function (data) {
      console.log("Pipe data from python script ...");
      largeDataSet.push(data);
    });

Advertisement

Answer

What seems to be happening is that ConfigParser().read(file) reads based off of the current working directory, which would be where the JavaScript file is, not inside the config folder.

You can get around that by using pathlib (pre-installed, core library)

from configparser import ConfigParser
from pathlib import Path
import sys
import re
import json
file = 'config.ini'
config = ConfigParser()
config.read((Path(__file__).parent / "config.ini").absolute())

rCARD_NUMBER = r"number:s(d+*+d+).*?"
regex = rCARD_NUMBER*int(config['atm']['bCARD_NUMBER'])
# re.DOTALL to match any characters including newline
input = open(sys.argv[1], "r")
# print(input.read())
matches = re.findall(regex, input.read(), re.DOTALL)
print(json.dumps(matches))

Your JavaScript and config.ini file should remain the same.

Advertisement