在 TypeScript 文件中的 JavaScript - Python 脚本
我如何在 TypeScript 文件中使用我的 Python 脚本?比如我怎么链接它?我需要遍历一个 XML 文件,我有一个 Python 代码可以更新一些细节,想在 TypeScript 服务器文件中使用它。
就像服务器应该在一个 XML 文件中更新一些细节一样。这个更新功能是用 Python 实现的,我想在 TypeScript 服务器代码中使用它。
答案#1
你可以在 Node 中使用 exec() 运行 Python 脚本:https://nodejs.org/api/child_process.html#child_processexeccommand-options-callback
一个最小的示例,假设你在运行节点脚本的机器上已安装了python3,可以是:
// 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
这样你就可以遍历你的 XML 文件,修改它并输出到 js/ts 文件,或者将其保存为文件,然后通过你的 js/ts 代码读取它。
