FindPython.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. */
  15. 'use strict';
  16. var nThen = require('nthen');
  17. var Spawn = require('child_process').spawn;
  18. var Fs = require('fs');
  19. // We're going to prefer python2.7 or python2 because we know they work
  20. // and our test code is very strict.
  21. // If neither of those work, we'll try python3.7 or python3 which we
  22. // de-prioritize because the testing script accepts ANY python3 version
  23. // (as of this writing, we don't know what python3 versions actually work)
  24. // whereas we know that python2.7 is the only working python2 version.
  25. var PYTHONS = ["python3.7", "python3", "python2.7", "python2", "python"];
  26. var SCRIPT = [
  27. 'import sys',
  28. 'print(sys.version_info)',
  29. // we know <= 2.6 is no good
  30. 'if sys.version_info[0] == 2 and sys.version_info[1] >= 7: exit(0)',
  31. // Lets hope that all python3 versions are ok...
  32. 'if sys.version_info[0] == 3: exit(0)',
  33. ].join('\n');
  34. var find = module.exports.find = function (tempFile, callback) {
  35. var nt = nThen(function (waitFor) {
  36. Fs.writeFile(tempFile, SCRIPT, waitFor(function (err) { if (err) { throw err; } }));
  37. }).nThen;
  38. PYTHONS.forEach(function (python) {
  39. nt = nt(function (waitFor) {
  40. console.log("testing python " + python);
  41. var py = Spawn(python, [tempFile]);
  42. var cont = waitFor();
  43. py.stdout.on('data', function (dat) { console.log(dat.toString('utf8')); });
  44. py.on('close', function(ret) {
  45. if (ret === 0) {
  46. callback(undefined, python);
  47. waitFor.abort();
  48. } else {
  49. cont();
  50. }
  51. });
  52. py.on('error', function (err) {
  53. if (err !== 'ENOENT') { console.log('error starting python ' + err); }
  54. });
  55. // Don't worry about errors, try the next.
  56. }).nThen;
  57. });
  58. nt(function (waitFor) {
  59. callback(new Error("no sutible python2 or python3 executable found ( < 2.7 unsupported)"));
  60. });
  61. };