I am very new to both python and node.js. Basically I am trying to call a python script from node.js.Any help would be much appreciated.
I have installed python-shell npm package.
When I run the python script from cmd, it works fine and I can see the output.
I have installed python 3.8.
This is my python script:
# script.py
my_name = 'Lily'
my_age = 22
my_height = 172 # cm
my_weight = 71 # kg
my_eyes = 'Brown'
my_teeth = 'White'
my_hair = 'Black'
print ("Let's talk about %s." % my_name)
print ("He's %d centimeters tall." % my_height)
print ("He's %d kilograms heavy." % my_weight)
print ("Actually that's not too heavy.")
print ("He's got %s eyes and %s hair." % (my_eyes, my_hair))
print ("His teeth are usually %s depending on the coffee." % my_teeth)
# this line is tricky, try to get it exactly right
print ("If I add %d, %d, and %d I get %d. I don't know what that means but, whatever." % (
my_age, my_height, my_weight, my_age + my_height + my_weight))
Here is my node.js script:
function Runpy(){
var {PythonShell} = require('python-shell');
var options = {
mode: 'text',
pythonPath: 'C:/Users/User1/AppData/Local/Programs/Python/Python38',
pythonOptions: ['-u'],
scriptPath: 'C:/PythonScripts/script.py'
};
PythonShell.run('script.py', options, function (err, results) {
if (err) throw err;
// results is an array consisting of messages collected during execution
console.log('results: %j', results);
});
}
return Runpy();
When I run node ./sample.js I get the following error:
events.js:174
throw er; // Unhandled 'error' event
^
Error: spawn C:/Users/User1/AppData/Local/Programs/Python/Python38 ENOENT
at Process.ChildProcess._handle.onexit (internal/child_process.js:240:19)
at onErrorNT (internal/child_process.js:415:16)
at process._tickCallback (internal/process/next_tick.js:63:19)
at Function.Module.runMain (internal/modules/cjs/loader.js:834:11)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
Emitted 'error' event at:
at Process.ChildProcess._handle.onexit (internal/child_process.js:246:12)
at onErrorNT (internal/child_process.js:415:16)
[... lines matching original stack trace ...]
at bootstrapNodeJSCore (internal/bootstrap/node.js:622:3)
I have referred to this stackoverflow post Using PythonShell module in Nodejs where it is suggested to use absolute path to the script and also correct path to the python executable which i am doing but still getting the above error.
Thanks!
I got this working. The path to the python executable was incomplete. I was just pointing to 'C:/Users/user1/AppData/Local/Programs/Python/Python38' which should be 'C:/Users/user1/AppData/Local/Programs/Python/Python38/python3'. Indeed a silly mistake
Related
I copied a code from StackOverflow to read text from a base64 of an image:
let base64 = req.body.toString("base64");
let imageBuffer = Buffer.from(base64, "base64");
const worker = createWorker();
(async () => {
await worker.load();
await worker.loadLanguage('eng');
await worker.initialize('eng');
console.log("Recognizing...");
const { data: { text } } = await worker.recognize(imageBuffer);
console.log("Recognized text:", text);
await worker.terminate();
})();
But I a getting this Error:
Error opening data file ./eng.traineddata
Please make sure the TESSDATA_PREFIX environment variable is set to your "tessdata" directory.
Failed loading language 'eng'
Tesseract couldn't load any languages!
Recognizing...
AdaptedTemplates != nullptr:Error:Assert failed:in file /workspace/tesseract/src/classify/adaptmatch.cpp, line 196
undefined
undefined
C:\Users\jaysm\OneDrive\Desktop\QBase\node_modules\tesseract.js\src\createWorker.js:173
throw Error(data);
^
Error: RuntimeError: abort(undefined). Build with -s ASSERTIONS=1 for more info.
at ChildProcess.<anonymous> (C:\Users\jaysm\OneDrive\Desktop\QBase\node_modules\tesseract.js\src\createWorker.js:173:15)
at ChildProcess.emit (events.js:315:20)
at emit (internal/child_process.js:903:12)
at processTicksAndRejections (internal/process/task_queues.js:81:21)
[nodemon] app crashed - waiting for file changes before starting...
What is the problem with my code?
I found some solutions of this error but they were with python or some other languages but none with NodeJS.
Actually my problem was not of setting TESSDATA_PREFIX as environment variable but i had not placed the eng.traineddata file in the base directory.
I placed the eng.traineddata file and the issue was resolved!
Trying to run the command mentioned in sections below, it is intended to run retire.js on some javascript files/libraries and pipe the output in a json file. The command works and produces output in a json file but ends with an error.
When I try the same command directly by copy pasting the command in command line it works without an error.
I have tried the exexSync version and shelljs as well though get error in Shelljs as well. However, I am not able to understand what is causing the problem.
using node-exec-promise.exec :
exec('node C:/Users/walee/AppData/Roaming/npm/node_modules/retire/bin/retire --outputformat json --outputpath D:/Internship/local/testing/1.json').
then(function(retire_out){
console.log('Retire Command Success ');
console.log(' Retire_out Result ',retire_out);
return retire_out;
}, function(err){
console.error(err)
}
Using Shelljs:
if (shell.exec('node
C:/Users/walee/AppData/Roaming/npm/node_modules/retire/bin/retire --outputformat json --outputpath D:/Internship/local/testing/1.json').code !== 0) {
shell.echo('Error: Git commit failed');
shell.exit(1);
}
Expected Result is a Json file with known vulnerabilities found by retire.js, the file gets populated and it has valid json.
However, I get the following error in command line:
{ Error: Command failed: node C:/Users/walee/AppData/Roaming/npm/node_modules/retire/bin/retire --outputformat json --outputpath D:/Internship/local/testing/1.json
at ChildProcess.exithandler (child_process.js:294:12)
at ChildProcess.emit (events.js:189:13)
at maybeClose (internal/child_process.js:970:16)
at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
killed: false,
code: 13,
signal: null,
cmd:
'node C:/Users/walee/AppData/Roaming/npm/node_modules/retire/bin/retire --outputformat json --outputpath D:/Internship/local/testing/1.json' }
Because retire exits with an exitcode of 13 if there are vulnerabilities found, you'll want a .catch before any .then to "allow" exitcode 13.
Also, since you've specified --outputpath for retire, the output will NOT go to stdout, so you will need to read the outputfile in the .then code - also, since retire would return an "error" (13) - node-exec-promise doesn't even give you access to stdout/stderr in the err that is passed to the .catch code anyway!
The following is pseudo-code, since I'm not fully familiar with node-exec-promise:
exec('node C:/Users/walee/AppData/Roaming/npm/node_modules/retire/bin/retire --outputformat json --outputpath D:/Internship/local/testing/1.json')
.catch(err => {
if (err.code !== 13) {
throw err;
}
})
.then(() => {
// read the output file if you want to display it here
})
.catch(err => {
//handle other errors here
});
I'm kind of new to JS and I can't solve this problem, so I hope you can help me.
I will explain shortly what the situation is, I installed the app Homebridge from Github on my Raspberry: https://github.com/nfarina/homebridge
Installation was successful, so, so far so good. But then I installed the plugin eWeLink for the Homebridge app: https://github.com/gbro115/homebridge-ewelink the installation went good as well, but on the startup there seems to be a probleem in the index.js from the plugin, I get the following output:
[2018-5-31 23:10:37] [eWeLink] A total of [0] accessories were loaded from the local cache [2018-5-31 23:10:37] [eWeLink] Requesting
a list of devices from eWeLink HTTPS API at
[https://eu-ota.coolkit.cc:8080] [2018-5-31 23:10:37] Homebridge is
running on port 51826. [2018-5-31 23:10:37] [eWeLink] eWeLink HTTPS
API reports that there are a total of [108] devices registered
/usr/lib/node_modules/homebridge-ewelink/index.js:98
body.forEach((device) => { ^
TypeError: body.forEach is not a function at
/usr/lib/node_modules/homebridge-ewelink/index.js:98:22 at
Object.parseBody
(/usr/lib/node_modules/homebridge-ewelink/node_modules/request-json/main.js:74:12)
at Request._callback
(/usr/lib/node_modules/homebridge-ewelink/node_modules/request-json/main.js:148:26)
at Request.self.callback
(/usr/lib/node_modules/homebridge-ewelink/node_modules/request/request.js:186:22)
at emitTwo (events.js:126:13) at Request.emit (events.js:214:7) at
Request.
(/usr/lib/node_modules/homebridge-ewelink/node_modules/request/request.js:1163:10)
at emitOne (events.js:116:13) at Request.emit (events.js:211:7) at
IncomingMessage.
(/usr/lib/node_modules/homebridge-ewelink/node_modules/request/request.js:1085:12)
So the terminal tells me there is a error on line 98 from the index.js, that will be the next part of the script:
var devicesFromApi = new Map();
var newDevicesToAdd = new Map();
body.forEach((device) => {
platform.apiKey = device.apikey;
devicesFromApi.set(device.deviceid, device);
});
// Now we compare the cached devices against the web list
platform.log("Evaluating if devices need to be removed...");
function checkIfDeviceIsStillRegistered(value, deviceId, map) {
var accessory = platform.accessories.get(deviceId);
if (devicesFromApi.has(deviceId)) {
platform.log('Device [%s] is regeistered with API. Nothing to do.', accessory.displayName);
} else {
platform.log('Device [%s], ID : [%s] was not present in the response from the API. It will be removed.', accessory.displayName, accessory.UUID);
platform.removeAccessory(accessory);
}
}
I found some similar problems with the fromEach function but I still can't seem to figure out what I should change in the script.
Hope you can help me :)
body is not an Array, therefore you cannot invoke .forEach on it, you can try converting it like
Array.from(body).forEach(function (device) { ... }
Take a look on this answer that might help : forEach is not a function error with JavaScript array
I'm using a library called python-shell to try and send data back and forth between node and python.
The code below should work but when I run it I get this error:
events.js:160
throw er; // Unhandled 'error' event
^
Error: write EPIPE
at exports._errnoException (util.js:1022:11)
at Socket._writeGeneric (net.js:712:26)
at Socket._write (net.js:731:8)
at doWrite (_stream_writable.js:334:12)
at writeOrBuffer (_stream_writable.js:320:5)
at Socket.Writable.write (_stream_writable.js:247:11)
at Socket.write (net.js:658:40)
at PythonShell.send (C:\Users\user\Desktop\node py project\fourth draft\node
_modules\python-shell\index.js:205:16)
at Object.<anonymous> (C:\Users\user\Desktop\node py project\fourth draft\in
dex.js:4:9)
at Module._compile (module.js:570:32)
my index.js:
var PythonShell = require('python-shell');
var pyshell = new PythonShell('script.py');
pyshell.send(JSON.stringify([1,2,3,4,5]));//the problem function
pyshell.on('message', function (message) {
// received a message sent from the Python script (a simple "print" statement)
console.log(message);
});
// end the input stream and allow the process to exit
pyshell.end(function (err) {
if (err){
throw err;
};
console.log('finished');
});
my script.py:
import sys, json
#Read data from stdin
def read_in():
lines = sys.stdin.readlines()
# Since our input would only be having one line, parse our JSON data from that
return json.loads(lines[0])
def main():
#get our data as an array from read_in()
lines = read_in()
# Sum of all the items in the providen array
total_sum_inArray = 0
for item in lines:
total_sum_inArray += item
#return the sum to the output stream
print total_sum_inArray
# Start process
if __name__ == '__main__':
main()
I think it has to do with the env path for python on win 7.
Any ideas? Library docs are located here: https://github.com/extrabacon/python-shell. Also I'm on Windows 7 Node v6.9.2 Python v3.6.1.
Try passing the parameter of python path to the script as below
var pyshell = new PythonShell('script.py',{pythonPath : '<path/to/python>'});
In this way you are explicitly setting the path to python executable command, regardless of any OS.
Here is reference of all the available options, that can be passed to the python-shell constructor.
Hope this fixes the issue, if it has to do anything with the Python path issues.
Before posting this question I went through a couple of SO posts with the same heading. All of them suggested me to restart my app..I tried that but I am still getting the error.
The code that is throwing the error is
app.post('/insert', function(request, response) {
var connection = mySequel.createConnection(ConnectionParams);
connection.connect();
var UserName = request.body.UserName;
// insert into userrecords values ("123456",DEFAULT,DEFAULT,DEFAULT,10);
var InsertQuery = "insert into userrecords values (" + UserName + ",DEFAULT,DEFAULT,DEFAULT,-10);";
connection.query(InsertQuery, function(error, result, fields) {
if (error) {
response.send("error");
console.log(error);
throw error;
} else {
// response.send("success");
console.log(result.insertId);
response.send(result.insertId);
}
});
connection.end();
});
The error caused by the code is this
events.js:160
2017-04-26T11:42:52.410094+00:00 app[web.1]:
2017-04-26T11:42:52.410092+00:00 app[web.1]: throw er; // Unhandled 'error' event
2017-04-26T11:42:52.410096+00:00 app[web.1]: Error: Quit inactivity timeout
2017-04-26T11:42:52.410097+00:00 app[web.1]: at Quit.<anonymous> (/app/node_modules/mysql/lib/protocol/Protocol.js:160:17)
2017-04-26T11:42:52.410093+00:00 app[web.1]: ^
2017-04-26T11:42:52.410098+00:00 app[web.1]: at emitNone (events.js:86:13)
2017-04-26T11:42:52.410099+00:00 app[web.1]: at Quit._onTimeout (/app/node_modules/mysql/lib/protocol/sequences/Sequence.js:127:8)
2017-04-26T11:42:52.410099+00:00 app[web.1]: at Quit.emit (events.js:185:7)
2017-04-26T11:42:52.410100+00:00 app[web.1]: at ontimeout (timers.js:380:14)
2017-04-26T11:42:52.410101+00:00 app[web.1]: at tryOnTimeout (timers.js:244:5)
2017-04-26T11:42:52.410102+00:00 app[web.1]: at Timer.listOnTimeout (timers.js:214:5)
I am hosting my app on Heroku and whenever I try to access this URL the app is crashing forcing me to restart the dyno. The data I am sending is being successfully inserted into the DB but the auto incremented primary key is not being returned to my app. Instead I get a server error.
JSON.stringify() returns the correct value once and after that the app crashed which maked the subsequent requests to fail.
How can I solve this problem?
Try converting your response into JSON before sending it.
Like
response.send(JSON.stringify(result.insertId));
I too once had a similar problem and I think that is how I solved it.
EDIT:
I went through the myql npm library and found something called Pool. Pool is used when you app needs to handle more than one request at a time. I suggest that you try that. There is a good example availble here.
I have same problem, i just downgrade to react-scripts#2.1.8
this is the steps:
cd my-app
npm install react-scripts#2.1.8
npm start