Example #1
0
    def opts():
        optz.help( '''%prog [опции] папка ..
обхожда папките и зарежда данни от файлове именовани "opis", и изпълнява действия с тези данни''')
        gg = optz.grouparg( 'данни')
        optz.str( 'prevodi',        help= 'файл-речник с преводи файл=заглавие или заглавие=файл (lat=cyr)', **gg)
        optz.str( 'prevodi_meta',   help= 'файл-речник с преводи на понятия (lat=cyr) - хора, организации, ..', **gg)
        optz.str( 'filename_enc',   help= 'кодировка на имената на файловете [или това от терминала]', **gg)
        gg = optz.grouparg( 'описи')
        optz.bool( 'zapis_opisi',   help= '(пре)записва описите', **gg)
        optz.append( 'etiket', '-e',help= 'добавя етикета към _всички описи'+helplist, **gg)
        optz.bool( 'sort_prevodi',  help= 'пренарежда преводите по азбучен ред', **gg)
        optz.bool( 'popravi_opisi', help= 'имената в речника с преводи имат превес над местните в описите', **gg)

        optz.bool( 'podravni_po_grupi', help= 'подравнява в описа всяка група за себе си; иначе подравнява всички заедно', **gg)
        optz.bool( 'mnogoredovi_etiketi',   help= 'многоредовите се записват като 1 ключ:: с много редове, без пренасяне (иначе много ключ:реда)', **gg)

        optz.int(  'shirina_tekstove',  default=80, help= 'ширина на пренасяне на текстове; подразбиране- %default', **gg)
        optz.bool( 'yaml')  #ignore
        optz.bool( 'noyaml')

        #optz.bool( 'vinagi',  '-f',help= 'записва независимо дали има разлики', **gg)

        gg = optz.grouparg( 'обхождане')
        optz.append( 'opisi',           help= 'шаблон за името на описите ['+' '.join( OPISI)+']'+helplist, **gg)
        optz.bool( 'simvolni', '-L',    help= 'обхожда и символни връзки', **gg)
        optz.append( 'bez',             help= 'пропуска (папки) по дадения шаблон'+helplist,  **gg)
        optz.append( 'samo',            help= 'включва само (папки) по дадения шаблон'+helplist,  **gg)
        optz.append( 'papka_s_opisi',   help= 'счита всички файлове вътре за описи (и се прилагат горните шаблони)'+helplist, **gg)

        gg = optz.grouparg( 'действия с папки')
        optz.bool( 'preimenovai_papki', help= 'преименова+превежда папките на място', **gg)
        optz.str(  'prehvyrli_papki',   help= 'прехвърля+превежда папки+съдържание към тук/', **gg)
        optz.bool( 'prehvyrli_simvolno', help= 'прехвърля като символни връзки (иначе са твърди)', **gg)

        optz.bool( 'davai',         help= 'извършва промените', **gg)

        #разни
        optz.bool( 'stderr',        help= 'грешки и съобщения към stderr')
        optz.count( 'podrobno', '-v', help= 'показва подробности')
Example #2
0
                    [ kv for kv in s if kv[0]=='title' ] +
                    [ kv for kv in s if kv[0]!='title' ]
                ]
            if 'itemi' in i:
                q = me._clone( params, is_html=is_html, is_dbg=is_dbg)
                q.update( item= i.key, grouped= 'kids', )
                q = '&'.join( k+'='+str(v) for k,v in sorted( q.items()))
                t += [ '<a href="query_itemalert?' +q+ '"> inside </a>' ]
            t = '\n<p> '.join( t)
            return t


    from svd_util import optz, eutf
    eutf.fix_std_encoding()
    optz.int( 'port', default= 5000,        help='[%default]' )
    optz.str( 'host', default= 'localhost', help='[%default]' )
    optz.bool( 'load', help= 'load saved data' )
    optz.bool( 'gen',  help= 'make fake data' )
    optz.bool( 'noautogen',  help= 'dont make fake data if nothing loaded' )
    optz.bool( 'save', help= 'save data at end' )
    optz.bool( 'notest', help= 'dont run test before serving' )
    optz,args = optz.get()

    if optz.argus: argus()

    if optz.load: simu.data_load()
    if optz.gen or simu.data_is_empty() and not optz.noautogen: simu.fakedata()
    if not optz.notest: simu.test()

    websimu1.setup()
    try:
