подсчет числа файлов в каталоге
ls | tee /dev/stderr | wc -l
find -type f|cat -n
find -type f|cat -n
1 import os
2
3 class SingleRun():
4 class InstanceRunningException(Exception):
5 pass
6 def __init__(self, lock_file):
7 #define the lock file name
8 self.lock_file = "/tmp/%s.pid" % lock_file
9 def __call__(self, func):
10 def f(*args, **kwargs):
11 if os.path.exists(self.lock_file):
12 #get process id, if lock file exists
13 pid = open(self.lock_file, "rt").read()
14 if not os.path.exists("/proc/%s" % pid):
15 #if process is not alive remove the lock file
16 os.unlink(self.lock_file)
17 else:
18 #process is running
19 raise self.InstanceRunningException(pid)
20 try:
21 #store process id
22 open(self.lock_file, "wt").write(str(os.getpid()))
23 #execute wrapped function
24 func(*args,**kwargs)
25 finally:
26 if os.path.exists(self.lock_file):
27 os.unlink(self.lock_file)
28 return f
Пример
1 @SingleRun(lock_file="x")
2 def a():
3 pass
4
5 @SingleRun(lock_file="x")
6 def b():
7 pass
8
9 @SingleRun(lock_file="y")
10 def c():
11 pass
import os
import fcntl
class DjangoLock:
def __init__(self, filename):
self.filename = filename
# This will create it if it does not exist already
self.handle = open(filename, 'w')
# flock() is a blocking call unless it is bitwise ORed with LOCK_NB to avoid blocking
# on lock acquisition. This blocking is what I use to provide atomicity across forked
# Django processes since native python locks and semaphores only work at the thread level
def acquire(self):
fcntl.flock(self.handle, fcntl.LOCK_EX)
def release(self):
fcntl.flock(self.handle, fcntl.LOCK_UN)
def __del__(self):
self.handle.close()
Usage:
lock = DJangoLock('/tmp/djangolock.tmp')
lock.acquire()
try:
pass
finally:
lock.release()
for i in foo:
if i == 0:
break
else:
print("i was never 0. Вызов будет если break не был вызван")
same as:
found = False
for i in foo:
if i == 0:
found = True
break
if not found:
print("i was never 0")
try:
do()
except Exception:
print "Catch!"
else:
print "Если не был пойман эксепшен - выполнится этот код внутри else!"
finally:
end()
foo = [x for x in xrange(10) if x % 2 == 0]
#same as
foo = []
for x in xrange(10):
if x % 2 == 0:
foo.append(x)
#set
{x for x in stuff}
#dicts python 2.7
{ a:a for a in range(10) }
[(i,j) for i in range(3) for j in range(i) ]
Тоже что
for i in range(5):
for j in range(i):
print i,j
# if + nested for
[(x, y) for x in range(4) if x % 2 == 1 for y in range(4)]
[(1, 0), (1, 1), (1, 2), (1, 3), (3, 0), (3, 1), (3, 2), (3, 3)]
enter_region: ; A "jump to" tag; function entry point.
tsl reg, flag ; Test and Set Lock
cmp reg, #0
jnz enter_region
ret
enter_critical_section:
TSL REGISTER, LOCK // Значение переменной LOCK копируется в регистр
// и устанавливается в 1.
CMP REGISTER, #0 // Старое значение сравнивается с нулем.
JNE enter_critical_section // Если оно ненулевое, значит кто-то уже вошел в критическую секцию и заблокировал её.
RET // Блокировка выполнена успешно, возвращаемся в вызывающую функцию.
leave_critical_section:
MOV LOCK, #0 // Разблокирование переменной.
RET // Возврат в вызывающую функцию.
class Squares(object):
def __init__(self, start, stop):
self.start = start
self.stop = stop
def __iter__(self): return self
def next(self):
if self.start >= self.stop:
raise StopIteration
current = self.start * self.start
self.start += 1
return current
# генератор аналогичный итератору приведенному выше
def squares(start, stop):
for i in xrange(start, stop):
yield i * i
for i in squares(1,4): print i
# или еще более локанично
# generator expression
gen = (i*i for i in xrange(1, 4))
for i in gen: print i
#django uniq numbers generator in request (accessable in templates)
def gen_uniq():
i=0
while True:
i=i+1
yield "uniq%d" % i
gen = gen_uniq()
def gen_method(self):
return gen.next()
request.gen_uniq = types.MethodType( gen_method, request )