Archive
[nodejs] raw_input in Node.js
Problem
How to read in Node.js from the console? For instance, how to rewrite the following Python script?
n1 = int(raw_input("1st number: "))
n2 = int(raw_input("2nd number: "))
print "The sum is:", n1+n2
Solution
#!/usr/bin/env node
"use strict";
var readline = require('readline');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function processNums(n1, n2) {
n1 = Number(n1);
n2 = Number(n2);
console.log("Their sum: " + (n1 + n2));
}
function start() {
rl.question('1st number: ', function (x) {
rl.question('2nd number: ', function (y) {
rl.close();
processNums(x, y);
});
});
}
function main() {
start();
}
main();
Tip from here.
make a script run under Python 2.x and 3.x too
Problem
I installed Manjaro Linux on one of my laptops, just to try something new. I’ve been using it for a week and I like it so far :) On my older laptop it runs smoother than Ubuntu.
Anyway, Manjaro switched to Python 3.x, that’s the default, thus “python” points to Python 3. I use Ubuntu on my other machines where Python 2 is the default. I would like to modify my scripts (at least some of them) to run on both systems.
For instance, in Python 2.x you call “raw_input”, while this function was renamed to “input” in Python 3.x.
Solution
Well, since January 2014 I start all my new scripts with this line:
from __future__ import (absolute_import, division,
print_function, unicode_literals)
It ensures a nice transition from Python 2 to Python 3.
To solve the “raw_input” problem, you can add these lines:
import sys
if sys.version_info >= (3, 0):
raw_input = input
You can continue using “raw_input”, but if it’s executed with Python 3.x, “raw_input” will point to the “input” function.
Of course, the ideal solution would be to switch to Python 3, but I’m not ready for that yet :)
Update (20141228)
At the moment I’m updating my jabbapylib library. The new version will be released soon :) Since it’s a library, it should work with both Python 2 and Python 3. When I write a new script, I tend to use Python 3 these days, but a library is different. A library should support both Python 2.x and 3.x. The most widely used solution is the Six compatibility library, which is a joy to use. To solve the raw_input issue for instance, just import the line
from six.moves import input
Then — just like in Python 3 — call the function “input()” to read from the standard input. For more info. read the official docs.