Example #3
0
        if cnomer: bf = str(cnomer)+'.'+bf
        wwime = splitext( join( orgdir, bf))[0]+'.wav'
        if nime.endswith('.flac'):
            cmds = [ 'flac', '-d', '-o', wwime, nime ]
            print( cmds)
            subprocess.call( cmds)
        elif nime.endswith('.mp3'):
            cmds = 'lame --nohist -h -v -V 0 -S --decode'.split() + [ nime, wwime ]
            print( cmds)
            subprocess.call( cmds)

#   if not exists( wime):
#       open( wime, 'w').close()


if __name__ == '__main__':
    optz.bool( 'decode', '-d')
    optz.bool( 'nothing', '-n')
    optz.bool( 'link',    help= 'само връзка към новото име')
    optz.bool( 'nomove',  help= 'не мести към .../0/, а направи връзка')
    optz.str( 'where',  default= '.', help= '[%default]')    #'/zapisi/novo/'

    optz,argz = optz.get()
    command = optz.link and os.link

    for fime in argz:
        print( fime)
        go( fime, optz.where, nedei= optz.nothing, command= command, move= not optz.nomove, decode= optz.decode)

# vim:ts=4:sw=4:expandtab
Example #4
0
    else:
        iztrij = None
        if ospath.islink(d):
            iztrij = d
            d = ospath.realpath( d)
        rename( d, cel)
        if iztrij: remove( iztrij)
    #cd ~/azcom/zdetski/`basename $gotovo`
    #m lnfrom ; m sym2; m
    #m zl
    # . e3*
    print( '')

if __name__ == '__main__':
    optz.bool( 'zapis')
    optz.str( 'gotovo')
    optz.bool( 'obnovi')

    optz.bool( 'opis')
    optz.bool( 'premesti')
    optz.bool( 'izvadki')
    optz.bool( 'parcheta')
    optz.bool( 'log')
    optz.str( 'rubrika')
    optz,args = optz.get()
    obvivka.naistina = optz.zapis
    obvivka.log = optz.log #False

    if optz.izvadki or ospath.isfile( args[0] ):
        izvadki2zapis2dir2srez2opis( args[0])
    else:
Example #5
0
#   optz.bool( 'preferdaily',   help= 'при наличие на дневна и всичко, без филтри' )

    choices= list( bnr_kanali.keys())
    optz.append( 'channel',   choices= choices,
                    help= 'канал за запис (разписание+източник) - от ('+ ' '.join(choices) + '); може няколко пъти; ['+kanal_default.name+']',
                    )
    optz.append( 'weekly',  help= 'входно седмично разписание: URL или файл; може няколко пъти' )
    optz.append( 'daily',   help= 'входно дневно разписание: URL или файл; може няколко пъти' )
    optz.append( 'stream',  help= 'източник за запис; може няколко пъти - към всяко разписание' )
    optz.append( 'filter',  help= 'допълнителен филтър съдържа-се-в-заглавието; може няколко' )
    optz.text(   'save_plan',  help= 'запис на резултатния списък в ТОВА.datetime' )
    optz.text(   'save_input', help= 'запис на входящите данни в ТОВА.wd.kanal.datetime' )
    optz.bool(   'save_text',  help= 'запис на текста отделно ако не се събира в името в име.text' )
    optz.bool(   'yesterday',  help= 'днеска е вчера' )
    optz.bool(   'today_daily',     help= 'извлича датата от името на файла с дневното разписание' )
    optz.str(    'channel_daily',   help= 'за кой канал е файла с дневното разписание' )
    optz.str(    'nalichni_opisi',  help= 'файлов-шаблон за достъп до наличните описи' )
    o,args = optz.get()

    if o.oenc:
        from svd_util.eutf import fix_std_encoding, filew
        fix_std_encoding( ENC= o.oenc)
        #print( '#', sys.stdout.encoding)

    def fopen( fn):
        if o.oenc: f = filew( o.oenc, fn)
        else: f = open( fn, 'w')
        return f

    for f in (o.filter or ()):
        INTITLES.append( f.lower().strip() )
Example #6
0
  <div style="overflow:auto; height:100%;">
''' + '\n<hr>'.join(
        form( what.decl, target= target, remove_empty_form_fields=remove_empty_form_fields, **kargs)
        for what in sorter( iface.methods_walk_instance( iface))
) + '''
 </div>
 <td height=100%> <iframe name=out width=100% height=100%> no-iframe? </iframe>
</table>
'''
    if help: r += '<hr>' + '\n<br>'.join( help.strip().split('\n'))
    urls = [ escape( x) for x in url_doco( iface, sepattrs=' ; ') ]
    return r + '''
