Пример #1
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)
Пример #2
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os,sys,re
from svd_util import optz
optz.bool( 'fake', help= 'do nothing')
optz.bool( 'link', help= 'link instead of move/rename')
optz.bool( 'dirfiles', '-r', help= 'dir and then files inside') #?
optz.bool( 'upper', '-u', help= 'just upper-case, all args are filepaths')
optz.bool( 'lower', '-l', help= 'just lower-case, all args are filepaths')
optz.bool( 'insymlink', help= 'rename inside symlinks-text, ignore non-symlinks')
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):
    r = os.path.split(x)
    return os.path.join( r[0], r[1].upper() if up else r[1].lower())

prg = os.path.basename( sys.argv[0] )
if prg.startswith( 'renu'): optz.upper = True
if prg.startswith( 'renl'): optz.lower = True

if   optz.upper: func = lambda x: renul(x,True)
elif optz.lower: func = lambda x: renul(x,False)
Пример #3
0
#!/usr/bin/env python
#$Id: cvs-vim-all.py,v 1.4 2007-12-07 20:46:52 sdobrev Exp $
from __future__ import print_function
from svd_util import gencxx, optz
optz.bool( 'head')
optz,argz = optz.get()

import os.path
#from textwrap import TextWrap
ext_c = '.changed .cpp .cxx .h .hpp .hxx .java'.split()
ext_make = '.mak'.split()

for a in argz:
    org = f = file(a).read()
    if not f.strip(): continue
    ext = os.path.splitext( a )[1].lower()
    is_c = ext in ext_c
    is_make = ext in ext_make or os.path.basename( a ).lower().startswith( 'makef' )

    if optz.head and gencxx._CVShead[:3] not in f:
        h = is_c and gencxx.CVShead or gencxx.CVShead_py
        f = h + f

    if gencxx._VIMtail.strip() not in f:
        h = is_c and gencxx.VIMtail or gencxx.VIMtail_py
        if is_make: h = h.replace( ':expandtab', ':noexpandtab' )
        f = f + h
    if not is_make:
        f = f.expandtabs(4)

    if f != org:
Пример #4
0
            rename( g, join( cel, basename(g)))
    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])
