A simple way to print few line stuck to the same position

2011-06-02 Thread TheSaint
Hello
I studying some way to print few line in the console that won't scroll down.
If was for a single line I've some idea, but several line it may take some 
vertical tab and find the original first position.
I don't know anything about course module, some example will be highly 
apreciated.

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A simple way to print few line stuck to the same position

2011-06-03 Thread TheSaint
Steven D'Aprano wrote:

> def spinner():
> chars = '|/-\\'

Not exactly.
I'd like to show 4~6 line of report and refreshing periodically all of them, 
avoiding to scroll down.
example:

this count 50
Second time 90
following line 110
another line xxx

The lines should remain on their position and update their data.
I think, I should go for course module, but it's a bit of learning, which I 
didn't embarked yet.

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A simple way to print few line stuck to the same position

2011-06-04 Thread TheSaint
Hans Mulder wrote:

> A minimalist solution would be to print the labels ("This count", etc.)
> only once, and position the cursor after it to update the report.

Generally a good point. Similar sequences are working for coloring and 
formatting text. I don't know whether the program would behave to someone 
else who using not konsole like I do.

> The module is called "curses" and, yes, it would be the best way to go.

OK, I didn't understand if I must setup a window first in order to implement 
cursor positioning.
-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A simple way to print few line stuck to the same position

2011-06-07 Thread TheSaint
Hans Mulder wrote:

> If you use curses, you must initialize it by calling curses.initscr(),
> which returns a "WindowObject" representing the konsole window.  To
> put things on the screen, you call methods on this object.  Keep in
> mind that a "window" in curses jargon is just a rectangle inside
> your konsole window

I've learned great things from you. Thank you very much.
The curse window I could realize it immediately that it's a part of console 
screen, in curses module. Usually it's represented as blue box with some 
shadow effect :)
Deleting old writing it's another good point.
Actually, I reduced in a simplier solution with one line report :P. I'll 
look into curses for some better visual effects.
Playing with tabs (vertical and horizontal) I think it won't be a reliable 
method, unless when the position it would stick to the upper left corner of
 the console.

--
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


The pythonic way equal to "whoami"

2011-06-07 Thread TheSaint
Hello,
I was trying to find out whose the program launcher, but os.environ['USER'] 
returns the user whom owns the desktop environment, regardless the program 
is called by root.
I'd like to know it, so the program will run with the right privileges.

Is there any standard function on python, that will do it?
-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The pythonic way equal to "whoami"

2011-06-08 Thread TheSaint
Kushal Kumaran wrote:

> os.geteuid
This return 0 for *root* . I don't know if it's a standard for all distro.
Mine is Archlinux.
I'd just like to avoid error caused by wrong access by user

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The pythonic way equal to "whoami"

2011-06-09 Thread TheSaint
Christopher Head wrote:

> It is. Until Linux capabilities, EUID==0 used to be special-cased in the
> kernel

Thank you all, I got a good learning *and* something to rememeber.
-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Iterating into maildir or mbox

2011-06-09 Thread TheSaint
Hello,

originally with python 2.4 ~ 2.7 (I think) iterating a maildir I was using

++Code+
try:
mbox= mailbox.PortableUnixMailbox(open(mbox,'r'))
except IOError:
# if file not found default is None
mbox= None
 while mbox:
 msg= next(mbox)
 if msg is None: break
 try:
 m= msg.getheader('message-id')
 if m: dx= m.strip('<>')
 else: continue
 except (IndexError, AttributeError, IOError):
 # message without ID, put some mark
 dx= str(time.time()).split('.')
 dx= int(dx[0])*int(dx[1])
 if dx in lmbox:continue
 lmbox[dx]= dx
 return lmbox
++Code+

I'm tryng to convert into Python 3.2, but I don't get why this is not 
iterable anymore.


-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


(*args **kwargs) how do I use' em?

2011-06-10 Thread TheSaint
Hello,
I'm seldomly writng python code, nothing but a beginner code.

I wrote these lines >>

=
_log_in= mhandler.ConnectHandler(lmbox, _logger, accs)
multhr= sttng['multithread']
if multhr:
_log_in= mhandler.mThreadSession(lmbox, _logger, accs)

for svr in servrs:
nmsvr, user, pwd, ptcl = servrs[svr]
al, dn= sttng['Cfilter']; er= sttng['filter']
try:
 rx.append( _log_in.connect((nmsvr, user, pwd, ptcl, (al, dn, er
except ProtocolError:
 print(svr+ errors['SerProb'])
except KeyboardInterrupt:
raise SystemExit(errors['YouStop'])
if multhr:
for s in rx:
try: s.start()
except (ProtocolError, AttributeError):
print(svr+ errors['SerProb'])
except KeyboardInterrupt:
raise SystemExit(errors['YouStop'])
for s in rx:
try: s.join() # waiting all threads to finish
except (ProtocolError, AttributeError):
print(svr+ errors['SerProb'])
except KeyboardInterrupt:
raise SystemExit(errors['YouStop'])

=

Surely ugly and I believe that would be a better way to pass the arguments 
as I mention on the subject.
Then it should give a dictionary of keywords and some function or a 
callable. I don't know how to put down these code lines.
I think I should restructure many points of my data.

Any suggestion will make me happier :)


-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: (*args **kwargs) how do I use' em?

2011-06-11 Thread TheSaint
OliDa wrote:

> maybe some clarification about kwargs...
> 
> http://stackoverflow.com/questions/1098549/proper-way-to-use-kwargs-in-
python

Great point. Now it's clearer :)

I think I'll share the dictionary which contains the configuration loaded 
form a file.
-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Handling emails

2011-06-12 Thread TheSaint
Hello
I wrote a program which was working on python 2.x. I'd like to go for newer 
version but I face the problem on how the emails are parsed.
In particular I'd like to extract the significant parts of the headers, but 
the query to the servers had turned in to list of bytes.
What could be a method that will parse and return the headers into ascii if 
I'll pass the headers as bytes. Even I don't know whether I can pass as they 
arrive to the program.

For example if I try:

import poplib.POP3
_pop= poplib.POP3(srvr)
_pop.user(args[1])
_pop.pass_(args[2])

header =_pop.top(nmuid, 0)

This will return a list of bytes string and I don't have idea to process 
them in order to have a dictionary containing
'from', 'to', 'cc', 'bcc', 'date', 'subject', 'reply-to', 'message-id'
as keys.

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Handling emails

2011-06-12 Thread TheSaint
Steven D'Aprano wrote:

First of all: thanks for the reply

>> header =_pop.top(nmuid, 0)
 
> To parse emails, you should use the email package. It already handles
> bytes and strings.
I've read several information this afternoon, mostly are leading to errors. 
That could be my ignorance fault :)
For what I could come over, I decided to write my own code.

def msg_parser(listOfBytes):
header={}
for lin in listOfBytes:
try: line= lin.decode()
except UnicodeDecodeError:
continue
for key in _FULLhdr:
if key in line:
header[key]= line
continue
return header

listOfBytes is the header content, whuch id given by 
libpop.POP3.top(num_msg. how_much), tuple second part.

However, some line will fail to decode correctly. I can't imagine why emails 
don't comply to a standard.

> Other than that, I'm not entirely sure I understand your problem. In
> general, if you have some bytes, you can decode it into a string by hand:

I see. I didn't learn a good english yet :P. I'm Italian :)
 
 header = b'To: python-list@python.org\n'
 s = header.decode('ascii')
 s
> 'To: python-list@python.org\n'

I know this, in case to post the entire massege header and envelope it's not 
applicable.
The libraries handling emails and their headers seems to me a big confusion 
and I suppose I should take a different smaller approach.

I'll try to show a header (if content isn't privacy breaker) but as the 
above example the *_pop.top(nmuid, 0)* won't go into your example