<hr>
<b>Valid URLs</b>:<br>
''' + '\n<br>'.join( urls)

#''' + '\n &nbsp; '.join( ahref( n,u) for n,u in buttonsurl) + '''


if __name__ == '__main__':
    from svd_util import optz
    optz.str( 'root', help= 'root/base url')
    optz.str( 'title', )
    optz.bool( 'dont_remove_empty_form_fields', )
    optz,args = optz.get()
    #from simu import simu as f
    from face__io import IO as f
    print html( f, **dict( (k,v) for k,v in optz.__dict__.items() if v))

# vim:ts=4:sw=4:expandtab
Example #7
0
'''
име:           Как щастието се скри в четирилистна детелина
автор:         ИринаКарадимчева
откъде:        ВзаП 20140801
издание:       радио
ориг_описание: >-
  „Как щастието се скри в четирилистна детелина“ от Ирина Карадимчева
ориг_рубрика:  Време за приказка

===>
hb-0801-1820+ВзаП+Как_щастието_се_скри_в_четирилистна_детелина--Ирина_Карадимч
'''

optz.bool( 'move',    help= 'преименувай към новото име')
optz.bool( 'link',    help= 'направи символна връзка = новото име')
optz.str(  'target',  help= 'къде да сложи горните')
optz.bool( 'avtori_otdelni',   help= 'ползва #автори_отделни: вместо автор:')
_podredbi = 'ime+rubr+vreme rubr+ime+vreme vreme+rubr+ime'.split()
_podredba = _podredbi[0]
optz.str( 'podredba',
    type= 'choice', choices= _podredbi, default= _podredba,
    help= 'подредба в името, подразбиране: %default, другите са: '+' '.join(p for p in _podredbi if p!=_podredba) )
#optz.str(  'prefix',  help= 'слага пред новото име')

optz,argz = optz.get()
for dir in argz:
    fn = dir + '/opis'
    print( '... ', dir)
    try:
        f = open(fn).readlines()
    except Exception as e:
Example #8
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os,sys,re
from svd_util import optz
optz.bool( 'fake', '-n', help= 'do nothing')
optz.bool( 'link', help= 'link instead of move/rename')
optz.bool( 'dirfiles', '-r', help= 'dir and then files inside') #?
optz.bool( 'lower', '-l', help= 'just lower-case, all args are filepaths')
optz.bool( 'upper', '-u', help= 'just upper-case, all args are filepaths')
optz.int(  'levels',    default=0, help= 'levels above leaf to rename lower/upper, default [%default]')
optz.str(  'movepath',  help= 'rename and move into')
optz.str(  'command',   help= 'exec this with 2 args instead of os.rename/os.link')
optz.bool( 'insymlink', help= 'rename inside symlinks (text it points to), ignore non-symlinks')
optz.bool( 'outsymlink', help= 'if --insymlink, also rename/cmd actual symlinked-path')
optz.bool( 'thesymlink', help= 'if --insymlink, also rename/cmd the symlink itself')
#optz.bool( 'filter',    help= 'additional filter for inside symlinks; action applies if this matches inside symlink')  mmm use instead find -lname ?
optz.bool( 'noerror',   help= 'skip errors')
optz.bool( 'abssymlink', help= 'rename symlinks to point to abs-full-path, ignore non-symlinks')
optz.bool( 'quiet', )
optz.help( '''
%prog [options] regexp subst filepaths
   subst can also use $1..$6 for groups
   if filepath is - , reads stdin, one filepath per line
   ! put -- before args if any filepath/regexp/subst starts with -
%prog -u/-l [options] filepaths
renu* [options] filepaths
renl* [options] filepaths
'''.strip() )
optz,argz = optz.get()

def renul( x, up, levels =optz.levels):
Example #9
0
    with f: #open( fname, 'w', newline='') as f:
        c = csv.writer(f, **(delimiter and dict( delimiter=delimiter) or {}))
        for row in array:
            c.writerow( row )

if __name__ == '__main__':
    from svd_util import optz, osextra
    optz.help( '''
extract excel sheet(s) into .csv
args-in-any-order: file.xlsx [sheetname] [sheetname] ..
 unless --allsheets, no sheet-names means first if only one, else shows all sheet-names and stops
 examples:
    ... path/to/somename.xls --all --dir --path .   -->> dumps all sheets as ./somename/sheetname*.csv