Пример #5
0
''')


if __name__ == '__main__':

    srcs = dict( (d.__name__, d) for d in Iztochnik.__subclasses__())

    from svd_util import optz
    optz.text( 'ienc',          help= 'входно кодиране; подразбиране - автоматично' )
    optz.text( 'oenc',          help= 'изходно кодиране', )
    optz.int(  'stranici',      help= 'колко страници; подразбиране - според източника', default=0 )
    optz.list( 'iztochnik',
        type= 'choice', choices= sorted( srcs),
        help= 'източник (%s), може няколко пъти; подразбиране - всички' % ' '.join( sorted( srcs)) )
    optz.text( 'skriti',    help= 'файл с филтрите')
    optz.bool( 'podrobno',  help= 'показва извлечените имена')
    optz.bool( 'trij',      help= 'изтрива филтрираните елементи вместо само да ги скрива/свива')
    optz,argz = optz.get()

    if optz.ienc=='auto': optz.ienc=None

    if optz.oenc:
        from svd_util.eutf import fix_std_encoding, filew
        fix_std_encoding( ENC= optz.oenc)
    def fopen( fn):
        if optz.oenc: f = filew( optz.oenc, fn)
        else: f = open( fn, 'w')
        return f

    Iztochnik.iztrij = optz.trij
    if optz.skriti: skriti = re_skriti( open( optz.skriti).read())
Пример #6
0
autoconvert (source-files) from cp1251 to utf AND fix the "coding" line

преобразува (файлове) от 1251 в УТФ и оправя реда за "coding"
"""
try:
    from svd_util import eutf, optz
except:
    import os.path, sys

    p = os.path.realpath(__file__).split("/")
    sys.path.insert(0, "/".join(p[:-2]))
    import eutf, optz  # hope it lives in ..

import os, sys, re

optz.bool("keeputf", help='keep "coding utf" line even if file is ascii')
optz.bool("forceutf", help='add  "coding utf" line even if file is ascii')
optz.bool("dirsymlink", help="walk symlink dirs")
optz.bool("symlink", help="walk symlink files")
optz.bool("doit", help="do overwrite")

optz, args = optz.get()

re_c = re.compile("^#.*?coding\s*[=:]\s*([-\w.]+)")
u8 = "utf-8"


def walker(a):
    if not os.path.isdir(a):
        yield "", a
    else:
Пример #7
0
            if o.cron_earlier_minutes: sizemins += o.cron_earlier_minutes
            if o.cron_later_minutes:
                sizemins += o.cron_later_minutes

        print( t.minute, t.hour, t.day, t.month, '*',
                o.cron_user or '',
                o.cron,
                sizemins and '-m '+str(sizemins) or '',
                '--fname', fname,
                '--stream', x.stream,
             )

if __name__ == '__main__':

    from svd_util import optz
    optz.bool( 'html_strict',   help= 'хтмл-парсер: стриктен' )
    optz.bool( 'html_notfixed', help= 'хтмл-парсер: непоправен оригинален' )
    optz.text( 'ienc',          help= 'входно кодиране [автоматично]' )
    optz.text( 'oenc',          help= 'изходно кодиране [%default] (напр. за crontab)', )
    optz.text( 'cron',          help= 'прави crontab, пускайки тази команда (може с аргументи)')
#    optz.text( 'cron_file',     help= 'записва го в този файл, иначе stdout')
    optz.text( 'cron_user',     help= 'потребител за crontab, ако трябва' )
    optz.bool( 'cron_fname_notime',     help= 'без дата/час в резултатното име' )
    optz.int(  'cron_earlier_minutes',  help= 'пуска толкова минути по-рано')
    optz.int(  'cron_later_minutes',    help= 'спира толкова минути по-късно')
    optz.int(  'cron_later_percent',    help= 'спира толкова процента по-късно')
    optz.bool( 'nofilter',      help= 'всичко, без филтри' )
    optz.int(  'days',          help= 'филтър толкова дни от днес [%default]', default=1 )
    optz.append( 'force',       help= 'включва на запис, формат: канал-чч:мм-чч:мм[-име] но може без име', )
#   optz.bool( 'preferdaily',   help= 'при наличие на дневна и всичко, без филтри' )
Пример #8
0
#!/usr/bin/env python2

import sys
import re
import subprocess, os

from svd_util import optz

optz.bool("dryrun", "-n")
optz.bool("verbose", "-v")
optz.bool("autoon")
optz.bool("nomenu")
optz.bool("noscan")
optz.bool("crypto", "-c")
optz.text("iface", default="wlan0")  # ath0
optz.text("essid")
optz, args = optz.get()

o_n = optz.dryrun
o_v = optz.verbose
o_menu = not optz.nomenu
o_scan = not optz.noscan
with_crypt = optz.crypto  # opt('-c', '--crypt', '--crypto')

iface = optz.iface or "ath0"

res = dict(
    addr=re.compile("Cell.*? - Address: ([0-9A-F:]+)"),
    essid=re.compile('ESSID:"([^"]*)"'),
    quality=re.compile("Quality[=:](\d+)/(\d+)"),
    crypto=re.compile("Encryption key:(on|off)"),
Пример #9
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function

from svd_util import optz
from svd_util.struct import DictAttr
optz.int( 'year', default= 2012)
optz.bool( '2011', )

y2011 = DictAttr(
 superannuation = 0.09,
 bands = [
    [  6000 , .15 ],
    [ 37000 , .30 ],
    [ 80000 , .37 ],
    [180000 , .45 ],
    ],
 levy = dict(
    medical = 0.015,
    #medical_no_private = 0.01 # additional 1% if no-private-health care
    flood = [
        [  50000,  .005 ],
        [ 100000,  .01  ],
        ]
    )
)

all = {
    2011: y2011,
    2012: DictAttr(     #2012-2013
      y2011,
Пример #10
0
    d = re.sub(b"<([^>]*?<)", rb"\1", d)
    # if d!=d1: print( 2222222)

    if ienc:
        d = d.decode(ienc)
    return d


from svd_util.struct import DictAttr
from svd_util import optz

optz.text("url", default="http://pozvanete.bg/imoti-prodava-offline&maxAds=100?page={npage}")
optz.int("pages", default=11)
optz.list("includes_info")
optz.list("excludes_name")
optz.bool("load")
optz.bool("save")
optz.bool("cache")
optz.bool("io", help="load+save")
optz.text("fload", default="danni.pozv", help="[%default]")
optz.text("fsave", default="danni.pozv", help="[%default]")
optz.bool("allprn", help="покажи всички въобще, а не само новите")
optz.bool("curprn", help="покажи всички сега-прочетени, а не само новите")
optz.text("merge", help="смеси тези данни")
optz.bool("podrobno", "-v", help="видимост!")
optz.bool("prezapis", help="презаписва дори и да няма нужда")
optz.bool("debug", help="само гледа входа")


def oprosti(t):
    return tuple(t.replace(",", " ").lower().split())
Пример #11
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= 'показва подробности')
Пример #12
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#from __future__ import print_function #,unicode_literals
'apply moves-around-dirs/deletes from template/ into .'

import os
join = os.path.join

from svd_util import optz
optz.bool( 'real', '-y', )
optz.append( 'exclude', help='dirs', default= [] )
optz.append( 'ignore' , help='file-names', default= [])
optz,args = optz.get()
none = not optz.real

template = args[0].rstrip('/')

tree = {}
paths = set()

try: os.mkdir( 'del')
except Exception as e: print( e)

optz.exclude = [ a.rstrip('/') for a in optz.exclude ]

for path, dirs, files in os.walk( template ):
    subpath = path[ len(template): ].lstrip('/').split( '/')
    p = join( *subpath[:] )
    if p in optz.exclude:
        dirs[:] = []
        continue
Пример #13
0
'''
autoconvert (source-files) from cp1251 to utf AND fix the "coding" line

