Reading compressed files

2007-02-21 Thread Shadab Sayani
Hi,
  I have compressed files compressed using different techniques  (especially 
unix compress). So I want to have a module that reads any  of these 
(.Z,.bz,.tgz files) files and manipulates the data.
  The data has a syntax.It contains
  HEADER (some information)
  BODY  (some information)
  FOOTER   (some information)
  If it were a normal text file I can get the values corresponding to HEADER 
BODY and FOOTER by open function.
  But here the files are in different format .Z , .bz ,.tgz,.gz .But I  know 
these are the only formats.Also I cannot rely upon the extensions  of the file 
(a .Z file can have no extension at all).Is there a way to  identify  which 
file am I reading and then  read it?If so how  to read it?
  Thanks and Regards,
  Shadab.
  
 Send instant messages to your online friends http://uk.messenger.yahoo.com -- 
http://mail.python.org/mailman/listinfo/python-list

Re: Regex Speed

2007-02-21 Thread Pop User
[EMAIL PROTECTED] wrote:
> While creating a log parser for fairly large logs, we have run into an
> issue where the time to process was relatively unacceptable (upwards
> of 5 minutes for 1-2 million lines of logs). In contrast, using the
> Linux tool grep would complete the same search in a matter of seconds.
>   
Its very hard to beat grep depending on the nature of the regex you are 
searching using. The regex engines in python/perl/php/ruby have traded 
the speed of grep/awk for the ability to do more complex searches.

http://swtch.com/~rsc/regexp/regexp1.html

This might not be your problem but if it is you can always popen grep.

It would be nice if there were a Thompson NFA re module.

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


BDFL in wikipedia

2007-02-21 Thread Jorge Vargas
Hi I just hit this page in wikipedia BDFL[1]

and it redirected me to Guido's wikipedia[2] entry
now without causing any troubles (read flamewar) shouldn't

a) that page have an explanation of what BDFL is
b) shouldn't it mention Linus, Larry Wall, others?[3]
c) for the ones that have been around longer then me who was the first
being call like that?

[1] http://en.wikipedia.org/wiki/BDFL
[2] http://en.wikipedia.org/wiki/Guido_van_Rossum
[3] http://www.answers.com/topic/list-of-benevolent-dictators-for-life
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.0 unfit for serious work?

2007-02-21 Thread Steven D'Aprano
On Tue, 20 Feb 2007 21:19:26 -0800, John Nagle wrote:

>  Well, something faster really should take over.  It's a bit
> embarassing that the main implementation of Python is still a
> pure interpreter.  Even Javascript has a JIT compiler now.
> And it's tiny, under 1MB.

Python has a compiler, just like Java. That's where the .pyc files come
from.

You might also notice the built-in function "compile", which compiles text
strings into byte-code and puts it into a code object. The dis module may
also be of interest.



-- 
Steven D'Aprano 

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


Re: eval('000052') = 42?

2007-02-21 Thread Laurent Pointal
Astan Chee a écrit :
> Hi,
> I just tried to do
> eval('00052') and it returned 42.
> Is this a known bug in the eval function? Or have I missed the way eval
> function works?
> Thanks

Ad Erik replied, a literal value beginning by 0 is interpreted as an
octal value (and beginning by 0x it is interpreted as hexadecimal value).

You may use int construction from string, which allow to specify a base
(default to ten):

>>> int('00052')
52
>>> int('00052',10)
52
>>> int('00052',8)
42

Note: this avoid possible evaluation of undesired Python expressions...

A+

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


Re: BDFL in wikipedia

2007-02-21 Thread Andrew McNamara
>Hi I just hit this page in wikipedia BDFL[1]
>
>and it redirected me to Guido's wikipedia[2] entry
>now without causing any troubles (read flamewar) shouldn't
>
>a) that page have an explanation of what BDFL is
>b) shouldn't it mention Linus, Larry Wall, others?[3]
>c) for the ones that have been around longer then me who was the first
>being call like that?
>
>[1] http://en.wikipedia.org/wiki/BDFL
>[2] http://en.wikipedia.org/wiki/Guido_van_Rossum
>[3] http://www.answers.com/topic/list-of-benevolent-dictators-for-life

I'm sure you'll get 101 people telling you this, but this really isn't a
question for the python list, rather, it's a question for the Wikipedia
editors (and that's anyone).

I suspect, in this case, the redirect is implicit. It's happening
because the Wikipedia search engine finds no page called BDFL, and the
Guido_van_Rossum is the next closest match.

If you care and you have enough to say on the subject, maybe you could
start a BDFL page.

-- 
Andrew McNamara, Senior Developer, Object Craft
http://www.object-craft.com.au/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regex Speed

2007-02-21 Thread John Machin
On Feb 21, 12:14 pm, Pop User <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > While creating a log parser for fairly large logs, we have run into an
> > issue where the time to process was relatively unacceptable (upwards
> > of 5 minutes for 1-2 million lines of logs). In contrast, using the
> > Linux tool grep would complete the same search in a matter of seconds.
>
> Its very hard to beat grep depending on the nature of the regex you are
> searching using. The regex engines in python/perl/php/ruby have traded
> the speed of grep/awk for the ability to do more complex searches.
>
> http://swtch.com/~rsc/regexp/regexp1.html
>
> This might not be your problem but if it is you can always popen grep.
>
> It would be nice if there were a Thompson NFA re module.

Or a Glushkov NFA simulated by bit parallelism re module ... see
http://citeseer.ist.psu.edu/551772.html
(which Russ Cox (author of the paper you cited) seems not to have
read).

Cox uses a "pathological regex" (regex = "a?" * 29 + "a" * 29, in
Python code) to make his point: grep uses a Thompson gadget and takes
linear time, while Python perl and friends use backtracking and go off
the planet.

The interesting thing is that in Navarro's NR-grep, that's not
pathological at all; it's a simple case of an "extended pattern" (? +
and * operators applied to a single character (or character class)) --
takes linear time with a much easier setup than an NFA/DFA and not
much code executed per byte scanned.

Getting back to the "It would be nice ..." bit: yes, it would be nice
to have even more smarts in re, but who's going to do it? It's not a
"rainy Sunday afternoon" job :-)

Cheers,
John

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


Re: converting u'11\xa022' to '11\xa022'

2007-02-21 Thread Laurent Pointal
Gabriel Genellina a écrit :
> En Wed, 21 Feb 2007 00:31:32 -0300, alf <[EMAIL PROTECTED]> escribió:

>> 2-list of supported encodings?
> I don't know how to query the list, except by reading the documentation
> for the codecs module.

>>> from encodings import aliases
>>> aliases.aliases
{'iso_ir_6': 'ascii', '1140': 'cp1140', 'tis620': 'tis_620', 'iso8859':
'latin_1', 'chinese': 'gb2312', 'mskanji': 'cp932', 's_j
is': 'shift_jis', 'iso_celtic': 'iso8859_14', 'ebcdic_cp_wt': 'cp037',

'utf_16_be', 'latin3': 'iso8859_3', 'iso_ir_148': 'iso88
59_9', 'ebcdic_cp_ca': 'cp037', 'tis_620_0': 'tis_620'}
>>> enc = aliases.aliases.keys()
>>> enc
['iso_ir_6', '1140', 'tis620', 'iso8859', 'chinese', 'mskanji', 's_jis',
'iso_celtic', 'ebcdic_cp_wt', 'csibm863', 'ebcdic_cp_he
', 'csHPRoman8', 'cp936', 'iso_8859_5_1988', 'maccyrillic', 'csibm857',

', 'iso_8859_11_2001', 'latin8', 'greek', '8859', 'big5_hkscs',
'iso_ir_144', 'unicodebigunmarked', 'latin3', 'iso_ir_148', 'ebc
dic_cp_ca', 'tis_620_0']
>>>


Note: this include some encodings like 'quotedprintable', 'zip', 'zlib'...




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


Re: converting u'11\xa022' to '11\xa022'

2007-02-21 Thread Gabriel Genellina
En Wed, 21 Feb 2007 06:24:55 -0300, Laurent Pointal  
<[EMAIL PROTECTED]> escribió:

> Gabriel Genellina a écrit :
>> En Wed, 21 Feb 2007 00:31:32 -0300, alf <[EMAIL PROTECTED]> escribió:
>
>>> 2-list of supported encodings?
>> I don't know how to query the list, except by reading the documentation
>> for the codecs module.
>
 from encodings import aliases

Nice to know! But would be nicer if this feature were documented.
In fact, I can't find any documentation about the encodings package,  
except for encodings.idna

-- 
Gabriel Genellina

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


Re: ipython shortcut to reload modules

2007-02-21 Thread Greenberg
[EMAIL PROTECTED] wrote:
> Hey!
> 
> I'm using ipython as my python shell and often run scripts with the
> magic command %run:
> 
> In [1]: %run script.py
> 
> If modules are loaded within the script these are not reloaded when I
> rerun the script. Hence, when I changed some of the modules loaded, I
> have to call
> 
> In [2]: reload(module1)
> Out [2]:  In [3]: reload(module2)
> Out [3]:  In [4]: %run script.py
> 
> Is there a shortshut to reload the modules automatically before
> rerunning the script?

No. But if you're including them in the script, they won't be reloaded 
because they're already present in the namespace. If you do %reset 
before your %run, it'll clear up the namespace, so your script's import 
should work. Downside: its effectively the same as quitting out of 
ipython, and restarting it. Other then that, I don't think you have much 
choice.
Oh, if you use the %edit command to edit these files, it should reload 
them when you're done editing.
-Jordan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: BDFL in wikipedia

2007-02-21 Thread Gabriel Genellina
En Wed, 21 Feb 2007 05:28:30 -0300, Andrew McNamara  
<[EMAIL PROTECTED]> escribió:

>> Hi I just hit this page in wikipedia BDFL[1]
>> and it redirected me to Guido's wikipedia[2] entry
>> [1] http://en.wikipedia.org/wiki/BDFL
>
> I suspect, in this case, the redirect is implicit. It's happening
> because the Wikipedia search engine finds no page called BDFL, and the
> Guido_van_Rossum is the next closest match.

No, both BDFL and Benevolent_Dict... have an explicit redirect to Guido's  
entry.
It used to be quite different in the past, but the topic has been heavily  
discussed and edited.
See  
http://en.wikipedia.org/wiki/Talk:Benevolent_Dictator_for_Life#Concerned_about_accuracy_-_BDs_versus_BDFLs
Guido appears to be the *only* one called BDFL.

-- 
Gabriel Genellina

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


Re: Weird result returned from adding floats depending on order I add them

2007-02-21 Thread Steve Holden
joanne matthews (RRes-Roth) wrote:
> I'm getting different results when I add up a list of floats depending
> on the order that I list the floats. For example, the following returns
> False:
> def check():
>   totalProp=0
>   inputs=[0.2,0.2,0.2,0.1,0.2,0,0.1]
>   for each in inputs:
> 
>   totalProp+=each
>   print "totalProp=",totalProp
>   if totalProp != 1:
>   print "Your proportions must add up to 1"
>
>   return False
>   return True
> 
> However, if I swap, the 4th and 5th list items like this:
> 
> totalProp=0
> inputs=[0.2,0.2,0.2,0.2,0.1,0,0.1]
> for each in inputs:
> 
>totalProp+=each
>print "totalProp=",totalProp
>if totalProp != 1:
> print "Your proportions must add up to 1"
>
> return False
>return True
> 
> I get True returned. Can anyone tell me whats going on and how I can
> avoid the problem. Thanks
> 
> Joanne Matthews

I take it by now you understand that you need to test that the sum of 
your numbers is with some small delta of the value you actually require?

I seem to remember this question has been asked on a number of threads, 
just don't know whether this is the same question as the others.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note:  http://holdenweb.blogspot.com
See you at PyCon? http://us.pycon.org/TX2007

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


Re: Reading compressed files

2007-02-21 Thread Steve Holden
Shadab Sayani wrote:
> Hi,
> I have compressed files compressed using different techniques 
> (especially unix compress). So I want to have a module that reads any of 
> these (.Z,.bz,.tgz files) files and manipulates the data.
> The data has a syntax.It contains
> HEADER (some information)
> BODY  (some information)
> FOOTER   (some information)
> If it were a normal text file I can get the values corresponding to 
> HEADER BODY and FOOTER by open function.
> But here the files are in different format .Z , .bz ,.tgz,.gz .But I 
> know these are the only formats.Also I cannot rely upon the extensions 
> of the file (a .Z file can have no extension at all).Is there a way to 
> identify  which file am I reading and then  read it?If so how to read it?
> Thanks and Regards,
> Shadab.
> 
> Send instant messages to your online friends http://uk. messenger.yahoo.com
> 
The usual way is that used by the "file" utility - take a look at the 
/etc/magic file to see if you can gain any clues from that.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Blog of Note:  http://holdenweb.blogspot.com
See you at PyCon? http://us.pycon.org/TX2007

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


Re: BDFL in wikipedia

2007-02-21 Thread Carl Banks
On Feb 20, 9:27 pm, "Jorge Vargas" <[EMAIL PROTECTED]> wrote:
> Hi I just hit this page in wikipedia BDFL[1]
>
> and it redirected me to Guido's wikipedia[2] entry
> now without causing any troubles (read flamewar) shouldn't
>
> a) that page have an explanation of what BDFL is
> b) shouldn't it mention Linus, Larry Wall, others?[3]

Since when is Larry Wall benevolent?  He should be called the SDFL.

:)


Carl Banks

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


Re: Sorting directory contents

2007-02-21 Thread Wolfgang Draxinger
Tim Williams wrote:

> Are you running on windows?

No. Of course I could use some installed tool, like ls, but I
want a portable solution.

> HTH :)

Not really. Windows is only a niche for desktop systems. In my
case the python script is running on a heterogenous grid
monitoring system accessing a _large_ distributed Oracle9i DB -
a query can take up to half a minute, so obviously I'm caching
the results of previous queries in the mentioned files, where
the modification time is the sorting criterium for later
reading.

Wolfgang Draxinger
-- 
E-Mail address works, Jabber: [EMAIL PROTECTED], ICQ: 134682867

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


Re: eval('000052') = 42?

2007-02-21 Thread André Malo
Astan Chee wrote:

> Hi,
> I just tried to do
> eval('00052') and it returned 42.
> Is this a known bug in the eval function? Or have I missed the way eval
> function works?

You know, it's just the answer to the ultimate question of Life, the
universe, and everything.

SCNR, nd

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


Re: Weird result returned from adding floats depending on order I add them

2007-02-21 Thread Rhamphoryncus
On Feb 20, 6:08 am, "John Machin" <[EMAIL PROTECTED]> wrote:
> >>> for x in b:
>
> ...tot += x
> ...print repr(x), repr(tot)
> ...
> 0.20001 0.20001
> 0.20001 0.40002
> 0.20001 0.60009
> 0.20001 0.80004
> 0.10001 0.90002
> 0.10001 1.0
>
>
>
> As you can see, 0.1 and 0.2 can't be represented exactly as floating
> point numbers. Consequently there is only a rough chance that they
> will add up to what you think they should add up to.

Although your point is correct, this is actually a myth about repr.
The goal of repr is to be able to round-trip all numbers, so
eval(repr(n)) == n.  From that perspective it would be perfectly legal
if it printed out a nice and short "0.2" or "0.1".

