How to connect node.js app with python script?

别来无恙 提交于 2019-12-08 11:48:10

问题


I've node app in Meteor.js and short python script using Pafy.

import pafy

url = "https://www.youtube.com/watch?v=AVQpGI6Tq0o"
video = pafy.new(url)

allstreams = video.allstreams
for s in allstreams:
	print(s.mediatype, s.extension, s.quality, s.get_filesize(), s.url)

What's the most effective way of connecting them so python script get url from node.js app and return back output to node.js? Would it be better to code it all in Python instead of Meteor.js?


回答1:


Well, there are plenty of ways to do this, it depends on your requirements. Some options could be:

  1. Just use stdin/stdout and a child process. In this case, you just need to get your Python script to read the URL from stdin, and output the result to stdout, then execute the script from Node, maybe using child_process.spawn. This is I think the simplest way.
  2. Run the Python part as a server, let's say HTTP, though it could be anything as long as you can send a request and get a response. When you need the data from Node, you just send an HTTP request to your Python server which will return you the data you need in the response.

In both cases, you should return the data in a format that can be parsed easily, otherwise you are going to have to write extra (and useless) logic just to get the data back. Using JSON for such things is quite common and very easy. For example, to have your program reading stdin and writing JSON to stdout, you could change your script in the following way (input() is for Python 3, use raw_input() if you are using Python 2)

import pafy
import json

url = input()
video = pafy.new(url)

data = []

allstreams = video.allstreams
for s in allstreams:
    data.append({
        'mediatype': s.mediatype,
        'extension': s.extension,
        'quality': s.quality,
        'filesize': s.get_filesize(),
        'url': s.url
    })

result = json.dumps(data)
print(result)

Here is a very short example in NodeJS using the Python script

var spawn = require('child_process').spawn;

var child = spawn('python', ['my_script.py']);

child.stdout.on('data', function (data) {
    var parsedData = JSON.parse(data.toString());
    console.log(parsedData);
});

child.on('close', function (code) {
    if (code !== 0) {
        console.log('an error has occurred');
    }
});

child.stdin.write('https://www.youtube.com/watch?v=AVQpGI6Tq0o');
child.stdin.end();


来源:https://stackoverflow.com/questions/32264359/how-to-connect-node-js-app-with-python-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!