Added support for both version of python

This commit is contained in:
Maxim Stewart 2020-08-27 16:48:55 -05:00
parent e578231d76
commit 53adcfaf1e
1 changed files with 39 additions and 11 deletions

View File

@ -1,23 +1,51 @@
#!/usr/bin/env python
#!/usr/sbin/python
import sys
import json
import struct
import subprocess
import os, sys, json, struct, threading, subprocess
# Python 2.x version (if sys.stdin.buffer is not defined)
DLPATH = os.path.expanduser("~") + "/Downloads"
MAJOR_VERSION = sys.version_info[0]
def threaded(fn):
def wrapper(*args, **kwargs):
threading.Thread(target=fn, args=args, kwargs=kwargs).start()
return wrapper
# Python 2.x and 3.x read version
# Read a message from stdin and decode it.
def getMessage():
rawLength = sys.stdin.read(4)
message = None
rawLength = None
if MAJOR_VERSION == 2: # py2
rawLength = sys.stdin.read(4)
else: # py3
rawLength = sys.stdin.buffer.read(4)
if len(rawLength) == 0:
sys.exit(0)
messageLength = struct.unpack('@I', rawLength)[0]
message = sys.stdin.read(messageLength)
if MAJOR_VERSION == 2: # py2
message = sys.stdin.read(messageLength)
else: # py3
message = sys.stdin.buffer.read(messageLength).decode("utf-8")
return json.loads(message)
@threaded
def downloadVideo(command):
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
while True:
receivedMessage = getMessage()
if receivedMessage:
command = "cd ~/Downloads && youtube-dl " + receivedMessage;
subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
outputFile = DLPATH + "/%\(title\)s.%\(ext\)s "
command = "youtube-dl --no-playlist -o " + outputFile + receivedMessage;
downloadVideo(command)