преобразува (файлове) от 1251 в УТФ и оправя реда за "coding"
'''
try:
    from svd_util import eutf, optz
except:
    import os.path, sys
    p = os.path.realpath( __file__).split('/')
    sys.path.insert( 0, '/'.join( p[:-2]) )
    import eutf,optz #hope it lives in ..

import os, sys, re

optz.bool( 'keeputf',   help= 'keep "coding utf" line even if file is ascii')
optz.bool( 'forceutf',  help= 'add  "coding utf" line even if file is ascii')
optz.bool( 'dirsymlink',    help= 'walk symlink dirs')
optz.bool( 'symlink',       help= 'walk symlink files')
optz.bool( 'doit',      help= 'do overwrite')

optz,args = optz.get()

re_c = re.compile( '^#.*?coding\s*[=:]\s*([-\w.]+)')
u8 = 'utf-8'

def walker( a):
    if not os.path.isdir( a):
        yield '', a
    else:
        for path, dirs, files in os.walk( a, followlinks= optz.dirsymlink):
Пример #14
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):
Пример #15
0
#!/usr/bin/env python
#sdobrev 2007-

from svd_util import optz
optz.help( '''default use is filter: %prog [options] input_encoding output_encoding <input >output
    output_encoding default is utf8 ;
    use "utf2" as special input_encoding to double decode utf8