As for the actual value, although you can't express all non-repeating
base-10 values with non-repeating base-2, you can express base-2 with
base-10.  It just gets a little long:

>>> '%.60f' % 0.2
'0.20001110223024625156540423631668090820312500'
>>> '%.60f' % 0.1
'0.1555111512312578270211815834045410156250'

Unfortunately this method of printing out floats won't work for
smaller values, since the %f formatting limits the number of decimal
places.

But if you want a more compact exact representation I have bodged
together a way of printing out floats in base-16:

>>> hexfloat(0.2)
hexfloat('0.34')
>>> hexfloat(0.1)
hexfloat('0.1A')

Interesting, if a bit confusing.

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


Re: eval('000052') = 42?

2007-02-21 Thread Bart Ogryczak
On Feb 21, 5:09 am, Astan Chee <[EMAIL PROTECTED]> wrote:
> Hi,
> I just tried to do
> eval('00052') and it returned 42.
> Is this a known bug in the eval function? Or have I missed the way eval
> function works?

It works just fine. Read up on integer literals.

>>> 52   #decimal
52
>>> 052  #octal
42
>>> 0x52 #hexadecimal
82


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


Re: Sorting directory contents

2007-02-21 Thread Peter Otten
Wolfgang Draxinger wrote:

> I got, hmm not really a problem, more a question of elegance:
> 
> In a current project I have to read in some files in a given
> directory in chronological order, so that I can concatenate the
> contents in those files into a new one (it's XML and I have to
> concatenate some subelements, about 4 levels below the root
> element). It all works, but somehow I got the feeling, that my
> solution is not as elegant as it could be:
> 
> src_file_paths = dict()
> for fname in os.listdir(sourcedir):
> fpath = sourcedir+os.sep+fname
> if not match_fname_pattern(fname): continue
> src_file_paths[os.stat(fpath).st_mtime] = fpath
> for ftime in src_file_paths.keys().sort():
> read_and_concatenate(src_file_paths[ftime])
> 
> of course listdir and sorting could be done in a separate
> function, but I wonder if there was a more elegant approach.

If glob.glob() is good enough to replace your custom match_fname_pattern()
you can save a few steps:

pattern = os.path.join(sourcedir, "*.xml")
files = glob.glob(pattern)
files.sort(key=os.path.getmtime)
for fn in files:
read_and_concatenate(fn)

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


Re: BDFL in wikipedia

2007-02-21 Thread Steven D'Aprano
On Wed, 21 Feb 2007 02:25:44 -0800, Carl Banks wrote:

>> a) that page have an explanation of what BDFL is
>> b) shouldn't it mention Linus, Larry Wall, others?[3]
> 
> Since when is Larry Wall benevolent?  He should be called the SDFL.
> 
> :)

I can't think what the S stands for... if it was M, I'd say Malevolent,
but S?


-- 
Steven.

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


Re: BDFL in wikipedia

2007-02-21 Thread Robin Becker
Carl Banks wrote:
..
> 
> Since when is Larry Wall benevolent?  He should be called the SDFL.
> 
.

even the great leader has been referred to as the MDFL :)

most language designers get to do it once and then recognize the result as 
either beneficial or otherwise. The alternative is a constantly changing 
language without any clear goal or endpoint. That's fine for some not for 
others.
-- 
Robin Becker

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


Performance project for the SigEx Foundry

2007-02-21 Thread pablo
have been testing performances of different scripting languages
fordatabase access, text processing and client application data
transfer. So far, I am getting better performance from PHP, but I
don't have any hard data to back it up compared to others.

This is a large project for the SigEx Foundry and it involves hundreds
of servers. I am looking for articles/studies/benchmarks on the
subject.

Thank you,

Pablo
Server Side Developer
Student for the SigEx Foundry
funded by SigEx Ventures

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


Re: Sorting directory contents