> If this is not what you mean, perhaps you should give an example of what
> header looks like

The difference is that previous version returning text strings and the 
following processes are based on strings manipulations.
Just to mention, my program reads headers from POP3 or IMAP4 server and 
apply some regex filtering in order to remove unwanted emails from the 
server. All the filters treating IO as ascii string of characters.
 
I passed my modules to 2to3 for the conversion to the newer python, but at 
the first run it told that downloaded header is not a string.

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Deditor 0.3.0

2011-06-13 Thread TheSaint
Kruptein wrote:

> Deditor is a text-editor for python developers,

I'd like a editor that runs programs on trace and highlight the line(s) 
where it step into.
Obviously, if running at normale speed it will disable or if the speed is 
reduced it will works.

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Function within class and in modules

2011-06-15 Thread TheSaint
Hello
sorry, I'm bit curious to understand what could be the difference to pack up 
a class for some number of functions in it and a simple module which I just 
import and use the similar functions?
The only perspective that I think of is that class might instantiate a 
function several time. For my use I don't have multithread and mostly 
programs are sequencial.

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Function within class and in modules

2011-06-16 Thread TheSaint
Zach Dziura wrote:

> Just repeat this to yourself: Python ISN'T Java

I never had to do anything in Java. But mostly something in Sumatra :D
I'm getting the point that I'll need class very seldom.
Only to understand some more the use of self, whether I'll use a class.

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Composing regex from a list

2011-06-16 Thread TheSaint
Hello,
Is it possible to compile a regex by supplying a list?

lst= ['good', 'brilliant'. 'solid']

re.compile(r'^'(any_of_lst))

without to go into a *for* cicle?

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Composing regex from a list

2011-06-17 Thread TheSaint
Steven D'Aprano wrote:

> def compile_alternatives(*args):

Thank you all, for these good points. For my eyes seem that explicit or 
implicit it will take some looping to concatenate the list elements into a 
string.

I will see pypy later.

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What's the best way to write this base class?

2011-06-18 Thread TheSaint
John Salerno wrote:

> class Character:

I'd vote to point 1

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


How to iterate on a changing dictionary

2011-06-19 Thread TheSaint
Hello

Trying to pop some key from a dict while is iterating over it will cause an 
exception.
How I can remove items when the search result is true.

Example:

while len(dict):
   for key in dict.keys():
  if dict[key] is not my_result:
 dict.pop(key)
else:
   condition_to_break
print('Dictionary is over')

this is my mistake, but where to fix?
-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What would you like to see in a File Organizer ?

2011-06-19 Thread TheSaint
zainul franciscus wrote:

> we are looking for
> some ideas for good functionality for the application. T

I was looking for a file cataloger. this program may go into same category 
as far as handling file names ad file system's structures.
It also manage to store unused files into zipped archives and recall them 
transparently once the system is looking for it.

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to iterate on a changing dictionary

2011-06-20 Thread TheSaint
Lie Ryan wrote:

Thank you all for the information, really apreciated.

> While there are legitimate reasons for iterating a dictionary, I'd
> consider the alternatives first.

Perhaps the correct answer is in what you said.

For certain reasons, searching in a dictionary is the fastest method, 
secondly the positions of the data aren't relevant and easy to find.

My primer purpose is to know how much of work is done as soon the child 
process reports completion of a part. The order of the given jobs are not 
linear as it could do with a list.

To make an example: imaging Bingo.Shuffle the numbers, each number sorted 
should be removed from the container, how would it implemented?

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to iterate on a changing dictionary

2011-06-21 Thread TheSaint
Terry Reedy wrote:

> Other situations will need other solutions.
> 
Like a job's completion list.

Some number of workers get a job, and by time the caller sould know who and 
what has finished. Then a dictionary would hold number of remaining jobs.
Similar a downloading list.

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Emails backup in python 3.2

2011-06-21 Thread TheSaint
Hello,
I'm looking for an idea how to backup emails retrieved by poplib and save 
them into mailbox.mbox file.
The problem is the received message which is a list of bytes streams, 
mailbox.mbox don't expect a list.
What conversion should I do?
A file type io.StringIO ?
decoding every bytes stream which might not have any declared codec?

As far as python moved into unicode, why doesn't it handle these undecoded 
bytes as it was with strings before?

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Emails backup in python 3.2

2011-06-22 Thread TheSaint
Michael Hrivnak wrote:

> Do you have a special reason for wanting to implement
> your own email storage?

Learning python :)

It seems very easy to get my mails with the poplib help.
Usually I work with Kmail which imports mbox files.
I'm not prone to set up a SMTP server on my PC.

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


How to save a email message?

2011-07-02 Thread TheSaint
Hello,
I'm trying to gather some mail and save it. I don't get why it isn't saved 
as expected.

==

>>> import poplib, socket, sys
>>> from configparser import Error as ProtocolError
>>> args= sys.argv[1:] # this is fake but is here as example

>>> def Pop3_access(*args):
>>>'''Accessing a pop server, doing a function and return a result'''

>>>func= args[0]; args= args[1:]
>>>try:
>>>   pop= poplib.POP3(srv_info[0])
>>>   pop.user(srv_info[1])
>>>   pop.pass_(srv_info[2])
>>>except (poplib.error_proto):
>>>   raise ProtocolError
>>>except (socket.timeout,socket.gaierror):
>>>   try: pop.quit()
>>>   except NameError: pass # it wasn't started
>>>   return
>>>result= func(pop, args)
>>>pop.quit()
>>>return result

>>> def func(pop, N):
...return pop.retr(N)
...
>>> msg= Pop3_access(func, 4)
>>> from io import BytesIO as B
>>> fp= B()
>>> for l in msg[1]:
...fp.write(l)
...fp.write('\n'.encode())
...
34
1
50
1
63
1
65
1
36
1
52
1
41
1
114
1
45
1
38
1
74
1
56
1
37
1
34
1
28
1
23
1
33
1
56
1
57
1
17
1
44
1
31
1
54
1
30
1
30
1
0
1
31
1
0
1
39
1
0
1
12
1
32
1
49
1
0
1
6
1
64
1
68
1
0
1
>>> from mailbox import mbox as Mbx
>>> mbx= Mbx('/tmp/mb', True)
>>> mbx.add(fp)
0
>>> mbx.get_message(0)

>>> print(mbx.get_message(0))


>>>
===

The result is an empty message, but the fp.getvalue() shows file-like 
stream.
Am I missing some point?

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to save a email message?

2011-07-02 Thread TheSaint
Steven D'Aprano wrote:

Thank you very much.

> But if you seek back to the beginning:
> 
 x.seek(0)
> 0
 x.read()
> b'hello'
> 

Found the matter and *is* working
I discover another problem:
one message contains also a different encoding, but mostly it is not 
possible to represent that writing on the normale console output.

> 
> from mailbox import mbox as Mbx
> 
> raises eyebrow
> 
> Do you need to rename mbox? You don't even save a keypress:
> shift-m b x and m b o x both take 4 keypresses.

You stroke a right point :D
I could just use its own name

The code was not exactly run from the python shell. I was trying to make a 
*complete* picture from my module. In fact there aren't the arguments to 
access the pop server.
I'd like to mention that I've looked into the output file, which shows only 
"From MAILER DEAMON" + date of the action, but no message at all.

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: HOWTO: Parsing email using Python part1

2011-07-03 Thread TheSaint
aspineux wrote:

> Hope this help someone.
> 
Yeah
I will learn alot and surely applying to my code.