''' .strip())
optz.bool( 'reverse', help= 'reverses each line' )
optz.text( 'input',   '-i', default= '-', help= 'input  filename, -/empty means stdin, default: stdin')
optz.text( 'output',  '-o', default= '-', help= 'output filename, = means overwrite input, -/empty means stdout, default: stdout')
#optz.bool( 'overwrite')
#optz.bool( 'unicodeio', help= 'i/o is utf, but encode2input+decode2output')
optz, argz = optz.get()

import codecs
import sys
import os

stdin = sys.stdin
stdout= sys.stdout
_v3 = sys.version_info[0]>=3
if _v3:
    stdin= stdin.buffer
    stdout=stdout.buffer

e_from = argz[0]
e_to = (argz[1:] or ['utf8'])[0]

utf2 = e_from == 'utf2'
if utf2: e_from = 'utf8'
Пример #16
0
#!/usr/bin/env python
from __future__ import print_function

from svd_util import optz
import os
from os.path import *
issymlink = islink

optz.description( 'move/link real-source-of-symlink into elsewhere')
optz.bool( 'mv', help='do move, default is (hard)link')
optz.bool( 'fake',    '-n', help='do nothing')
optz.bool( 'deldest', '-f', help='delete destname before acting')
optz.bool( 'quiet', '-q', )
optz.bool( 'srcname', help='use link-target-name instead of link-name itself')
optz.bool( 'dellink',  help='delete symlink after acting')
optz,args = optz.get()
optz.verbose = not optz.quiet
if len(args)==1:
    raise RuntimeError( 'last arg must be target dir/filename')
dest = args.pop()
destdir = os.path.isdir( dest )
if len(args)>2 and not destdir:
    raise RuntimeError( 'last arg must be dir')

func = optz.mv and os.rename or os.link
for a in args:
    if not issymlink( a):
        #if optz.verbose:
        print( '... non-symlink', a)
        continue
    f = realpath(a)
Пример #17
0
return      върни
try         опитай
while       докато
with        със
yield       предай произведи добий
'''
extra_charset = 'А-Яа-я'


p2b = dict( a.strip().split()[:2]
            for a in translation.split('\n')
            if a.strip() )

import sys, re
from svd_util import optz
optz.bool( 'lat2cyr', default= False)
optz.bool( 'grammar', default= False)
optz.bool( 'vim',     default= False)
#optz.bool( 'all_variants',  default= False, help= 'allow all alternatives; default: only first listed')
optz.bool( 'dump', )
opts,args = optz.get()

def tx( w):
    w = p2b.get(w,w)
    if opts.lat2cyr:
        from util import lat2cyr
        w = lat2cyr.zvuchene.lat2cyr(w)
    return w


class reader:
Пример #18
0
import sys
import datetime, calendar, time
import os.path
from svd_util import optz, datetimez
optz.text( 'year')
optz.text( 'hour')
optz.bool( 'ilocal')
optz.bool( 'olocal')
optz.bool( 'fake', '-n' )
optz,args = optz.get()

def delta( dt, what):
    v = getattr( optz, what)
    if v:
        iv = int(v)
        if v[0].isdigit():
            dt = dt.replace( **{ what: iv })
        else:
            if what == 'hour':
                what = 'seconds'
                iv = 3600*iv
            dt = dt + datetime.timedelta( **{ what: iv })
    return dt

for a in args:
    d = os.path.getmtime(a)

    dti = datetimez.timestamp2datetime( d, local= optz.ilocal)
    dt = dti
    dt = delta( dt, 'year')
    dt = delta( dt, 'hour')
Пример #19
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os, sys, re
import pprint
from svd_util import optz

optz.bool("ednakvo_ime_razlika_razmer")
optz.bool("samoime")
optz.append("sravni")
optz.append("prevod")
optz, args = optz.get()


def walk(a):
    ff = []
    for path, dirs, files in os.walk(a, followlinks=False):
        for f in files:
            if not f.endswith("jpg"):
                continue
            ff.append((f, path, os.stat(os.path.join(path, f)).st_size))
    ff.sort()
    return ff


ff = walk(args and args[0] or ".")

if optz.ednakvo_ime_razlika_razmer:
    u = ""
    for f, p, s in ff:
        prn = 0
        if not u:
Пример #20
0
#!/usr/bin/env python
#sdobrev 2013
#copy fulltree of timemachine backups , symlinking the common (~hardlinked) dirs

#see http://hints.macworld.com/article.php?story=20080623213342356

from os.path import join
import os.path as ospath
import os, stat, shutil

from svd_util import optz, osextra
optz.list( 'exclude',    help= 'exclude filepattern (multiple)')
optz.list( 'include',    help= 'include filepattern (multiple)')
optz.list( 'direxclude', help= 'exclude dirpattern  (multiple)')
optz.list( 'dirinclude', help= 'include dirpattern  (multiple)')
optz.bool( 'dont',      '-n', help= 'dont actualy do anything')
optz.bool( 'verbose',   '-v', help= 'verbose')
optz.bool( 'linkusage', help= 'symlink used or unused links to archive/_used/ or _unused')
optz.text( 'orgarchive', help= 'path to the original hidden archive .HPF...')
optz.text( 'archive', help= 'archive-dir-name -instead of that hidden .HPF... [%DEFAULT]', default= '_archiv')
optz,argz = optz.get()

