2

how do I use my python script in a typescript file? Like how do I link it ? I have to traverse a xml file which I have a python code which updates some details and wanted to use it in the typescript server file.

Like the server should update some details in a xml file. this update functionality is implemented in python and I wanted to use it in the typescript server code.

vinayak
  • 23
  • 1
  • 5
  • Transpile (port) the Python script into TypeScript? Or run it through the shell? – kelsny Aug 16 '22 at 19:52
  • 1
    You can create a new process and call the python code. Look into inter-process communication. This can get messy with passing arguments and getting output back. You may be better of rewriting the Python code in TypeScript. – Robert Aug 16 '22 at 19:52
  • See if this is want you need: https://stackoverflow.com/questions/30689526/how-to-call-python-script-from-nodejs – PM 77-1 Aug 16 '22 at 19:53

1 Answers1

3

You can run the python script in node using exec(): https://nodejs.org/api/child_process.html#child_processexeccommand-options-callback

A minimal example assuming you have python3 installed on the machine running your node script could be:

// shell.py

print('printed in python')
// server.js

import {exec} from 'child_process'
//if you don't use module use this line instead:
// const { exec } = require('child_process')

exec('python3 shell.py', (error, stdout, stderr) => {
  if (error) {
    console.log(`error: ${error.message}`);
  }
  else if (stderr) {
    console.log(`stderr: ${stderr}`);
  }
  else {
    console.log(stdout);
  }
})
// using it in the shell

% node server.js

// should output this:

printed in python

This way you could traverse your XML file, change it and output it to the js/ts file, or save it as a file and just read that via your js/ts code.

Community
  • 1
  • 1
leonbubova
  • 109
  • 1
  • 4