0

I must call a python script from Node.js code. I know that I can use the function spawn to create a new child process and then it calls the script python.

This is the problem: I have a variable called date (used in Node.js) that I must use how command line argument in my script python.

This is my code in Node.js:

...
function searchOnGoogle(query, date, options, out, cb) {
    // startdate = 2451545 // Julian date for 2000/01/01

    var python = require('child_process').spawn('python', ["getTweetStartDate.py", date]);
    var startdate = "";
    python.stdout.on('data', function(data){ startdate += data });
    // Tweet start date set 1 month before the tweet date
    ...

And this is "getTweetStartDate.py" :

import math
import conversionDate
import sys

def oneMonthBeforeJulianDate(dataStartTweet):
    dataStartTweetJulian = conversionDate.jd2date(math.modf(float(dataStartTweet))[1])
    year = dataStartTweetJulian[0]
    month = dataStartTweetJulian[1]
    day = dataStartTweetJulian[2]

    if month == 1:
        month = 12
        year -= 1
    else:
        month -= 1

    dataStartTweetFinal = conversionDate.date2jd(year, month, day)

    filename = "/home/IPA/IPA_ws/gum_en/src/DEBUG_"+str(randint(0, 10000000000000000000))+".txt"
    new_file = open(filename, 'w')
    new_file.write(str(dataStartTweetFinal))
    new_file.close()

    return dataStartTweetFinal

dataGiuliana = sys.argv[1]
print oneMonthBeforeJulianDate(dataGiuliana)
sys.stdout.flush()

The problem is that the concatenation between startdate and data doesn't work. In particular if I use console.log() inside python.stdout.on('data', function(data){ ... }); I see the correct value; else if I use console.log() outside python.stdout.on('data', function(data){ ... }); I see the empty string. Why?

Can someone help me?

Thanks!!

glorfindel
  • 199
  • 3
  • 11
  • What does "doesn't work" mean, exactly? Did you try listening to `python.stderr` to see if there is an error? Does the python script work as expected when you make a similar call from a shell? – Aaron Dufour Oct 08 '15 at 18:35
  • The python script works perfectly. The problem is that I don't see anything, maybe because I have the empty string how returned value. Is it corrected how do I use the variable date when I call the python script? – glorfindel Oct 08 '15 at 18:37
  • Maybe show more code? It isn't clear how/when you try to use `startdate`. – Aaron Dufour Oct 08 '15 at 19:09
  • I modify the code and now there is the complete code. – glorfindel Oct 10 '15 at 17:14
  • Update the problem!!! – glorfindel Oct 10 '15 at 20:03
  • Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Aaron Dufour Oct 11 '15 at 04:39

0 Answers0