target  = argz.pop( -1)
archive = optz.archive

def match1( f, p):
    return fnmatch.fnmatch( f,p)
def match( f, patterns):
    for p in patterns:
        if match1( f, p): return True
def included( a, inc, exc):
Пример #21
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from svd_util import optz
optz.usage( '%prog [options] < metatoc-script-stdin')
optz.text( 'outpath2opispath', help= 'какво да се добави към outpath за да се стигне до .../opis')
optz.bool( 'opis', help= 'състави опис')
optz.bool( 'toc',  help= 'състави .toc за CDTEXT')
optz.bool( 'cyr2lat',   help= 'ако cd-toc приема само латиница')
opts,args = optz.get()

import sys
import os.path
from svd_util import struct, py3
dictOrder = py3.dictOrder
DictAttr = struct.DictAttr

#allitems = []
#paths = dictOrder()
albumi = dictOrder()

def add( *items, **ka):
    #global allitems
    for i in items:
        i = DictAttr( i)
        #allitems.append( i)
        path = i.path
        opis = os.path.join( path, opts.outpath2opispath or '', 'opis')
        i.opis = opis
        ialbum = i.album or i.title
        try:
Пример #22
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
from svd_util import optz
import os,sys

optz.bool( 'fake')
optz.text( 'input',  '-i', help= 'input encoding', default= 'utf8')
optz.text( 'output', '-o', help= 'output encoding')
optz,argz = optz.get()
#if opt('-icp1251', '-i=cp1251'): ienc = 'cp1251'
#if opt('-icp866', '-i=cp866'): ienc = 'cp866'
#if opt('-outf8', '-o=utf8'): oenc = 'utf8'

for x in argz:
    dir,x = os.path.split( x)
    fn = x.decode( optz.ienc)
    print( x, fn)
    if optz.fake: continue
    if optz.oenc: fn = fn.encode( optz.oenc)
    os.rename( *(os.path.join( dir,f) for f in (x, fn)))

# vim:ts=4:sw=4:expandtab
Пример #23
0
import os, fnmatch
from os.path import isdir, basename, exists, join, dirname, realpath
from svd_util import optz, osextra

optz.help( '''
walklink sourceitem[s] target  -  mv/cp/ln that sees through dir+file symlinks
    if targetnotexists
        TODO if one source, rename it
        else - make targetdir, move sources into it
    if target.exists
        if target.isdir, move sources into it
        TODO elif target.isfile and one source.isfile and --force, overwrite target
        else error: multiple or non-file sources into existing target.file
''')

optz.bool( 'force', '-f', help= 'force source file to overwrite target file if exists')
optz.list( 'exclude',    help= 'exclude filepattern (multiple)')
optz.list( 'include',    help= 'include filepattern (multiple)')
optz.list( 'direxclude', help= 'exclude dirpattern  (multiple)')
optz.list( 'dirinclude', help= 'include dirpattern  (multiple)')
optz.bool( 'verbose', '-v')
optz.simvolni = True #',  '-L', help= 'обхожда и символни връзки')

ops = {
    os.rename : 'mv move',
    os.link   : 'ln link',
#   os.link   : 'cp copy',
    None:       'print',
}
op2op = {}
for op,names in ops.items():
Пример #24
0
from svd_util import optz