'''.strip())
    optz.str( 'csv',        help= 'name of output file.csv ; used as prefix if allsheets; defaults to path+name of file.xlsx + .sheetname-if-specified')
    optz.str( 'path',       help= 'output path, default is whereever .xls is')
    optz.bool( 'allsheets', help= 'save all sheets, named csvname.sheetname.csv')
    optz.bool( 'dir_from_name',  help= 'create outname as folder, i.e. csvname/sheetname.csv')
#    optz.bool( 'nostrip',   help= 'do not strip empty columns/rows at right/bottom - see also --strip_top_left')
    optz.str( 'strip',      help= 'strip empty columns/rows at where - left,top,bottom,right, comma separated; default [%default]', default= 'right,bottom')
    optz.str( 'columns',    help= 'columns to extract, comma separated (index-0-based, or excel letter A-...) ; default to all')  #name if first row of result .csv contain names) ; may be multiple
    optz.str( 'delimiter',  help= '.csv column delimiter, default is comma ","')
    oparser = optz.oparser
    optz,argz = optz.get()
    fcsv = optz.csv
    sheets = []
    fxls = None
    for a in argz:
        if a.lower().endswith( '.xls') or a.lower().endswith( '.xlsx'):
            fxls = a
Example #10
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function #,unicode_literals
import sys,os,re
from svd_util import optz

optz.help( 'find all video files under argument[s] and symlink as flat-filenames into . (replacing / with :)')
optz.bool( 'real', '-y', help='do it')
optz.bool( 'follow_symlinks', )
optz.str(  'exclude', help= 'regexp to exclude filepaths')
optz,argz = optz.get()

print( 'dirs:', argz)
ignore = None
if optz.exclude:
    print( 'excluding:', optz.exclude)
    ignore = re.compile( optz.exclude)

exts = 'mov mkv mp4 avi 3gp'.lower().split()
def walk( roots, followlinks =optz.follow_symlinks, exts =exts):
    for root in roots:
        for path,dirs,files in os.walk( root, followlinks= followlinks):
            for f in files:
                fpath = os.path.join( path, f)
                if ignore and ignore.search( fp): continue
                #'name', '.ext'
                if os.path.splitext(f)[-1][1:].lower() in exts:
                    yield fpath

def do( afrom, bto):
    print( afrom, ':>', bto)
Example #11
0
def get_hash( a):
    st = os.stat( a)
    time = st.st_mtime or st.st_ctime
    #PRId64 = 'I64d'
    #return hash.Format("d%"+PRId64+"s%"+PRId64, time, st.st_size);
    return 'd%ds%d' % (time, st.st_size)



import sys, os
from os.path import *
target = expanduser( '~/.xbmc/userdata/Thumbnails/')

from svd_util import optz
caches='0 ln sym'.split()
optz.str( 'cache', type='choice', choices= caches,
            help='fake the cache, and how - 0=empty file, ln=hardlink, sym=symlink')
optz.str(   'sqltextures',  help= 'path to the Textures13.db, to fill the texture table with fake rows' )
optz.bool(  'sqlsizes',     help= 'fill relations to sizes table')

optz,argz = optz.get()

def walker( a):
    for path,dirs,files in os.walk( a):
        for f in files:
            fp = join( path, f)
            c = get_crc32( fp)
            cf = join( c[0], c + splitext(f)[-1].lower() )
            cfp = join( target, cf)
            yield fp, c, cf, cfp

if optz.sqltextures:
Example #12
0
            md -p $P/$b
            ln -nsf ../../$a/org/$b $P/$b/$a
        done
        cd -
    fi
done
'''

import sys,os
from glob import glob
from os.path import join, split, isdir, realpath, exists, lexists, basename
from instr import meta_prevodi
from svd_util.lowercase import dict_lower
from svd_util import optz
optz.help( '%prog [опции] папка-изход  папки-входящи..')
optz.str( 'prevodi_meta',   help= 'файл-речник с преводи на понятия (lat=cyr) - хора..')
optz,args = optz.get()
out = args[0]
all = args[1:]

meta_prevodi = optz.prevodi_meta and meta_prevodi( optz.prevodi_meta, dict= dict_lower, nomer_stoinost=1) or {}

def ignored( f, org):
    if not isdir( f): return True
    if isdir( org): return False
    if glob( f+'/*.mp3'): return False
    return True

count = 0
for f in all:
    f = f.rstrip('/')
Example #13
0
    for i in range(1,5):
        for f in fmts:
            k = f[:i]
            if k in oo: assert oo[k] == f, (f,oo[k])
            else: oo[k] = f
        #oo.update( (f[:i],f) for f in fmts)
    return oo

