Modified code to work on android, removed sys.exit() code (it force exit android application as well), write result as json string into file, added new entry point: main.py.

This commit is contained in:
Redwid 2018-05-21 08:45:25 +01:00
parent 1e4fe5a7cc
commit 653c98af7e
8 changed files with 69 additions and 42 deletions

View File

@ -50,10 +50,7 @@ def report_warning(message):
Print the message to stderr, it will be prefixed with 'WARNING:' Print the message to stderr, it will be prefixed with 'WARNING:'
If stderr is a tty file the 'WARNING:' will be colored If stderr is a tty file the 'WARNING:' will be colored
''' '''
if sys.stderr.isatty() and compat_os_name != 'nt': _msg_header = 'WARNING:'
_msg_header = '\033[0;33mWARNING:\033[0m'
else:
_msg_header = 'WARNING:'
output = '%s %s\n' % (_msg_header, message) output = '%s %s\n' % (_msg_header, message)
if 'b' in getattr(sys.stderr, 'mode', '') or sys.version_info[0] < 3: if 'b' in getattr(sys.stderr, 'mode', '') or sys.version_info[0] < 3:
output = output.encode(preferredencoding()) output = output.encode(preferredencoding())

View File

@ -600,10 +600,7 @@ class YoutubeDL(object):
else: else:
if self.params.get('no_warnings'): if self.params.get('no_warnings'):
return return
if not self.params.get('no_color') and self._err_file.isatty() and compat_os_name != 'nt': _msg_header = 'WARNING:'
_msg_header = '\033[0;33mWARNING:\033[0m'
else:
_msg_header = 'WARNING:'
warning_message = '%s %s' % (_msg_header, message) warning_message = '%s %s' % (_msg_header, message)
self.to_stderr(warning_message) self.to_stderr(warning_message)
@ -612,10 +609,7 @@ class YoutubeDL(object):
Do the same as trouble, but prefixes the message with 'ERROR:', colored Do the same as trouble, but prefixes the message with 'ERROR:', colored
in red if stderr is a tty file. in red if stderr is a tty file.
''' '''
if not self.params.get('no_color') and self._err_file.isatty() and compat_os_name != 'nt': _msg_header = 'ERROR:'
_msg_header = '\033[0;31mERROR:\033[0m'
else:
_msg_header = 'ERROR:'
error_message = '%s %s' % (_msg_header, message) error_message = '%s %s' % (_msg_header, message)
self.trouble(error_message, tb) self.trouble(error_message, tb)
@ -1735,7 +1729,11 @@ class YoutubeDL(object):
if self.params.get('forceformat', False): if self.params.get('forceformat', False):
self.to_stdout(info_dict['format']) self.to_stdout(info_dict['format'])
if self.params.get('forcejson', False): if self.params.get('forcejson', False):
self.to_stdout(json.dumps(info_dict)) #self.to_stdout(json.dumps(info_dict))
self.to_stdout('Writing json data to youtube_dl.json')
with open('youtube_dl.json', 'w') as f:
f.write(json.dumps(info_dict).encode('utf-8'))
f.close()
# Do nothing else if in simulate mode # Do nothing else if in simulate mode
if self.params.get('simulate', False): if self.params.get('simulate', False):

View File

