Skip to content

Instantly share code, notes, and snippets.

@vlasovskikh
Created September 1, 2010 21:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vlasovskikh/561401 to your computer and use it in GitHub Desktop.
Save vlasovskikh/561401 to your computer and use it in GitHub Desktop.
Tool for watching Google Video hosted videos with mplayer
#!/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()
@TheBits
Copy link

TheBits commented Feb 14, 2011

Андрей Сергеевич у меня большой вопрос состоящий из нескольких частей.
В 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-программистов.

@vlasovskikh
Copy link
Author

@TheBits для regexp m, если он есть, всегда верно bool(m) is True, так что это безопасно. приём соответствует pep8 (см.). более краткая форма: return unquote(m.group(1)) if m else None

@TheBits
Copy link

TheBits commented Feb 15, 2011

Спасибо.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment