Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
123
rated 0 times [  127] [ 4]  / answers: 1 / hits: 6476  / 9 Years ago, fri, august 28, 2015, 12:00:00

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?


More From » python

 Answers
4

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();

[#34588] Thursday, August 27, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cody

Total Points: 679
Total Questions: 111
Total Answers: 111

Location: Czech Republic
Member since Thu, Aug 11, 2022
2 Years ago
;