Merci Beaucoup
-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem!!

2011-07-04 Thread TheSaint
Irmen de Jong wrote:

> No, I misplaced my crystal ball.

I'm waiting mine, brand new in HD :D, with remote control :D :D

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Finding duplicated photo

2011-07-08 Thread TheSaint
Hello,

I came across the problem that Gwenview moves the photo from the camera 
memory by renaming them, but later I forgot which where moved.
Then I tought about a small script in python, but I stumbled upon my 
ignorance on the way to do that.

PIL can find similar pictures. I was thinking to reduce the foto into gray 
scale and resize them to same size, what algorithm should take place?
Is PIL able to compare 2 images?
 
-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding duplicated photo

2011-07-08 Thread TheSaint
Billy Mays wrote:

> It worked surprisingly well even
> with just the 64bit hash it produces.
> 
I'd say that comparing 2 images reduced upto 32x32 bit seems too little to 
find if one of the 2 portrait has a smile referred to the other.
I think it's about that mine and your suggestion are similar, but I'd like 
to scale pictures not less than 256x256 pixel.
Also to take a wider case which the comparison involve a rotated image.

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why the following python program does not face any concurrency problems without synchronize mechanism?

2011-07-10 Thread TheSaint
smith jack wrote:

>  have run this program for many times,and the result is always 5050
You might not need to make it in a multiprocess environment

Try it in the python (3) shell

>>> tot= 0
>>> for k in range(1,100):
...   tot += k
...   print(tot)
... 

And watch the risults.

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tabs -vs- Spaces: Tabs should have won.

2011-07-17 Thread TheSaint
Ian Kelly wrote:

> but if somebody later tries to edit the
> file using 8-space tabs

I came across this and I like to put a note on top of the script
to remember to modify it accordingly.


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Recommendations for household finance scripting?

2011-07-19 Thread TheSaint
markolopa wrote:

> I would like to find a good system to keep track of my household
> finance. Do Python programmers have suggestions on that? Do you use
> Python to help on this task?

libreOffice doesn't do it?

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list comprehension to do os.path.split_all ?

2011-07-29 Thread TheSaint
Alan Meyer wrote:

> This is not properly portable to all OS, but you could simply split on
> the slash character, e.g.,
> 
> pathname.split('/')

more portable  pathname.split(os.sep)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to solve it?

2011-08-02 Thread TheSaint
守株待兔 wrote:

> from matplotlib.matlab import *
maybe you didn't install it

http://matplotlib.sourceforge.net/

BTW you haven't mention what version of python you're running.


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: allow line break at operators

2011-08-10 Thread TheSaint
Yingjie Lan wrote:

> #the new way
> x = 1+2+3+4+ #line continues as it is clearly unfinished
> 
> 1+2+3+4
> 
Genrally I prefer this way.
> Of course, the dot operator is also included, which may facilitate method
> chaining:
> 
> x = svg.append( 'circle' ).

Dot-ended is to tiny thing that might cause oversights. *If* it'll be used 
as a secondary option I think it doesn't matter, otherwise *if* use as a 
compulsory writing mode I'd say it is pretty mistake prone.


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: indentation

2011-08-14 Thread TheSaint
Amit Jaluf wrote:

>  is it necessary indentation in python ?
> 
Try without and report it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: monitor mouse coordinates in real-time

2011-08-14 Thread TheSaint
Jabba Laci wrote:

> Could you please help me out how to close the application correctly?
> 
I think you should put a flag into the code, which the parent might modify 
it, so it will tell the child process to quit.
Then the flag should need to be read periodically to know whether is time to 
quit.

-- 
http://mail.python.org/mailman/listinfo/python-list


A suggestion for an easy logger

2011-05-07 Thread TheSaint
Hello,
I've resumed my hold project and I like to convert it for py3k2.
My knowledge has stagnated at version 2.4, then I found some improvements, 
but it will take me some time before I get used to.

I was using this logger >>
=
class log:
   """ It outputs lists and strings on file or any possible device that
   allows write mode. Options are: output file writing mode and special end
   of line (EOL)"""

   def __init__(self, output= None, mode= 'w', lsp= EOL):
   """ Can instantiate even no output is given. Choose to build an open file
   object to append to, or new and give a different line separator"""

  self.lsp = lsp
  self.output= output
  self.mode= mode
  try:  self.output= open(output, self.mode)
  except (IOError, TypeError): self.output = None

   def logger(self, strng, allowed=None):
  # without any output will simply send log to nowhere :-)
  if not allowed and not self.output: return
  # no allowed to write the output
  # keep silent even temporary skip writing
  # if allowed, it will go to stderr
  if isinstance(strng,list):
 a= EOL.join(strng)+ EOL
 strng = a
  strng= strng.replace(EOL,self.lsp)
  # when not allowed just return
  if allowed is None:   return
  if strng == '?close?':
 try: # try to close the file
self.output.close()
return
 except IOError: return # silently ignore the failure
  if self.output and Exists(self.output):
 self.output.write(strng)
  else:
 sys.stderr.write(strng)
 sys.stderr.flush()
  return

=

It is somehow convulitive, isn't it?
I do believe the builtin *print* would do more better than my logger.
Basically I would like a class which shoudl do:
1) print to stdout either with or without carriage return 
2) writing to a file
3) Skip some output

Everything should do according to the caller.
I didn't picked up the logging module, a way of confusion on my point of 
view. Some small example might easy my aberration :P

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What other languages use the same data model as Python?

2011-05-07 Thread TheSaint
Gregory Ewing wrote:

>  because modern architectures are so freaking complicated
> that it takes a computer to figure out the best instruction
> sequence

certainly is, I would not imagine one who writes on scraps of paper
:D :D :D

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A suggestion for an easy logger

2011-05-07 Thread TheSaint
Vinay Sajip wrote:

WoW :O , the creator !!

> import logging
> 
> logging.basicConfig(level=logging.DEBUG)

I'm getting there, but the result it's not what I would.
As far as I got to know, it should take to write a configuration file, which 
I still not aware of.
I'd like to just have the 4 conditions mentioned in the first post.
Once I'll get into the dirt I'll try to bring up also the other features 
that logging module gives.

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A suggestion for an easy logger

2011-05-07 Thread TheSaint
TheSaint wrote:

> I'd like to just have the 4 conditions mentioned in the first post.
> 
OK, my analysis led me to the print() function, which would suffice for 
initial my purposes.
Meanwhile I reading the tutorials, but I couldn't get how to make a 
formatter to suppress or keep the LF(CR) at the end of the statement.

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A suggestion for an easy logger

2011-05-08 Thread TheSaint
Vinay Sajip wrote:

8<
> For Python 3.2 and later, it's the terminator attribute of the
> StreamHandler. See:
8<
> Unfortunately, for earlier Python versions, you'd need to subclass and
> override StreamHandler.emit() to get equivalent functionality :-(
> 
I'm with 3.2 and willing to stay :)
I was trying
==code==
>>>logging.basicConfig(format='%(message)s',terminator='',level=logging.DEBUG)  
>>>  
>>> logging.debug('here we are')
DEBUG:root:here we are  
   
>>>  
==code==

First I didn't espect to see much more than my message. I agree that I'm 
very new to the module

Second the will terminator appear only to real stdout, or am I doing 
something incorrect?

Note: some word wrapping doesn't show the python shell correctly.

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A suggestion for an easy logger

2011-05-09 Thread TheSaint
Vinay Sajip wrote:

> logging.basicConfig(level=logging.DEBUG, format='%(message)s')

logging.basicConfig(format='%(message)s', level=logging.DEBUG)

I formulated in the reverse order of arguments, may that cause an 
unpredicted result?

The other points became clearer..

Once again
Thank You

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A suggestion for an easy logger

2011-05-10 Thread TheSaint
Vinay Sajip wrote:

> No, you can pass keyword arguments in any order - that's what makes
> them keyword, as opposed to positional, arguments.

I getting puzzled :)
==code==
myself@laptop-~> python
Python 3.2 (r32:88445, Apr 15 2011, 11:09:05) 
[GCC 4.5.2 20110127 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import logging, sys
>>> logging.basicConfig(level=logging.DEBUG, format='%(message)s')
>>> sh = logging.StreamHandler(sys.stdout)
>>> sh.terminator = ''
>>> logging.getLogger().addHandler(sh)
>>> logging.debug('here we are')
here we are
here we are>>> print(logging.__version__)
0.5.1.2
==code==

Terminator is removed, but as you stated it's doing double print-out
One more point is, if you'd have the time to look back to one of the first 
posts, that the leading *"DEBUG:root:"* doesn't show :-/
It's reported herein the version of Python and logging module's version.

For my thinking I'd go to look into the code and docs as well, to understand 
what I should do to have my 4 way of logging.
I repeat, I'm very new on using logging module, but I should go in that way, 
it isn't necessary to re-invent the wheel :).
Also I'd like to say that's only for my own learning, which I do as hobby.

-- 
goto /dev/null 
-- 
http://mail.python.org/mailman/listinfo/python-list


Py3k,email header handling

2011-05-11 Thread TheSaint
Hello,
some time ago, I wrote a program to eliminate undesided emails from the 
server(s) and leave those which comply to certain filter criteria.

I started it when I got to know whit Python 2.3. Now a days I'd like to 
spend some time to improve it, just for my interest, however it didn't 
gather anybody's interest before.
Now python 3.2 (and some version before) started to use byte, rather than 
text strings, almost for all data handling in compliance to unicode. My 
problem arise that my program handle text strings, so I'd like to rewrite 
the code

My program reads from IMAP4 or POP3 server, I'd prefer that a function/class  
will return either a list or a dictionary which contains the following 
fields:

'from', 'to', 'cc', 'bcc', 'date', 'subject', 'reply-to', 'message-id'

The list may be organized as tuple (from, its_content,), etc,etc for each 
field, but I think dictionary would be more efficient to use.

1) is there a way to call the IMAPlib or POPlib and pass the data directly 
to email.parser.HeaderParser to achieve my intention?

2) If the above will do, do re.compile compile unicode results?
I guess yes.

3) any related documentation...

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Py3k,email header handling

2011-05-11 Thread TheSaint
Steven D'Aprano wrote:

> Before you re-write it, you should run 2to3 over it and see how much it
> can do automatically:

Widely done, only the results from some query has radically changed on 
favour of unicode. Errors raising about results which are not strings 
anymore.
 
> I'm afraid I don't understand the question.

Making an example :

from poplib import POP3 as pop3
pop3.user('userid')
pop3.pass_('password')
numMsg, total = pop3.stat()
for cnt in numMsgs:
   header = pop3.top(cnt)
   # here I'd like to pass the header to some function that will return
   # a dictionary filling
   # from', 'to', 'cc', 'bcc', 'date', 'subject', 'reply-to', 'message-id'
   # keys, if nothing the leave empty string or None
   dict = email.header,decode_header(header) # but might not my result
   # Should I subclass this?

The same would be from the IMAP4 message parsing. Some different process 
would take, would it ?

> If you have any more concrete questions, please ask.

If these aren't concrete questions, forgive me, I perhaps got into wrong 
news group.
In the other and I hugely apreciated your clues. I'll see the docs some more 
long to achieve a clear learning.

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unicode by default

2011-05-12 Thread TheSaint
John Machin wrote:

> On Thu, May 12, 2011 2:14 pm, Benjamin Kaplan wrote:
>>
>> If the file you're writing to doesn't specify an encoding, Python will
>> default to locale.getdefaultencoding(),
> 
> No such attribute. Perhaps you mean locale.getpreferredencoding()

what about sys.getfilesystemencoding()
In the event to distribuite a program how to guess which encoding will the 
user has?


-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to install easy_install

2011-05-14 Thread TheSaint
rusi wrote:

>  tried to install easy_install (This is on windows)
> I downloaded the executable and ran it. It claimed to have done its
> job.

Perhaps, the abit to just click is disordering some easy steps like copy the 
script files into the normal place.
Only when there's a particular copy then it's the time to pay attention, 
like some executable and/or framework.
In the README.txt should mention these few easy steps

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Converting a set into list

2011-05-14 Thread TheSaint
Hello

I've stumble to find a solution to get a list from a set



>>> aa= ['a','b','c','f']
>>> aa
['a', 'b', 'c', 'f']
>>> set(aa)
{'a', 'c', 'b', 'f'}
>>> [k for k in aa]
['a', 'b', 'c', 'f']


I repute the comprehension list too expensive, is there another method?

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a set into list

2011-05-14 Thread TheSaint
Peter Otten wrote:

> mylist = list(myset)
> Do you notice the similarity to converting a list to a set?
> 
There was something confusing me yesterday in doing that, but (for me 
strangely) I got cleared out.

The point was that after a result from:

newset= set(myset1) & set(myset2)
list= [newset]

<< [{'bla', 'alb', 'lab'}]

Probably list(set) is not like [set].

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a set into list

2011-05-14 Thread TheSaint
Ben Finney wrote:

> Another method to do what?
> 
Sorry, some time we expect to have said it as we thought it.

The example was to show that after having made a set

set(aa)

the need to get that set converted into a list.
My knowledge drove me to use a comprehension list as a converter.
In another post I got to know the simplest way to state

list(aa)
Where aa is a set.

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Trace in a class

2011-05-14 Thread TheSaint
Hello,
first of all, I'm a dummy in programming. My methods are just do-it-and-try-
it.
For more convinience I commonly using  and go with step-into 
and breakpoints.
Lately I was setting a class, but it's incomplete and just calling it at the 
pdb prompt line I can't use breakpoints or stop it to check what values are 
coming into the play.

BTW, would it be much difference to use the class functions outside the 
class. I mean I don't declare the class statement just leave funtions alone 
in the module.

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a set into list

2011-05-15 Thread TheSaint
SigmundV wrote:

> I think the OP wants to find the intersection of two lists.
> list(set(list1) & set(list2)) is indeed one way to achieve this. [i
> for i in list1 if i in list2] is another one

Exactly. I was confused on that I wasn't able to have a list in return.
The set intersection is the smartest result better than a "for" loop or a 
comprehension list.
Infact the operatin loops are compiled into python, therfore they are the 
fastest.
-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a set into list

2011-05-15 Thread TheSaint
Chris Torek wrote:

> >>> x = ['three', 'one', 'four', 'one', 'five']
> >>> x
> ['three', 'one', 'four', 'one', 'five']
> >>> list(set(x))
> ['four', 'five', 'three', 'one']

Why one *"one"* has purged out?
Removing double occurences in a list?
-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a set into list

2011-05-15 Thread TheSaint
Steven D'Aprano wrote:

 s = set()
 s.add(42)
 s.add(42)
 s.add(42)
 print s
> set([42])

Good to know. I'll remember it

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a set into list

2011-05-16 Thread TheSaint
Thomas Rachel wrote:

> Which loops do you mean here?

list(set) has been proved to largely win against
list = []
for item in set:
list.append(item)
or [list.append(item) for item in set]

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


how to get PID from subprocess library

2011-05-19 Thread TheSaint
hello,

