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.
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.
Related
I'm trying to make a snake game with Electron and deep reinforcement learning. The reinforcement learning stuff I do in python and the game in Javascript. Now how can I call a function like this in python?
makeSomeThing(x) {
}
or
getValue() {
return x;
}
Please build your python script to an executable binary file. You can use pyinstaller to package your python scripts to a standalone executable file.
Then you can spawn this binary file at your Electron project like this.
import { spawn } from 'child_process';
// in my case I'm storing the file at bin directory at the root path of the application
// You can change this whatever you want
const pythonPath = const basicURL = process.env.NODE_ENV === 'development'
? path.join(__dirname, './bin/xxxx')
: path.join(process.resourcesPath, 'bin', 'xxxx');
const params = ['arg1', 'arg2']; // params that your python scripts need.
const pythonChildProcess = spawn(pythonPath, params);
pythonChildProcess.stdout.on('data', data => {
console.log(`stdout: ${data}`);
// Here is where the output goes
});
pythonChildProcess.stderr.on('data', data => {
console.log(`tderr: ${data}`);
// Here is where the error output goes
});
pythonChildProcess.on('close', code => {
console.log(`closing code: ${code}`);
// Here you can get the exit code of the script
});
Well, I don't know if it is the answer that you expect, but I would create a standalone python service that exposes some API.
Create a client in electron and use python API to send data and get processed information from the Python service
You cant call Javascript API from python. You need something in the middle anyway.
I have a problem, I'm trying to execute file that sending mail using nodemailer and I need to execute it from another JS file I tried to do it like this:
const exec = require('child_process').exec;
exec('"C:/Users/NikitaSeliverstov/node_modules/.bin/send.js"');
but mail is not sending. I don't need to send params the file send.js just sending text file with fully specified path . Sorry for obvious question but I can't figure it out.
Also I tried to do it like this:
const exec = require('child_process').exec;
exec('"node C:/Users/NikitaSeliverstov/node_modules/.bin/send.js"');
you need to specify a callback function which will be called after your exec command is executed:
i created 2 files:
anotherTest.js
console.log('another test');
test.js
const exec = require('child_process').exec;
const child = exec('node anotherTest.js',
(error, stdout, stderr) => {
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
if (error !== null) {
console.log(`exec error: ${error}`);
}
});
this is the output:
stdout: another test
stderr:
you run the test.js script by doing "node test.js" in the terminal/console. you can change the arguments of the exec command with the arguments that you want.
Is there a way where I can invoke a windows batch file from inside the javascript code? Or any other healthy way to do the below through any node package?
scripts.bat
ECHO "JAVASCRIPT is AWESOME"
PAUSE
scripts.js
// Code to read and run the batch file //
On the command prompt:
C:/> node scripts.js
One way to do this is with child_process. You just have to pass the file you want to execute.
const execFile = require('child_process').execFile;
const child = execFile('scripts.bat', [], (error, stdout, stderr) => {
if (error) {
throw error;
}
console.log(stdout);
});
Here is my problem, I want to create a CLI that automatically runs a test. Without the CLI, I'm able to run everything perfectly with the node command:
node test.js
Basically, I want to do the exact same thing as the command before, so I googled for a technique that does this. I found this:
#!/usr/bin/env node
'use strict';
const options = process.argv;
const { execFile } = require('child_process');
const child = execFile('node', ['../dist/test.js'], (error, stdout, stderr) => {
if (error) {
throw error;
}
console.log(stdout);
});
This method doesn't work for me because, in the test.js file, I'm using the ora package. And because this package is making real-time animations, it doesn't come in stdout.
Is there any way of executing in real time (without subprocess) my test.js using Node? I'm open to other methods, but I want to publish the CLI on NPM, so keep in mind that it has to be in JavaScript š.
You can find every file that I've talked here on GitHub. Normally, you wouldn't need this link, but I'm giving it to you if you need to have a closer look.
You should simply call your test() function from your CLI code, after requiring the module that defines it. Have a look at mocha and jasmine: you will see that while both tools provide a CLI, they also provide instructions for invoking the test frameworks from arbitrary JS code.
I can't think of a way without a sub-process. but this may help.
The child process exec will not work with the continuous output commands as it buffers the output the process will halt when that buffer is full.
The suitable solution is spwan :
var spwan = require('child_process').spwan
var child = spwan('node', ['../dist/test.js'])
child.stdout.on('data', function(data) {
console.log(data)
})
child.stderr.on('data', function(data) {
console.log(data)
})
Here is my solution, you can use the fs library to get the code of the file, and then, you simply use eval to execute in the same process.
const fs = require("fs");
function run(file) {
fs.readFile(file, (err, data) => {
eval(data.toString('utf8'))
})
}
I'm having trouble identifying the path to a file in the public directory c:\TEMP\todos\.meteor\local\build\programs\server\public\main.py. Meteor complains the file or directory doesn't exist. Already searched the other postings about the similar issue (e.g., Reading files from a directory inside a meteor app) but didn't help.
Here is the error message.
=> Your application has errors. Waiting for file change.
=> Modified -- restarting.
=> Meteor server restarted
W20151206-04:05:57.893(-5)? (STDERR) Error inside the Async.runSync: ENOENT, no such file or directory 'c:\TEMP\todos\.meteor\local\build\programs\server\public'
Client code
Meteor.call('runPython', function(err, response) {
if(err){
} else {
console.log(response);
}
})
Server code
Meteor.startup( function (){
Meteor.methods({
runPython: function (){
var PythonShell = Meteor.npmRequire('python-shell');
var fs = Meteor.npmRequire('fs');
var runPython = Async.runSync(function (done){
var files = fs.readdirSync('./public/');
// PythonShell.run('main.py', function ... was tried first but Meteor complained that "main.py doesn't exist". So below is a different attempt.
var py = _(files).reject(function(fileName){
return fileName.indexOf('.py') <0;
})
PythonShell.run(py, function (err) {
// PythonShell.run(path.join(py,"main.py") ... was also tried but resulted in the same error
if (err) throw err;
console.log('script running failed');
});
})
return "Success";
}
})
})
All files inside the public folder should be read using '/':
var files = fs.readdirSync('/');
More here: http://docs.meteor.com/#/full/structuringyourapp
For server-side only (might be your case and probably a better solution) you can put everything under the private/ folder and access them by using the Assets API: http://docs.meteor.com/#/full/assets_getText
Clearly I was overthinking it. Specifying a full path to the file was all I needed to do.
PythonShell.run('c:\\project\\public\\main.py', function ...
If your application allows moving the Python script to /private instead of /public, you can take advantage of Meteor's Assets:
Assets allows server code in a Meteor application to access static server assets, which are located in the private subdirectory of an applicationās tree. Assets are not processed as source files and are copied directly into your applicationās bundle.
e.g. If you move your script to /private/scripts/script.py you can generate the absolute path the Meteor way by doing Assets.absoluteFilePath('scripts/script.py').