I want to put in my system info about machine available GPU and status for real time monitoring. I'm outputting as XML the GPU info using
$ nvidia-smi -x -q
This command will print output current GPU status (like usage, temperature, etc.) as well formatted XML (with defined DTD). My XML output is here.
There is no option to output directly from nvidia-smi to json, so at this time the only option I see is to convert the XML to JSON from Node.js.
The problem is that I need it as JSON, so I'm trying to convert to JSON within my Node application. I have used in turn several npm available modules like xml2json, node-xml2js, etc. but having different errros with each of then (null, undefined, etc). Using a simple DOMParser in the browser (window.DOMParser) will work instead. It seems to be an error with this XML since when I have one GPU output like here the JSON is converted fine as showed in this gist.
I'm using node spawn to call the nvdia-smi command and then to parse the output like:
(function() {
var XMLParser = require('./xml2json');
function gpuInfo() {
var _data='';
var curl = require('child_process').spawn('nvidia-smi', ['-x','-q']);
curl.stdout.on('data', function(data) {
_data+= new Buffer(data,'utf-8').toString();
});
curl.stdout.on('end', function(data) {
var x2js = new XMLParser();
var json = x2js.xml_str2json( _data );
console.log(JSON.stringify( json,null,2));
});
curl.on('exit', function(code) {
if (code != 0) {
console.log('Failed: ' + code);
}
});
}
module.exports = {
gpuInfo:gpuInfo
}
In this case I'm using a modified version of xml2json browser client module combined with the xmldom module, but it seems not be a stable solution, so my parsing is done here like:
this.parseXmlString = function(xmlDocStr) {
if (xmlDocStr === undefined) {
return null;
}
var xmlDoc;
var DOMParser = require('xmldom').DOMParser;
var parsererrorNS = null;
try {
xmlDoc = new DOMParser().parseFromString( xmlDocStr, "text/xml" );
if( parsererrorNS!= null && xmlDoc.getElementsByTagNameNS(parsererrorNS, "parsererror").length > 0) {
xmlDoc = null;
}
}
catch(err) {
xmlDoc = null;
}
return xmlDoc;
};
Are out of here
- Another way to obtain these info as json?
- A more efficient solution via some robust XML / JSON parser module?
via loretoparisi
No comments:
Post a Comment