Читалка ithappens

в 23:02, , рубрики: fun, ithappens, linux, python, метки: , ,

Вот-с, собственно вечерком накодил читалку ithappens на питоне. Умеет сохранять цитаты в формат fortune (правда я не проверял :D) и выводить в файл, либо на терминал.

#!/usr/bin/env python
#  -*- coding: utf-8 -*-
#Public domain

'''Ithappens - show random quote'''

#только для python2
from __future__ import unicode_literals
from __future__ import print_function

from textwrap import fill
import os,sys
from lxml import etree

if sys.version_info[0] == 2: #подменяю open
    from codecs import open


def getTerminalSize(): #http://stackoverflow.com/questions/566746/how-to-get-console-window-width-in-python
    '''Get tuple of terminal size'''
    env = os.environ
    def ioctl_GWINSZ(fd):
        try:
            import fcntl, termios, struct
            cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ,'1234'))
        except:
            return None
        return cr
    cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2)
    if not cr:
        try:
            fd = os.open(os.ctermid(), os.O_RDONLY)
            cr = ioctl_GWINSZ(fd)
            os.close(fd)
        except:
            pass
    if not cr:
        try:
            cr = (env['LINES'], env['COLUMNS'])
        except:
            cr = (25, 80)
    return int(cr[1]), int(cr[0])


def print_quote(url,file=sys.stdout, fortune=False):
    '''print quote to given file'''
    path='/body/table/tr/td[@class="main"]/table[@class="content"]/tr/td[@class="text"]/div[@class="text"]/p[@class="text"]'
    parser = etree.HTMLParser()

    tree = etree.parse(url,parser)
    title = tree.find('/head/title').text.split('—')[1].strip()
    w,h = getTerminalSize()
    charno = (w-len(title)+2)/2
    print ('{chars} {title} {chars}'.format(title=title, chars='#'*charno))
    elem=tree.find(path)
    for i in elem.iter():
        if i.text is not None:
            text, end = i.text, i.tail if i.tail is not None else ''
        elif i.tail is not None:
            text,end = i.tail, ''
        else:
            continue
        print (fill(text + end, w),file=file)

    if fortune:
        print ('%',file=file)


if __name__ == '__main__':
    usage = """usage: {file} <args> <quote ID>
    -h: Show help message
    -f: write a fortune file format
    -o <file> write to file (default is stdout)

If no IDs passed, then print random quote""".format(file=os.path.basename(sys.argv[0]))
    fortune = False
    file = False
    quotes = []
    for arg in sys.argv[1:]:
        if arg == '-f': #fortune
            fortune = True
        elif arg == '-o': #file
            file = True
        elif arg in ('--usage','--help','-h'):
            print (usage)
            exit()
        elif file is True:
            file = arg
        else:
            try:
                int(arg)
            except ValueError:
                print ('Failed to parse Quote ID argument - seems like it is not int',file=sys.stderr)
                exit()
            else:
                quotes.append(arg)

    if not file:
        out=sys.stdout
    elif file is True:
        print('Output to file requested in -o but no file specified')
        exit()
    else:
        out = open(file, 'at',encoding='utf-8')

    if not quotes:
        print_quote('http://ithappens.ru/random/',file=out, fortune=fortune)

    for q in quotes:
        print_quote('http://ithappens.ru/story/{id}'.format(id=q),file=out, fortune=fortune)

    out.close()


использование

chmod +x ithappens.py
./ithappens.py

Автор: pashazz

* - обязательные к заполнению поля


https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js