function run() { var pyshell = new PythonShell('rfid.py', { mode: 'text' }); console.log('started up rfid.py, waiting on RFID/NFC card'); pyshell.on('message', handleMessage); pyshell.end(handleScriptEnded); function handleMessage(data) { console.log('received: ' + data); needle.post('https://entry.1128wnewport.com/api/entry/authenticate', { uid: data }, { multipart: false, json: true }, function (err, resp, body) { console.log(body); //if (!err && resp.statusCode == 200) //console.log(resp.body); // here you go, mister. }); } function handleScriptEnded(err) { if (err) { console.log(err) console.log('waiting 5 seconds before restarting'); setTimeout(function () { run(); }, 5000); } else { run(); }; } }
setupServer(callbacks) { let options = { mode: 'text', pythonOptions: ['-u'], scriptPath: path.join(__dirname, 'python') } if (this.pySerialServer) { delete this.pySerialServer } this.pySerialServer = new PythonShell('pyserialserver.py', options) this.pySerialServer.on('message', (message) => { console.log("pyserialserver.py - stdout:", message) }) this.pySerialServer.end( (err) => { console.log('pyserialserver.py finished') // If we didn't receive a disconnect event from socketio, we know // the python script crashed. We will attempt to restart it if (this.socketIoConnected === true) { console.log(err) console.log("Ungraceful Disconnection, restarting pyserialserver") this.socketIoConnected = false this.serialPortConnected = false callbacks.onServerError.call(callbacks.obj) this.setupServer(callbacks) } }) }
shell.on('message', function(magnet_link) { torrentShell = new pythonShell('../python_scripts/start_torrent.py'); torrentShell.send(magnet_link); torrentShell.on('error', function(err) { console.log("Error! " + err); }); });
exports.getRecommendations = function(req, res) { var idString = req.user.idString; var options = { mode: 'text', pythonPath: '/usr/bin/python', scriptPath: './scripts', args: ['[{"idString": "'+idString+'"}]'] }; pyshell = new PythonShell('collaborative_filtering.py', options); pyshell.on('message', function(message) { console.log(message.split(',')); console.log(typeof message); res.json({'predictions': message.split(',')}) }); pyshell.end(function(err) { if (err) throw err; console.log('Finished'); }) }
app.post('/python-parser', function(req, res) { var code = { 'code': req.body.code, 'mode': req.body.mode || 'simple' }; console.log( req.body.code); var options = { mode: 'json', pythonPath: '/usr/local/bin/python3.4', pythonOptions: ['-u'], // -u is unbuffered output scriptPath: __dirname }; var pyshell = new python('parser.py', options); pyshell.send(code); var response = ''; pyshell.on('message', function(message) { response = message; }); pyshell.end(function(err) { if (err) { res.json({ status: 'ERROR', message: 'Parsing failed.' }); } else { res.json(response); } }); });
app.post('/jsvee-transpiler-python', function(req, res) { var code = { 'code': req.body.code }; var options = { mode: 'json', pythonPath: config.pythonPath || '/usr/bin/python3', pythonOptions: ['-u'], // -u is unbuffered output scriptPath: __dirname }; var pyshell = new python('parser.py', options); pyshell.send(code); var response = ''; pyshell.on('message', function(message) { response = message; }); pyshell.end(function(err) { if (err) { res.json({ status: 'ERROR', message: 'Transpilation failed.' }); } else { res.json(response); } }); });
handler: (req, resp) => { var pythonScript = new PythonShell('gmusic.py'); pythonScript.on('message', track => { console.log(track); return resp(track).type('application/json').code(200); }); }
function onSchedule() { console.log("[Games Scraper] Pushing games list") var pyshell = new PythonShell('misc/time_scraper.py'); pyshell.on('message', function(d){ sendGames(JSON.parse(d)); console.log('[Games Scraper] Received games.') }); }
receive: (bot, message) => { const name = message.text; var pyshell = new PythonShell('my_script.py'); pyshell.on('message', function (message) { // received a message sent from the Python script (a simple "print" statement) return bot.say(message) }); return bot.setProp('name', name) .then(() => bot.say(`Great! I'll call you ${name} Is that OK? %[Yes](postback:yes) %[No](postback:no)`)) .then(() => 'finish'); }
function setSpeed(speed) { var args = { 'function': 'test', 'args': {'speed': speed, 'direction': 'left'} }; pyshell.send(JSON.stringify(args)); pyshell.on('message', function (message) { console.log(message); }); pyshell.end(function (err) { if (err) throw err; }); }
function(callback){ var sh = new PythonShell('getFBfriends.py'); sh.send(token); sh.on('message', function(msg){ result = JSON.parse(msg); console.log('msg arrived'); //console.log(result); callback(null, result); }); sh.end(function (err){ if(err) console.log(err); console.log('finished'); }); },
socket.on('initCamera',function (data) { var PythonShell = require('python-shell'); var pyshell = new PythonShell('initialize.py'); pyshell.send(data.number); pyshell.on('message', function (message) { console.log(message); }); for (var i = 0; i < data.number; i++) { pyshell.send(data.cams[i]); }; pyshell.on('message', function (message) { msgs.push(message); }); pyshell.end(function (err) { socket.emit('initDone'); if (err) throw err; console.log('finished'); }); });
var processCommands = function(command) { if(command === "say hello") console.log("Hello"); else if(command === "say hello via python") { shell = new pythonShell('../python_scripts/hello.py'); shell.send('Steve'); shell.on('message', function(message) { console.log(message); }); } else if(command.split(' ')[0] === "download") { query = command.replace('download ', ''); shell = new pythonShell('../python_scripts/get_magnet_link.py'); shell.send(query); shell.on('message', function(magnet_link) { torrentShell = new pythonShell('../python_scripts/start_torrent.py'); torrentShell.send(magnet_link); torrentShell.on('error', function(err) { console.log("Error! " + err); }); }); } }
app.get('/statesprediction?', function(request, response) { var query = request._parsedUrl.query; // console.log(query); var pyshell = new PythonShell('states.py', { mode: 'text' }); var count = 0; pyshell.send(query); pyshell.on('message', function (message) { console.log(message); response.writeHead(200, {'Content-Type': 'text/plain'}); response.end(String(message)+'\n'); }).on('close', function () { }).end(); });
socket.on('getLastKnown',function (data) { console.log("Person " + data.person_name ); var PythonShell = require('python-shell'); var pyshell = new PythonShell('getLastKnown.py'); pyshell.send(data.person_name); pyshell.on('message', function (message) { socket.emit('setLastKnown',{result:message}); }); pyshell.end(function (err) { if (err) throw err; console.log('finished'); }); });
app.post('/upload', multipart(), function(req, res){ //get filename // console.log(req); var filename = req.files.imageFile.originalFilename || path.basename(req.files.imageFile.path); var args = req.body; // console.log(args.x1+" "+args.y1); //copy file to a public directory var handleFileName = filename.substring(filename.lastIndexOf('/'), filename.lastIndexOf('.')) + '.png'; console.log(handleFileName); var targetPath = path.dirname(__filename) + '/public/uploadImages/' + handleFileName; console.log(targetPath); //copy file // fs.createReadStream(req.files.imageFile.path).pipe(fs.createWriteStream()); fs.createReadStream(req.files.imageFile.path).pipe(fs.createWriteStream(targetPath)); // console.log(imageFileName); var shell = new PythonShell('test.py', { mode: 'json'}); shell.send( { "path": './public/uploadImages/'+handleFileName, "args": [~~args.x1, ~~args.y1, ~~args.w, ~~args.h], "handleFileName": handleFileName } ); shell.on('message', function (message) { // 异步处理!!! // fs.createReadStream(req.files.files.path).pipe(fs.createWriteStream(targetPath)); // 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 shell.end(function (err) { if (err) throw err; // fs.createReadStream(req.files.imageFile.path).pipe(fs.createWriteStream(targetPath)); res.json({code: 200, msg: {url: 'http://' + req.headers.host + '/uploadImages/' + handleFileName}}); console.log('finished'); }); //return file url // res.json({code: 200, msg: {url: targetPath}}); });
socket.on('getTrack',function (data) { console.log("Person " + data.person_name ); var PythonShell = require('python-shell'); var pyshell = new PythonShell('getTrack.py'); pyshell.send(data.person_name); var msgs = [] pyshell.on('message', function (message) { msgs.push(message); }); pyshell.end(function (err) { socket.emit('setTrack',{result:msgs,person:data.person_name}); if (err) throw err; console.log('finished'); }); });
module.exports.getPyScriptResult = function(req, res, callback) { console.log("In getPyScriptResult"); var options = { mode: 'text', pythonPath: 'C:\\Eee\\Anaconda\\python', pythonOptions: ['-u'], scriptPath: 'C:\\Eee\\PythonLearn\\', args: ['value1'] }; // this is to run the script and results are what the script outputs /* PythonShell.run('hello.py', options, function (err, results) { if (err) throw err; // results is an array consisting of messages collected during execution console.log('results: %j', results); console.log('results: ', results.length); callback(err, results); });*/ var pyshell = new PythonShell('scr1.py', options); // sends a message to the Python script via stdin pyshell.send(4); pyshell.on('message', function (message) { // received a message sent from the Python script (a simple "print" statement) console.log(message); callback(null, message); }); // end the input stream and allow the process to exit pyshell.end(function (err) { if (err) { throw err; callback(err, null); } console.log('finished'); }); /*var client = new zerorpc.Client(); client.connect("tcp://127.0.0.1:4242"); client.invoke("hello", "World!", function(error, res, more) { console.log(res); res.write(res); });*/ };
getData: function () { const self = this; const fileName = 'getData.py'; console.log('Running ' + fileName); const fitbitPyShell = new PythonShell(fileName, {mode: 'json', scriptPath: 'modules/MMM-fitbit/python'}); fitbitPyShell.on('message', function (message) { if (message['type'] == 'data') { self.sendSocketNotification('DATA', message); } }); fitbitPyShell.end(function (err) { if (err) throw err; self.sendSocketNotification('UPDATE', 'Finished getting data'); console.log('Finished getting data'); }); },
function py_sum_func(number, progress_func) { var pyshell = new PythonShell('tasks.py', { scriptPath: __dirname, args: [number], pythonOptions: ['-u'] }); pyshell.on('message', function (message) { console.log(message); var parsed_message = JSON.parse(message); progress_func(parsed_message.name, parsed_message.value); }); pyshell.end(function (err) { if (err) throw err; console.log('finished'); }); }
.post(function(req, res) { var pyshell = new PythonShell(myPythonScriptPath); 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'); }); res.send("Analyzing..."); });
exports.postAlgo = (req, res) => { req.assert('sma-threshold', 'Percent value for SMA is not a number').isNumber(); req.assert('seed', 'Starting portfolio is not a valid amount').isNumber(); const errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/algo'); } const algoShell = new PythonShell('main_algo.py', { scriptPath: path.join(__dirname, '..', 'python-algorithm') }); let moneyMade = -1; algoShell.on('message', function(message) { console.log(message); if (message.substr(0, 16) === "Days: You made: ") { moneyMade = Number(message.substr(17)); } }); // How many shares? algoShell.send(req.body.seed); // Moving average threshold algoShell.send(req.body['sma-threshold']); // Moving average duration algoShell.send(req.body.method.substr(-2)); algoShell.end((err) => { console.log('Process terminated') if (err && err.exitCode !== 0) { res.send(err); } else { res.render('result', { profits: moneyMade }) res.end(); } }); };
router.post('/simulate', function(req, res, next) { var times = req.query.times; console.log("print times"); console.log(times); console.log("end print"); if (!times) { res.statusCode = 500; res.send("No Results Found"); console.log("finished"); } var options = { mode: 'json', pythonPath: '/usr/bin/python', pythonOptions: ['-u'], scriptPath: '../pythons/', args: [times] }; var pyshell = new PythonShell('simulate.py', options); // sends a message to the Python script via stdin console.log(req.body) pyshell.send(req.body); pyshell.on('message', function (message) { // received a message sent from the Python script (a simple "print" statement) console.log(message); res.send(message); }); // end the input stream and allow the process to exit pyshell.end(function (err) { if (err) { res.statusCode = 500; res.send("Error running simulation scripts"); } console.log('finished'); }); });
// Run selected script and gather all script inputs function RunScript(){ pythonArguments = {} for(i=0; i< document.getElementsByClassName('scriptInput').length; i++){ pythonArguments[document.getElementsByClassName('scriptInput')[i].id]=[] } for(i=0; i< document.getElementsByClassName('scriptInput').length; i++){ pythonArguments[document.getElementsByClassName('scriptInput')[i].id].push(document.getElementsByClassName('scriptInput')[i].value) } pythonArguments["action"]="measureDevice" console.log(pythonArguments) var options = { mode: 'text', pythonPath: 'python', args: [JSON.stringify(pythonArguments)] }; console.log(options["args"][0]) var shell = new PythonShell("/python-scripts/"+$('#scriptSelect').val()+'/script.py', options); console.log("Exicuting python script") shell.on('message', function (message) { console.log(message) $('#dataStream').html(message) }); }
router.post('/', function(req, res, next) { var id = req.body.id; console.log("Got the following id: ", id); var options = { args: id }; var pyshell = new PythonShell('./bin/scripts/stop.py', options, function (err, results) { if (err) throw err; // results is an array consisting of messages collected during execution console.log('results: %j', results); }); pyshell.send('hello'); pyshell.on('message', function (message) { // received a message sent from the Python script (a simple "print" statement) console.log(message); }); res.send("got it"); });
const PyShell = require('python-shell'); const pySettings = require('../config/pythonSettings.js'); const logger = require('../logger.js'); // create std in/out listeners for error handling const pyProcess = new PyShell('./server/chatterbot/chatterbot.py', pySettings); pyProcess.on('message', message => { logger.log('info', 'From Python chatterbot ', message); }); pyProcess.on('close', err => { if (err) { logger.log('error', 'python close error ', err); } else { logger.log('error', 'python closed'); } }); pyProcess.on('error', err => { if (err) { logger.log('error', 'python error ', err); } });
app.use(morgan('dev')); var apiRoutes = express.Router(); var enabled = true; fs.writeFile(dir, 'start', function (err) { if (err) throw err; }); var pyshell = new PythonShell('import_detector_v_0_2.py', function (err) { if (err) throw err; }); pyshell.on('message', function(msg) { console.log("Received from Python: "+msg); }); fs.readFile('/home/pi/AlarmBackend/apikey.txt', function(err, data) { if (err) throw err; // Fail if the file can't be read. apikey = data; fs.readFile('/home/pi/AlarmBackend/token.txt', function(err, newdata) { if (err) throw err; // Fail if the file can't be read. token = newdata; }); }); function sendTestMsg() { var message = new gcm.Message({ data: { key1: 'msg1'}
var PythonShell = require('python-shell'); var options = { mode: 'text', scriptPath: './', pythonOptions: ['-u'], args: ['asd'] }; var pyshell = new PythonShell('flipkart.py'); pyshell.on('message', function (message) { // received a message sent from the Python script (a simple "print" statement) console.log(message); }); pyshell.send('hello'); module.exports = function(scriptType, url, cb){ console.log(url); pyshell.send(url); PythonShell.run('flipkart.py', options, function (err, results) { if (err) throw err; // results is an array consisting of messages collected during execution console.log('results: %j', results); }); }
fs.exists(pdf_path, function (exist) { if (!exist) return callback('no file exists at the path you specified', null); //extract.process(pdf_path, options, cb); if (options == null) { return callback("must define options", null); } if (isNaN(options.from)) { return callback("must define options.from", null); } if (isNaN(options.to)) { return callback("must define options.to", null); } var delta = parseInt(options.to) - parseInt(options.from); argsarr.push("-p"); if (delta > 0) { var pages = []; pages.push(parseInt(options.from)); var to = parseInt(options.to); var from = parseInt(options.from); while (from < to) { var n = from + 1; pages.push(n); } argsarr.push(pages.join()); } else { argsarr.push(options.from); } if (delta < 0) { return callback("must follow the rule set from smaller than to", null); } else { delta = delta + 1; } argsarr.push("-m"); argsarr.push(delta); argsarr.push(pdf_path); // console.log("> Python Shell args", argsarr); var shell = new PythonShell('pdf2txt.py', { mode: 'text', scriptPath: env, args: argsarr }); shell.on('message', function (message) { // received a message sent from the Python script (a simple "print" statement) // console.log(message); output += bufferProcess.buffer(message, options) }); shell.end(function (err) { if (err) { callback(err.message, null); } else { //console.log(output); callback(null, output); } // console.log('finished'); // callback(null, output); }); //shell.send("start"); });