Browsing the topic python
net_monitor lives again
11 Comments | Filed under Linux-Planet devel english mandriva programming pythonWorking on Mandriva network tools, I looked on one of the most essential ones the network monitor (net_monitor). It was introduced a couple of releases before, and was mostly doing its job. However, it has a number of flaws and lack of features that motivated us to look closer at it.
The net_monitor currently used in all Mandriva versions is written in perl, is using internal drakx-net api (and is, therefore, only usable on Mandriva), and also have some issues such as memory leaks and non-usual interface. After a few thoughts and discussions we came to conclusion that it would be more adequate to project and rewrite it from scratch, turning it more modular, expansible and focused on common use cases.
Initially, I thought on using perl to write it, so it would still be part of drakx-net suite. However, after thinking on the code and the way it should work I felt that my brain was going to melt down
(perl is a nice language, but it is certainly not that compatible with me). So I ended up with python, which is my language of choice (together with C). Also, I’ve received many comments saying that the net_monitor is no more relevant, as every desktop environment provides its own network monitoring tool, and it should be dropped from drakx-net. By combining those issues, we came to decision that it would be more proper to separate net_monitor into a different package – this way, it won’t depend on any drakx-net internal functionalities, and user could uninstall it if required and use his own network monitoring tool if he wants to. And, at the same time, users would still have a cute little network monitoring application on their machines.
So, as a picture says more than a thousand words, I guess I’ll just add some pictures here than additional KBs of text
(EDIT: please note that the look and features of net_monitor have changed significantly in Mandriva since this post):
Surely, this is just an early and preliminary version, with many missing features and such. If you want to give it a try, just install net_monitor package, and it will create /usr/bin/net_monitor executable for you. It won’t conflict with existent net_monitor from drakx-net which is installed in /usr/sbin, so both of them may coexist on your system. If you look at /usr/share/doc/net_monitor/TODO, you’ll see some of the ideas that I intend to add to it, but the idea is to keep it simple and not transform it into an emacs of network monitoring
. And, of course, feel free to add your comments and suggestions (and bug reports) here!
P.S.: Just to prevent comments like ‘you should focus on fixing bugs instead of wasting time writing new things’. Net_monitor is present in Mandriva for years now, and if you look at bugzilla list it has a number of bugs and issues. So I am not creating a new app – I am bringing back from the land of the dead an old one
.
P.P.S.: Answering in advance to another question – yes, it would work on any Linux distro which has python and pygtk. You’ll just have to add some tricks into your network startup scripts to enable vnstat integration, but it will work just fine even without that.
As promised in the previous post, here come some first insight into the GUI for Tomoyo Linux, which will be present in Mandriva 2010.
As far as I know, this is the first GUI for Tomoyo out there (except the TomoyoGUI Eclipse Plugin, but it seems to be quite eclipse-bound and abandoned. Its page is in Japanese, but the all-mighty google translator helped me to take a peek into it). But, of course, I might be wrong – so please let me know if you know of any other GUI for Tomoyo Linux.
Obviously there are still a lot of things to do:
- add support for auditing/tomoyo security log into msec
- add support for reloading profile on-the-fly
- saving/loading/changing settings on the fly
- support complex statements
- everything else
so keep an eye on this blog for more news.
Regards,
Dr. Eugeni
Trabalhando com mandriva, vira e mexe encontro gente falando em francês. Como já faz quase 14 que não falo essa língua
, decidi apelar pro meu querido python e google translator.
Nada como uns 10 minutos de programação voltada a gambiarras
.
#!/usr/bin/python
#
# quick and dirty french2english translator
#
import urllib
import urllib2
from subprocess import Popen, PIPE
URL='http://translate.google.com/translate_t#fr|en|'
print "Paste your message"
msg = []
while 1:
try:
line = raw_input('>> ')
msg.append(line)
except:
break
s = ">>" + "\n>>".join(msg)
data = "http://translate.google.com/translate_a/t?client=t&%s&fr&tl=en" % urllib.urlencode({'text':s})
req = urllib2.Request('http://translate.google.com/translate_t', data, {'User-Agent':'Mozilla/5.0'})
resp = urllib2.urlopen(req).read()
p = Popen("lynx -dump -stdin | grep -- '>>'", shell=True, stdin=PIPE, stdout=PIPE)
p.stdin.write(resp)
p.stdin.close()
trans = p.stdout.read()
print trans
Agora é só dar ctrl-c no texto, depois rodar o programinha e dar ctrl-v seguido por ctrl-d
.
Ultimamente eu uso bastante programação funcional em python para tudo. Entretanto, fiquei brincando hoje e descobri que nem sempre ela oferece os melhores resultados.
Por exemplo, vamos imaginar a função que vai fazer todas as combinações entre os elementos de uma lista. Ela pode ser escrita de forma funcional:
# permutate-func
def permutate(l):
'''Returns all possible combinations of list values'''
return reduce(lambda x, y: y + x, [ [(x, y) for y in l if x != y] for x in l ])
ou de forma iterativa:
# permutate-iter
def permutate(l):
'''Returns all possible combinations of list values'''
res = []
for x in l:
for y in l:
if x != y:
res.append((x, y))
return res
Para listas pequenas não temos muita diferença de desempenho. Agora para listas maiores (por exemplo, com 1000 strings):
dups=['string%d' % x for x in range(1000)]
permutate(dups)
temos os seguintes resultados para programação funcional:
# time permutate-func
real 0m24.494s
user 0m20.763s
sys 0m1.698s
e os seguintes para o algoritmo iterativo:
# time permutate-iter
real 0m1.191s
user 0m1.150s
sys 0m0.036s
O tempo de 24 segundos caiu para apenas 1 segundo!
Qual conclusão tiramos disso? Embora programação funcional é extremamente poderosa, em alguns casos é melhor usar outras soluções para o problema
.
Descobri mais uma utilidade para os decorators em python:
import threading
class Thread(threading.Thread):
def __init__(self, f):
threading.Thread.__init__(self)
self.run = f
@Thread
def func():
print "Hello world!"
func.start()
Jeito simples e eficientes para criar funções threadizadas.
Update: É possível otimizar esse código para não precisar escrever .start() na mão, e deixar as funções compatíveis com a sua versão não-threadizada:
class Thread(threading.Thread):
def __init__(self, f):
threading.Thread.__init__(self)
self.run = f
def __call__(self):
return self.start()
@Thread
def func():
print "Hello world!"
func()
Mais um exemplo do poder de python + gtk. Para tirar um screenshot da tela, salvando-o em formato JPEG, o seguinte código é suficiente:
from gtk.gdk import *
screenshot = Pixbuf(COLORSPACE_RGB, False, 8, screen_width(), screen_height())
screenshot.get_from_drawable(get_default_root_window(), colormap_get_system(), \
0, 0, 0, 0, screen_width(), screen_height())
screenshot.save("tela.jpg", "jpeg", {"quality": "75"})
(Tá certo, dividi em 5 linhas para melhorar a legibilidade, mas no fundo são só 4 linhas mesmo).
Uma das maiores vantagens do python para mim é a legibilidade do código, facilidade de programação, e eficiência. Com quantas linhas de código seria possível fazer esse exemplo em qualquer outra linguagem? (Não vale apelar para import -window root tela.jpg porque aí é ImageMagick que faz toda a mágica!)
Cada vez mais e mais eu gosto dos recursos de programação funcional em python. E, como eu uso essa linguagem para resolver tarefas mais variáveis, não dá para não perceber que a velocidade de desenvolvimento e eficiência do código tornam-se cada vez melhores, por simplesmente aplicar técnicas de programação funcional.
Por exemplo, sem a programação funcional, eu usava o seguinte código antes para ler um arquivo com uma série de números, e determinar a média dos valores:
fd = open("data.log")
data = fd.readlines()
valores = []
le os dados
for line in data:
line_val = float(line.strip())
valores.append(line_val)
calcula a media
media = 0
for item in valores:
media += item
media /= len(media)
Re-escrevendo isso com técnicas de programação funcional, temos o seguinte:
le os valores do arquivo, transformando-os para floats, e ignorando strings vazias
valores = [float(val) for val in open("data.log").readlines() if len(val) > 1]
calcula a media, somando todos os valores e dividindo pelo número de elementos no vetor
media = reduce(lambda x, y: x+y, valores) / len(valores)
(É óbvio que é só um exemplo rápido, não estou tratando as excessões aqui, mas para resolver problemas simples do dia-a-dia é mais de que suficiente!)
O essencial são as funções lambda, map, reduce e filter. Todos os detalhes interessantes sobre esse estilo de programação eu achei aqui, e recomendo essa apresentação para todos!
De acordo com o Django Roadmap, faltam somente 9 tickets para a versão 1.0!
Finalmente, depois de alguns anos de desenvolvimento, veremos a versão 1.0 do melhor framework para construção de sites no universo
.
Uma apresentação excellente sobre programação funcional em python. Recomendo!
Functional Programming with Python (RuPy 2008)
Slashdot | World’s Shortest P2P App: 15 Lines
Leave a comment | Filed under devel programming pythonPois é – é possível fazer uma implementação completa de rede peer-to-peer usando somente 15 linhas de python (com um pouco de gambiarras envolvendo lambdas
).
Slashdot | World’s Shortest P2P App: 15 Lines
Impressionante.. como tudo em python!
Talvez pode ser útil para alguém
.
Este script pega a lista de músicas do mpd, seleciona um playlist aleatório, e coloca no ipod shuffle.
!/usr/bin/python
import os,random
ipod mountpoint - must be mounted!
MOUNTPOINT="/mnt/ipod"
def get_files():
'''Reads the list of mp3 files from mpd database'''
data = open(".mpd.db").readlines()
files = []
for l in data:
fields = l.strip().split(":",2)
if len(fields) < 2:
continue
if fields[0] == "file":
files.append(fields[1].strip())
return files
def get_free_space():
'''Gets available space from IPOD partition'''
line = os.popen("df -k %s | awk '{print $4}'" % MOUNTPOINT).readlines()[-1]
return int(line)
def fullcp(file, target):
'''copies file and directory structure'''
os.system('tar cf - "%s" | (cd %s && tar xf -)' % (file, target))
if name == "main":
try:
os.mkdir("%s/mp3" % MOUNTPOINT)
except:
print "Not creating %s/mp3!" % MOUNTPOINT
files = get_files()
freespace = get_free_space()
while 1:
# pega arquivo aleatorio
pos = random.randint(0, len(files))
curfile = files[pos]
del files[pos]
# determina o tamanho
res = os.stat(curfile)
size = res[6] / 1000
if freespace - size < 1:
break
freespace -= size
# copia
print "Copying [%8dK left]: %s" % (freespace, curfile)
fullcp(curfile, "%s/mp3/" % MOUNTPOINT)
É melhor usar ele junto com Shuffle-DB.
Por alguns meses fiquei pensando – para que servem os decorators em python? Ultimamente é fácil ver código do tipo:
@algum_metodo
def function(params):
____...
Aí hoje finalmente decidi descobrir como que isso funciona, e para que serve.
Em poucas palavras – realmente, decoratos são bem úteis. Eles não introduzem muitas novidades na linguagem, mas possibilitam evitar duplicação de código, e facilitar a implementação.
Por exemplo, suponhamos que precisamos rastrear todas as chamadas a uma de terminada função. Quais são as alternativas que temos?
- Mudar a função para ela fazer um print toda vez que ela é executada, e toda vez que ela termina;
- Fazer um wrapper para essa função;
- Usar um decorator.
Vamos pensar em uma função bem simples:
def minhafunc(s):
____print "<< %s >> " % s
Como que poderiamos fazer o wrapper para esta função esta função? Por exemplo:
def wrapper(func):
____print "entrando na func!"
____ret = func()
____print "saindo da func!"
____return ret
result = wrapper(minhafunc()) Obviamente, isso funciona.. Mas para funções bem simples.
Um outro jeito seria transformar função automaticamente:
def logger(func):
def wrapper(param):
_____print "entrando na func!"
_______ret = func(param)
________print "saindo da func!"
________return ret
____return wrapper
minhafunc = logger(minhafunc)
E agora vem a parte “mágica”. Decorators simplesmente permitem com que você evite a transformação de python em LISP, tirando a necessidade de empacotamento explícito dessas funções. Em outras palavras:
@logger
def minhafunc():
...
faz a mesma coisa que:
minhafunc = logger(minhafunc)
só que logo após a declaração da função.
Só isso
. É claro, que tem várias outras utilidades os decorators – facilitar o uso de threads em PyGTK; facilitar desenvolvimento de código sincronizado, etc.
Sem falar que fica bem mais legível o código:
@synchronized
@logged
def minhafunc():
____....
P.S.: O wordpress, para variar, deixa zoado o código.. Mas logo-logo este site vai migrar para Django. Desde que aprendi a mexer com ele, a minha opinião sobre os frameworks web mudou.. e muito!


