'''
име:           Как щастието се скри в четирилистна детелина
автор:         ИринаКарадимчева
откъде:        ВзаП 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:
Пример #25
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import prikazki
import opisvane
from svd_util import eutf, optz, lat2cyr
from glob import glob
import datetime #import datetime, timedelta
from svd_util.struct import DictAttr, attr2item

info = prikazki.info

gg = {}
optz.bool( 'simvolni', '-L',    help= 'обхожда и символни връзки', **gg)
optz.bool( 'davai',         help= 'извършва промените', **gg)
optz.bool( 'prezapis',      help= 'презаписва всички файлове (иначе само ако са различни)')

optz.text( 'html_enc',      help= 'кодировка на html [%default]', default='utf8', **gg)  #cp1251
optz.text( 'html_spisyk',   help= 'прави общ списък html-страница', **gg)
optz.text( 'html_novi',     help= 'прави списък новости отделен (иначе част от общия списък)', **gg)
optz.text( 'html_izbrani',  help= 'прави списък на само хубавите - извадка от общия списък', **gg)
optz.bool( 'obshto_otgore',         help= 'слага Общо: отгоре (иначе отдолу)', **gg)
optz.bool( 'obshto_broi_zapisi',    help= 'брои файловете със записи, а не папките', **gg)
optz.text( 'podredba',              help= 'подрежда по изброените полета [%default]',
            default= 'humor,ime_sglobeno,pored',
                **gg)
optz.bool( 'otkoga_e_mintime',      help= 'слага липсващо откога=най-ранното време на папката', **gg)
optz.int(  'kolko_dni_e_novo',   default=35, help= 'толкова дни нещо се счита за ново [%default]', **gg)
optz.int(  'kolko_sa_novi',      default=0,  help= 'толкова последни неща се считат за нови [%default]', **gg)

options,args = optz.get()
Пример #26
0
from svd_util import optz, osextra

optz.help(
    """
walklink sourceitem[s] target  -  mv/cp/ln that sees through dir+file symlinks
    if targetnotexists
        TODO if one source, rename it
        else - make targetdir, move sources into it
    if target.exists
        if target.isdir, move sources into it
        TODO elif target.isfile and one source.isfile and --force, overwrite target
        else error: multiple or non-file sources into existing target.file
"""
)

optz.bool("force", "-f", help="force source file to overwrite target file if exists")
optz.list("exclude", help="exclude filepattern (multiple)")
optz.list("include", help="include filepattern (multiple)")
optz.list("direxclude", help="exclude dirpattern  (multiple)")
optz.list("dirinclude", help="include dirpattern  (multiple)")
optz.simvolni = True  #',  '-L', help= 'обхожда и символни връзки')

ops = {
    os.rename: "mv move",
    os.link: "ln link",
    #   os.link   : 'cp copy',
    None: "print",
}
op2op = {}
for op, names in ops.items():
    for n in names.split():
Пример #27
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
Пример #28
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
Пример #29
0
                    [ 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:
        run_simple( optz.host, optz.port, websimu1.app, use_debugger= True, use_reloader= True)
Пример #30
0
#!/usr/bin/env python3
# -*- coding: utf8 -*-
from svd_util import optz
optz.usage( '%prog [optz] ot-dir < ren-script-stdin')
#optz.optany( 'ot')
optz.text(  'link_kym',  help= 'направи ново дърво от връзки с този корен')
optz.bool( 'rename',     help= 'преименувай на място')
optz.bool( 'rename_alt', help= 'преименувай на място и остави символна връзка към старото име.alt')
optz.list( 'opis', help= 'подменя имена в опис ; може няколко пъти')
optz.bool( 'link_zagolemi_pootdelno', help= 'връзки: раздели заголеми/ на /moze /neizv ..')
optz.bool( 'nothing', '-n')
oparser = optz.oparser
optz,args = optz.get()

import os, sys, stat
from os.path import join, exists, dirname, basename, splitext

allfiles = {}
def link( ot, ikym, *pfxs):
    print( ot, ikym)
    ot = join( dir_ot, ot)
    assert exists( ot)
    if not optz.link_zagolemi_pootdelno and sum('zagolemi' in p for p in pfxs):
        pfxs = ['zagolemi']
    for pfx in pfxs:
        kym = join( optz.link_kym, pfx, ikym)
        ss = list( os.stat( ot) )   ## dict( size= ss[ stat.ST_SIZE], ..
        for ix in stat.ST_CTIME, stat.ST_NLINK:
            ss[ix] = None
        if kym in allfiles:
            old = allfiles[kym]