I'm using to launch a program by subprocess.getstatusoutput. I'd like to 
know whether I can get the program ID, in order to avoid another launch.

For clarity sake, I'm calling aria2 (the download manager for linux) and I 
wouldn't like to call one more instance of it. So what will I use to find 
the PID of the launched program?

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to get PID from subprocess library

2011-05-20 Thread TheSaint
Miki Tebeka wrote:

> The best module for doing such things is subprocess. And the Popen object
> has a pid attribute

I knew that, it's my fault that I'm not good to manage with popen. I found 
simplier to use subprocess.getstatusoutput. Maybe this function doesn't 
return the child pid, so I should adopt to work with Popen :(

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to get PID from subprocess library

2011-05-21 Thread TheSaint
Kushal Kumaran wrote:

> That's how it is able to give you the status.  So, if you
> are using getstatusoutput, you will have only one instance of your
> command running.

My intent is to launch only one program instance, which will goes as daemon.
To avoid a second call I'd like rather to use Python than 
==code=
def start(self):
'''try to start aria2c as a daemon and return its handle to where it 
can
proceed to issue commands'''

# aria2c is running, then don't try it again
if (chkout('ps -A |grep aria2c')[0] > 0):
try:
chkout(self.ARIA_CMD)
except:
raise SystemExit('aria2c is not working as deamon')
elif self.handle: return self.handle
# everything is good, it will return an handle
self.handle= \
xmlrpclib.ServerProxy('http://localhost:%s/rpc' %int(self.numport))
return self.handle
==code=

Here I've named subprocess.getstatusoutput as chkout, I'm calling 2 more 
programs to find whether there's a running instance of aria2c. I think it's 
not nice, python libraries should get the matter done.

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to get PID from subprocess library

2011-05-22 Thread TheSaint
Kushal Kumaran wrote:

> You could look for a way to make aria2c not become a daemon and use
> subprocess.Popen to start it.  That gives you the PID and ways to see
> if the process is still running

I see. It's a step that I've to get on my account. Unfortunately I'll have 
to study it some more.

BTW. I removed grep from the command. Python does it with the *in* statement 
:)


-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to get PID from subprocess library

2011-05-23 Thread TheSaint
GMail Felipe wrote:


> For the "ps" command, have you seen the psuti module?
> 
> The link to it is: http://code.google.com/p/psutil/

You gave a brand new start :)
I bit of additional program to include into the package ;)

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to get PID from subprocess library

2011-05-24 Thread TheSaint
Anssi Saari wrote:

> Couldn't you just try to call something via this handle, like
> self.handle.aria2.getVersion()? If there's an error, then start aria2
> as a daemon and try again.
> 

Very good, you're right. Furthermore I should avoid to call that function 
several times. I think to join it with __init__ function
The program on exit must tell aria2c to quit.

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


How to catch a line with Popen

2011-05-28 Thread TheSaint
Hello.
I'm looking into subprocess.Popen docs.
I've launch the program with its arguments and that's smooth. I'm expecting 
to read the output by *comunicate()* at every line that prgram may blow 
during the process, but the output is given only when the child process is 
ended.
I'd like to process the lines to display an information in percentage during 
the running time of the child. Sorry but I'm poor of know-how, so I'm stuck 
over to find a clue.

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to catch a line with Popen

2011-05-29 Thread TheSaint
Tim Roberts wrote:

> Are you specifying a buffer size in the Popen command?  If not, then the
> Python side of things is unbuffered

The buffer is as per default. The program reports one line around 1/2 second 
time.
I think I'll look into the option as Nobody states:

p = subprocess.Popen(...)
for line in p.stdout:
...
p.wait()

It is strange that would take a for cycle, rather than catching the line on-
the-fly. I can judge it now, I'm going to try it out.

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to catch a line with Popen

2011-05-29 Thread TheSaint
Chris Rebert wrote:

> What do you mean by "on-the-fly" in this context

I just suppose to elaborate the latest line, as soon it's written on the 
pipe, and print some result on the screen.
Imaging something like

 p= Popen(['ping','-c40','www.google.com'], stdout=PIPE)
 for line in p.stdout:
 print(str(line).split()[7])

I'd like to see something like *time=54.4*
This is just an example, where if we remove the "-c40" on the command line, 
I'd expect to read the latest line(s), until the program will be killed.

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to catch a line with Popen

2011-05-29 Thread TheSaint
TheSaint wrote:

> I just suppose to elaborate the latest line, as soon it's written on the
> pipe, and print some result on the screen.

I think some info is also here:
http://alexandredeverteuil.blogspot.com/
-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to catch a line with Popen

2011-05-30 Thread TheSaint
Chris Torek wrote:

> In at least some versions of Python 2

I'm with P3k :P. However thank you for your guidelines.
Last my attempt was to use a *for* p.wait() , as mentioned earlier

That looks good enough. I noted some little delay for the first lines, 
mostly sure Popen assign some buffer even it is not set.

Haven't you try a perpetual ping, how would be the line_at_a_time ?

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to catch a line with Popen

2011-05-31 Thread TheSaint
Chris Torek wrote:

> Since it is a generator that only requests another line when called,
> it should be fine
Is it, then, that until the new itaration, the callee is on pause?

-- 
goto /dev/null
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Filter class

2006-10-07 Thread TheSaint
On 17:02, sabato 30 settembre 2006 TheSaint wrote:

> Hello NG,
> 
> Curious to know whether exists a filter class.
> I'm doing some rough mail filtering on my own criteria, but I'm very new on
> programming and I like to find some clue on passing a config file of rules
> which will be regex by Python.
> 
> TIA

I went to study some long and I developed a small program, herebelow.
But I'd appreciate if it vill come some suggestion for a pythonic cosmetic
fashion :)

Thank to everybody.

+
#! /usr/bin/env python
"""" Test the mailserver to clean unwanted mail"""

from poplib import POP3
import ConfigParser , sys , os , re
MULTILINE = 8

def call_POP(args):
if len(args) != 4: return
for cnt in range(len(args)):
if args[cnt] =='' or args[cnt] == None : return
a = POP3(args[0])
a.user(args[1])
print 'Server %s reply %s' %(args[0], a.pass_(args[2]))
(numMsgs, totalSize) = a.stat()
msg9 = ''
for i in range(1, numMsgs +1):
for hdrline in a.top(i,0)[1]:
for argmn in args[3]:
if not re.search(argmn[1], hdrline): continue
lsenty = 0
if argmn[0].startswith('a') and not argmn[0].startswith('d'):
continue
#list only the messages that aren't matching
if lsenty == i: continue # no duplicate messages
fwrt.write('Msg No %03d\nTEST  "%s" \n %s\n' \
  %(i,argmn[1], hdrline))
lsenty = i
fwrt.write('\n\n')
a.quit()

def get_mydir(file):
if os.name == 'posix':
adir = os.path.split(file)[0]
afil = os.path.split(file)[1]
if adir == '': adir = os.getcwd()
for pth in ('~/', '$HOME/'):
if pth in adir: adir = os.environ['HOME']
file = adir + '/' + afil
if not os.path.exists(file):
print 'Configuration file not found'
return 0
return file

if len(sys.argv) != 3:
print 'Incorrect  Number of arguments!'
sys.exit(0)
infil = get_mydir(sys.argv[1])
if not infil: sys.exit(0)
opnfil = sys.argv[2]
fwrt = open(opnfil,'w')