iformats = formats
oformats = formats + 'text'.split()
ifmts = fullmap( iformats)
ofmts = fullmap( oformats)

from svd_util import optz
optz.usage( '%prog [options] files')
optz.str( 'input',  default='python', type='choice', choices = list(ifmts), help= f'input format [%default]: {", ".join(iformats)} ; initial letters also work')
optz.str( 'output', default ='html',  type='choice', choices = list(ofmts) + 'text'.split(), help= f'output format [%default]: {", ".join(oformats)} ; initial letters also work')
optz.str( 'subst_in',   help= 'file to put the output substituting some part (what/where depends on output-type, i.e. json_opera)')
optz.bool( 'flat' , help= 'dump')
#optz.bool( 'html',  help= 'out=.html')
#optz.bool( 'adr',   help= 'out=.adr')
#optz.bool( 'netscape',   help= 'out=.html, netscape/firefox/opera export dl/dt style')
optz.text( 'rootiname',  help= 'root = in[ /from/here ]')
optz.text( 'rootoname',  help= 'out[ /to/there ] = root')
optz.text( 'skip',   help= 'path/to/skip')
optz.bool( 'nounique',  help= 'ignore UNIQUEID' )
optz.bool( 'align',     help= '(for out=.adr)')
optz.bool( 'notrash',   help= 'ignore trash (for out=.adr)' )
optz.bool( 'nosort',    help= 'dont sort items' )
options,args = optz.get()
Example #14
0
#!/usr/bin/python3

import datetime, subprocess, sys, time
import os.path
from svd_util import optz
optz.int( 'seconds', '-s', default= 0 )
optz.int( 'retry_n', default= 1 )
optz.int( 'retry_delay_seconds', default= 20 )
optz.int( 'minutes', '-m', default= 30 )
optz.int( 'seconds_extra', default= 3 )
optz.str( 'stream', default= 'http://stream.bnr.bg:8003/botev.mp3'
                #'http://streaming.bnr.bg/HristoBotev'
            )
#optz.str( 'stream', default= 'http://streaming.bnr.bg/Horizont' )
optz.str( 'fname',  default= '' )
optz.multi( 'exec',  default= [], help= 'in syntax of find - outfname is {} ; can be multiple times' )
optz.str( 'logfname', )
optz.bool( 'quiet_mplayer', )

from svd_util.py.wither import wither

def rec( o, *, fname, secs, mins, stream ):
    now = datetime.datetime.now().strftime( '%Y%m%d.%H.%M.%S')
    if not fname:
        fname = o.stream.split('://')[-1].replace('/','_')

    ofname = '-'.join( [fname, now, ]
        ).replace( ' ', '_' #just in case
        ).replace( ':', ''  #mplayer codec-options separator
        ).replace( ',', ''  #also
        ) + '.wav'
Example #15
0
            assert res == exp
    for w,w1 in zip( t0.split(), t1.split() ):
        tst( hyphtext( w, **cfg), w1 )
    tst( hyphtext( t0, **cfg), t1 )
    print( t1)


if __name__ =='__main__':
    from svd_util import optz
    optz.help( u'''
    %prog [options] <infile  >outfile
    %prog [options] думи за пренасяне ...
    '''.rstrip())
    optz.text( 'hyphen',help= u'"тире" за отбелязване на пренасянето (меко/скрито-тире); подразбира се "%default"', default= config.hyphen )
    optz.bool( 'html',  help= u'ползва HTML-меко-тире %(HTML_HYPHEN)r (вместо горното)' % locals() )
    optz.str( 'start',  help= u'започва да променя след този текст' )
    optz.bool( 'htmlpre',   help= u'пропуска съдържанието на <pre>..</pre> групи' )
    optz.int( 'minsize',    help= u'думи под тази дължина не се пренасят; подразбира се %default', default =config.minsize )
    optz.bool( 'utf',   help= u'вх/изх utf8' )
    optz.bool( 'iutf',  help= u'вх  utf8' )
    optz.bool( 'iguess',help= u'вх  познай кодировката' )
    optz.bool( 'outf',  help= u'изх utf8' )
    optz.bool( 'i1251', help= u'вх  cp1251' )
    optz.bool( 'o1251', help= u'изх cp1251' )
    optz.bool( 'cp1251',help= u'вх/изх cp1251' )
    optz.bool( 'test',  help= u'самопроверка' )
    optz.bool( 'demo',  help= u'демо' )
    optz,args = optz.get()

    if optz.test:
        test()