@ -10,6 +10,7 @@ import io
import os import os
import random import random
import sys import sys
import json
from .options import ( from .options import (
@ -464,18 +465,30 @@ def _real_main(argv=None):
ydl.to_screen('--max-download limit reached, aborting.') ydl.to_screen('--max-download limit reached, aborting.')
retcode = 101 retcode = 101
sys.exit(retcode) #sys.exit(retcode)
return
def reportDone(result):
data = {}
data['result'] = result
f = open('youtube_dl.done', 'w')
f.write(json.dumps(data))
f.close()
def main(argv=None): def main(argv=None):
try: try:
_real_main(argv) _real_main(argv)
reportDone('OK')
except DownloadError: except DownloadError:
sys.exit(1) reportDone('DownloadError')
#sys.exit(1)
except SameFileError: except SameFileError:
sys.exit('ERROR: fixed output name but more than one file to download') reportDone('ERROR: fixed output name but more than one file to download')
#sys.exit('ERROR: fixed output name but more than one file to download')
except KeyboardInterrupt: except KeyboardInterrupt:
sys.exit('\nERROR: Interrupted by user') reportDone('ERROR: Interrupted by user')
#sys.exit('\nERROR: Interrupted by user')
__all__ = ['main', 'YoutubeDL', 'gen_extractors', 'list_extractors'] __all__ = ['main', 'YoutubeDL', 'gen_extractors', 'list_extractors']

View File

@ -4,7 +4,7 @@ from __future__ import unicode_literals
import base64 import base64
import binascii import binascii
import collections import collections
import ctypes #import ctypes
import email import email
import getpass import getpass
import io import io

View File

@ -240,7 +240,7 @@ class FileDownloader(object):
self._report_progress_prev_line_length = len(fullmsg) self._report_progress_prev_line_length = len(fullmsg)
clear_line = '\r' clear_line = '\r'
else: else:
clear_line = ('\r\x1b[K' if sys.stderr.isatty() else '\r') clear_line = ('\r\x1b[K\r')
self.to_screen(clear_line + fullmsg, skip_eol=not is_last_line) self.to_screen(clear_line + fullmsg, skip_eol=not is_last_line)
self.to_console_title('youtube-dl ' + msg) self.to_console_title('youtube-dl ' + msg)

View File

@ -866,10 +866,7 @@ class InfoExtractor(object):
if mobj: if mobj:
break break
if not self._downloader.params.get('no_color') and compat_os_name != 'nt' and sys.stderr.isatty(): _name = name
_name = '\033[0;34m%s\033[0m' % name
else:
_name = name
if mobj: if mobj:
if group is None: if group is None:

20
youtube_dl/main.py Normal file
View File

@ -0,0 +1,20 @@
#!/usr/bin/env python
from __future__ import unicode_literals
# Execute with
# $ python youtube_dl/__main__.py (2.6+)
# $ python -m youtube_dl (2.7+)
import sys
if __package__ is None and not hasattr(sys, 'frozen'):
# direct call of __main__.py
import os.path
path = os.path.realpath(os.path.abspath(__file__))
sys.path.insert(0, os.path.dirname(os.path.dirname(path)))
import youtube_dl
if __name__ == '__main__':
youtube_dl.main()

View File

@ -8,7 +8,7 @@ import binascii
import calendar import calendar
import codecs import codecs
import contextlib import contextlib
import ctypes #import ctypes
import datetime import datetime
import email.utils import email.utils
import email.header import email.header
@ -1183,6 +1183,8 @@ def unified_strdate(date_str, day_first=True):
upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d') upload_date = datetime.datetime.strptime(date_str, expression).strftime('%Y%m%d')
except ValueError: except ValueError:
pass pass
except TypeError:
pass
if upload_date is None: if upload_date is None:
timetuple = email.utils.parsedate_tz(date_str) timetuple = email.utils.parsedate_tz(date_str)
if timetuple: if timetuple:
@ -1753,23 +1755,23 @@ def setproctitle(title):
if sys.platform.startswith('java'): if sys.platform.startswith('java'):
return return
try: #try:
libc = ctypes.cdll.LoadLibrary('libc.so.6') # libc = ctypes.cdll.LoadLibrary('libc.so.6')
except OSError: #except OSError:
return # return
except TypeError: #except TypeError:
# LoadLibrary in Windows Python 2.7.13 only expects # # LoadLibrary in Windows Python 2.7.13 only expects
# a bytestring, but since unicode_literals turns # # a bytestring, but since unicode_literals turns
# every string into a unicode string, it fails. # # every string into a unicode string, it fails.
return # return
title_bytes = title.encode('utf-8') #title_bytes = title.encode('utf-8')
buf = ctypes.create_string_buffer(len(title_bytes)) #buf = ctypes.create_string_buffer(len(title_bytes))
buf.value = title_bytes #buf.value = title_bytes
try: #try:
libc.prctl(15, buf, 0, 0, 0) # libc.prctl(15, buf, 0, 0, 0)
except AttributeError: #except AttributeError:
return # Strange libc, just skip this # return # Strange libc, just skip this
return
def remove_start(s, start): def remove_start(s, start):
return s[len(start):] if s is not None and s.startswith(start) else s return s[len(start):] if s is not None and s.startswith(start) else s