cfg = ConfigParser.ConfigParser()
cfg.read(infil)
infil = ''
fltr = 'Filters'
if  fltr in cfg.sections():
infil = cfg.items(fltr)
for section in cfg.sections():
if section.lower() in ('setting', 'filters'): continue
adir = 0
afil = {}
for pth in ('server', 'user', 'pass'):
afil[adir] = cfg.get(section, pth)
adir += 1
afil[adir] = infil
print 'Now trying to connect to ' + section
call_POP(afil)
fwrt.close()

+

Also the config File enclosed (some detail is obscured for obvious purposes).

==
[Jaring]
PASS = xxx
USER = w
SERVER = e

[Vodafone]
SERVER = popmm
USER = godddllr
PASS = rrettt

[TMnet]
SERVER = fgotee
USER = gggrrdfng
PASS = rrro

[YahooIt]
SERVER = ffpogakfbmb
USER = fglkfrtrtthajl
PASS = fg8uarewaehueh

[Setting]
#All section is not impemented. It's supposed to give either a filepath or
# none
LOG = no
# obviously how much we want to know about the process
VERBOSE = 3
# Some case we won't need errors from python and let the matter die as is
SWALLOW_ERR = yes
# some implementation of threading to have the way to log on
# all the server in parallel
PARALLEL = yes

[Filters]
# A = Allow (anything which starts with "a" is filtered as allowed)
# to keep as good.

A01 = ^From: .*\.cz
A02 = ^(To|Cc): .*w
A03 = ^(To|Cc): .*godddllr@
A04 = ^(To|Cc): .*fglkfrtrtthajl@
A05 = ^(To|Cc): .*122951205u@
A06 = ^From: .*\.my

# D = Deny (anything which starts with "a" is filtered as denied) and will
# fill the list for deletion.

D01 = ^From: .*\.com\.my
D02 = \*\*\*SPAM\*\*\*
==

Let me say that is an experimental program for learning purpose, yet. More
things should be implemented like :
1 Real deletion for those email listed in the report file.
2 a single group pattern for the regex search
3 Logging errors and all functions mentioned in the "Setting" section.
4 last but not least a GUI.

The idea was born when i was looking for the "mailfilter" package for Arch
Linux. Actually has been retired. Then I tought " It would be good if a
platform indipendent program will do the same job or a bit more".

Testing on win32 platform is good help.
So, if somebody like to join, very welcome for all of the possible chances,
please try to contact me at _fulvio AT tm DOT net DOT my_.

Fulvio
-- 
http://mail.python.org/mailman/listinfo/python-list


Very newbie programming

2006-06-10 Thread TheSaint
Hello!

Is there a more pythonic way to implement the following program:

8<--8<--8<--8<--

#! /usr/bin/env python

import os
import sys
a = os.listdir('/media')

# no mount dirs were found, exit nicely

if len(a) == 0:
sys.exit(0)

# Maybe collecting the arguments via command line
# will make the program more flexible

mnt = open("/etc/mtab")
ptn = open("/proc/partitions")
dskt = '/home/user/Desktop/'

c =[]

# Filling the c with the list of devices which are recorded to be mounted

d = filter((lambda a: a[:2] =='/d'),mnt.readlines()) # non /dev-mounts are
off
d = map((lambda a: a.split()[:1]),d) # only the first info column is used

[c.append(str(a)[2:-2]) for a in d]

# checking against /proc/partitions to see if there're mountpoints without
# corresponding partition which has been removed from the list
#  ALL mountpoints with available partition will be removed from the list

x = ptn.readlines()
for a in x[2:]:
b = a.split()[-1]
for d in c:
if b == d.rsplit('/',1)[-1]:
c.remove(d)

if len(c) != 1:
sys.exit(0) # if none or more than one match exit

cmnd = str(c)[2:-2]
err = os.system('umount ' + cmnd)
a = os.listdir(dskt)

#retrieve the info from the KDE desktop icons

for i in a:
if 'desktop' not in i: continue
y = open(dskt + i)
d = y.readlines()
for x in d:
if 'URL=/media' not in x: continue
icon = i
dvc = x[11:-1]
break

err += os.system('rm -f ' + dskt + icon)
err += os.system('rmdir /media/' + dvc)
sys.exit(err)
# if something went wrong exit with high number
8<--8<--8<--8<--

I still have a long learnig curve, please give some advise in order to make
the program a bit faster o nicer :)

F
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Very newbie programming

2006-06-10 Thread TheSaint
Maric Michaud wrote:

> Le Samedi 10 Juin 2006 17:44, TheSaint a écrit :

>>
> begin using more explicit variable names.

Frankly it's a very rooted way of programming, since C64 basic :-)

A part of this, how python catch variables, the longer the slower, isn't it?
Even supposing to use a set of similar name of variables.
Of course nowadays this operations ending up in term of msecs. I still be
used in old fashion. I'll change it by the time of necessity.

> and I generally avoid creating names I use only once, so :
> 
> if not os.listdir('/media') :

Great idea and common sense :-)


> There more expressive or more direct ways of doing all these, I like one
> liners (but a two steps can be more clear) :

I like the clearer. I think python does it as we would think it off.

>> x = ptn.readlines()
> 
> this time we cut in two steps but this also just filtering.

I found the bothering of having to remove the trailing LF "\n". Perhaps need
some new function to strip the last LF, for all of the files opened.

>> if len(c) != 1:
>> sys.exit(0) # if none or more than one match exit
>>

> why ?
> 
> os.system('umount "%s"' % devices[0])

I wasn't able to handle more than one mount a time. Furthermore, the script
is executed every minute in a cron schedule. I don't expect to remove
devices in so fast fashion :-)
BTW, this operation is necessary because the kernel doesn't do it on its
own, for pendrives and Compact Flash into PCMCIA socket. (Kernel 2.6.15
actually)
One more point, suppose to use multiple removal, how will it remove also the
icon(s) from the KDE desktop?
Good to applying myself on studying on it :-)

> this will do exactly  the same
> 
> for icon_file in (open(dskt + e) for e in os.listdir(dskt) if '.desktop'
> in e) :
> for line in icon_file :
> if  'URL=/media' in line :
> icon = icon.name
> dvc = line[11:-1]
> break
> 
A simple question, how do I'll get out of all loops, once found the right
result?

F

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Very newbie programming

2006-06-11 Thread TheSaint
Maric Michaud wrote:

> Le Samedi 10 Juin 2006 17:44, TheSaint a écrit :
> devices = [ e for e in devices if e.split('/')[-1] in partitions ]

This is _not_ the expected result :)

is missing a not as :
devices = [ e for e in devices if e.split('/')[-1] *not* in partitions ]

>> if len(c) != 1:
>> sys.exit(0) # if none or more than one match exit
>>
>> cmnd = str(c)[2:-2]
>> err = os.system('umount ' + cmnd)
> 
> why ?
> 
> os.system('umount "%s"' % devices[0])

> for line in icon_file :
> if  'URL=/media' in line :
> icon = icon.name
> dvc = line[11:-1]
> break

The question is correct, I should go a step further. But as it will unmount
multiple (ghost) partitions it should also remove the icons from the
desktop as well. So I'm bit confused how to remove *each* icon, unless do
it into the "for" loop.
I'd like to get the search as fast as possible and solve the appropriate
icon with the right device, after all :)
Suppose to have the pendrive and the Compact Flash, which both are mounted
in /media, what will be removed syncronized with its mount?
I didn't get this problem so deep as long as I just considered to use one
device at time.

F

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Very newbie programming

2006-06-11 Thread TheSaint
George Sakkis wrote:

> 
> If by 'rooted' you mean old enough, so is 'goto'... 

I was meaning a sort of (very) old style of programming. In fact I wrote
some few hundreds lines on my own, but probably memory was much better
the :)

> will 
> thank yourself for doing so if you have to go back at this code a few
> months later.

