#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
# Copyright (c) 2010 Andrey Vlasovskikh | |
# | |
# Permission is hereby granted, free of charge, to any person obtaining | |
# a copy of this software and associated documentation files (the | |
# "Software"), to deal in the Software without restriction, including | |
# without limitation the rights to use, copy, modify, merge, publish, | |
# distribute, sublicense, and/or sell copies of the Software, and to | |
# permit persons to whom the Software is furnished to do so, subject to | |
# the following conditions: | |
# | |
# The above copyright notice and this permission notice shall be included | |
# in all copies or substantial portions of the Software. | |
# | |
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | |
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | |
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. | |
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY | |
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, | |
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE | |
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | |
from __future__ import unicode_literals, print_function | |
import sys, os, re | |
from urllib import urlopen, unquote | |
ENCODING='utf-8' | |
def fatal(msg): | |
print('error: {0}'.format(msg), file=sys.stderr) | |
sys.exit(1) | |
def video_url(page): | |
'str -> str or None' | |
m = re.search(r'videoUrl\\x3d(.*?)\\x26', page) | |
if not m: | |
return None | |
return unquote(m.group(1)) | |
def print_video_url(): | |
if len(sys.argv) != 2: | |
fatal('usage: {0} URL'.format(sys.argv[0])) | |
data = urlopen(sys.argv[1]).read().decode(ENCODING) | |
url = video_url(data) | |
if not url: | |
fatal('video url not found') | |
print(video_url(data)) | |
def launch_mplayer(): | |
if len(sys.argv) != 2: | |
fatal('usage: {0} URL'.format(sys.argv[0])) | |
data = urlopen(sys.argv[1]).read().decode(ENCODING) | |
url = video_url(data) | |
if not url: | |
fatal('video url not found') | |
os.execvp('mplayer', ['mplayer', url]) | |
if __name__ == '__main__': | |
#launch_mplayer() | |
print_video_url() | |
Андрей Сергеевич у меня большой вопрос состоящий из нескольких частей.
В PEP 8 (раздел Programming Recommendations) рекомендуют делать проверку на None при помощи is. Так как re.search возвращает None если ничего не нашёл, то проверку правильнее будет писать как "if m is not None: return m". Стоит ли придерживаться PEP 8 строго?
Этот вопрос у меня возникает потому что в Ruby-стиле три строчки (38:40) эквивалентно записали бы как одну строчку "return m and unquote(m.group(1))". При такой записи всё работает так как надо и сама запись короткая, но не соблюдается PEP 8. В тех исходниках которые я видел, and и or всегда встречаются только в выражении для if. То есть однострочная запись может быть не очевидна для других Python-программистов.
@TheBits для regexp m
, если он есть, всегда верно bool(m) is True
, так что это безопасно. приём соответствует pep8 (см.). более краткая форма: return unquote(m.group(1)) if m else None
Спасибо.
This script was inspired by vp. Unfortunately, I have no time to do this in vp because of rc(1) and awk(1).