2007-02-21 Thread Jussi Salmela
Larry Bates kirjoitti:
> Wolfgang Draxinger wrote:
>> Jussi Salmela wrote:
>>
>>> I'm not claiming the following to be more elegant, but I would
>>> do it like this (not tested!):
>>>
>>> src_file_paths = dict()
>>> prefix = sourcedir + os.sep
>>> for fname in os.listdir(sourcedir):
>>>  if match_fname_pattern(fname):
>>>  fpath = prefix + fname
>>>  src_file_paths[os.stat(fpath).st_mtime] = fpath
>>> for ftime in src_file_paths.keys().sort():
>>>  read_and_concatenate(src_file_paths[ftime])
>> Well, both versions, mine and yours won't work as it was written
>> down, as they neglegt the fact, that different files can have
>> the same st_mtime and that .sort() doesn't return a
>> sorted list.
>>
>> However this code works (tested) and behaves just like listdir,
>> only that it sorts files chronologically, then alphabetically.
>>
>> def listdir_chrono(dirpath):
>> import os
>> files_dict = dict()
>> for fname in os.listdir(dirpath):
>> mtime = os.stat(dirpath+os.sep+fname).st_mtime
>> if not mtime in files_dict:
>> files_dict[mtime] = list()
>> files_dict[mtime].append(fname)
>> 
>> mtimes = files_dict.keys()
>> mtimes.sort()
>> filenames = list()
>> for mtime in mtimes:
>> fnames = files_dict[mtime]
>> fnames.sort()
>> for fname in fnames:
>> filenames.append(fname)
>> return filenames
>>
>> Wolfgang Draxinger
> 
> Four suggestions:
> 
> 1) You might want to use os.path.join(dirpath, fname) instead of
>dirpath+os.sep+fname.
> 
> 2) You may be able to use glob.glob() to filter the files
>more easily.
> 
> 3) You didn't handle the possibility that there is s subdirectory
>in the current directory.  You need to check to make sure it is
>a file you are processing as os.listdir() returns files AND
>directories.
> 
> 4) If you just put a tuple containing (mtime, filename) in a list
>each time through the loop you can just sort that list at the
>end it will be sorted by mtime and then alphabetically.
> 
> Example (not tested):
> 
> def listdir_chrono(dirpath):
> import os
> #
> # Get a list of full pathnames for all the files in dirpath
> # and exclude all the subdirectories.  Note: This might be
> # able to be replaced by glob.glob() to simplify.  I would then
> # add a second optional parameter: mask="" that would allow me
> # to pass in a mask.
> #
> # List comprehensions are our friend when we are processing
> # lists of things.
> #
> files=[os.path.join(dirpath, x) for x in os.listdir(dirpath)
>if not os.path.isdir(os.path.join(dirpath, x)]
> 
> #
> # Get a list of tuples that contain (mtime, filename) that
> # I can sort.
> #
> flist=[(os.stat(x).st_mtime, x) for x in files]
> 
> #
> # Sort them.  Sort will sort on mtime, then on filename
> #
> flist.sort()
> #
> # Extract a list of the filenames only and return it
> #
> return [x[1] for x in flist]
> #
> # or if you only want the basenames of the files
> #
> #return [os.path.basename(x[1]) for x in flist]
> 
> 
> 
> -Larry Bates
> 

And as in Peter Ottens glob.glob variation, this shortens considerably 
by using sort with key instead of a separate list flist:

files.sort(key=lambda x:(os.stat(x).st_mtime, x))

Cheers,
Jussi
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eval('000052') = 42?

2007-02-21 Thread Neil Cerutti
On 2007-02-21, André Malo <[EMAIL PROTECTED]> wrote:
> Astan Chee wrote:
>
>> Hi,
>> I just tried to do
>> eval('00052') and it returned 42.
>> Is this a known bug in the eval function? Or have I missed the way eval
>> function works?
>
> You know, it's just the answer to the ultimate question of
> Life, the universe, and everything.

Yeah, but I was hoping the question would've turned out better.

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


Re: f---ing typechecking

2007-02-21 Thread Neil Cerutti
On 2007-02-21, Hendrik van Rooyen <[EMAIL PROTECTED]> wrote:
>  "Nick Craig-Wood" <[EMAIL PROTECTED]> wrote:
>> Ie
>> 
>> x += a
>> 
>> does not equal
>> 
>> x = x + a
>> 
>> which it really should for all types of x and a
>
> One would hope so , yes.
>
> However, I think that the first form is supposed to update in place, 
> while the second is free to bind a new thing to x
>
>> (That is the kind of statement about which I'm sure someone
>> will post a perfectly reasonable counterexample ;-)
>
> I don't think its reasonable - its just an accident of implementation..

Yup. It's analogous to the way you can do hill-starts with a
manual transmission, but not with an automatic transmission.

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


Re: PLY for standard library

2007-02-21 Thread Jakub Stolarski
On 20 Lut, 19:29, "Alan Isaac" <[EMAIL PROTECTED]> wrote:
> If not, what module providing substantially similar functionality is?
>
AFAIK there's no parser generator module in standard library.

I would like to see PLY in standard library too.

--
Jakub Stolarski

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


metaclasses (beginner question)

2007-02-21 Thread Laszlo Nagy

   Hello,

I would like to create a hierarchy classes, where the leaves have a 
special attribute called "producer_id". In addition, I would like to 
have a function that can give me back the class assigned to any 
producer_id value. I tried to implement this with a metaclass, but I 
failed. Please help me, what I did wrong?

Thanks,

   Laszlo


class ProducerHandlerType(type):
producer_handlers = {}
@classmethod
def registerProducerHandler(cls,producer_id):
ph = cls.producer_handlers
if ph.has_key(producer_id):
ccls = ph[producer_id]
raise Exception("This producer already has a calculator: 
"+str(ccls))
else:
print "Registering "+str(cls)+" for producer_id=",producer_id
ph[producer_id] = cls

def __init__(cls,name,bases,dct):
super(ProducerHandlerType,cls).__init__(cls,name,bases,dct)
if hasattr(cls,'producer_id'):
cls.registerProducerHandler(getattr(cls,'producer_id'))
else:
print "No producer_id for ",str(cls)


class A(ProducerHandlerType):
pass

class B(A):
producer_id = 1

class C(A):
producer_id = 2

# Metaclass methods are not called above, and the line below prints an 
empty dict. :-(
print B.producer_handlers
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: metaclasses (beginner question)

2007-02-21 Thread Peter Otten
Laszlo Nagy wrote:

> I would like to create a hierarchy classes, where the leaves have a
> special attribute called "producer_id". In addition, I would like to
> have a function that can give me back the class assigned to any
> producer_id value. I tried to implement this with a metaclass, but I
> failed. Please help me, what I did wrong?

> class ProducerHandlerType(type):
  ...

> class A(ProducerHandlerType):
> pass
> 
> class B(A):
> producer_id = 1

> # Metaclass methods are not called above, and the line below prints an
> empty dict. :-(

Without looking into the details -- the (subclass of) type is meant to be
the class of the class, or the other way round, your normal classes are
instances of (a subclass of) type. You determine the factory Python uses to
make a class by adding

__metaclass__ = factory

to the class body, so you'll probably end with something like

class ProducerHandlerType(type):
# your code 

class A:
__metaclass__ = ProducerHandlerType

The subclasses of A will now invoke your customised metaclass machinery.

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


Replacement for GnomeDateEdit?

2007-02-21 Thread Thomas Bollmeier
Hi,

I'm currently designing a dialog using pygtk/Glade. One of the
attributes to be edited is a date. I tried to use the GnomeDateEdit
widget that is available among the widgets in glade. Unfortunately the
"time"-property only allows me to use timestamps for dates >= January
1st 1970. Since the date to be edited is a birth date this constraint
is not acceptable for my application. Does anyone know whether there
is another widget around with a pygtk-binding that I could use
instead?

Best regards,
Thomas

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


Tkinter checkbuttons and variables

2007-02-21 Thread Gigs_
from Tkinter import *

states = []

def onpress(i):
 states[i] = not states[i]


root = Tk()
for i in range(10):
 chk = Checkbutton(root, text= str(i), command=lambda i=i: 
onpress(i))
 chk.pack(side=LEFT)
 states.append(0)
root.mainloop()
print states

after exiting i get everything like it suppose to but when i put command 
like this:
command=lambda: onpress(i)
i got only last checkbutton check.

Why i have to pass this default argument?


btw i have python 2.5
thx
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter checkbuttons and variables

2007-02-21 Thread Diez B. Roggisch
Gigs_ schrieb:
> from Tkinter import *
> 
> states = []
> 
> def onpress(i):
> states[i] = not states[i]
> 
> 
> root = Tk()
> for i in range(10):
> chk = Checkbutton(root, text= str(i), command=lambda i=i: onpress(i))
> chk.pack(side=LEFT)
> states.append(0)
> root.mainloop()
> print states
> 
> after exiting i get everything like it suppose to but when i put command 
> like this:
> command=lambda: onpress(i)
> i got only last checkbutton check.
> 
> Why i have to pass this default argument?

Because python creates a closure around the lambda that allows 
expressions inside the lambda to access surrounding variables. However, 
these variables are looked up at _runtime_, when the command is actually 
executed. Naturally, the value of i then is 9, because that's what it 
has been assigned in the last loop iteration.

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


Re: Tkinter checkbuttons and variables

2007-02-21 Thread Eric Brunel
On Wed, 21 Feb 2007 15:50:57 +0100, Gigs_ <[EMAIL PROTECTED]> wrote:
> from Tkinter import *
>
> states = []
>
> def onpress(i):
>  states[i] = not states[i]
>
>
> root = Tk()
> for i in range(10):
>  chk = Checkbutton(root, text= str(i), command=lambda i=i:  
> onpress(i))
>  chk.pack(side=LEFT)
>  states.append(0)
> root.mainloop()
> print states
>
> after exiting i get everything like it suppose to but when i put command  
> like this:
> command=lambda: onpress(i)
> i got only last checkbutton check.
>
> Why i have to pass this default argument?

I'm basically not answering your question here, but the usual way to get a  
checkbuttons's state is as follows:

states = []
root = Tk()
for i in range(10):
   stateVar = BooleanVar()
   chk = Checkbutton(root, text=str(i), variable=stateVar)
   chk.pack(side=LEFT)
   states.append(stateVar)
root.mainloop()
print [v.get() for v in states]

If you want to get the value of one of your states, use the get() method  
on BooleanVar. If you want to change such a state, use the set(value)  
method.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: metaclasses (beginner question)

2007-02-21 Thread Laszlo Nagy

> Without looking into the details -- the (subclass of) type is meant to be
> the class of the class, or the other way round, your normal classes are
> instances of (a subclass of) type. You determine the factory Python uses to
> make a class by adding
>
> __metaclass__ = factory
>
> to the class body, so you'll probably end with something like
>
> class ProducerHandlerType(type):
> # your code 
>
> class A:
> __metaclass__ = ProducerHandlerType
>
> The subclasses of A will now invoke your customised metaclass machinery.
>   
Thanks, I missed that. I added the __metaclass__ line and it worked like 
a charm.

  Laszlo

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


Re: builtin set literal

2007-02-21 Thread Dave Opstad
In article <[EMAIL PROTECTED]>,
 Paul Rubin  wrote:

> [...]  However, Python seems to use the -ed suffix for the 
> non-mutating versions of these functions, e.g. sorted(list) instead 
> of the mutating list.sort().  

I've found this to be useful in my own Python libraries. For instance, a 
graphic object has move(), scale() etc. methods which mutate, and 
moved(), scaled() etc. methods which return new instances. It's 
English-specific, but still mnemonically useful.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: starship.python.net is down

2007-02-21 Thread Matthew . Cahn
Hi,

Any news on starship.python.net?  It still seems to be down.

Matthew

On Feb 16, 8:57 am, Tom Bryan <[EMAIL PROTECTED]> wrote:
> One of the system administrators had to reboot starship.python.net last
> night, but it appears that the machine did not come back up properly.
> starship.python.net is currently down while we investigate.
>
> ---Tom


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


Question about updating in a GUI

2007-02-21 Thread Gheorghe Postelnicu
Hi,

I have a GUI which does some visualization based on VTK and Tkinter.

The problem I have is kinda complicated to describe, but here is a
sketch of it: I have a basic Observer pattern in place for events
(such as the change current 2D slice visualized) and it generally
works well.

However, I just tried inserting a new mode in my GUI, which triggers
an update in the above interface. In general, modes react to these
event changes by refreshing the data, so the code is really
straightforward. However, for this specific mode, I need some
persistent data. So I need to tell my Callback to keep the data and
not refresh it, as is usually the case.

I tried to set a flag that would be set during this operation (my
application is not multi-threaded and I took a chance), but the
updates in the renderer in VTK are not synchronous, so the flag gets
cleared before all the updates occured, so my data still gets flushed
away.

Any suggestions on how I should be approaching this?

Thanks,
-- 
Gheorghe Postelnicu, PhD
MGH, Harvard Medical School
-- 
http://mail.python.org/mailman/listinfo/python-list


Creating a daemon process in Python

2007-02-21 Thread Sakagami Hiroki
Hi,

What is the easiest way to create a daemon process in Python?  Google
says I should call fork() and other system calls manually, but is
there no os.daemon() and the like?

Regards,

--
Sakagami Hiroki

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


Re: getting a thread out of sleep

2007-02-21 Thread mark
On 20 Feb 2007 21:26:18 -0800, placid <[EMAIL PROTECTED]> wrote:
> On Feb 21, 4:21 pm, "placid" <[EMAIL PROTECTED]> wrote:
> > On Feb 21, 4:12 pm, mark <[EMAIL PROTECTED]> wrote:
> > > On 20 Feb 2007 20:47:57 -0800, placid <[EMAIL PROTECTED]> wrote:
> > > > On Feb 21, 3:08 pm, mark <[EMAIL PROTECTED]> wrote:
> > > > > Right now I have a thread that  sleeps for sometime and check if an
> > > > > event has happened and go back to sleep. Now instead I want the thread
> > > > > to sleep until the event has occured process the event and go back to 
> > > > > sleep
> >
> > > > > class eventhndler(threading.Thread):
> > > > > def __init__(self):
> > > > > threading.Thread.__init__(self)
> > > > > def run(self):
> > > > > while True:
> > > > > time.sleep(SLEEPTIME)
> > > > > do event stuff'''
> >
> > > > The way i would do this is by using an threading.Event (
> > > >http://docs.python.org/lib/event-objects.html)
> >
> > > > 
> >
> > > > class eventhandler(threading.Thread):
> > > > def __init__(self):
> > > > threading.Thread.__init__(self)
> > > > self.event = threading.Event()
> > > > def run:
> > > > while True:
> > > > # block until some event happens
> > > > self.event.wait()
> > > > """ do stuff here """
> > > > self.event.clear()
> > > > 
> >
> > > > the way to use this is to get the main/separate thread to set() the
> > > > event object.
> >
> > > Can you give an example of how to get the main threead to set teh event 
> > > object?
> > > this is exactly what i wanted to do!
> > > thanks a lot!
> > > mark>
> oops I've miss-typed the thread variable name the following should
> work
>
> 
> if __name__ == "__main__":
> evtHandlerThread = eventhandler()
> evtHandlerThread.start()
>
> # do something here #
> evtHandlerThread.event.set()
>
> # do more stuff here #
> evtHandlerThread.event.set()
>
> 


Can I have the same thread process two or more events? Can you tell
how to do this? The code you gave is waiting on one event right. How
can I do it for more events?
thanks a lot!
mark
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a daemon process in Python

2007-02-21 Thread Benjamin Niemann
Hello,

Sakagami Hiroki wrote:

> What is the easiest way to create a daemon process in Python?  Google
> says I should call fork() and other system calls manually, but is
> there no os.daemon() and the like?

You could try



HTH

-- 
Benjamin Niemann
Email: pink at odahoda dot de
WWW: http://pink.odahoda.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a daemon process in Python

2007-02-21 Thread Eirikur Hallgrimsson
Sakagami Hiroki wrote:
> Hi,
>
> What is the easiest way to create a daemon process in Python?
I find that this works great.  I just pasted my copy, I think you can 
find it via Google.

Eirikur


#  Daemon Module - basic facilities for becoming a daemon process
#  By Coy Krill
#  Combines ideas from Steinar Knutsens daemonize.py and
#  Jeff Kunces demonize.py

"""Facilities for Creating Python Daemons"""

import os
import time
import sys

class NullDevice:
def write(self, s):
pass

def daemonize():
if (not os.fork()):
# get our own session and fixup std[in,out,err]
os.setsid()
sys.stdin.close()
sys.stdout = NullDevice()
sys.stderr = NullDevice()
if (not os.fork()):
# hang around till adopted by init
ppid = os.getppid()
while (ppid != 1):
time.sleep(0.5)
ppid = os.getppid()
else:
# time for child to die
os._exit(0)
else:
# wait for child to die and then bail
os.wait()
sys.exit()


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


Re: BDFL in wikipedia

2007-02-21 Thread Toby A Inkster
Steven D'Aprano wrote:
> Carl Banks wrote:
>> 
>> Since when is Larry Wall benevolent?  He should be called the SDFL.
> 
> I can't think what the S stands for... if it was M, I'd say Malevolent,
> but S?

Scented, Sexy, Spanish... no, probably not those.

I assume "Sadistic".

-- 
Toby A Inkster BSc (Hons) ARCS
Contact Me ~ http://tobyinkster.co.uk/contact
Geek of ~ HTML/SQL/Perl/PHP/Python*/Apache/Linux
Now Playing ~ ./vol/music/gorkys_zygotic_mynci_-_poodle_rockin.ogg

* = I'm getting there!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: BDFL in wikipedia

2007-02-21 Thread Toby A Inkster
Jorge Vargas wrote:

> shouldn't it mention Linus, Larry Wall, others?[3]

Despite the link you posted, I don't think Linus, Larry Wall, Rasmus
Lerdorf, etc describe themselves as BDFLs, even if they fulfil similar
roles within their respective development communities.

-- 
Toby A Inkster BSc (Hons) ARCS
Contact Me ~ http://tobyinkster.co.uk/contact
Geek of ~ HTML/SQL/Perl/PHP/Python*/Apache/Linux
Now Playing ~ ./vol/music/snug/from_solar_to_polar/04_naked_+_smiling.ogg

* = I'm getting there!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regex Speed

2007-02-21 Thread Pop User
John Machin wrote:
> Or a Glushkov NFA simulated by bit parallelism re module ... see
> http://citeseer.ist.psu.edu/551772.html
> (which Russ Cox (author of the paper you cited) seems not to have
> read).
>   
NR-grep looks interesting, I'll read that. Thanks.
> Cox uses a "pathological regex" (regex = "a?" * 29 + "a" * 29, in
> Python code) to make his point: grep uses a Thompson gadget and takes
> linear time, while Python perl and friends use backtracking and go off
> the planet.
>
>   
It might be pathological but based on the original posters timings his 
situation seems to relate.
My main point was that its quite possible he isn't going to get faster 
than grep regardless of
the language he uses and if grep wins, use it.  I frequently do. 

> Getting back to the "It would be nice ..." bit: yes, it would be nice
> to have even more smarts in re, but who's going to do it? It's not a
> "rainy Sunday afternoon" job :
One of these days.  :)



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


network simulator in Python ?

2007-02-21 Thread DanielJohnson
I was wondering if anyblody can suggest me a network simulator written
in python in which I can add on my own code and extend its
functionality.

I am looking for a simulator which will simualte TCP, UDP, RTP and
most networking protocol. The learning curve for ns2 and other
simulator is too high for me at this time and thats why I am
considering Python for it.

Every help will be appreciated.

Thanks

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


Re: f---ing typechecking

2007-02-21 Thread Nick Craig-Wood
Delaney, Timothy (Tim) <[EMAIL PROTECTED]> wrote:
>  Nick Craig-Wood wrote:
> 
> > x += a
> > 
> > does not equal
> > 
> > x = x + a
> > 
> > which it really should for all types of x and a
> 
>  Actually, this will *never* be the case for classes that do in-place
>  augmented assignment.
> 
>  a = [1]
>  b = [2]
> 
>  c = a + b
>  print a, b, c
> 
>  a += b
>  print a, b, c

Not sure what that is trying to show, it appears to back my point
up...

To rephrase your example

  >>> x = [1]
  >>> a = [2]
  >>> x += a
  >>> x
  [1, 2]

  >>> x = [1]
  >>> a = [2]
  >>> x = x + a
  >>> x
  [1, 2]
  >>> 

Which appears to support my point, x (and a for that matter) are the
same for both methods wheter you do x = x + a or x += a.

The mechanism is different certainly, but the result should be the
same otherwise you are breaking the basic rules of arithmetic the
programmer expects (the rule of least suprise).

>  You'll note that I didn't rebind 'a' in the non-augmented assignment. If
>  you do, augmented and non-augmented assignment may look the same, but
>  they can be very different.

Perhaps if you post a worked example from the python interpreter I'll
get what you mean!

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regex Speed

2007-02-21 Thread garrickp
On Feb 20, 6:14 pm, Pop User <[EMAIL PROTECTED]> wrote:

> Its very hard to beat grep depending on the nature of the regex you are
> searching using. The regex engines in python/perl/php/ruby have traded
> the speed of grep/awk for the ability to do more complex searches.
>
> http://swtch.com/~rsc/regexp/regexp1.html

Some darned good reading. And it explains what happened fairly well.
Thanks!

> > And python 2.5.2.
>
> 2.5.2? Who needs crystal balls when you've got a time machine? Or did
> you mean 2.5? Or 1.5.2 -- say it ain't so, Joe!

2.5. I'm not entirely sure where I got that extra 2. I blame Monday.

In short... avoid using re as a sledgehammer against every problem. I
had a feeling that would be the case.

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


Re: Weird result returned from adding floats depending on order I add them

2007-02-21 Thread Miki
Hello Joanne,

> ... [float problem] ...
> I get True returned. Can anyone tell me whats going on and how I can
> avoid the problem. Thanks

If you want to be truly accurate, you can use gmpy.mpq (http://
gmpy.sourceforge.net/).
>>> a = [0.2, 0.2, 0.2, 0.1, 0.2, 0.1]
>>> b = [0.2, 0.2, 0.2, 0.2, 0.1, 0.1]
>>> qa = [gmpy.mpq(int(i * 10), 10) for i in a]
>>> qb = [gmpy.mpq(int(i * 10), 10) for i in b]
>>> sum(qa)
mpq(1)
>>> sum(qb)
mpq(1)
>>> sum(qa) == sum(qb)
True

HTH,
--
Miki <[EMAIL PROTECTED]>
http://pythonwise.blogspot.com

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


Re: Reading compressed files

2007-02-21 Thread Jordan
On Feb 21, 5:21 am, Steve Holden <[EMAIL PROTECTED]> wrote:
> Shadab Sayani wrote:
> > Hi,
> > I have compressed files compressed using different techniques
> > (especially unix compress). So I want to have a module that reads any of
> > these (.Z,.bz,.tgz files) files and manipulates the data.
> > The data has a syntax.It contains
> > HEADER (some information)
> > BODY  (some information)
> > FOOTER   (some information)
> > If it were a normal text file I can get the values corresponding to
> > HEADER BODY and FOOTER by open function.
> > But here the files are in different format .Z , .bz ,.tgz,.gz .But I
> > know these are the only formats.Also I cannot rely upon the extensions
> > of the file (a .Z file can have no extension at all).Is there a way to
> > identify  which file am I reading and then  read it?If so how to read it?
> > Thanks and Regards,
> > Shadab.
>
> > Send instant messages to your online friendshttp://uk. messenger.yahoo.com
>
> The usual way is that used by the "file" utility - take a look at the
> /etc/magic file to see if you can gain any clues from that.
>
> regards
>   Steve
> --
> Steve Holden   +44 150 684 7255  +1 800 494 3119
> Holden Web LLC/Ltd  http://www.holdenweb.com
> Skype: holdenwebhttp://del.icio.us/steve.holden
> Blog of Note:  http://holdenweb.blogspot.com
> See you at PyCon?http://us.pycon.org/TX2007- Hide quoted text -
>
> - Show quoted text -

You really need to check the docs and do a little research before
asking questions like this.  Check out tarfile and zlib modules (use
these for opening .tgz, .gz, .bz2 etc), and then go search for the
different ways each (.Z, .tgz, .gz, .bz etc) formats their header
files so that you can determine what each type of archive is.

> The data has a syntax.It contains
> HEADER (some information)
> BODY  (some information)
> FOOTER   (some information)
> If it were a normal text file I can get the values corresponding to
> HEADER BODY and FOOTER by open function.
> But here the files are in different format .Z , .bz ,.tgz,.gz ...

What do you mean if it was a normal text file?? Use 'rb' for reading
binary and you shouldn't have a problem if you know the syntax for
each of these files.  What you need to do is research each syntax and
write a regexp or other string searching function to determine each
format based on the archive header syntax. While you're at it, open a
few archives with a hex editor or using open(...,'rb') and take a look
at the syntax of each file to see if you can determine it yourself.
Goodluck.

Cheers,
Jordan

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


Converting a text data file from positional to tab delimited.

2007-02-21 Thread Zeljko Sikic
Hi,

You should try www.TextMaster.ca   and download
SW which can convert text file from fix positioned to TAB delimited or any
other text format.

Regards,

Jake

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

datetime - easy way to make it use local timezone?

2007-02-21 Thread bwooster47
Is there an easy way to have an automatically constructed local time
zone tzinfo object be used with datetime?

Following code shows the problem - the time module works fine mostly
(%Z works, but %z does not, but that may be the way it is), uses

# The following python code outputs: note the time() modules print EST
and EDT (daylight savings),
# but datetime does not.

#--- t = time.time() =  117217
# t tuple =  (2007, 2, 22, 13, 46, 40, 3, 53, 0)  %Z%z =  EST+
# dt tuple =  (2007, 2, 22, 13, 46, 40, 3, 53, -1)  %Z%z =

#--- t = time.time() =  117734
# t tuple =  (2007, 4, 23, 10, 53, 20, 0, 113, 1)  %Z%z =  EDT+
# dt tuple =  (2007, 4, 23, 10, 53, 20, 0, 113, -1)  %Z%z =

 python code-
import time
from datetime import datetime

t = 117217 # Feb 22

t_tuple = time.localtime(t)

dt = datetime.fromtimestamp(t)
dt_tuple = dt.timetuple()

print "#---", "t = time.time() = ", t
print "# t tuple = ", t_tuple, " %Z%z = ", time.strftime("%Z%z",
t_tuple)
print "# dt tuple = ", dt_tuple, " %Z%z = ", dt.strftime("%Z%z")

t += 517   # Apr 23

t_tuple = time.localtime(t)

dt = datetime.fromtimestamp(t)
dt_tuple = dt.timetuple()

print "#---", "t = time.time() = ", t
print "# t tuple = ", t_tuple, " %Z%z = ", time.strftime("%Z%z",
t_tuple)
print "# dt tuple = ", dt_tuple, " %Z%z = ", dt.strftime("%Z%z")

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


Re: Performance project for the SigEx Foundry

2007-02-21 Thread bearophileHUGS
Pablo:
> I am looking for articles/studies/benchmarks on the subject.

It's not easy to test that, you need to be equally expert on all the
languages to test them. This may be a starting point for you:
http://shootout.alioth.debian.org/

Bye,
bearophile

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


Re: Python 3.0 unfit for serious work?

2007-02-21 Thread Aahz
In article <[EMAIL PROTECTED]>,
Jay Tee <[EMAIL PROTECTED]> wrote:
>
>If backwards compatibility is not a consideration, then it would be a
>miracle if there were no problems.

Backwards compatibility is a consideration AND there will be problems.
That is, the goal of 3.0 is to lower the priority of backwards
compatibility enough to make some incompatible changes, but not to reduce
the priority of compatibility to zero.  Just for example, "foo" will
become a Unicode string.

Note that I believe it will be many years, perhaps even a decade, before
"python" on a Unix system starts up Python 3.0.  Python 2.x will have at
least two releases after 3.0 gets released, and I can't imagine that any
OS will have "python" refer to 3.0 while 2.x is still under active
development or even for a while after.  I'd expect any OS to provide a
python3.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"I disrespectfully agree."  --SJM
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.0 unfit for serious work?

2007-02-21 Thread olsongt
On Feb 20, 9:04 pm, "Jeff Templon" <[EMAIL PROTECTED]> wrote:
> yo,
>
> Bjorn, I am not sure I see why my post is bull crap.  I think all you
> are doing is agreeing with me.  My post was entitled "Python 3.0 unfit
> for serious work", you just indicated that the Linux distros will
> agree with me, in order to be taken seriously, the distros will have
> to include 2.x python for a very long time.  If 3.0 and 2.x have any
> serious degree of incompatibility, python will be a favorite subject
> for religious rants and heated arguments for many people.  And if we
> don't manage to restrain our d evelopers from using features that force
> us prematurely to move to 3.0 ... and don't underestimate what this
> means, because this means other things will have to move as well,
> which may have dependencies on yet other things like C++ library
> versions ... then I would have to, for reasons of maintainability,
> argue against continuing to allow python code development in the
> project.  I love python, but not enough to make 20+ people's lives
> difficult.
>
> There are already people making this sort of argument in our project.
>
>JT

I don't know the specifics of your app, but why does everyone insist
that they need to use the 'system' python?

At least one commercial python app I work with installs it's own
completely independant version of python.  For many apps where
predictible behaviour is required you can install 'your' python,
under /opt/myapp or /usr/local/myapp or whatever instead of python,
python2.2, python3, etc.  The downside is that you'll waste another
15Mb harddrive space, and you'll need to update your internal source
tree 4 or 5 times when maintenance releases come out.

Apologies if this sounds like a rant, I really mean it in a
constructive way.

-Grant

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


Re: builtin set literal

2007-02-21 Thread bearophileHUGS
Steven Bethard:
> take a look at the current state of tuples:
>1, 2
>1,
>()

That's not a good situation. I presume the situation/syntax of tuples
in Python 2.x can't be improved. But can it be improved for Py 3.0?
Notes:
- I think in Matlab a single element is seen as the same thing as an
array with len = 1.
- I think Ruby solves the problem of the list/tuple with a freezing
function/operator (like I suggested some time ago).

Bye,
bearophile

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


Re: builtin set literal

2007-02-21 Thread Steven Bethard
[EMAIL PROTECTED] wrote:
> Steven Bethard:
>> take a look at the current state of tuples:
>>1, 2
>>1,
>>()
> 
> That's not a good situation. I presume the situation/syntax of tuples
> in Python 2.x can't be improved. But can it be improved for Py 3.0?

I'm not really losing any sleep over the current tuple syntax. ;-) The 
empty tuple is so uncommon in my code that the fact that it's spelled 
differently just doesn't bother me.

And anyway, if I've learned anything from the Python community over the 
years, it's that syntax is best left to Guido. ;-)

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


Re: Regex Speed

2007-02-21 Thread Kirk Sluder
In article <[EMAIL PROTECTED]>,
 "John Machin" <[EMAIL PROTECTED]> wrote:

> Getting back to the "It would be nice ..." bit: yes, it would be nice
> to have even more smarts in re, but who's going to do it? It's not a
> "rainy Sunday afternoon" job :-)

Well, just as an idea, there is a portable C library for this at 
http://laurikari.net/tre/ released under LGPL.  If one is willing to 
give up PCRE extensions for speed, it might be worth the work to 
wrap this library using SWIG.

The cheap way in terms of programmer time is to pipe out to grep or 
awk on this one.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: eval('000052') = 42?

2007-02-21 Thread Roger Miller
On Feb 20, 7:37 pm, "John Machin" <[EMAIL PROTECTED]> wrote:
> On Feb 21, 3:09 pm, Astan Chee <[EMAIL PROTECTED]> wrote:
>
> > Hi,
> > I just tried to do
> > eval('00052') and it returned 42.
> > Is this a known bug in the eval function? Or have I missed the way eval
> > function works?
> > Thanks
>
> Eight fives are forty. Forty plus two is forty two. I see no bug here,
> only a language design strangeness which can be blamed on the then-
> pervasive influence of all things from Bell Labs :-)

So is this anachronism slated for removal in Python 3?


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


Re: PLY for standard library

2007-02-21 Thread Paul McGuire
On Feb 21, 7:02 am, "Jakub Stolarski" <[EMAIL PROTECTED]>
wrote:
> On 20 Lut, 19:29, "Alan Isaac" <[EMAIL PROTECTED]> wrote:> If not, what 
> module providing substantially similar functionality is?
>
> AFAIK there's no parser generator module in standard library.
>
> I would like to see PLY in standard library too.
>
> --
> Jakub Stolarski

Other candidates besides PLY:
http://www.nedbatchelder.com/text/python-parsers.html
http://wiki.python.org/moin/LanguageParsing

I'm not sure this is a "one size fits all" problem space.

Personally I find PLY's use of docstrings for grammar definition a bit
too clever (as I'm sure others have their own personal likes and
dislikes on any of these packages, even (gasp) pyparsing).

-- Paul

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


Debug Build of Python

2007-02-21 Thread Mark E. Fenner
Hi all,

Just curious how to get an "all bells and whistles" debug build of python. 
In the source for 2.4.3, I see the following debug related options:


>From README:
(1)
e.g. "make OPT=-g" will build a debugging version of Python
on most platforms
(2)
Additional debugging code to help debug memory management problems can
be enabled by using the --with-pydebug option to the configure script.


>From Misc/SpecialBuilds.txt:
This file describes some special Python build types enabled via
compile-time preprocessor defines.

Here we have a bunch of defines documented.  Where should these be be set? 
Is there a particular .h file?  Are any of them implied by the debugging
options to make and ./configure?

Regards,
Mark
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 3.0 unfit for serious work?

2007-02-21 Thread Jay Tee
On Feb 21, 8:06 pm, [EMAIL PROTECTED] wrote:

> I don't know the specifics of your app, but why does everyone insist
> that they need to use the 'system' python?

Hey Grant, don't worry it's not a rant.  A completely valid question.
Again it's a problem of dependency management ... one of the things
we've had to deal with is one of the applications : they have a
framework largely built in python, and I think they were indeed at one
point shipping their own python because they used features not present
in the "system" python.

However, they did use the middleware installed on the system, and this
middleware is also partially written in python ... except it was
expecting the system python.  So you get into very tricky things
having to sanity check the PYTHONPATH, that the "user" python path is
not getting exported into middleware land, nor is the application's
desired PYTHONPATH being destroyed by middleware.  We had just such an
issue here last week, we had solved the problem for bourne shell
users, but csh for some reason had a different behavior, and the user
app could not longer find its python modules.

About the only code for which we don't seem to have these issues is
compiled C.  C++ is nasty because the compilers are still catching up
to the standard; the last I heard, a big segment of C++ code was stuck
because it was full of apparently illegal constructs that the previous
compiler (the g++ shipped stock with RHEL3) accepted, but the RHEL-4
native version refused to compile.

A colleague of mine pointed out today that this is an old problem, and
used to be handled by automake at compile time, with code full of
ifdefs ... now we've moved the problem to run time.  Which I think is
harder, because sometimes we don't find the problem until our binary
is halfway across the world ...

JT

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


Re: wxPython: non-GUI thread launching new frame? Delegates?

2007-02-21 Thread cyberco
Oh boyI must have hit an all time programmers-low with this
That was plain stupid.
2B

> You don't need the lambda - you can use:
>
> wx.CallAfter(parent.OnRequest, param)


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


FloatCanvas in a wxpython application.... layout problems

2007-02-21 Thread nelson -
Hi all,
 i'm developing an application that uses Floatcanvas to diplay a
cartesian plane. how can i embed it into a "complex" layout?

I have this controls


MENUS
TOOLBAR
NOTEBOOK
FLOATCANVAS
PYSHELL

The problem is that i can show all the components but i can't insert
the floatcanvas in the right position... it is'n displaied... can
annyone give me an example of use of floatcanvas in an application
with more than one panel...

thanks a lot!

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


[Ann] PyGooCanvas 0.6.0

2007-02-21 Thread Gian Mario Tagliaretti
I am pleased to announce version 0.6.0 of the Python bindings for
Goocanvas.

It is available at:

https://developer.berlios.de/projects/pygoocanvas/

The bindings are updated with the new Goocanvas API

PyGooCanvas 0.6.0   (Feb 19 2007)
=

 o Rename and implement latest API changes according to
  goocanvas 0.6 (Gian Mario)
 o wrap GooCanvasItem.find_child_property as classmethod (Gian Mario)
 o New example of Table (Gian Mario)
 o Wrap goo_canvas_polyline_model_new_line Gian Mario)
 o Wrap goo_canvas_item_model_[get|set]_child_properties (Gian Mario)
 o Wrap goo_canvas_item_[get|set]_child_properties (Gian Mario)
 o Add setters for bounds_x1, bounds_x2, bounds_y1,
  bounds_y2 of goocanvas.ItemSimple.  Closes LP#81992. (Gustavo)
 o Wrap all new methods of goocanvas.Style (Gustavo)
 o Implement mapping methods in goocanvas.Style (Gustavo)
 o _wrap_GooCanvasItem__proxy_do_get_bounds,
  _wrap_GooCanvasItem__proxy_do_update,
  Override to implement proper 'return value' semantics for the
  bounds parameter. (Gustavo)
 o Add a reversewrapper. Parameter handler for GooCanvasBounds* (Gustavo)
 o Added new examples (Gian Mario, Gustavo)
 o _cairo_pattern_to_gvalue: allow pattern=None in properties (Gustavo)
 o Regenerated defs files with new goocanvas include files (Gian Mario)

Blurb:
==

Goocanvas [1] is a canvas widget for GTK+, It is similar in many ways
to  FooCanvas, hence the name, but it uses cairo for rendering, it has
an optional  model/view split, and uses interfaces for items & views
(so you can easily turn any application object into a canvas item or
view).

PyGooCanvas is a wrapper which exposes the goocanvas API to the
python world.  It is fairly complete; most of the API are covered.

The documentation is a work in progress, needs quite a lot of work in
order to reflect the new API, a lot of new examples are provided,
anyway help will be greatly appreciated.

Like the GTK+ library, PyGTK and GooCanvas itself PyGooCanvas is
licensed under  the GNU LGPL, so is suitable for use in both
free software and proprietary applications.

PyGooCanvas requires:
=

 o Goocanvas >= 0.6.0
 o PyGObject >= 2.10.1 (2.11.3 to build the docs)
 o PyGTK >= 2.10.4
 o PyCairo >= 1.2.0

Bug reports should go to
https://launchpad.net/pygoocanvas/

[1] http://sourceforge.net/projects/goocanvas

cheers
--
Gian Mario Tagliaretti
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a daemon process in Python

2007-02-21 Thread garrickp
On Feb 21, 9:33 am, Eirikur Hallgrimsson <[EMAIL PROTECTED]>
wrote:
> Sakagami Hiroki wrote:
> > What is the easiest way to create a daemon process in Python?

I've found it even easier to use the built in threading modules:

import time

t1 = time.time()
print "t_poc.py called at", t1

import threading

def im_a_thread():
time.sleep(10)
print "This is your thread speaking at", time.time()

thread = threading.Thread(target=im_a_thread)
thread.setDaemon(True)
thread.start()
t2 = time.time()
print "Time elapsed in main thread:", t2 - t1


Of course, your mileage may vary.

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


Re: Python 3.0 unfit for serious work?

2007-02-21 Thread [EMAIL PROTECTED]
On Feb 21, 1:44 pm, [EMAIL PROTECTED] (Aahz) wrote:
>
> Note that I believe it will be many years, perhaps even a decade, before
> "python" on a Unix system starts up Python 3.0.

That's a pretty safe bet considering that the factory-installed
"python" on my Linux system is still 1.x and you run "python2" to get
2.x (I haven't done a new OS install in a couple of years, but 2.x had
been out for years when I did the install).  And 2.x is much less
likely to break 1.x code than 3.x will be to break 2.x code.

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


Question about classes and possible closure.

2007-02-21 Thread Steven W. Orr
This is all an intro learning experience for me, so please feel free to 
explain why what I'm trying to do is not a good idea.

In the Cookbook, they have a recipe for how to create global constants.

-
class _const:
 class ConstError(TypeError): pass
 def __setattr__(self,name,value):
 if self.__dict__.has_key(name):
 raise self.ConstError, "Can't rebind const(%s)"%name
 self.__dict__[name]=value

import sys
sys.modules[__name__]=_const()


I'd like to be able to create constants within a class. (Yes I understand 
that uppercase names is a far better and easier convention but this is a 
learning experience for me.)

I can't get this to work, but my idea is that MyClass is defined thusly:

class ConstError(TypeError): pass
class Myclass:
 def mprint(self):
 print "C1 = ", self._C1

 # Define a subclass to create constants. It refs upself to access
 # the uplevel copy of self.
 class _const:
 class ConstError(TypeError): pass
 def __setattr__(_upself,name,value):
 if upself.__dict__.has_key(name):
 raise self.ConstError, "Can't rebind const(%s)"%name
 else:
 print "Just set something"
 upself.__dict__[name]=value

 # I want the const instance to be contained in this class so I
 # instantiate here in the constructor.
 def __init__(self):
 upself = self
 upself.consts = const()
 upself.consts._C1 = 0
 setattr(upself.consts, "_C1", 44)
 self = upself

Then the call in another file is this:
#! /usr/bin/python
from c2 import Myclass
foo = Myclass()
foo.mprint()
# end

Is it possible to nest a class in another class and is it possible to make 
this work?

TIA

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a daemon process in Python

2007-02-21 Thread Benjamin Niemann
[EMAIL PROTECTED] wrote:

> On Feb 21, 9:33 am, Eirikur Hallgrimsson <[EMAIL PROTECTED]>
> wrote:
>> Sakagami Hiroki wrote:
>> > What is the easiest way to create a daemon process in Python?
> 
> I've found it even easier to use the built in threading modules:
> 
> import time
> 
> t1 = time.time()
> print "t_poc.py called at", t1
> 
> import threading
> 
> def im_a_thread():
> time.sleep(10)
> print "This is your thread speaking at", time.time()
> 
> thread = threading.Thread(target=im_a_thread)
> thread.setDaemon(True)
> thread.start()
> t2 = time.time()
> print "Time elapsed in main thread:", t2 - t1
> 
> 
> Of course, your mileage may vary.

That's not a daemon process (which are used to execute 'background services'
in UNIX environments).

-- 
Benjamin Niemann
Email: pink at odahoda dot de
WWW: http://pink.odahoda.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: BDFL in wikipedia

2007-02-21 Thread Jorge Vargas
On 2/21/07, Andrew McNamara <[EMAIL PROTECTED]> wrote:
> >Hi I just hit this page in wikipedia BDFL[1]
> >
> >and it redirected me to Guido's wikipedia[2] entry
> >now without causing any troubles (read flamewar) shouldn't
> >
> >a) that page have an explanation of what BDFL is
> >b) shouldn't it mention Linus, Larry Wall, others?[3]
> >c) for the ones that have been around longer then me who was the first
> >being call like that?
> >
> >[1] http://en.wikipedia.org/wiki/BDFL
> >[2] http://en.wikipedia.org/wiki/Guido_van_Rossum
> >[3] http://www.answers.com/topic/list-of-benevolent-dictators-for-life
>
> I'm sure you'll get 101 people telling you this, but this really isn't a
> question for the python list, rather, it's a question for the Wikipedia
> editors (and that's anyone).
>
well then here is a good place to find editors :)

> I suspect, in this case, the redirect is implicit. It's happening
> because the Wikipedia search engine finds no page called BDFL, and the
> Guido_van_Rossum is the next closest match.
>
with my little knowledge of mediawiki that has to be set by someone.
it's not automatic.

> If you care and you have enough to say on the subject, maybe you could
> start a BDFL page.
>
well that's the point I have here with c) I really don't know enough
about it to write something there that is why I ask here.

> --
> Andrew McNamara, Senior Developer, Object Craft
> http://www.object-craft.com.au/
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: BDFL in wikipedia

2007-02-21 Thread Jorge Vargas
On 2/21/07, Toby A Inkster <[EMAIL PROTECTED]> wrote:
> Jorge Vargas wrote:
>
> > shouldn't it mention Linus, Larry Wall, others?[3]
>
> Despite the link you posted, I don't think Linus, Larry Wall, Rasmus
> Lerdorf, etc describe themselves as BDFLs, even if they fulfil similar
> roles within their respective development communities.
>
yea I just got that as an example, from around the web, I really
haven't follow the internals of any of those communities to be able to
know if they do or don't.

> --
> Toby A Inkster BSc (Hons) ARCS
> Contact Me ~ http://tobyinkster.co.uk/contact
> Geek of ~ HTML/SQL/Perl/PHP/Python*/Apache/Linux
> Now Playing ~ ./vol/music/snug/from_solar_to_polar/04_naked_+_smiling.ogg
>
> * = I'm getting there!
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: BDFL in wikipedia

2007-02-21 Thread Jorge Vargas
On 2/21/07, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
> En Wed, 21 Feb 2007 05:28:30 -0300, Andrew McNamara
> <[EMAIL PROTECTED]> escribió:
>
> >> Hi I just hit this page in wikipedia BDFL[1]
> >> and it redirected me to Guido's wikipedia[2] entry
> >> [1] http://en.wikipedia.org/wiki/BDFL
> >
> > I suspect, in this case, the redirect is implicit. It's happening
> > because the Wikipedia search engine finds no page called BDFL, and the
> > Guido_van_Rossum is the next closest match.
>
> No, both BDFL and Benevolent_Dict... have an explicit redirect to Guido's
> entry.
> It used to be quite different in the past, but the topic has been heavily
> discussed and edited.
> See
> http://en.wikipedia.org/wiki/Talk:Benevolent_Dictator_for_Life#Concerned_about_accuracy_-_BDs_versus_BDFLs
> Guido appears to be the *only* one called BDFL.
>
ahhh thanks Gabriel that should clear it out :)

> --
> Gabriel Genellina
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getting a thread out of sleep

2007-02-21 Thread placid
On Feb 22, 3:23 am, mark <[EMAIL PROTECTED]> wrote:
> On 20 Feb 2007 21:26:18 -0800, placid <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Feb 21, 4:21 pm, "placid" <[EMAIL PROTECTED]> wrote:
> > > On Feb 21, 4:12 pm, mark <[EMAIL PROTECTED]> wrote:
> > > > On 20 Feb 2007 20:47:57 -0800, placid <[EMAIL PROTECTED]> wrote:
> > > > > On Feb 21, 3:08 pm, mark <[EMAIL PROTECTED]> wrote:
> > > > > > Right now I have a thread that  sleeps for sometime and check if an
> > > > > > event has happened and go back to sleep. Now instead I want the 
> > > > > > thread
> > > > > > to sleep until the event has occured process the event and go back 
> > > > > > to sleep
>
> > > > > > class eventhndler(threading.Thread):
> > > > > > def __init__(self):
> > > > > > threading.Thread.__init__(self)
> > > > > > def run(self):
> > > > > > while True:
> > > > > > time.sleep(SLEEPTIME)
> > > > > > do event stuff'''
>
> > > > > The way i would do this is by using an threading.Event (
> > > > >http://docs.python.org/lib/event-objects.html)
>
> > > > > 
>
> > > > > class eventhandler(threading.Thread):
> > > > > def __init__(self):
> > > > > threading.Thread.__init__(self)
> > > > > self.event = threading.Event()
> > > > > def run:
> > > > > while True:
> > > > > # block until some event happens
> > > > > self.event.wait()
> > > > > """ do stuff here """
> > > > > self.event.clear()
> > > > > 
>
> > > > > the way to use this is to get the main/separate thread to set() the
> > > > > event object.
>
> > > > Can you give an example of how to get the main threead to set teh event 
> > > > object?
> > > > this is exactly what i wanted to do!
> > > > thanks a lot!
> > > > mark>
> > oops I've miss-typed the thread variable name the following should
> > work
>
> > 
> > if __name__ == "__main__":
> > evtHandlerThread = eventhandler()
> > evtHandlerThread.start()
>
> > # do something here #
> > evtHandlerThread.event.set()
>
> > # do more stuff here #
> > evtHandlerThread.event.set()
>
> > 
>
> Can I have the same thread process two or more events? Can you tell
> how to do this? The code you gave is waiting on one event right. How
> can I do it for more events?
> thanks a lot!
> mark

I don't think a thread can block on more than one event at a time. But
you can make it block on more then one event one at a time.



class eventhandler(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.events = [threading.Event(), threading.Event()]
self.currentEvent = None
def run:
while True:
for event in self.events:
self.currentEvent = event
# block until some event happens
self.currentEvent.wait()
""" do stuff here """
self.currentEvent.clear()

if __name__ == "__main__":
 evtHandlerThread = eventhandler()
 evtHandlerThread.start()

 # do something here #
 evtHandlerThread.currentEvent.set()

 # do more stuff here #
 evtHandlerThread.currentEvent.set()



what the thread does is sequentially waits for two events to happen
and then execute the same code. You could change this code to perform
different functions for different event objects.

Cheers

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


Re: CherryPy/Turbogears on server not controlled by me

2007-02-21 Thread Jorge Vargas
On 2/20/07, Brian Blais <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I was wondering if there is a way to run CherryPy/Turbogears on a server that 
> I don't
> have root access to.

I have never run ANY webapp as root. you should follow that advice. in
fact don't run any server as root.

> If I just choose a random port, I think the security guys on
> the server would get annoyed at me.  What are my options?  I can talk to the 
> admin,

why will the port be a problem are they all closed? if so well the
only way is to poke a whole in the firewall and you can't do that
without the boring talk to the admin.

> but they are very slow/reluctant to make changes...it took me a couple months 
> to get
> them to upgrade to 2.4 from 2.3 last year, even when 2.5 was out.
>
>
> thanks,
>
> Brian Blais
>
> --
> -
>
>   [EMAIL PROTECTED]
>   http://web.bryant.edu/~bblais
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a daemon process in Python

2007-02-21 Thread garrickp
On Feb 21, 3:34 pm, Benjamin Niemann <[EMAIL PROTECTED]> wrote:
> That's not a daemon process (which are used to execute 'background services'
> in UNIX environments).

I had not tested this by running the script directly, and in writing a
response, I found out that the entire interpreter closed when the main
thread exited (killing the daemonic thread in the process). This is
different behavior from running the script interactively, and thus my
confusion.

Thanks! ~Garrick

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


ANN: IbPy 0.7.0-9.00 - Interactive Brokers Python API

2007-02-21 Thread Troy Melhase
IbPy - Interactive Brokers Python API
=
IbPy 0.7.0-9.00 Released 21 Feb 2007


What is IbPy?
--
IbPy is a third-party implementation of the API used for accessing the
Interactive Brokers on-line trading system.  IbPy implements
functionality that the Python programmer can use to connect to IB,
request stock ticker data, submit orders for stocks and futures, and
more.


What's new in this release?
--
IbPy is all new.  TWS API version 9.00 is supported.

IbPy is now generated by machine translation of the reference Java
source code provided by Interactive Brokers.  The translation is made
possible by the java2python_ package.

This version has 100% feature parity with the reference
implementation.  All API calls are supported, as are all options of
each call.  An additional interface (similar to the interface provided
by earlier IbPy releases) is also included.

Because the sources are translated, future versions of the TWS API
will be supported in a matter of hours or days (not weeks or worse).


Where can I get IbPy?
--
IbPy is available for download from Google Code:

http://ibpy.googlecode.com/files/IbPy-0.7.0-9.00.tar.gz

Project page:

http://code.google.com/p/ibpy/


How do I use IbPy?
--
See the IbPy wiki page "Getting Started with IbPy":

http://code.google.com/p/ibpy/wiki/GettingStarted


What are the requirements?
--
IbPy requires Python 2.5 or newer.  Previous versions are not supported.

TWS requires a web browser capable of executing Sun(R) Java(tm)
applets.  TWS can also be started directly with Sun(R) Java(tm) and
the stand-alone package supplied by Interactive Brokers.


What is Interactive Brokers?
--
From the page "`About The Interactive Brokers Group`__":

  Interactive Brokers conducts its broker/dealer and proprietary trading
  businesses on 60 market centers worldwide. In its broker dealer agency
  business, IB provides direct access ("on line") trade execution and
  clearing services to institutional and professional traders for a wide
  variety of electronically traded products including options, futures,
  stocks, forex, and bonds worldwide. In its proprietary trading
  business IB engages in market making for its own account in about
  6,500 different electronically traded products. Interactive Brokers
  Group and its affiliates now trade 19% of the world’s exchange traded
  equity options*, and executes approximately 500,000 trades per day.


What is Python?
--
From the page "`What is Python?`__":

  Python is an interpreted, interactive, object-oriented programming
  language.  It is often compared to Tcl, Perl, Scheme or Java.

  Python combines remarkable power with very clear syntax. It has
  modules, classes, exceptions, very high level dynamic data types, and
  dynamic typing.  There are interfaces to many system calls and
  libraries, as well as to various windowing systems (X11, Motif, Tk,
  Mac, MFC). New built-in modules are easily written in C or C++. Python
  is also usable as an extension language for applications that need a
  programmable interface.

  The Python implementation is portable: it runs on many brands of UNIX,
  on Windows, DOS, OS/2, Mac, Amiga... If your favorite system isn't
  listed here, it may still be supported, if there's a C compiler for
  it. Ask around on comp.lang.python -- or just try compiling Python
  yourself.

  The Python implementation is copyrighted but freely usable and 
distributable,
  even for commercial use.


What Else?
--
IbPy is not a product of Interactive Brokers, nor am I affiliated with
IB.  I am a satisfied IB customer, of course.

IbPy is installed with distutils.  Refer to the Python distutils
documentation for more information.  The digest version is::

$ tar xzf IbPy-0.7.0-9.00.tar.gz
$ cd IbPy-0.7.0-9.00
$ python setup.py install

The TWS demo system is available here:

http://interactivebrokers.com/cgi-pub/jtslink.pl?user_name=edemo

The stand-alone TWS and other API software is available from IB:

http://interactivebrokers.com/

IbPy is distributed under the New BSD License.  See the LICENSE file
in the release for details.

I'm very interested in your experience with IbPy.  Please drop me an
note with any feedback you have.


Troy Melhase
mailto:[EMAIL PROTECTED]



.. _java2python: http://code.google.com/p/java2python/
__ http://www.interactivebrok

pexpect regex help

2007-02-21 Thread jonathan . sabo
I have a pexpect script to walk through a cisco terminal server and I
was hoping to get some help with this regex because I really suck at
it.

This is the code:

index = s.expect(['login: ', pexpect.EOF, pexpect.TIMEOUT])
if index == 0:
m = re.search('((#.+\r\n){20,25})(\s.*)',
s.before)  #<-- MY PROBLEM
print m.group(3),
print ' %s %s' % (ip[0], port)
s.send(chr(30))
s.sendline('x')
s.sendline('disco')
s.sendline('\n')
elif index == 1:
print s.before
elif index == 2:
print
print '%s %s FAILED' % (ip[0], port)
print 'This host may be down or locked on the TS'
s.send(chr(30))
s.sendline('x')
s.sendline('disco')
s.sendline('\n')

This is attempting to match the hostname of the connected host using
the output of a motd file which unfortunately is not the same
everywhere...  It looks like this:

#
#   This system is the property
of: #
#
#
#DefNet
#
#
#
#   Use of this system is for authorized users
only.#
#   Individuals using this computer system without authority, or
in #
#   excess of their authority, are subject to having all of
their   #
#   activities on this system monitored and recorded by
system  #
#
personnel.  #
#
#
#   In the course of monitoring individuals improperly using
this   #
#   system, or in the course of system maintenance, the
activities  #
#   of authorized users may also be
monitored.  #
#
#
#   Anyone using this system expressly consents to such
monitoring  #
#   and is advised that if such monitoring reveals
possible #
#   evidence of criminal activity, system personnel may provide
the #
#   evidence of such monitoring to law enforcement
officials.   #
#

pa-chi1 console login:

And sometimes it looks like this:

#
#   This system is the property
of: #
#
#
#DefNet
#
#
#
#   Use of this system is for authorized users
only.#
#   Individuals using this computer system without authority, or
in #
#   excess of their authority, are subject to having all of
their   #
#   activities on this system monitored and recorded by
system  #
#
personnel.  #
#
#
#   In the course of monitoring individuals improperly using
this   #
#   system, or in the course of system maintenance, the
activities  #
#   of authorized users may also be
monitored.  #
#
#
#   Anyone using this system expressly consents to such
monitoring  #
#   and is advised that if such monitoring reveals
possible #
#   evidence of criminal activity, system personnel may provide
the #
#   evidence of such monitoring to law enforcement
officials.   #
#
pa11-chi1 login:

The second one works and it will print out pa11-chi1  but when there
is a space or console is in the output it wont print anything or it
wont match anything...I want to be able to match just the hostname
and print it out.

Any ideas?

Thanks,

Jonathan

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


Re: pexpect regex help

2007-02-21 Thread jonathan . sabo
On Feb 21, 6:13 pm, [EMAIL PROTECTED] wrote:
> I have a pexpect script to walk through a cisco terminal server and I
> was hoping to get some help with this regex because I really suck at
> it.
>
> This is the code:
>
> index = s.expect(['login: ', pexpect.EOF, pexpect.TIMEOUT])
> if index == 0:
> m = re.search('((#.+\r\n){20,25})(\s.*)',
> s.before)  #<-- MY PROBLEM
> print m.group(3),
> print ' %s %s' % (ip[0], port)
> s.send(chr(30))
> s.sendline('x')
> s.sendline('disco')
> s.sendline('\n')
> elif index == 1:
> print s.before
> elif index == 2:
> print
> print '%s %s FAILED' % (ip[0], port)
> print 'This host may be down or locked on the TS'
> s.send(chr(30))
> s.sendline('x')
> s.sendline('disco')
> s.sendline('\n')
>
> This is attempting to match the hostname of the connected host using
> the output of a motd file which unfortunately is not the same
> everywhere...  It looks like this:
>
> #
> #   This system is the property
> of: #
> #
> #
> #DefNet
> #
> #
> #
> #   Use of this system is for authorized users
> only.#
> #   Individuals using this computer system without authority, or
> in #
> #   excess of their authority, are subject to having all of
> their   #
> #   activities on this system monitored and recorded by
> system  #
> #
> personnel.  #
> #
> #
> #   In the course of monitoring individuals improperly using
> this   #
> #   system, or in the course of system maintenance, the
> activities  #
> #   of authorized users may also be
> monitored.  #
> #
> #
> #   Anyone using this system expressly consents to such
> monitoring  #
> #   and is advised that if such monitoring reveals
> possible #
> #   evidence of criminal activity, system personnel may provide
> the #
> #   evidence of such monitoring to law enforcement
> officials.   #
> #
>
> pa-chi1 console login:
>
> And sometimes it looks like this:
>
> #
> #   This system is the property
> of: #
> #
> #
> #DefNet
> #
> #
> #
> #   Use of this system is for authorized users
> only.#
> #   Individuals using this computer system without authority, or
> in #
> #   excess of their authority, are subject to having all of
> their   #
> #   activities on this system monitored and recorded by
> system  #
> #
> personnel.  #
> #
> #
> #   In the course of monitoring individuals improperly using
> this   #
> #   system, or in the course of system maintenance, the
> activities  #
> #   of authorized users may also be
> monitored.  #
> #
> #
> #   Anyone using this system expressly consents to such
> monitoring  #
> #   and is advised that if such monitoring reveals
> possible #
> #   evidence of criminal activity, system personnel may provide
> the #
> #   evidence of such monitoring to law enforcement
> officials.   #
> #
> pa11-chi1 login:
>
> The second one works and it will print out pa11-chi1  but when there
> is a space or console is in the output it wont print anything or it
> wont match anything...I want to be able to match just the hostname
> and print it out.
>
> Any ideas?
>
> Thanks,
>
> Jonathan



It is also posted here more clearly and formatted as it would appear
on the terminal:  http://www.pastebin.ca/366822

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


Re: getting a thread out of sleep

2007-02-21 Thread mark
On 21 Feb 2007 14:47:50 -0800, placid <[EMAIL PROTECTED]> wrote:
> On Feb 22, 3:23 am, mark <[EMAIL PROTECTED]> wrote:
> > On 20 Feb 2007 21:26:18 -0800, placid <[EMAIL PROTECTED]> wrote:
> >
> >
> >
> > > On Feb 21, 4:21 pm, "placid" <[EMAIL PROTECTED]> wrote:
> > > > On Feb 21, 4:12 pm, mark <[EMAIL PROTECTED]> wrote:
> > > > > On 20 Feb 2007 20:47:57 -0800, placid <[EMAIL PROTECTED]> wrote:
> > > > > > On Feb 21, 3:08 pm, mark <[EMAIL PROTECTED]> wrote:
> > > > > > > Right now I have a thread that  sleeps for sometime and check if 
> > > > > > > an
> > > > > > > event has happened and go back to sleep. Now instead I want the 
> > > > > > > thread
> > > > > > > to sleep until the event has occured process the event and go 
> > > > > > > back to sleep
> >
> > > > > > > class eventhndler(threading.Thread):
> > > > > > > def __init__(self):
> > > > > > > threading.Thread.__init__(self)
> > > > > > > def run(self):
> > > > > > > while True:
> > > > > > > time.sleep(SLEEPTIME)
> > > > > > > do event stuff'''
> >
> > > > > > The way i would do this is by using an threading.Event (
> > > > > >http://docs.python.org/lib/event-objects.html)
> >
> > > > > > 
> >
> > > > > > class eventhandler(threading.Thread):
> > > > > > def __init__(self):
> > > > > > threading.Thread.__init__(self)
> > > > > > self.event = threading.Event()
> > > > > > def run:
> > > > > > while True:
> > > > > > # block until some event happens
> > > > > > self.event.wait()
> > > > > > """ do stuff here """
> > > > > > self.event.clear()
> > > > > > 
> >
> > > > > > the way to use this is to get the main/separate thread to set() the
> > > > > > event object.
> >
> > > > > Can you give an example of how to get the main threead to set teh 
> > > > > event object?
> > > > > this is exactly what i wanted to do!
> > > > > thanks a lot!
> > > > > mark>
> > > oops I've miss-typed the thread variable name the following should
> > > work
> >
> > > 
> > > if __name__ == "__main__":
> > > evtHandlerThread = eventhandler()
> > > evtHandlerThread.start()
> >
> > > # do something here #
> > > evtHandlerThread.event.set()
> >
> > > # do more stuff here #
> > > evtHandlerThread.event.set()
> >
> > > 
> >
> > Can I have the same thread process two or more events? Can you tell
> > how to do this? The code you gave is waiting on one event right. How
> > can I do it for more events?
> > thanks a lot!
> > mark
>
> I don't think a thread can block on more than one event at a time. But
> you can make it block on more then one event one at a time.
>
> 
>
> class eventhandler(threading.Thread):
>def __init__(self):
>threading.Thread.__init__(self)
>self.events = [threading.Event(), threading.Event()]
>self.currentEvent = None
>def run:
>while True:
>for event in self.events:
>self.currentEvent = event
># block until some event happens
>self.currentEvent.wait()
>""" do stuff here """
>self.currentEvent.clear()
>
> if __name__ == "__main__":
> evtHandlerThread = eventhandler()
> evtHandlerThread.start()
>
> # do something here #
> evtHandlerThread.currentEvent.set()
>
> # do more stuff here #
> evtHandlerThread.currentEvent.set()
>
> 
>
> what the thread does is sequentially waits for two events to happen
> and then execute the same code. You could change this code to perform
> different functions for different event objects.

Once the thread starts it is going to wait on the event that is the
first element of the list right?  This would mean :
evtHandlerThread.currentEvent.set(): that I have only one event right?
Can you explain how I can have different event objects. I dont see how
I can do different functinos for same event.

Thanks a lot!

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


RE: f---ing typechecking

2007-02-21 Thread Delaney, Timothy (Tim)
Nick Craig-Wood wrote:

> Which appears to support my point, x (and a for that matter) are the
> same for both methods wheter you do x = x + a or x += a.
>
> The mechanism is different certainly, but the result should be the
> same otherwise you are breaking the basic rules of arithmetic the
> programmer expects (the rule of least suprise).

No - for a mutable object, x may be bound to the original, but
*modified* object after augmented assignment. Any name also bound to
that object will therefore refer to the modified object.

For an immutable object, augmented assignment will not ever modify the
original object.

The two operations may have *very* different effects.

>>> a = [1]
>>> b = [2]
>>> c = a
>>> d = a
>>> c = a + b
>>> a, b, c
([1], [2], [1, 2])
>>> id(a), id(b), id(c)
(11082528, 11271104, 11082328)
>>> a += b
>>> a, b, c
([1, 2], [2], [1, 2])
>>> id(a), id(b), id(c), a is d
(11082528, 11271104, 11082328, True)

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


Re: Question about classes and possible closure.

2007-02-21 Thread Dustan
On Feb 21, 4:30 pm, "Steven W. Orr" <[EMAIL PROTECTED]> wrote:
> This is all an intro learning experience for me, so please feel free to
> explain why what I'm trying to do is not a good idea.
>
> In the Cookbook, they have a recipe for how to create global constants.
>
> -
> class _const:
>  class ConstError(TypeError): pass
>  def __setattr__(self,name,value):
>  if self.__dict__.has_key(name):
>  raise self.ConstError, "Can't rebind const(%s)"%name
>  self.__dict__[name]=value
>
> import sys
> sys.modules[__name__]=_const()
> 
>
> I'd like to be able to create constants within a class. (Yes I understand
> that uppercase names is a far better and easier convention but this is a
> learning experience for me.)
>
> I can't get this to work, but my idea is that MyClass is defined thusly:
>
> class ConstError(TypeError): pass
> class Myclass:
>  def mprint(self):
>  print "C1 = ", self._C1

Looking ahead, this should be "self.consts._C1", not "self._Cl".

>  # Define a subclass to create constants. It refs upself to access
>  # the uplevel copy of self.

It's better to stick with the conventions. But regardless, you have to
be consistent, as we see in a moment.

>  class _const:
>  class ConstError(TypeError): pass

This is redundant. Even though this ConstError and the one defined
before the Myclass definition are in completely different scopes, so
there's no conflict, I doubt this is what you meant to do.

>  def __setattr__(_upself,name,value):

Notice your first argument here is "_upself", with an underscore.

>  if upself.__dict__.has_key(name):

Now you're using "upself", without an underscore, which is undefined.

>  raise self.ConstError, "Can't rebind const(%s)"%name

Now you're using "self", which is also undefined.

>  else:
>  print "Just set something"
>  upself.__dict__[name]=value

Once again, "upself" instead of "_upself".

Just follow the convention: always use "self".

>
>  # I want the const instance to be contained in this class so I
>  # instantiate here in the constructor.
>  def __init__(self):
>  upself = self

Why "upself = self"? You could just as easily use "self". Follow the
conventions.

>  upself.consts = const()

I'm guessing this is your error? That should be "upself.consts =
self._const()"

>  upself.consts._C1 = 0
>  setattr(upself.consts, "_C1", 44)

Obviously, this is going to raise an error, because you're redefining
_Cl.

>  self = upself

Again, why the weird juggling between self and upself? First of all,
self and upself are references to the same object right now, so "self
= upself" has no after-effect at all. Second of all, even if it did,
all it would be doing is reassigning the local variable "self" to a
different object; it has no effect on the object you're working with.

> Then the call in another file is this:
> #! /usr/bin/python
> from c2 import Myclass
> foo = Myclass()
> foo.mprint()
> # end
>
> Is it possible to nest a class in another class and is it possible to make
> this work?

Yes, it is possible to nest a class in another class. Yes, it is
possible to make this work. However, it is good practice to post your
error message along with your code, so we don't have to guess.

Here's an untested rewrite of your code:

class Myclass:
 def mprint(self):
 print "C1 = ", self.consts._C1

 # Define a subclass to create constants. It refs upself to access
 # the uplevel copy of self.
 class _const:
 class ConstError(TypeError): pass
 def __setattr__(_upself,name,value):
 if _upself.__dict__.has_key(name):
 raise _upself.ConstError, "Can't rebind
const(%s)"%name
 else:
 print "Just set something"
 _upself.__dict__[name]=value

 # I want the const instance to be contained in this class so I
 # instantiate here in the constructor.
 def __init__(self):
 self.consts = const()
 self.consts._C1 = 0
 # This will raise an error
 setattr(self.consts, "_C1", 44)

> TIA
>
> --
> Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
> happened but none stranger than this. Does your driver's license say Organ ..0
> Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
> individuals! What if this weren't a hypothetical question?
> steveo at syslang.net

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


Re: network simulator in Python ?

2007-02-21 Thread [EMAIL PROTECTED]
On Feb 21, 12:26 pm, "DanielJohnson" <[EMAIL PROTECTED]> wrote:
> I was wondering if anyblody can suggest me a network simulator written
> in python in which I can add on my own code and extend its
> functionality.
>
> I am looking for a simulator which will simualte TCP, UDP, RTP and
> most networking protocol. The learning curve for ns2 and other
> simulator is too high for me at this time and thats why I am
> considering Python for it.
>
> Every help will be appreciated.
>
> Thanks

Google for Scapy

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


Convert to binary and convert back to strings

2007-02-21 Thread Harlin Seritt
Hi...

I would like to take a string like 'supercalifragilisticexpialidocius'
and write it to a file in binary forms -- this way a user cannot read
the string in case they were try to open in something like ascii text
editor. I'd also like to be able to read the binary formed data back
into string format so that it shows the original value. Is there any
way to do this in Python?

Thanks!

Harlin

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


Re: Convert to binary and convert back to strings

2007-02-21 Thread Colin J. Williams
Harlin Seritt wrote:
> Hi...
> 
> I would like to take a string like 'supercalifragilisticexpialidocius'
> and write it to a file in binary forms -- this way a user cannot read
> the string in case they were try to open in something like ascii text
> editor. I'd also like to be able to read the binary formed data back
> into string format so that it shows the original value. Is there any
> way to do this in Python?
> 
> Thanks!
> 
> Harlin
> 
Try opening your file in the 'wb' mode.

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


jython import search path

2007-02-21 Thread Russ
I have a Python program that I want to run in Jython so I can get Java
bytecode output. The program runs fine in Python, but when I change
the first line of the main program to make it run in Jython, it fails
to find some of the imported modules. These are just plain Python
imports of code I wrote myself in another directory.

Apparently Jython does not use the PYTHONPATH environment variable. I
created an environment variable called JYTHONPATH just to see what
would happen, but it didn't work either. How am I supposed to tell
Jython where to search for imported modules? Thanks.

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


Re: getting a thread out of sleep

2007-02-21 Thread placid
On Feb 22, 10:20 am, mark <[EMAIL PROTECTED]> wrote:
> On 21 Feb 2007 14:47:50 -0800, placid <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Feb 22, 3:23 am, mark <[EMAIL PROTECTED]> wrote:
> > > On 20 Feb 2007 21:26:18 -0800, placid <[EMAIL PROTECTED]> wrote:
>
> > > > On Feb 21, 4:21 pm, "placid" <[EMAIL PROTECTED]> wrote:
> > > > > On Feb 21, 4:12 pm, mark <[EMAIL PROTECTED]> wrote:
> > > > > > On 20 Feb 2007 20:47:57 -0800, placid <[EMAIL PROTECTED]> wrote:
> > > > > > > On Feb 21, 3:08 pm, mark <[EMAIL PROTECTED]> wrote:
> > > > > > > > Right now I have a thread that  sleeps for sometime and check 
> > > > > > > > if an
> > > > > > > > event has happened and go back to sleep. Now instead I want the 
> > > > > > > > thread
> > > > > > > > to sleep until the event has occured process the event and go 
> > > > > > > > back to sleep
>
> > > > > > > > class eventhndler(threading.Thread):
> > > > > > > > def __init__(self):
> > > > > > > > threading.Thread.__init__(self)
> > > > > > > > def run(self):
> > > > > > > > while True:
> > > > > > > > time.sleep(SLEEPTIME)
> > > > > > > > do event stuff'''
>
> > > > > > > The way i would do this is by using an threading.Event (
> > > > > > >http://docs.python.org/lib/event-objects.html)
>
> > > > > > > 
>
> > > > > > > class eventhandler(threading.Thread):
> > > > > > > def __init__(self):
> > > > > > > threading.Thread.__init__(self)
> > > > > > > self.event = threading.Event()
> > > > > > > def run:
> > > > > > > while True:
> > > > > > > # block until some event happens
> > > > > > > self.event.wait()
> > > > > > > """ do stuff here """
> > > > > > > self.event.clear()
> > > > > > > 
>
> > > > > > > the way to use this is to get the main/separate thread to set() 
> > > > > > > the
> > > > > > > event object.
>
> > > > > > Can you give an example of how to get the main threead to set teh 
> > > > > > event object?
> > > > > > this is exactly what i wanted to do!
> > > > > > thanks a lot!
> > > > > > mark>
> > > > oops I've miss-typed the thread variable name the following should
> > > > work
>
> > > > 
> > > > if __name__ == "__main__":
> > > > evtHandlerThread = eventhandler()
> > > > evtHandlerThread.start()
>
> > > > # do something here #
> > > > evtHandlerThread.event.set()
>
> > > > # do more stuff here #
> > > > evtHandlerThread.event.set()
>
> > > > 
>
> > > Can I have the same thread process two or more events? Can you tell
> > > how to do this? The code you gave is waiting on one event right. How
> > > can I do it for more events?
> > > thanks a lot!
> > > mark
>
> > I don't think a thread can block on more than one event at a time. But
> > you can make it block on more then one event one at a time.
>
> > 
>
> > class eventhandler(threading.Thread):
> >def __init__(self):
> >threading.Thread.__init__(self)
> >self.events = [threading.Event(), threading.Event()]
> >self.currentEvent = None
> >def run:
> >while True:
> >for event in self.events:
> >self.currentEvent = event
> ># block until some event happens
> >self.currentEvent.wait()
> >""" do stuff here """
> >self.currentEvent.clear()
>
> > if __name__ == "__main__":
> > evtHandlerThread = eventhandler()
> > evtHandlerThread.start()
>
> > # do something here #
> > evtHandlerThread.currentEvent.set()
>
> > # do more stuff here #
> > evtHandlerThread.currentEvent.set()
>
> > 
>
> > what the thread does is sequentially waits for two events to happen
> > and then execute the same code. You could change this code to perform
> > different functions for different event objects.
>
> Once the thread starts it is going to wait on the event that is the
> first element of the list right?  This would mean :

This is correct.

> evtHandlerThread.currentEvent.set(): that I have only one event right?

this means that the current event occurred.

> Can you explain how I can have different event objects. I dont see how
> I can do different functinos for same event.
>
> Thanks a lot!
>
> mark

To run different functions for the same event is easy, just write a
wrapper class around threading.event() and include some method that
you will run and assign this to different functions for each
EventWrapper.



class EventWrapper():
def __init__(self,work ):
 self.event = threading.Event()
 self.eventWork = work

   def wait(self):
self.event.wait()

   def clear(self)
self.event.clear()

def eventWork(self):
print "no work"

class eventhandler(threading.Thread):
 def __init__(self, events = None):
 threading.Thread.__init__(self)
 self.events = events
 self.currentEvent = None
 def run:
 while True:
 if self.events:
 

Re: Convert to binary and convert back to strings

2007-02-21 Thread Grant Edwards
On 2007-02-21, Harlin Seritt <[EMAIL PROTECTED]> wrote:

> I would like to take a string like
> 'supercalifragilisticexpialidocius' and write it to a file in
> binary forms -- this way a user cannot read the string in case
> they were try to open in something like ascii text editor.

Why wouldn't they be able to read it?  ASCII _is_ binary.

> I'd also like to be able to read the binary formed data back
> into string format so that it shows the original value. Is
> there any way to do this in Python?

What you're describing as "this" doesn't seem to make any
sense.

-- 
Grant Edwards   grante Yow!  Kids, don't gross me
  at   off... "Adventures with
   visi.comMENTAL HYGIENE" can be
   carried too FAR!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert to binary and convert back to strings

2007-02-21 Thread Larry Bates
Harlin Seritt wrote:
> Hi...
> 
> I would like to take a string like 'supercalifragilisticexpialidocius'
> and write it to a file in binary forms -- this way a user cannot read
> the string in case they were try to open in something like ascii text
> editor. I'd also like to be able to read the binary formed data back
> into string format so that it shows the original value. Is there any
> way to do this in Python?
> 
> Thanks!
> 
> Harlin
> 
I promise you that everything written to a file is done in binary.
Computers don't know how to work with anything BUT binary.  I think
what you want to do is to encrypt/obstifucate the string.  For that
you will need to encrypt the string, write it out, read it back in,
and decrypt it.  If you want it to be REALLY strong use pyCrypto
and something like AES-256.

http://www.amk.ca/python/code/crypto

If you just want to make it somewhat hard for someone to decypher
you can do something like below (sorry I can't remember where I
found this to attribute to someone):
import random
import zlib
import time

def tinycode(key, text, reverse=False):
rand = random.Random(key).randrange
if not reverse:
text = zlib.compress(text)
text = ''.join([chr(ord(elem)^rand(256)) for elem in text])
if reverse:
text = zlib.decompress(text)
return text

def strToHex(aString):
hexlist = ["%02X" % ord(x) for x in aString]
return ''.join(hexlist)

def HexTostr(hString):
res = ""
for i in range(len(hString)/2):
realIdx = i*2
res = res + chr(int(hString[realIdx:realIdx+2],16))
return res

if __name__ == "__main__":

keyStr = "This is a key"
#testStr = "which witch had which witches wrist watch abc def ghi"

testStr=time.strftime("%Y%m%d", time.localtime())

print "String:", testStr
etestStr = tinycode(keyStr, testStr)
print "Encrypted string:", etestStr
hex=strToHex(etestStr)
print "Hex: ", hex
print "Len(hex):", len(hex)
nonhex=HexTostr(hex)
#testStr = tinycode(keyStr, etestStr, reverse=True)
testStr = tinycode(keyStr, nonhex, reverse=True)
print "Decrypted string:", testStr

WARNING: THIS IS NOT A STRONG ENCRYPTION ALGORITHM.  It is just a
nuisance for someone that really wants to decrypt the string. But
it might work for your application.

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


Re: jython import search path

2007-02-21 Thread Larry Bates
Russ wrote:
> I have a Python program that I want to run in Jython so I can get Java
> bytecode output. The program runs fine in Python, but when I change
> the first line of the main program to make it run in Jython, it fails
> to find some of the imported modules. These are just plain Python
> imports of code I wrote myself in another directory.
> 
> Apparently Jython does not use the PYTHONPATH environment variable. I
> created an environment variable called JYTHONPATH just to see what
> would happen, but it didn't work either. How am I supposed to tell
> Jython where to search for imported modules? Thanks.
> 
Maybe Jython expert has the perfect answer but til then.

Did you try:

sys.path.append('path to search')

Usually this works if nothing else does.

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


Re: Convert to binary and convert back to strings

2007-02-21 Thread Harlin Seritt
On Feb 21, 7:02 pm, "Colin J. Williams" <[EMAIL PROTECTED]> wrote:
> Harlin Seritt wrote:
> > Hi...
>
> > I would like to take a string like 'supercalifragilisticexpialidocius'
> > and write it to a file in binary forms -- this way a user cannot read
> > the string in case they were try to open in something like ascii text
> > editor. I'd also like to be able to read the binary formed data back
> > into string format so that it shows the original value. Is there any
> > way to do this in Python?
>
> > Thanks!
>
> > Harlin
>
> Try opening your file in the 'wb' mode.
>
> Colin W.

Thanks for the help.

I tried doing this:

text = 'supercalifragilisticexpialidocius'

open('sambleb.conf', 'wb').write(text)

Afterwards, I was able to successfully open the file with a text
editor and it showed:
'supercalifragilisticexpialidocius'

I am hoping to have it show up some weird un-readable text. And then
of course be able to convert it right back to a string. Is this even
possible?

Thanks,

Harlin

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


Which Crypto Library?

2007-02-21 Thread GiBo
Hi

I need some encryption done in my Python 2.5 application. I wonder
what's the most recommended library? I've found M2crypto and some
OpenSSL wrappers and Python Cryptography Toolkit and some others. No
surprise I'm confused :-)

What's the most often used library for crypto?

For now I need a simple AES, no asymmetric crypto or GPG involved.

Thanks!

GiBo



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


Re: Convert to binary and convert back to strings

2007-02-21 Thread Harlin Seritt
On Feb 21, 7:12 pm, Larry Bates <[EMAIL PROTECTED]> wrote:
> Harlin Seritt wrote:
> > Hi...
>
> > I would like to take a string like 'supercalifragilisticexpialidocius'
> > and write it to a file in binary forms -- this way a user cannot read
> > the string in case they were try to open in something like ascii text
> > editor. I'd also like to be able to read the binary formed data back
> > into string format so that it shows the original value. Is there any
> > way to do this in Python?
>
> > Thanks!
>
> > Harlin
>
> I promise you that everything written to a file is done in binary.
> Computers don't know how to work with anything BUT binary.  I think
> what you want to do is to encrypt/obstifucate the string.  For that
> you will need to encrypt the string, write it out, read it back in,
> and decrypt it.  If you want it to be REALLY strong use pyCrypto
> and something like AES-256.
>
> http://www.amk.ca/python/code/crypto
>
> If you just want to make it somewhat hard for someone to decypher
> you can do something like below (sorry I can't remember where I
> found this to attribute to someone):
> import random
> import zlib
> import time
>
> def tinycode(key, text, reverse=False):
> rand = random.Random(key).randrange
> if not reverse:
> text = zlib.compress(text)
> text = ''.join([chr(ord(elem)^rand(256)) for elem in text])
> if reverse:
> text = zlib.decompress(text)
> return text
>
> def strToHex(aString):
> hexlist = ["%02X" % ord(x) for x in aString]
> return ''.join(hexlist)
>
> def HexTostr(hString):
> res = ""
> for i in range(len(hString)/2):
> realIdx = i*2
> res = res + chr(int(hString[realIdx:realIdx+2],16))
> return res
>
> if __name__ == "__main__":
>
> keyStr = "This is a key"
> #testStr = "which witch had which witches wrist watch abc def ghi"
>
> testStr=time.strftime("%Y%m%d", time.localtime())
>
> print "String:", testStr
> etestStr = tinycode(keyStr, testStr)
> print "Encrypted string:", etestStr
> hex=strToHex(etestStr)
> print "Hex: ", hex
> print "Len(hex):", len(hex)
> nonhex=HexTostr(hex)
> #testStr = tinycode(keyStr, etestStr, reverse=True)
> testStr = tinycode(keyStr, nonhex, reverse=True)
> print "Decrypted string:", testStr
>
> WARNING: THIS IS NOT A STRONG ENCRYPTION ALGORITHM.  It is just a
> nuisance for someone that really wants to decrypt the string. But
> it might work for your application.
>
> -Larry

Thanks Larry! I was looking for something more beautiful but what the
hey, it works!

Harlin

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


Re: jython import search path

2007-02-21 Thread Russ
On Feb 21, 4:15 pm, Larry Bates <[EMAIL PROTECTED]> wrote:
> Russ wrote:
> > I have a Python program that I want to run in Jython so I can get Java
> > bytecode output. The program runs fine in Python, but when I change
> > the first line of the main program to make it run in Jython, it fails
> > to find some of the imported modules. These are just plain Python
> > imports of code I wrote myself in another directory.
>
> > Apparently Jython does not use the PYTHONPATH environment variable. I
> > created an environment variable called JYTHONPATH just to see what
> > would happen, but it didn't work either. How am I supposed to tell
> > Jython where to search for imported modules? Thanks.
>
> Maybe Jython expert has the perfect answer but til then.
>
> Did you try:
>
> sys.path.append('path to search')
>
> Usually this works if nothing else does.
>
> -Larry

Thanks. That's a good workaround, but I would like to know the
"correct" way to do it too if anyone out there knows.

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


Re: getting a thread out of sleep

2007-02-21 Thread mark
On 21 Feb 2007 16:10:51 -0800, placid <[EMAIL PROTECTED]> wrote:
> On Feb 22, 10:20 am, mark <[EMAIL PROTECTED]> wrote:
> > On 21 Feb 2007 14:47:50 -0800, placid <[EMAIL PROTECTED]> wrote:
> >
> >
> >
> > > On Feb 22, 3:23 am, mark <[EMAIL PROTECTED]> wrote:
> > > > On 20 Feb 2007 21:26:18 -0800, placid <[EMAIL PROTECTED]> wrote:
> >
> > > > > On Feb 21, 4:21 pm, "placid" <[EMAIL PROTECTED]> wrote:
> > > > > > On Feb 21, 4:12 pm, mark <[EMAIL PROTECTED]> wrote:
> > > > > > > On 20 Feb 2007 20:47:57 -0800, placid <[EMAIL PROTECTED]> wrote:
> > > > > > > > On Feb 21, 3:08 pm, mark <[EMAIL PROTECTED]> wrote:
> > > > > > > > > Right now I have a thread that  sleeps for sometime and check 
> > > > > > > > > if an
> > > > > > > > > event has happened and go back to sleep. Now instead I want 
> > > > > > > > > the thread
> > > > > > > > > to sleep until the event has occured process the event and go 
> > > > > > > > > back to sleep
> >
> > > > > > > > > class eventhndler(threading.Thread):
> > > > > > > > > def __init__(self):
> > > > > > > > > threading.Thread.__init__(self)
> > > > > > > > > def run(self):
> > > > > > > > > while True:
> > > > > > > > > time.sleep(SLEEPTIME)
> > > > > > > > > do event stuff'''
> >
> > > > > > > > The way i would do this is by using an threading.Event (
> > > > > > > >http://docs.python.org/lib/event-objects.html)
> >
> > > > > > > > 
> >
> > > > > > > > class eventhandler(threading.Thread):
> > > > > > > > def __init__(self):
> > > > > > > > threading.Thread.__init__(self)
> > > > > > > > self.event = threading.Event()
> > > > > > > > def run:
> > > > > > > > while True:
> > > > > > > > # block until some event happens
> > > > > > > > self.event.wait()
> > > > > > > > """ do stuff here """
> > > > > > > > self.event.clear()
> > > > > > > > 
> >
> > > > > > > > the way to use this is to get the main/separate thread to set() 
> > > > > > > > the
> > > > > > > > event object.
> >
> > > > > > > Can you give an example of how to get the main threead to set teh 
> > > > > > > event object?
> > > > > > > this is exactly what i wanted to do!
> > > > > > > thanks a lot!
> > > > > > > mark>
> > > > > oops I've miss-typed the thread variable name the following should
> > > > > work
> >
> > > > > 
> > > > > if __name__ == "__main__":
> > > > > evtHandlerThread = eventhandler()
> > > > > evtHandlerThread.start()
> >
> > > > > # do something here #
> > > > > evtHandlerThread.event.set()
> >
> > > > > # do more stuff here #
> > > > > evtHandlerThread.event.set()
> >
> > > > > 
> >
> > > > Can I have the same thread process two or more events? Can you tell
> > > > how to do this? The code you gave is waiting on one event right. How
> > > > can I do it for more events?
> > > > thanks a lot!
> > > > mark
> >
> > > I don't think a thread can block on more than one event at a time. But
> > > you can make it block on more then one event one at a time.
> >
> > > 
> >
> > > class eventhandler(threading.Thread):
> > >def __init__(self):
> > >threading.Thread.__init__(self)
> > >self.events = [threading.Event(), threading.Event()]
> > >self.currentEvent = None
> > >def run:
> > >while True:
> > >for event in self.events:
> > >self.currentEvent = event
> > ># block until some event happens
> > >self.currentEvent.wait()
> > >""" do stuff here """
> > >self.currentEvent.clear()
> >
> > > if __name__ == "__main__":
> > > evtHandlerThread = eventhandler()
> > > evtHandlerThread.start()
> >
> > > # do something here #
> > > evtHandlerThread.currentEvent.set()
> >
> > > # do more stuff here #
> > > evtHandlerThread.currentEvent.set()
> >
> > > 
> >
> > > what the thread does is sequentially waits for two events to happen
> > > and then execute the same code. You could change this code to perform
> > > different functions for different event objects.
> >
> > Once the thread starts it is going to wait on the event that is the
> > first element of the list right?  This would mean :
>
> This is correct.
>
> > evtHandlerThread.currentEvent.set(): that I have only one event right?
>
> this means that the current event occurred.
>
> > Can you explain how I can have different event objects. I dont see how
> > I can do different functinos for same event.
> >
> > Thanks a lot!
> >
> > mark
>
> To run different functions for the same event is easy, just write a
> wrapper class around threading.event() and include some method that
> you will run and assign this to different functions for each
> EventWrapper.
>
> 
>
> class EventWrapper():
> def __init__(self,work ):
>  self.event = threading.Event()
>  self.eventWork = work
>
>def wait(self):
> self.event.wait()
>
>def clear(self

Re: Convert to binary and convert back to strings

2007-02-21 Thread [EMAIL PROTECTED]
On Feb 21, 5:50 pm, "Harlin Seritt" <[EMAIL PROTECTED]> wrote:
> Hi...
>
> I would like to take a string like 'supercalifragilisticexpialidocius'
> and write it to a file in binary forms -- this way a user cannot read
> the string in case they were try to open in something like ascii text
> editor. I'd also like to be able to read the binary formed data back
> into string format so that it shows the original value. Is there any
> way to do this in Python?
>
> Thanks!
>
> Harlin

import gmpy  # GNU Multi-Prceision library for Python

f = open('getty.txt','r')
s = f.read()
f.close

print
print 'source file:'
print
print s

count = 0
f = open('getty_binary.txt','w')
for c in s:
o = ord(c)
b = gmpy.digits(o,2)
d = '0'*(8-len(b)) + b
w = '%s ' % d
f.write(w)
count += 1
if count % 5==0:
f.write('\n')
f.close

f = open('getty_binary.txt','r')
s = f.readlines()
f.close

print
print 'binary file:'
print

for i in s:
print i,
print

c = []
for k in s:
q = k.split()
for m in q:
c.append(chr(int(m,2)))

new_s = ''.join(c)

print
print 'decoded binary:'
print
print new_s
print


## output


##source file:
##
##Four score and seven years ago,
##our fathers brought forth on this continent
##a new nation, conceived in liberty
##and dedicated to the propostion that
##all men are created equal.
##
##
##binary file:
##
##01000110 0110 01110101 01110010 0010
##01110011 01100011 0110 01110010 01100101
##0010 0111 01101110 01100100 0010
##01110011 01100101 01110110 01100101 01101110
##0010 0001 01100101 0111 01110010
##01110011 0010 0111 01100111 0110
##00101100 1010 0110 01110101 01110010
##0010 01100110 0111 01110100 01101000
##01100101 01110010 01110011 0010 01100010
##01110010 0110 01110101 01100111 01101000
##01110100 0010 01100110 0110 01110010
##01110100 01101000 0010 0110 01101110
##0010 01110100 01101000 01101001 01110011
##0010 01100011 0110 01101110 01110100
##01101001 01101110 01100101 01101110 01110100
##1010 0111 0010 01101110 01100101
##01110111 0010 01101110 0111 01110100
##01101001 0110 01101110 00101100 0010
##01100011 0110 01101110 01100011 01100101
##01101001 01110110 01100101 01100100 0010
##01101001 01101110 0010 01101100 01101001
##01100010 01100101 01110010 01110100 0001
##1010 0111 01101110 01100100 0010
##01100100 01100101 01100100 01101001 01100011
##0111 01110100 01100101 01100100 0010
##01110100 0110 0010 01110100 01101000
##01100101 0010 0111 01110010 0110
##0111 0110 01110011 01110100 01101001
##0110 01101110 0010 01110100 01101000
##0111 01110100 1010 0111 01101100
##01101100 0010 01101101 01100101 01101110
##0010 0111 01110010 01100101 0010
##01100011 01110010 01100101 0111 01110100
##01100101 01100100 0010 01100101 01110001
##01110101 0111 01101100 00101110 1010
##
##
##decoded binary:
##
##Four score and seven years ago,
##our fathers brought forth on this continent
##a new nation, conceived in liberty
##and dedicated to the propostion that
##all men are created equal.








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


guess file type in python

2007-02-21 Thread mark
Is there any way to guess the file type using python?
thanks
mark

For example in unix:

file code.py
code.py: a python script text executable

file Eccentric.gif
Eccentric.gif: GIF image data, version 89a, 237 x 277
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Which Crypto Library?

2007-02-21 Thread James Stroud
GiBo wrote:
> Hi
> 
> I need some encryption done in my Python 2.5 application. I wonder
> what's the most recommended library? I've found M2crypto and some
> OpenSSL wrappers and Python Cryptography Toolkit and some others. No
> surprise I'm confused :-)
> 
> What's the most often used library for crypto?
> 
> For now I need a simple AES, no asymmetric crypto or GPG involved.
> 
> Thanks!
> 
> GiBo
> 
> 
> 

I use pycrypto without any simplification wrappers (e.g. ezPyCrypto) and 
it seems straightforward to me. You might try the simplification 
wrappers though.

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


Bug in time module - %z works in perl, not in python?

2007-02-21 Thread bwooster47
Following python code prints out incorrect UTC Offset - the python
docs say that %z is not fully supported on all platforms - but on
Linux Fedora FC5, perl code works and python does not - is this a bug
or is this expected behavior? For a EST timezone setup, Perl prints
correct -0500, while Python prints + - this is Python 2.4.

Perl:
$now_string = strftime "%Y-%m-%d %H:%M:%S %Z%z", localtime;
print $now_string, "(iso local)\n";

2007-02-21 21:16:16 EST-0500 (iso localtime, perl)

Python:
now_string = time.strftime("%Y-%m-%d %H:%M:%S %Z%z", time.localtime())
print now_string, " (iso localtime, python)"

2007-02-21 21:15:58 EST+  (iso localtime, python)

Is this expected behavior, or a bug?

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


Re: Convert to binary and convert back to strings

2007-02-21 Thread Grant Edwards
On 2007-02-22, Harlin Seritt <[EMAIL PROTECTED]> wrote:

>> Try opening your file in the 'wb' mode.

> I tried doing this:
>
> text = 'supercalifragilisticexpialidocius'
>
> open('sambleb.conf', 'wb').write(text)
>
> Afterwards, I was able to successfully open the file with a text
> editor and it showed:
> 'supercalifragilisticexpialidocius'

Of course it did.

> I am hoping to have it show up some weird un-readable text.
> And then of course be able to convert it right back to a
> string. Is this even possible?

Sure.  That's what is called "encryption".  There are a bunch
of encryption libraries for Python.

http://www.amk.ca/python/code/crypto
http://www.freenet.org.nz/ezPyCrypto
http://www.example-code.com/python/encryption.asp
http://www.chilkatsoft.com/python-encryption.asp

-- 
Grant Edwards   grante Yow!  Two with FLUFFO,
  at   hold th' BEETS...side of
   visi.comSOYETTES!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: guess file type in python

2007-02-21 Thread GiBo
mark wrote:
> Is there any way to guess the file type using python?
> thanks
> mark
> 
> For example in unix:
> 
> file code.py
> code.py: a python script text executable
> 
> file Eccentric.gif
> Eccentric.gif: GIF image data, version 89a, 237 x 277

"file" tool uses libmagic.so library which in turn uses /etc/magic file
with file format descriptions. To get some reliable results you'll have
to call libmagic. The "file-4.xx.tar.gz" source tarball has python
bindings included and there's a python-magic package (at least in
Debian) that provides libmagic bindings for python.

HTH,

GiBo



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


Re: Bug in time module - %z works in perl, not in python?

2007-02-21 Thread attn . steven . kuo
On Feb 21, 6:17 pm, [EMAIL PROTECTED] wrote:
> Following python code prints out incorrect UTC Offset - the python
> docs say that %z is not fully supported on all platforms - but on
> Linux Fedora FC5, perl code works and python does not - is this a bug
> or is this expected behavior? For a EST timezone setup, Perl prints
> correct -0500, while Python prints + - this is Python 2.4.
>
> Perl:
> $now_string = strftime "%Y-%m-%d %H:%M:%S %Z%z", localtime;
> print $now_string, "(iso local)\n";
>
> 2007-02-21 21:16:16 EST-0500 (iso localtime, perl)
>
> Python:
> now_string = time.strftime("%Y-%m-%d %H:%M:%S %Z%z", time.localtime())
> print now_string, " (iso localtime, python)"
>
> 2007-02-21 21:15:58 EST+  (iso localtime, python)
>
> Is this expected behavior, or a bug?




Seems to be a bug.  I can duplicate the
problem here (Python 2.4.3, Red Hat Desktop release 4).

I do see the correct output, however, if I pass just
the format string to strftime:

>>> print time.strftime("%Y-%m-%d %H:%M:%S %Z %z")
2007-02-21 18:42:03 PST -0800

>>> print time.strftime("%Y-%m-%d %H:%M:%S %Z %z", time.localtime())
2007-02-21 18:42:11 PST +

--
Hope this helps,
Steven

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


Re: getting a thread out of sleep

2007-02-21 Thread placid
On Feb 22, 12:08 pm, mark <[EMAIL PROTECTED]> wrote:
> On 21 Feb 2007 16:10:51 -0800, placid <[EMAIL PROTECTED]> wrote:
>
> > On Feb 22, 10:20 am, mark <[EMAIL PROTECTED]> wrote:
> > > On 21 Feb 2007 14:47:50 -0800, placid <[EMAIL PROTECTED]> wrote:
>
> > > > On Feb 22, 3:23 am, mark <[EMAIL PROTECTED]> wrote:
> > > > > On 20 Feb 2007 21:26:18 -0800, placid <[EMAIL PROTECTED]> wrote:
>
> > > > > > On Feb 21, 4:21 pm, "placid" <[EMAIL PROTECTED]> wrote:
> > > > > > > On Feb 21, 4:12 pm, mark <[EMAIL PROTECTED]> wrote:
> > > > > > > > On 20 Feb 2007 20:47:57 -0800, placid <[EMAIL PROTECTED]> wrote:
> > > > > > > > > On Feb 21, 3:08 pm, mark <[EMAIL PROTECTED]> wrote:
> > > > > > > > > > Right now I have a thread that  sleeps for sometime and 
> > > > > > > > > > check if an
> > > > > > > > > > event has happened and go back to sleep. Now instead I want 
> > > > > > > > > > the thread
> > > > > > > > > > to sleep until the event has occured process the event and 
> > > > > > > > > > go back to sleep
>
> > > > > > > > > > class eventhndler(threading.Thread):
> > > > > > > > > > def __init__(self):
> > > > > > > > > > threading.Thread.__init__(self)
> > > > > > > > > > def run(self):
> > > > > > > > > > while True:
> > > > > > > > > > time.sleep(SLEEPTIME)
> > > > > > > > > > do event stuff'''
>
> > > > > > > > > The way i would do this is by using an threading.Event (
> > > > > > > > >http://docs.python.org/lib/event-objects.html)
>
> > > > > > > > > 
>
> > > > > > > > > class eventhandler(threading.Thread):
> > > > > > > > > def __init__(self):
> > > > > > > > > threading.Thread.__init__(self)
> > > > > > > > > self.event = threading.Event()
> > > > > > > > > def run:
> > > > > > > > > while True:
> > > > > > > > > # block until some event happens
> > > > > > > > > self.event.wait()
> > > > > > > > > """ do stuff here """
> > > > > > > > > self.event.clear()
> > > > > > > > > 
>
> > > > > > > > > the way to use this is to get the main/separate thread to 
> > > > > > > > > set() the
> > > > > > > > > event object.
>
> > > > > > > > Can you give an example of how to get the main threead to set 
> > > > > > > > teh event object?
> > > > > > > > this is exactly what i wanted to do!
> > > > > > > > thanks a lot!
> > > > > > > > mark>
> > > > > > oops I've miss-typed the thread variable name the following should
> > > > > > work
>
> > > > > > 
> > > > > > if __name__ == "__main__":
> > > > > > evtHandlerThread = eventhandler()
> > > > > > evtHandlerThread.start()
>
> > > > > > # do something here #
> > > > > > evtHandlerThread.event.set()
>
> > > > > > # do more stuff here #
> > > > > > evtHandlerThread.event.set()
>
> > > > > > 
>
> > > > > Can I have the same thread process two or more events? Can you tell
> > > > > how to do this? The code you gave is waiting on one event right. How
> > > > > can I do it for more events?
> > > > > thanks a lot!
> > > > > mark
>
> > > > I don't think a thread can block on more than one event at a time. But
> > > > you can make it block on more then one event one at a time.
>
> > > > 
>
> > > > class eventhandler(threading.Thread):
> > > >def __init__(self):
> > > >threading.Thread.__init__(self)
> > > >self.events = [threading.Event(), threading.Event()]
> > > >self.currentEvent = None
> > > >def run:
> > > >while True:
> > > >for event in self.events:
> > > >self.currentEvent = event
> > > ># block until some event happens
> > > >self.currentEvent.wait()
> > > >""" do stuff here """
> > > >self.currentEvent.clear()
>
> > > > if __name__ == "__main__":
> > > > evtHandlerThread = eventhandler()
> > > > evtHandlerThread.start()
>
> > > > # do something here #
> > > > evtHandlerThread.currentEvent.set()
>
> > > > # do more stuff here #
> > > > evtHandlerThread.currentEvent.set()
>
> > > > 
>
> > > > what the thread does is sequentially waits for two events to happen
> > > > and then execute the same code. You could change this code to perform
> > > > different functions for different event objects.
>
> > > Once the thread starts it is going to wait on the event that is the
> > > first element of the list right?  This would mean :
>
> > This is correct.
>
> > > evtHandlerThread.currentEvent.set(): that I have only one event right?
>
> > this means that the current event occurred.
>
> > > Can you explain how I can have different event objects. I dont see how
> > > I can do different functinos for same event.
>
> > > Thanks a lot!
>
> > > mark
>
> > To run different functions for the same event is easy, just write a
> > wrapper class around threading.event() and include some method that
> > you will run and assign this to different functions for each
> > EventWrapper.
>
> > 
>
> 

  1   2   >