I have to admit that's purely true :)
 
> You can set a boolean "found" flag to False, make it True in the if

Thank you to point it out, I forgotten such solution. BTW I was on the way
of an "try/exept". But I should go back study the corect use :)

> from fileinput import FileInput

I'll read the manual (as you pointed hereby) and I think I can read the
entire directory file by file.

> Btw, you can delete a file or directory with os.unlink and os.rmdir,
> respectively; no need for os.system.

I still on learning, you know? :)
Reading is the way to solve some problem, and your suggestions (you all) are
very precious.

F
-- 
http://mail.python.org/mailman/listinfo/python-list


Linux info

2006-06-13 Thread TheSaint
Hello there,

I still learning, but I couldn't find anything which tells me where a
symlink is pointing to.
A part of os.system('ls -l ' + path) and cutting down to the need, I haven't
got any specialized function.

F
-- 
http://mail.python.org/mailman/listinfo/python-list


Filter class

2006-09-30 Thread TheSaint
Hello NG,

Curious to know whether exists a filter class.
I'm doing some rough mail filtering on my own criteria, but I'm very new on
programming and I like to find some clue on passing a config file of rules
which will be regex by Python.

TIA
-- 
http://mail.python.org/mailman/listinfo/python-list


Publish a program

2008-05-21 Thread TheSaint
Hello,

I'm not a master of python :) If I would publish my program for reviewing,
where should I upload it?


--
http://mail.python.org/mailman/listinfo/python-list


Re: Publish a program

2008-05-21 Thread TheSaint
On 18:15, mercoledì 21 maggio 2008 alex23 wrote:

> On May 21, 7:52 pm, TheSaint <[EMAIL PROTECTED]> wrote:

> There's also http://python.pastebin.com, which lets you create a new
> paste by modifying an existing one, and keeps them linked for easy
> diff'ing.
> 
> Sample: http://python.pastebin.com/d3964b241

Thank you for the reply :)
In my case, it's rather a set of modules which trying to remove spam from the
mailbox(es) either by POP3 or IMAP4 according regex criteria.
The project is working quiet good, the most advantage is that it downloads
only the header for speed needs. Some time I'm doing it by GPRS in roaming
and volume it _matters_ much.
I simply like that somebody will express some opinion about my job, as
meaning of teaching me better. After all that's what I'm trying to do ;)

Other idea, I'll apreciate somebody to join and put new views on this
project.



--
http://mail.python.org/mailman/listinfo/python-list

Re: how to proccess the blank in the path on linux

2008-05-22 Thread TheSaint
On 22:26, mercoledì 21 maggio 2008 zhf wrote:

> I want ro walk a directory and its sub directory on linux

os.path.walk() should do the job.
Recursively you should try this, which I found on some web site:

8<-8<-8<-8<-8<-8<-

def file_find(folder, fname):
"""search for a filename fname starting in folder"""
for root, dirs, files in os.walk(folder):
for file in files:
# make search case insensitive
if fname.lower() == file.lower():
return Path.join(root, fname)

8<-8<-8<-8<-8<-8<

Definitely I don't know about path with spaces or Unicode file names.


--
http://mail.python.org/mailman/listinfo/python-list

Re: Publish a program

2008-05-22 Thread TheSaint
On 22:32, mercoledì 21 maggio 2008 [EMAIL PROTECTED] wrote:

>> appreciate somebody to join and put new views on this project
> 
> Send us a link to one of the sites with your code, eg.
> http://python.pastebin.com
 
Thank you!
Go to : http://it.geocities.com/call_me_not_now/index.html
--
http://mail.python.org/mailman/listinfo/python-list

Re: Publish a program

2008-05-22 Thread TheSaint
On 10:48, giovedì 22 maggio 2008 alex23 wrote:

> Have you thought about putting the full project somewhere like
> http://code.google.com/ ?

Greatly apreciated your suggestion, unfortunately I saw it a bit late ;)

My project is available at http://it.geocities.com/call_me_not_now/index.html

I like if somebody will help me to build a GUI. I've look at Eric but I
didn't feel comfortable with, perhaps BOA or the like would give me the
right tools to build a graphic interface.
I'd like something that for the given shapes/widgets will gives the python
code respectively.


--
http://mail.python.org/mailman/listinfo/python-list

Re: Assignment and comparison in one statement

2008-05-23 Thread TheSaint
On 06:59, sabato 24 maggio 2008 Johannes Bauer wrote:

> However, this "assignment and comparison" is not working. What's the
> "Python way" of doing this kind of thing?

If you want speak a language that isn't understood mostly you'll face
unexpected risults.
When you got started with C/C++, were you writing plain english to do
programs?
Far away to be a flame, each language have its own grammar that some time it
will need to be learnt.
Therefore, even myself still bad to write english, since my mind thinking
italian sentences.

--
http://mail.python.org/mailman/listinfo/python-list


Re: Assignment and comparison in one statement

2008-05-25 Thread TheSaint
On 19:14, sabato 24 maggio 2008 Johannes Bauer wrote:

> Well, I do not really see your point
You wrote C statements and I felt that you were trying to apply to python
interpreter.
I think that a minimun of knoweledge on python grammar it's the base for
doing some programming.
If your examples were there only to explain your meaning, then I'm wrong
here.

--
http://mail.python.org/mailman/listinfo/python-list


Re: graphical ide??

2008-05-28 Thread TheSaint
On 19:48, martedì 27 maggio 2008 Alex Gusarov wrote:

> I tried Eric (on windows), but then decided in favour of Eclipse +
> PyDev.

I'm a KDE fan :) and I like Qt design. I've Qt designer installed, but I much
like if I can use an IDE which write python code, rather than wrappers.

I've just been disappointed by Boa Constructor, it disappeared suddenly while
trying some test.
Which other SDK write in python code?


--
http://mail.python.org/mailman/listinfo/python-list

File browser in python gui

2008-05-31 Thread TheSaint
hi there,

I've started to build a GUI for my Mailsweeper by the help of QT4 Designer.
I came across the problem that there isn't any prebuild file browser like
Kdialog.
I know some other sample, but PyGTK builded. I'm not happy to use a different
widget set or to have to design my own file browser with QT4 widgets. 
It's almost thousand times people need to use such browser, I wonder why I
couldn't find one on the entire day searching on web site.
A QT XML file (.ui extension) should do fine, if someone would help :)

-- 
Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: File browser in python gui

2008-05-31 Thread TheSaint
On 22:39, sabato 31 maggio 2008 Sebastian 'lunar' Wiesner wrote:

> What about QtGui.QFileDialog?

Yeah! Thank you!
So strange that I was looking for all around and it was already in my
computer.
I'm gonna back to study a little function that will return an existing/new
file or None (if Cancel is pressed)
-- 
Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: SMS sending and receiving from website?

2008-05-31 Thread TheSaint
On 22:01, sabato 31 maggio 2008 globalrev wrote:

> also, lets say i want to send a SMS to my own phone from the internet.
> how would i do that?

IMO, nowadays free SMS sending, via internet, is gone. There should be the
chance from one's own subscribed network.
-- 
Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: File browser in python gui

2008-06-01 Thread TheSaint
On 02:48, domenica 01 giugno 2008 TheSaint wrote:

> I'm gonna back to study a little

I'm facing tough time, I can't get clear by Trolltech's C++ examples.
I'm a bit puzzled :), I'd like to remain with the QT widget set, but hard
learning curve.
Other simplified developing TK are giving different widgets, I don't expect
to mix up :(

-- 
Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: [Business apps for Windows] Good grid + calendar, etc.?

2008-06-01 Thread TheSaint
On 19:59, domenica 01 giugno 2008 Gilles Ganault wrote:

> require rich widgets like (DB)grids, calendars, etc.

Qt seems to go a bit further. Try Eric4 as SDK.
-- 
Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html
--
http://mail.python.org/mailman/listinfo/python-list


Shed my a light :)

2008-06-02 Thread TheSaint
Hi,
I using eval for quite strange reason, as long as I don't know a different
way to implement.

An example:

actions= ('print', 'sum', 'divide', 'myfunction')
parameters=(5, 'nothing',5.63, object)

for routines in actions:
 routines(parameters)

I'd like to note that actions are string or string expressions of the program
functions or python itself, so I've in my program something like:

for nn in actions:
   eval('cp.%s' %nn)

Where cp is an instance.

So I'm asking here whether exist a way that these string become functions
inside my program, without using eval()

-- 
Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: Shed my a light :)

2008-06-02 Thread TheSaint
On 19:06, lunedì 02 giugno 2008 Chris wrote:

>> actions= ('print', 'sum', 'divide', 'myfunction')
>> parameters=(5, 'nothing',5.63, object)

8< 8<
> getattr(...)
> getattr(object, name[, default]) -> value
8< 8<
> for nn in actions:
> func = getattr(cp, nn)
> if callable(func):
> func(parameters)
I got the point of Duncan and I should remain on evail() because the
evaluation is made on a construct of string expression, which give me the
final name of the function I want to call.
I've tried on Pyshell and clearly said the object str is not callable.

Some of those string are functions inside the module, so I was expecting a
sequence of calls according the passed in functions names, but they *must*
be processed as a python statements ;(

-- 
Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html
--
http://mail.python.org/mailman/listinfo/python-list

Re: Shed my a light :)

2008-06-02 Thread TheSaint
On 22:00, lunedì 02 giugno 2008 Paul Melis wrote:

> This doesn't exactly make sense, as what you want isn't really clear...
Sorry, I'm bad to express my toughts even I my nature language :)
I'll give a go to getattr() and see whether the results come in my taste :)

-- 
Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html
--
http://mail.python.org/mailman/listinfo/python-list

Re: Formatting Output

2008-06-03 Thread TheSaint
On 06:15, martedì 03 giugno 2008 Mensanator wrote:

> In Access, I create a query with this SQL:
But this isn't python itself.
I'd like to see a small function to let 'locate' the cursor into a TTY
console. Surely it can't scroll.
If it is not possible, then ncurses is the way. I don't know if it works on
win32.

-- 
Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html
--
http://mail.python.org/mailman/listinfo/python-list

Re: ConfigObj quoting issues

2008-06-03 Thread TheSaint
On 14:25, martedì 03 giugno 2008 Roopesh wrote:

> This error is because of the presence of \', \", \n etc.
> 
> I had to do the following to make it work.
> address[i].replace("\'",'').replace('\"','').replace('\n','')
> 
it's rather ugly :)
I suggest use re module as follow:

import re
address[i] = re.sub('(`|"|\n)',re.MULTILINE,address[i])

if you've a big chunck of email it'd be fine to compile the regex.

match = re.compile(`|"|\n)
address[i] = match.sub(address[i])

I think there would be a problem with unicode email addresses. But I doubt
the existance of unicode addresses nowadays.
Unsure for the syntax, pls check
http://www.python.org/doc/2.4/lib/re-syntax.html
  ^^^ according your version, but they're quite the
same

-- 
Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html
--
http://mail.python.org/mailman/listinfo/python-list

Re: Python doesn't understand %userprofile%

2008-06-10 Thread TheSaint
On 00:11, mercoledì 11 giugno 2008 Tim Golden wrote:

> "%USERPROFILE%/dir/file".

os.environ('USERPROFILE') should return an info regarding that environment
variable.
I guess that, not yet tried.
-- 
Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html
--
http://mail.python.org/mailman/listinfo/python-list

My fight with classes :)

2008-06-11 Thread TheSaint
Hi,
I'm very new with classes. I still reading something around ;)

I got started to try a concatenation of 2 type of string, which have a
particular property to start with A or D.

My class here:
""" Small class to join some strings according to the leading first
 letter"""

def __init__(self):
self.valueA= ''
self.valueD= ''

def __add__(self, value):
if not isinstance(value, str): return
if value.lower().startswith('a'):
self.valueA += value
if value.lower().startswith('d'):
self.valueD += value
return self.valueA ,self.valueD

__call__= __add__
__iadd__= __add__

my test on the shell:

>>> from utilities import StrJoin as zx
>>> k= zx()
>>> k

>>> k +'aks'
('aks', '')
>>> k +'daks'
('aks', 'daks')
>>> k +'hdaks'
('aks', 'daks')
>>> k +'dhks'
('aks', 'daksdhks')
>>> j('boi')
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'j' is not defined
>>> k('boi')
('aks', 'daksdhks')
>>> k('aboi')
('aksaboi', 'daksdhks')
>>> k('duboi')
('aksaboi', 'daksdhksduboi')
>>> k += 'liu'
>>> k += 'aliu'
Traceback (most recent call last):
  File "", line 1, in 
TypeError: can only concatenate tuple (not "str") to tuple
>>> k
('aksaboi', 'daksdhksduboi')

Do I miss something?

I'd rather like to avoid class, but a function won't allow me to store so
easily data between several call.
Mostly I'd expect to pass to the built instance in a more elaborated
function. Then I mean call will be the primer goal.

-- 
Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: can't assign to literal

2008-06-11 Thread TheSaint
On 16:47, mercoledì 11 giugno 2008 Chris wrote:

> SciTE and Notepad++
Pype, spe, just to point it out. Jedit, but rather a bloatware.
I'd like to know which is the litest multi platform and indipendent.
Pype is very good when compiled in exe, but not doing in Linux in that way.

-- 
Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html
--
http://mail.python.org/mailman/listinfo/python-list

Re: catastrophic regexp, help!

2008-06-11 Thread TheSaint
On 12:20, mercoledì 11 giugno 2008 cirfu wrote:

> patzln = re.compile("(\w* *)* zlatan ibrahimovic (\w* *)*")

I think that I shouldn't put anything around the phrase you want to find.

patzln = re.compile(r'.*(zlatan ibrahimovic){1,1}.*')

this should do it for you. Unless searching into a special position.

In the other hand, I'd like to understand how I can substitute a variable
inside a pattern.

if I do:
import os, re
EOL= os.linesep

re_EOL= re.compile(r'[?P\s+2\t]'))

for line in open('myfile','r').readlines():
   print re_EOL.sub('',line)

Will it remove tabs, spaces and end-of-line ?
It's doing but no EOL :(

-- 
Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html
--
http://mail.python.org/mailman/listinfo/python-list

Re: can't assign to literal

2008-06-11 Thread TheSaint
On 00:15, giovedì 12 giugno 2008 Ethan Furman wrote:

> I like Vim (Vi Improved)
What about justifying text ?
-- 
Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html
--
http://mail.python.org/mailman/listinfo/python-list

Re: can't assign to literal

2008-06-11 Thread TheSaint
On 01:37, giovedì 12 giugno 2008 Ethan Furman wrote:

> Do you mean indenting, or wrapping?
I mean fill the line by increasing spaces between words in order to get a
paragraph aligned both side, left and right on the page.
So if the width is 78 chars it wouldn't have jig saw end to the right side,
unless applying some word hyphenation.
This feature would be nice for writing here and some plain documentation
plain text. Beside that it might doing for Python scripts as well.

-- 
Mailsweeper Home : http://it.geocities.com/call_me_not_now/index.html
--
http://mail.python.org/mailman/listinfo/python-list

  1   2   >