Re: Pass 'this' to a python script in an extended application

2007-01-19 Thread Stou Sandalski
I figured it out.  I just made my main class a singleton and it worked
fine... it always works right after I post a message =)

Stou

Stou Sandalski wrote:
> Hi,
>
> I have an application consisting of a main C++ class (and other
> classes) stored inside a DLL.  The application uses a small main
> executable that links against the main DLL, then initializes and runs
> the core class.  The python bindings are inside a .pyd module that also
> links against the core DLL file.  I was able to generate the python
> bindings against the core class using SWIG.   The application can now
> be run either by the bootstrap executable or through the python console
> like:
>
> import foo
> s = foo.MainClass()
> s.run();
>
> This is awesome, however I want to be able to launch python scripts
> from within the application itself (no matter how it was started) and
> supply these scripts with a "pointer" to the already initialized main
> Class something like:
>
> import foo
>
> s = foo.GetMainClass()
> s.someMethod().
>
> I found this:
>
> http://docs.python.org/ext/extending-with-embedding.html
>
> but the problem is that I don't know how to "give" the python
> interpreter a "pointer" to my class that will be compatible with the
> already defined bindings that SWIG generated.  I am trying to keep the
> core application dll from knowing about the .pyd extension module.
>
> I apologize if this post belongs in a group dedicated to SWIG.
> 
> Stou

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


Re: Units of measurement

2007-01-19 Thread Tim Roberts
Paul Rubin  wrote:
>
>I'm sure this has been done before, but it just struck my fancy, an
>example of Python's "emulating numeric types", inspired by the old
>Unix "units" utility, and the Frink language.  
>...
># could include more units but you get the idea
>...
>c = 186282*mile/second
>print 'speed of light =', c/(furlong/fortnight), 'furlongs per fortnight'
># ...

I could not skip to the next message without cutting, pasting, and
executing that script to find out what the speed of light actually was in
furlongs per fortnight.

Now I need to figure out how to work that into a cocktail party
conversation.  "Hey, the deficit isn't the only thing that is approaching
1.8 trillion..."
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is it possible to fasten the import of cgi?

2007-01-19 Thread Tim Roberts
Cecil Westerhof <[EMAIL PROTECTED]> wrote:
>
>I have a cgi-script dat uses the modules cgi, os, sys and time. Offcourse I
>can not time the time used to import time, but os and sys do not take more
>as a millisecond. My script itself takes 3 or 4 milliseconds. But importing
>cgi takes 95 milliseconds. (This is on my test system a PII 300 MHz. Is
>there a way to make this more fast? The import off cgi makes the script at
>least 20 times as slow. Something like mod-python is not a possibility. I
>could use it on my test machine, but not at the osting provider.

Realistically, do you plan to support more than a few dozen requests per
minute?  If not, then it doesn't matter at all.  The script launch overhead
is an insignificant part of the user's browser experience.

If you do expect a hundred requests per minute, then CGI is not an
appropriate choice.  You either need to switch to a one of the web
frameworks (like CherryPy or Django or WebWare or one of the hundreds of
others), or  move to PHP.
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to read and write huge binary files

2007-01-19 Thread Tim Roberts
"Lad" <[EMAIL PROTECTED]> wrote:
>
>What is a good  way to read binary data from HUGE  file and write  it
>to another file?

How huge?  I regularly process 100-megabyte MPEG files in Python, both by
reading the whole thing in as a string, and by using "mmap" to map the file
into memory.
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Login Form

2007-01-19 Thread Ghirai
Hello python-list,

I need to make a login form, if possible without cookies.
Can anyone point me in the right direction? Or are there any
examples?

Thanks.

-- 
Best regards,
Ghirai.

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


Re: PyODBC Stored proc calling

2007-01-19 Thread king kikapu
No one is using pyodbc ??  :)

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


error when import gtk.glade

2007-01-19 Thread Milad Rastian

hello
when I import gtk.glade I got this error :

Traceback (most recent call last):
 File "MainWindow.py", line 20, in ?
   import gtk.glade
ImportError: DLL load failed: The specified module could not be found.

I setup gtk and when I create my interface in my code my gtk window open
correctly
tnx
--
/
Milad Rastian
-- 
http://mail.python.org/mailman/listinfo/python-list

www.OutpatientSurgicare.com/video/

2007-01-19 Thread AwesomeMultimedia.com
www.OutpatientSurgicare.com/video/
Outpatient Doctors Surgery Center is committed to offering the
healthcare the community needs.  We offer patients a meaningful
alternative to traditional surgery. This state-of-the-art outpatient
surgery center, located in the heart of Orange County, at 10900 Warner
Avenue, Suite 101A, Fountain Valley, Ca 92708, offers the latest
innovations in outpatient surgery and technology.
Please Call For Our Special Cash Discount
Toll Free: 1-877-500-2525
Please Visit Our Websites:
We offer extreme cosmetic surgery makeover packages.
http://www.SurgeonToTheStars.com
http://www.1cosmeticsurgery.com
Specializing in the cure of hyperhidrosis, sweaty palms, underarm and
foot sweating.
http://www.CuresweatyPalms.com
http://www.ControlExcessiveSweating.com
No. 1 Weight Loss Surgery Center
http://www.ControlWeightLossNow.com
http://www.FreeLapBandSeminar.com
Hernia Treatment Center
http://www.HerniaDoc.com
Take care of your feet
http://www.CureFootPain.com
The Experts in CARPAL TUNNEL SYNDROME
http://www.CureHandPain.com

Accidental Urine Leaks ?  End Urinary Incontinence
http://www.WomanWellnessCenter.com
Hemorrhoid Treatment Center
http://www.hemorrhoidtreatmentcenter.com

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


Re: Is it possible to fasten the import of cgi?

2007-01-19 Thread BJörn Lindqvist
On 1/18/07, Cecil Westerhof <[EMAIL PROTECTED]> wrote:
> I have a cgi-script dat uses the modules cgi, os, sys and time. Offcourse I
> can not time the time used to import time, but os and sys do not take more
> as a millisecond. My script itself takes 3 or 4 milliseconds. But importing
> cgi takes 95 milliseconds. (This is on my test system a PII 300 MHz. Is
> there a way to make this more fast? The import off cgi makes the script at
> least 20 times as slow. Something like mod-python is not a possibility. I
> could use it on my test machine, but not at the osting provider.

Maybe python-launcher-daemon can help you?
http://blogs.gnome.org/view/johan/2007/01/18/0 But if you can not use
mod_python then you probably can not use any long running processes
either.

-- 
mvh Björn
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why this script can work?

2007-01-19 Thread Diez B. Roggisch
Jm lists wrote:

> Please help with this script:
> 
> class ShortInputException(Exception):
> '''A user-defined exception class.'''
> def __init__(self,length,atleast):
> Exception.__init__(self)
> self.length=length
> self.atleast=atleast
> 
> try:
> s=raw_input('Enter something --> ')
> if len(s)<3:
> raise ShortInputException(len(s),3)
> # Other work can continue as usual here
> except EOFError:
> print '\nWhy did you do an EOF on me?'
> except ShortInputException,x:
> print 'ShortInputException: The input was of length %d, was
> expecting at least %d' %(x.length,x.atleast)
> else:
> print 'No exception was raised.'
> 
> 
> My questions are:
> 
> 1) ShortInputException,x:   what's the 'x'? where is it coming?

except , :

will catch an exception of the kind specified in  (it might
actually be more than one), and store the exception object in the variable
named 

> 2) The 'if' and 'else' are not in the same indent scope,why this can work?


Because additionally to if, also for and try have else-clauses. The latter
two are only being called if the body of the control structure hasn't been
left due to "unnatural" circumstances. See this:




for i in xrange(10):
pass
else:
print "test 1"

for i in xrange(10):
break
else:
print "test 2"

try:
pass
except:
pass
else:
print "test 3"

try:
raise "I know I shouldn't rais strings..."
except:
pass
else:
print "test 4"



It will only print 

test 1
test 3


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


Re: Match 2 words in a line of file

2007-01-19 Thread harvey . thomas

Rickard Lindberg wrote:

> I see two potential problems with the non regex solutions.
>
> 1) Consider a line: "foo (bar)". When you split it you will only get
> two strings, as split by default only splits the string on white space
> characters. Thus "'bar' in words" will return false, even though bar is
> a word in that line.
>
> 2) If you have a line something like this: "foobar hello" then "'foo'
> in line" will return true, even though foo is not a word (it is part of
> a word).

Here's a solution using re.split:

import re
import StringIO

wordsplit = re.compile('\W+').split
def matchlines(fh, w1, w2):
w1 = w1.lower()
w2 = w2.lower()
for line in fh:
words = [x.lower() for x in wordsplit(line)]
if w1 in words and w2 in words:
print line.rstrip()

test = """1st line of text (not matched)
2nd line of words (not matched)
3rd line (Word test) should match (case insensitivity)
4th line simple test of word's (matches)
5th line simple test of words not found (plural words)
6th line tests produce strange words (no match - plural)
7th line "word test" should find this
"""
matchlines(StringIO.StringIO(test), 'test', 'word')

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


Re: Why this script can work?

2007-01-19 Thread Jm lists
Thanks for all the helps.
I'm not habitual for this usage of 'else',other languages seem don't
support this syntax.
i.g,writting the codes below by Perl would get an error:

# perl -le 'for $i  (1..10){print $i}  else{print "finished"}'
syntax error at -e line 1, near "}else"
Execution of -e aborted due to compilation errors.

2007/1/19, Diez B. Roggisch <[EMAIL PROTECTED]>:
> Jm lists wrote:
>
> > Please help with this script:
> >
> > class ShortInputException(Exception):
> > '''A user-defined exception class.'''
> > def __init__(self,length,atleast):
> > Exception.__init__(self)
> > self.length=length
> > self.atleast=atleast
> >
> > try:
> > s=raw_input('Enter something --> ')
> > if len(s)<3:
> > raise ShortInputException(len(s),3)
> > # Other work can continue as usual here
> > except EOFError:
> > print '\nWhy did you do an EOF on me?'
> > except ShortInputException,x:
> > print 'ShortInputException: The input was of length %d, was
> > expecting at least %d' %(x.length,x.atleast)
> > else:
> > print 'No exception was raised.'
> >
> >
> > My questions are:
> >
> > 1) ShortInputException,x:   what's the 'x'? where is it coming?
>
> except , :
>
> will catch an exception of the kind specified in  (it might
> actually be more than one), and store the exception object in the variable
> named 
>
> > 2) The 'if' and 'else' are not in the same indent scope,why this can work?
>
>
> Because additionally to if, also for and try have else-clauses. The latter
> two are only being called if the body of the control structure hasn't been
> left due to "unnatural" circumstances. See this:
>
>
>
>
> for i in xrange(10):
> pass
> else:
> print "test 1"
>
> for i in xrange(10):
> break
> else:
> print "test 2"
>
> try:
> pass
> except:
> pass
> else:
> print "test 3"
>
> try:
> raise "I know I shouldn't rais strings..."
> except:
> pass
> else:
> print "test 4"
>
>
>
> It will only print
>
> test 1
> test 3
>
>
> Diez
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Match 2 words in a line of file

2007-01-19 Thread harvey . thomas

Rickard Lindberg wrote:

> I see two potential problems with the non regex solutions.
>
> 1) Consider a line: "foo (bar)". When you split it you will only get
> two strings, as split by default only splits the string on white space
> characters. Thus "'bar' in words" will return false, even though bar is
> a word in that line.
>
> 2) If you have a line something like this: "foobar hello" then "'foo'
> in line" will return true, even though foo is not a word (it is part of
> a word).

Here's a solution using re.split:

import re
import StringIO

wordsplit = re.compile('\W+').split
def matchlines(fh, w1, w2):
w1 = w1.lower()
w2 = w2.lower()
for line in fh:
words = [x.lower() for x in wordsplit(line)]
if w1 in words and w2 in words:
print line.rstrip()

test = """1st line of text (not matched)
2nd line of words (not matched)
3rd line (Word test) should match (case insensitivity)
4th line simple test of word's (matches)
5th line simple test of words not found (plural words)
6th line tests produce strange words (no match - plural)
7th line "word test" should find this
"""
matchlines(StringIO.StringIO(test), 'test', 'word')

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


Re: How to find out if another process is using a file

2007-01-19 Thread Tom Wright
js  wrote:
> How about using lock?
> Let writing process locks the files before writing, and unlock after
> the job's done.

Is locking mandatory or co-operative? I don't have any control over the
process which is doing the writing, so if it's co-operative it's no good to
me.

If it's mandatory, then I can try to acquire a lock on the file - if this
fails or blocks, then the other process must have it open.  Will this work?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Match 2 words in a line of file

2007-01-19 Thread bearophileHUGS
Rickard Lindberg, yesterday I was sleepy and my solution was wrong.

> 2) If you have a line something like this: "foobar hello" then "'foo'
> in line" will return true, even though foo is not a word (it is part of
> a word).

Right. Now I think the best solution is to use __contains__ (in) to
quickly find the lines that surely contains both substrings, then on
such possibly rare cases you can use a correctly done RE. If the words
are uncommon enough, such solution may be fast and reliable.
Using raw tests followed by slow and reliable ones on the rare positive
results of the first test is a solution commonly used in Computer
Science, that often is both fast and reliable. (It breaks when the
first test is passed too much often, or when it has some false
negatives).

Probably there are even faster solutions, scanning the whole text at
once instead of inside its lines, but the code becomes too much hairy
and probably it's not worth it.

Bye,
bearophile

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


Re: selective logger disable/enable

2007-01-19 Thread Vinay Sajip
Gary Jefferson wrote:

> Suppose I have 3 modules that belong to a project, 'A', 'A.a' and 'B',
> and each module has its own logger, created with:
>
> module1logger = logging.getLogger('project.A')
>
> and
>
> module2logger = logging.getLogger('project.A.a')
>
> and
>
> module3logger = logging.getLogger('project.B')
>
>
> And I want to selectively enable/disable these, per module (for
> example, I only want logging from A and A.a, or just from B, etc).  It
> seems like logging.Filter is supposed to let me do this, but I can't
> see how to apply it globally.  Is there really no other way that to add
> a addFilter(filter) call to each of these loggers individually?
>

The documentation for Logger - see

http://docs.python.org/lib/node406.html

- shows that there are addFilter() and removeFilter() methods on the
Logger class which you can use to add or remove filters from individual
Logger instances. From the above page (entitled "14.5.1 Logger
Objects"):

addFilter(filt)
Adds the specified filter filt to this logger.

removeFilter(filt)
Removes the specified filter filt from this logger.

The parent section of Section 14.5.1, which is Section 14.5, was the
first search result when I just searched Google for "python logging".

Best regards,

Vinay Sajip

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


Re: How to find out if another process is using a file

2007-01-19 Thread Diez B. Roggisch
Tom Wright wrote:

> js  wrote:
>> How about using lock?
>> Let writing process locks the files before writing, and unlock after
>> the job's done.
> 
> Is locking mandatory or co-operative? I don't have any control over the
> process which is doing the writing, so if it's co-operative it's no good
> to me.
> 
> If it's mandatory, then I can try to acquire a lock on the file - if this
> fails or blocks, then the other process must have it open.  Will this
> work?

AFAIK it's cooperative.

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


Re: Why this script can work?

2007-01-19 Thread Diez B. Roggisch
Jm lists wrote:

> Thanks for all the helps.
> I'm not habitual for this usage of 'else',other languages seem don't
> support this syntax.
> i.g,writting the codes below by Perl would get an error:

I personally consider this part of python also somewhat obscure. But I just
don't use it and don't bother.

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


Re: Traversing the properties of a Class

2007-01-19 Thread Steven D'Aprano
On Thu, 18 Jan 2007 18:03:41 +, Neil Cerutti wrote:

> On 2007-01-18, EdG <[EMAIL PROTECTED]> wrote:
>> For debugging purposes, I would like to traverse the class
>> listing out all the properties.
> 
> This is the first thing that came to mind.
> 
> def show_properties(cls):
>   for attr in dir(cls):
> if isinstance(getattr(cls, attr), property):
>   print attr

Funny. The first thing that came to my mind was, "Thank you for sharing.
Did you have a question?"

*wink*



-- 
Steven.

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


Re: How to find out if another process is using a file

2007-01-19 Thread Tom Wright
Jean-Paul Calderone wrote:
> A better solution is to name or place files which are begin written in a
> which is recognizable and only rename or move them to their final location
> when they have been completely written.
> 
> For example, name files ".new" as they are being written.  When they are
> fully written, drop the ".new" suffix.  On the reader side, ignore any
> file with a name ending in ".new".

Yes, that would work very neatly but I don't have any control over the
writing process.  I think the modification time route might be the best
option, but thanks to all for their replies.

-- 
I'm at CAMbridge, not SPAMbridge
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Iterator length

2007-01-19 Thread Steven D'Aprano
On Thu, 18 Jan 2007 16:55:39 -0800, bearophileHUGS wrote:

> What's your point? Maybe you mean that it consumes the given iterator?
> I am aware of that, it's written in the function docstring too. But
> sometimes you don't need the elements of a given iterator, you just
> need to know how many elements it has. A very simple example:
> 
> s = "aaabaabb"
> from itertools import groupby
> print [(h,leniter(g)) for h,g in groupby(s)]

s isn't an iterator. It's a sequence, a string, and an iterable, but not
an iterator.

I hope you know what sequences and strings are :-)

An iterable is anything that can be iterated over -- it includes sequences
and iterators.

An iterator, on the other hand, is something with the iterator protocol,
that is, it has a next() method and raises StopIteration when it's done.

>>> s = "aaabaabb"
>>> s.next()
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: 'str' object has no attribute 'next'

An iterator should return itself if you pass it to iter():

>>> iter(s) is s
False
>>> it = iter(s); iter(it) is it
True

You've said that you understand len of an iterator will consume the
iterator, and that you don't think that matters. It might not matter in
a tiny percentage of cases, but it will certainly matter all the rest
of the time!

And let's not forget, in general you CAN'T calculate the length of an
iterator, not even in theory:

def randnums():
while random.random != 0.123456789:
yield "Not finished yet"
yield "Finished"

What should the length of randnums() return?

One last thing which people forget... iterators can have a length, the
same as any other object, if they have a __len__ method:

>>> s = "aaabaabb"
>>> it = iter(s)
>>> len(it)
16

So, if you want the length of an arbitrary iterator, just call len()
and deal with the exception.



-- 
Steven.

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


when format strings attack

2007-01-19 Thread [EMAIL PROTECTED]
http://www.ddj.com/184405774;jsessionid=BDDEMUGJOPXUMQSNDLQCKHSCJUNN2JVN

I saw a warning from homeland security about this.  I only comment on
the because I am trying to use os.system('command1 arg') and it doesn't
work but I do see examples with % that is borrowed from the c language.
 Seems like if I can write a batch file that does something the same
behavior should happen in the os module..

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


Re: Determining when a file is an Open Office Document

2007-01-19 Thread Steven D'Aprano
On Fri, 19 Jan 2007 12:22:04 +1100, Ben Finney wrote:

> tubby <[EMAIL PROTECTED]> writes:
> 
>> Silly question, but here goes... what's a good way to determine when
>> a file is an Open Office document? I could look at the file
>> extension, but it seems there would be a better way.
> 
> Yes, the name of a file may be useful for communicating with humans
> about that file's intended use, but is a lousy, unreliable way to make
> a definite statement about the actual contents of the file.
> 
> The Unix 'file' command determines the type of a file by its contents,
> not its name. This functionality is essentially a database of "magic"
> byte patterns mapping to file types, 

Ah, another lousy, unreliable way to make a definite statement about the
actual contents of a file. Looking at magic bytes inside a file is hardly
bullet-proof (although file seems to be moderately reliable in practice,
at least under Linux).

Simple example: is the file consisting of two bytes "x09x0A" meant to be a
text file with a tab and a newline, or a binary file consisting of a
single two-byte int? There's no way to tell just from the contents.
It's a circular problem: to be sure what the file is ("it's a two-byte
int") one has to understand the contents ("the integer 2305") -- but you
can only understand the contents if you know what the file is.

There are only two ways out of this vicious circle: 

(1) Have the creator of the file unambiguously label it. Some file systems
associate file-type metadata to files (e.g. Classic Apple Macintosh did
that), but sadly the main file systems in use today do not.

(2) Make an educated guess from various heuristics and conventions. The
old DOS 8.3 naming system is one such convention, and modern operating
systems tend to follow it. The Unix "file" utilities database of magic
bytes is such a heuristic.


-- 
Steven.

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


Standard streams

2007-01-19 Thread raghu
what is standard streams in case of python?

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


Re: Standard streams

2007-01-19 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, raghu wrote:

> what is standard streams in case of python?

Do you mean `sys.stdin`, `sys.stdout` ans `sys.stderr`?

Ciao,
Marc 'BlackJack' Rintsch

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


Why do I have to call del explicitly for com objects?

2007-01-19 Thread bg_ie
Hi,

I'm creating objects in my python script belonging to a COM object
which I dispatch using win32com.client.DispatchEx. Hence, dllhost.dll
is the concerned process. The problem is that the objects destructor
within the com object is not called if the object lives past a certain
number of seconds. For example, this function will not call the
destructor concerned with obj unless the sleep is commented out.

def fnction:
  obj = comobj.createACertainObject()
  obj.doStuff()
  sleep(10)
  obj.doMoreStuff()
  #del obj

It seems to me that the GC forgets about obj after a certain amount of
time. I can force the destructor to be called using del obj at the end
of my function, but why do I have to call this explicitly?

Thanks for your help,

Barry.

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


Re: Iterator length

2007-01-19 Thread bearophileHUGS
Steven D'Aprano:
> > s = "aaabaabb"
> > from itertools import groupby
> > print [(h,leniter(g)) for h,g in groupby(s)]
>
> s isn't an iterator. It's a sequence, a string, and an iterable, but not
> an iterator.

If you look better you can see that I use the leniter() on g, not on s.
g is the iterator I need to compute the len of.


> I hope you know what sequences and strings are :-)

Well, I know little still about the C implementation of CPython
iterators :-)

But I agree with the successive things you say, iterators may be very
general things, and there are too many drawbacks/dangers, so it's
better to keep leniter() as a function separated from len(), with
specialized use.

Bye and thank you,
bearophile

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


how to mimik a main() function to start a program with entry point?

2007-01-19 Thread krishnakant Mane
hello all.
I have one simple query and may be that's to stupid to answer but I am
not finding the answer any ways.
I have a set of modules in my package and out if which one is my
actual starting point to my entire program.  say for example I have an
entire database application ready and I want a main (as in java or c)
to initiate the program and may be bring up a login screen and then
pass the control on to the main window.
if I am giving raw source code that is easy because I will tell user
to run the command ./xyz.py which has that function.
but if I freze it into an executable with py2exe for example , how do
I solve this problem?
thanks.
Krishnakant.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: variable scope

2007-01-19 Thread Bruno Desthuilliers
gonzlobo a écrit :

Please keep this on clpy...


> Sorry, but I don't understand. I *should* pass firstMsg to the
> function like I did (PID_MinMax(firstMsg)), correct?

Yes.

> Then I should
> pass the variable back to the main loop by 'return firstMsg', correct?

s/variable/value/

Yes, you have to return the value from your function. But then, if you 
don't store this value somewhere, it's lost. What you have to understand 
is that you actually have *2* variables named 'firstMsg' : one in the 
'main loop', and one in PID_MinMax(). Rebinding the second name has no 
impact on the first. So you have to explicitely assign the return value 
of PID_MinMax() to the main loop's firstMsg variable. Else, this value 
is simply discarded.

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


Re: How to find out if another process is using a file

2007-01-19 Thread Amit Khemka
>
> Yes, that would work very neatly but I don't have any control over the
> writing process.  I think the modification time route might be the best
> option, but thanks to all for their replies.

Its not pythonic, but may be "lsof" on POSIX can be helpful:
see: 
http://www.physiol.ox.ac.uk/Computing/Online_Documentation/lsof-quickstart.txt


cheers,

-- 

Amit Khemka -- onyomo.com
Home Page: www.cse.iitd.ernet.in/~csd00377
Endless the world's turn, endless the sun's Spinning, Endless the quest;
I turn again, back to my own beginning, And here, find rest.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to mimik a main() function to start a program with entry point?

2007-01-19 Thread sturlamolden

krishnakant Mane wrote:

> I have a set of modules in my package and out if which one is my
> actual starting point to my entire program.  say for example I have an
> entire database application ready and I want a main (as in java or c)
> to initiate the program and may be bring up a login screen and then
> pass the control on to the main window.
> if I am giving raw source code that is easy because I will tell user
> to run the command ./xyz.py which has that function.
> but if I freze it into an executable with py2exe for example , how do
> I solve this problem?


If you cannot figure that out, you should not selling software.

if __name__ == '__main__':
  #whatever

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


Re: how to mimik a main() function to start a program with entry point?

2007-01-19 Thread [EMAIL PROTECTED]
def main():
print "Hello"

if __name__ == "__main__":
main()

Simply verify __name__ and run any function from there. This will cause
main() to be run if the script is run directly. I haven't used py2exe,
so I'm not sure if it still applies.

--Kevin




krishnakant Mane wrote:
> hello all.
> I have one simple query and may be that's to stupid to answer but I am
> not finding the answer any ways.
> I have a set of modules in my package and out if which one is my
> actual starting point to my entire program.  say for example I have an
> entire database application ready and I want a main (as in java or c)
> to initiate the program and may be bring up a login screen and then
> pass the control on to the main window.
> if I am giving raw source code that is easy because I will tell user
> to run the command ./xyz.py which has that function.
> but if I freze it into an executable with py2exe for example , how do
> I solve this problem?
> thanks.
> Krishnakant.

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


Re: how to mimik a main() function to start a program with entry point?

2007-01-19 Thread Roland Puntaier
Hi,

>From a python module you could use subprocess  and start the exe. Normally 
one must leave it to the OS to load a binary module, because there are 
certain things done during loading.
Nevertheless the location of the entry point is coded in the binary file 
format (e.g. PE for windows or ELF for Linux)
Whether it is possible from python to make an import of a python module in 
a python package gone through py2exe, I cannot answer.

But I think you mean how to tell py2exe, where the entry point is. Read: 
http://www.py2exe.org/index.cgi/Tutorial

Roland

[EMAIL PROTECTED] schrieb 
am 19.01.2007 14:30:33:

> hello all.
> I have one simple query and may be that's to stupid to answer but I am
> not finding the answer any ways.
> I have a set of modules in my package and out if which one is my
> actual starting point to my entire program.  say for example I have an
> entire database application ready and I want a main (as in java or c)
> to initiate the program and may be bring up a login screen and then
> pass the control on to the main window.
> if I am giving raw source code that is easy because I will tell user
> to run the command ./xyz.py which has that function.
> but if I freze it into an executable with py2exe for example , how do
> I solve this problem?
> thanks.
> Krishnakant.
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 

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


Re: Login Form

2007-01-19 Thread [EMAIL PROTECTED]
Ghirai wrote:
> Hello python-list,
>
> I need to make a login form, if possible without cookies.
> Can anyone point me in the right direction? Or are there any
> examples?
>
> Thanks.
>
> --
> Best regards,
> Ghirai.

You'd do pretty good using the 'cgi' module, which is documented at
http://www.python.org/doc/lib/module-cgi.html

A quick web search found an example site for the cgi module:
http://www.cs.virginia.edu/~lab2q/lesson_7/

Don't be afraid to search for good examples on the web, adapt them, and
try them out on your own box. 

--Kevin

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


PQueue and Python 2.5

2007-01-19 Thread Berteun Damman
Hello,

Recently I was looking for a Priority Queue module, and I've found
Pqueue by Andrew Snare [1]. When I use it with Python 2.4 everything
works okay, at least on the two system I've tested it on (Debian based
AMD 64) and OS PPC.

However, when I use it with Python 2.5 - again on the same machines,
exiting always gives a pointer error. The easiest to demonstrate this
is:

python2.5 -c 'from pqueue import PQueue; PQueue()'

On the Debian system:
$ python2.5 -c 'from pqueue import PQueue; PQueue()'
*** glibc detected *** free(): invalid pointer: 0x2ad7b5720288 ***
Abort

And on my PowerBook:
python2.5(8124) malloc: ***  Deallocation of a pointer not malloced:
0x3b4218; This could be a double free(), or free() called with the
middle of an allocated block;

A memory fault can also be immediately triggered by apply 'del' to a
PQueue-instance. As said, with Python 2.4 it seems to perform without
problems.

I haven't got a clue how to investigate this, but I would be willing to
help if someone has any ideas.

Berteun

[1] http://py.vaults.ca/apyllo.py/514463245.769244789.44776582

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


Re: Would a Dutch speaker please check this wiki page please?

2007-01-19 Thread Hendrik van Rooyen
"Martin P. Hellwig" <[EMAIL PROTECTED]> wrote:


> Stef Mientki wrote:
> > [EMAIL PROTECTED] wrote:
> >> Got a note about a new page on the Python Wiki:
> >>
> >>> "Wade" == Wade McDaniel <[EMAIL PROTECTED]> writes:
> >>
> >> http://wiki.python.org/moin/Selcuk_Altun
> >>
> >> I suspect it's junk since it doesn't seem to mention Python and the 
> >> website
> >> it mentions doesn't seem to exist.  Still, just in case...
> > The only (incorrect) Dutch sentence on the whole site is:
> >   "Welkom op me site www.keriwar.nl",
> > which should have been
> >   "Welkom op mijn site www.keriwar.nl"
> > but that could be explained, while his name "Selcuk Altun" is not 
> > orginated from the Netherlands.
> > I just expect that he is trying to setup a wiki,
> > but that's too soon to give it a judgement.
> > 
> > cheers,
> > Stef Mientki
> >>
> >> Thx,
> >>
> >> Skip
> 
> Could be Afrikaans too, but the page is gone now so I can't check.

No its not Afrikaans - the "me" would have had to be "my" and "site"
would have been "webwerf" - literally "web yard"...

Some Flemish dialect, perhaps?

- Hendrik



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


Re: How can I create a linked list in Python?

2007-01-19 Thread Hendrik van Rooyen
"Jorgen Grahn" <[EMAIL PROTECTED]> wrote:

> 
> FWIW, I oppose the idea (paraphrased from further up the thread) that linked
> lists and other data structures are obsolete and dying concepts, obsoleted
> by Python and other modern languages.
> 
> 99% of the time. a Python list is the right tool for the job, but that's
> only because we have CPU cycles to spare and the 'n' in our 'O(n)' is
> limited. You cannot call yourself a computer scientist without understanding
> things like linked lists.  No other data structure has the same
> characteristics (good and bad) as that one. Or those two, really.

+1

The concept of storing a pointer that points to the "next thing" is so basic
that it will never go away.  One meets it all time in chained buffer blocks, 
in tag sorts, etc...

And if you add a pointer to the "previous thing" too, then adding or taking
something out of what could become a ring is a constant effort.  Until you
run out of memory.

Ye Olde Universal Controlle Blocke:

- pointer to the start of data block
- length of allocated data block
- pointer to next control block
- pointer to previous control block
- next in pointer into data block
- next out pointer into data block
- optional length of data
- optional here starts or ends the lesson indicator

errrm... thats about it, unless you want a fast index too:

- pointer to first control block
- pointer to second control block
- pointer to third control block
...

Isn't it nice of python to hide all this stuff?

- Hendrik


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


Re: Wierd M2Crypto bug - phony "peer did not return certificate" error

2007-01-19 Thread Jean-Paul Calderone
On Fri, 12 Jan 2007 05:54:42 GMT, John Nagle <[EMAIL PROTECTED]> wrote:
>Heikki Toivonen wrote:
>> [EMAIL PROTECTED] wrote:
>>
>>>  That's a problem for me.  I need short timeouts; I'm accessing sites
>>>that might or might not have SSL support, and I need to quickly time
>>>out when there's no SSL server.
>>
>>
>> You should be able to do short timeouts, just not using the global
>> setdefaulttimeout. Have you tried Connection.set_socket_read/write_timeout?
>
> Yes.  That does not affect the connect timeout; it's only effective once
>the connection has been opened.  And adjusting the session timeout
>just recreates the blocking/non blocking problem.
>
> Incidentally, "get_socket_read_timeout()" doesn't work.  Generates
>"EXCEPTION at socket level: unpack str size does not match format",
>every time, at least with Python 2.4 on Windows.  The lower level
>function returns one number as a string, like "7200", and the unpack
>function tries to unpack it as "ll", which fails.
>
>> Also like I mentioned before, if you use the Twisted wrapper and let
>> Twisted handle network stuff you should be fine.
>
> That would mean struggling with Twisted and dealing with its bugs.
>(For example, has the MySQLdb mess been resolved for Twisted's API?)

http://twistedmatrix.com/trac/search?q=MySQLdb&noquickjump=1&ticket=on

I'd say so, unless you're referring to a bug you never reported (we only
fix those at about half the rate of reported bugs).

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


Re: Why this script can work?

2007-01-19 Thread Gabriel Genellina
"Jm lists" <[EMAIL PROTECTED]> escribió en el mensaje 
news:[EMAIL PROTECTED]

> I'm not habitual for this usage of 'else',other languages seem don't
> support this syntax.
> i.g,writting the codes below by Perl would get an error:
>
> [[[censored example]]]

If all languages had the same features, what would be the point of having 
different languages at all?

-- 
Gabriel Genellina 


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


Re: PyMeld for html templates?

2007-01-19 Thread metaperl

Sean Schertell wrote:


>
> Of course I'm going to try them all but I wonder if anyone has any
> thoughts on PyMeld as a template system for churning out general
> websites?
>

meld3 evolved from pymeld. I use meld3 -
http://plope.com/software/meld3/
this whole style of templating is known as push-style (coined by
Terence Parr). Most systems are pull-style.


> sorted. But how about PyMeld, any ideas on how to do it or whether it
> will even work as I've described?
>

the meat and bread problem: each page has meat and you want to wrap it
with some standard bread. it's a basic tree rewrite and since meld3
uses ElementTree underneath, it is a piece of cake.

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


Re: when format strings attack

2007-01-19 Thread Gabriel Genellina
<[EMAIL PROTECTED]> escribió en el mensaje 
news:[EMAIL PROTECTED]

> http://www.ddj.com/184405774;jsessionid=BDDEMUGJOPXUMQSNDLQCKHSCJUNN2JVN
>
> I saw a warning from homeland security about this.  I only comment on
> the because I am trying to use os.system('command1 arg') and it doesn't
> work but I do see examples with % that is borrowed from the c language.
> Seems like if I can write a batch file that does something the same
> behavior should happen in the os module..

Pure Python programs are not affected, but a review of the C implementation 
should be made to see if any (variant of) printf is used without a proper 
format. Anyway I doubt you could find something, because the vulnerability 
is so well known for ages.

-- 
Gabriel Genellina 


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


My first try using logger didn't work. Why?

2007-01-19 Thread CedricCicada
Greetings!

I want to write messages into the Windows event log.  I found
sevicemanager, but the source is always "Python Service", and I'd like
to be a bit more descriptive.  Poking around on the Internet revealed
the existence of the logging module.  It seems to have easily
understood methods with the power I need.  So I tried it.  Here's my
attempt:

logger = logging.getLogger("TahChung Part 1")
logger.setLevel(logging.INFO)
eventHandler = logging.NTEventLogHandler()
eventHandler.setlevel(logging.INFO)
formatter = logging.Formatter("%(message)s")
eventHandler.setFormatter(formatter)

logger.addHandler(eventHandler)
logger.error("This comes from the logger object.")

I get no error messages from this, but I also don't get anything in my
event log.  What am I doing wrong?

By the way, my source of instructions for how to do this was:
http://www.onlamp.com/pub/a/python/2005/06/02/logging.html

Rob Richardson
RAD-CON, Inc.

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


[ann] Appscript Installer 1.5 released

2007-01-19 Thread has
Announcing the release of Appscript Installer 1.5, containing all the
latest appscript-related modules, documentation and tools:

http://appscript.sourceforge.net/download.html

Appscript enhances the Python scripting language
(http://www.python.org) with robust, easy-to-use OS X application
scripting support, making Python a serious alternative to AppleScript
for automating your Mac.

This release contains several significant API changes, along with
various bugfixes and other internal improvements, and is recommended
for all users. In addition, the bundled osadict command line tool has
been overhauled to create a powerful interactive dictionary browser and
HTML exporter with support for py-appscript, rb-appscript and
AppleScript formatting styles.

(Existing appscript users: please read the 'API CHANGES' file included
with the appscript package before upgrading from older versions.)

For Python 2.3+ on Mac OS X 10.3 and later.

Enjoy,

has
-- 
http://appscript.sourceforge.net 
http://rb-appscript.rubyforge.org

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


Re: Iterator length

2007-01-19 Thread Steven D'Aprano
On Fri, 19 Jan 2007 05:04:01 -0800, bearophileHUGS wrote:

> Steven D'Aprano:
>> > s = "aaabaabb"
>> > from itertools import groupby
>> > print [(h,leniter(g)) for h,g in groupby(s)]
>>
>> s isn't an iterator. It's a sequence, a string, and an iterable, but not
>> an iterator.
> 
> If you look better you can see that I use the leniter() on g, not on s.
> g is the iterator I need to compute the len of.


Oops, yes you're right. But since g is not an arbitrary iterator, one can
easily do this:

print [(h,len(list(g))) for h,g in groupby(s)]

No need for a special function.



>> I hope you know what sequences and strings are :-)
> 
> Well, I know little still about the C implementation of CPython
> iterators :-)
> 
> But I agree with the successive things you say, iterators may be very
> general things, and there are too many drawbacks/dangers, so it's
> better to keep leniter() as a function separated from len(), with
> specialized use.

I don't think it's better to have leniter() at all. If you, the iterator
creator, know enough about the iterator to be sure it has a predictable
length, you know how to calculate it. Otherwise, iterators in general
don't have a predictable length even in principle.



-- 
Steven.

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


Re: when format strings attack

2007-01-19 Thread Nick Maclaren

In article <[EMAIL PROTECTED]>,
"Gabriel Genellina" <[EMAIL PROTECTED]> writes:
|> <[EMAIL PROTECTED]> escribió en el mensaje 
|> news:[EMAIL PROTECTED]
|> 
|> > http://www.ddj.com/184405774;jsessionid=BDDEMUGJOPXUMQSNDLQCKHSCJUNN2JVN
|> >
|> > I saw a warning from homeland security about this.  I only comment on
|> > the because I am trying to use os.system('command1 arg') and it doesn't
|> > work but I do see examples with % that is borrowed from the c language.
|> > Seems like if I can write a batch file that does something the same
|> > behavior should happen in the os module..
|> 
|> Pure Python programs are not affected, but a review of the C implementation 
|> should be made to see if any (variant of) printf is used without a proper 
|> format. Anyway I doubt you could find something, because the vulnerability 
|> is so well known for ages.

Not really.  There are LOTS of vulnerabilities that have been known
for ages and are still legion.  The reason that this is unlikely is
that it is both easy to spot and trivial to fix.


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

Re: My first try using logger didn't work. Why?

2007-01-19 Thread Vinay Sajip
[EMAIL PROTECTED] wrote:

> Greetings!
>
> I want to write messages into the Windows event log.  I found
> sevicemanager, but the source is always "Python Service", and I'd like
> to be a bit more descriptive.  Poking around on the Internet revealed
> the existence of the logging module.  It seems to have easily
> understood methods with the power I need.  So I tried it.  Here's my
> attempt:
>
> logger = logging.getLogger("TahChung Part 1")
> logger.setLevel(logging.INFO)
> eventHandler = logging.NTEventLogHandler()
> eventHandler.setlevel(logging.INFO)
> formatter = logging.Formatter("%(message)s")
> eventHandler.setFormatter(formatter)
>
> logger.addHandler(eventHandler)
> logger.error("This comes from the logger object.")
>
> I get no error messages from this, but I also don't get anything in my
> event log.  What am I doing wrong?
>
> By the way, my source of instructions for how to do this was:
> http://www.onlamp.com/pub/a/python/2005/06/02/logging.html
>
> Rob Richardson
> RAD-CON, Inc.

Well Rob,

Your first try didn't work because (based on your posted snippet) it
contained some errors.

The OnLAMP article was nice, but it's always best to go the the actual
documentation:

http://docs.python.org/lib/module-logging.html

Where you will see that NTEventLogHandler (described on page
http://docs.python.org/lib/node418.html) requires an initialiser
argument. Also, "setlevel" is misspelt - it should be "setLevel". The
following slightly modified version of your script puts an entry in the
NT Event Log on my machine:

import logging, logging.handlers

logger = logging.getLogger("TahChung Part 1")
logger.setLevel(logging.INFO)
eventHandler = logging.handlers.NTEventLogHandler("TahChung")
eventHandler.setLevel(logging.INFO)
formatter = logging.Formatter("%(message)s")
eventHandler.setFormatter(formatter)

logger.addHandler(eventHandler)
logger.error("This comes from the logger object.")

Best regards,


Vinay Sajip

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


Re: Why do I have to call del explicitly for com objects?

2007-01-19 Thread Gabriel Genellina
<[EMAIL PROTECTED]> escribió en el mensaje 
news:[EMAIL PROTECTED]

> I'm creating objects in my python script belonging to a COM object
> which I dispatch using win32com.client.DispatchEx. Hence, dllhost.dll
> is the concerned process. The problem is that the objects destructor
> within the com object is not called if the object lives past a certain
> number of seconds. For example, this function will not call the
> destructor concerned with obj unless the sleep is commented out.
>
> def fnction:
>  obj = comobj.createACertainObject()
>  obj.doStuff()
>  sleep(10)
>  obj.doMoreStuff()
>  #del obj

I don't understand the case.
del does not invoke a destructor, just decrements the object's reference 
count. When the rc reaches zero, the object is a candidate for GC. That is, 
"some time in the future", the GC would destroy it (unless it's part of a 
circular reference chain...)
So, *inside* your function, there is a reference held by the local variable 
obj. It is decremented automatically when you exit the function (and obj 
gets out of scope) or if you explicitely use del.
You can use sys.getrefcount() to see how many references an object has. (The 
output is +1 because getrefcount() has a temporary reference to the object 
too).

py> x="Hello World"
py> sys.getrefcount(x)
2

See how many references your obj have. After calling doStuff or doMoreStuff, 
you can have more references if those functions store `self` somewhere, or 
pass it to another method that does so.

> It seems to me that the GC forgets about obj after a certain amount of
> time. I can force the destructor to be called using del obj at the end
> of my function, but why do I have to call this explicitly?
If del obj works at the end, exiting the function should work too. Both ways 
you decrement the rc. There is something *more* in here.

-- 
Gabriel Genellina 


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


Re: PQueue and Python 2.5

2007-01-19 Thread Gabriel Genellina
"Berteun Damman" <[EMAIL PROTECTED]> escribió en el mensaje 
news:[EMAIL PROTECTED]

> Recently I was looking for a Priority Queue module, and I've found
> Pqueue by Andrew Snare [1].
That appears to be rather ancient, from 1999. Is it a pure Python 
implementation or has some C code too?

Python got in 2.3 a heapq module in its standard library; I think it is what 
you want, no need for an additional module.

> *** glibc detected *** free(): invalid pointer: 0x2ad7b5720288 ***
> Abort
>
> And on my PowerBook:
> python2.5(8124) malloc: ***  Deallocation of a pointer not malloced:
> 0x3b4218; This could be a double free(), or free() called with the
> middle of an allocated block;
>
> A memory fault can also be immediately triggered by apply 'del' to a
> PQueue-instance. As said, with Python 2.4 it seems to perform without
> problems.

Ah! then I bet:
- There is some C code involved.
- It carelessly mixes PyMem_Malloc with PyObject_Free or similar as 
described in
http://docs.python.org/whatsnew/ports.html

So do yourself a favor and forget about such old piece of code...

-- 
Gabriel Genellina 


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


Re: when format strings attack

2007-01-19 Thread Gabriel Genellina
"Nick Maclaren" <[EMAIL PROTECTED]> escribió en el mensaje
news:[EMAIL PROTECTED]
> In article <[EMAIL PROTECTED]>,
> "Gabriel Genellina" <[EMAIL PROTECTED]> writes:
> |>
> |> Pure Python programs are not affected, but a review of the C
> implementation
> |> should be made to see if any (variant of) printf is used without a
> proper
> |> format. Anyway I doubt you could find something, because the
> vulnerability
> |> is so well known for ages.
>
> Not really.  There are LOTS of vulnerabilities that have been known
> for ages and are still legion.  The reason that this is unlikely is
> that it is both easy to spot and trivial to fix.

Yes... Anyway, unless someone actually *do* revise the code, if it's easy or
not has no importance. I think that some automated tools were used to find
problems, but I don't know if this specific vulnerability was searched.

-- 
Gabriel Genellina


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


Re: Match 2 words in a line of file

2007-01-19 Thread Daniel Klein
On 18 Jan 2007 18:54:59 -0800, "Rickard Lindberg"
<[EMAIL PROTECTED]> wrote:

>I see two potential problems with the non regex solutions.
>
>1) Consider a line: "foo (bar)". When you split it you will only get
>two strings, as split by default only splits the string on white space
>characters. Thus "'bar' in words" will return false, even though bar is
>a word in that line.
>
>2) If you have a line something like this: "foobar hello" then "'foo'
>in line" will return true, even though foo is not a word (it is part of
>a word).

1) Depends how you define a 'word'.

2) This can be resolved with

templine = ' ' + line + ' '
if ' ' + word1 + ' ' in templine and ' ' + word2 + ' ' in templine:


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


Re: nsis and command-line argument

2007-01-19 Thread manouchk

manouchk wrote:
> Hi,
>
> is there a standart way to prepare a single exe with nsis that pass the
> command line to an exe created by py2exe on windows?
>
> py2exe allows to prepare an exe that get the command-line but needs
> some lib file so that it is not so elegant to ditribute. I tried a
> simple setup.nsis script to prepare a single file exe with works fine
> except that it does get the command-line.
>
> Is there a way do get the command line with the setup.nsis script?
> or any other simple method ?

Answering myself, well with NSIS it is not supported as written there :
http://www.py2exe.org/index.cgi/SingleFileExecutable

I'm looking for the py2exe option that allows that, I guess it could be
--bundle 1. It does not seem to be documented but I will try that.

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


Re: Is it possible to fasten the import of cgi?

2007-01-19 Thread Cecil Westerhof
BJörn Lindqvist wrote:

> On 1/18/07, Cecil Westerhof <[EMAIL PROTECTED]> wrote:
>> I have a cgi-script dat uses the modules cgi, os, sys and time. Offcourse
>> I can not time the time used to import time, but os and sys do not take
>> more as a millisecond. My script itself takes 3 or 4 milliseconds. But
>> importing cgi takes 95 milliseconds. (This is on my test system a PII 300
>> MHz. Is there a way to make this more fast? The import off cgi makes the
>> script at least 20 times as slow. Something like mod-python is not a
>> possibility. I could use it on my test machine, but not at the osting
>> provider.
> 
> Maybe python-launcher-daemon can help you?
> http://blogs.gnome.org/view/johan/2007/01/18/0 But if you can not use
> mod_python then you probably can not use any long running processes
> either.

By my current provider I can not use this. But I am going to look for
another. What are the pro's en cons off the different systems? FastCGI,
PyApache, mod_pythion and maybe others I am not aware off.

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

Re: Is it possible to fasten the import of cgi?

2007-01-19 Thread Cecil Westerhof
Tim Roberts wrote:

> Cecil Westerhof <[EMAIL PROTECTED]> wrote:
>>
>>I have a cgi-script dat uses the modules cgi, os, sys and time. Offcourse
>>I can not time the time used to import time, but os and sys do not take
>>more as a millisecond. My script itself takes 3 or 4 milliseconds. But
>>importing cgi takes 95 milliseconds. (This is on my test system a PII 300
>>MHz. Is there a way to make this more fast? The import off cgi makes the
>>script at least 20 times as slow. Something like mod-python is not a
>>possibility. I could use it on my test machine, but not at the osting
>>provider.
> 
> Realistically, do you plan to support more than a few dozen requests per
> minute?  If not, then it doesn't matter at all.  The script launch
> overhead is an insignificant part of the user's browser experience.

Not at the moment. The application is in alpha, so it is mostly a few
testers. At the moment it is going life I want to have another provider.
So I have a little time to search for another provider and select 'the best'
framework. ;-}

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


Re: Is it possible to fasten the import of cgi?

2007-01-19 Thread Cecil Westerhof
Gabriel Genellina wrote:

> I'll try to explain better: the cgi *protocol* (I'm not talking about the
> cgi *module*) requires a *new* python process to be created on *each*
> request. Try to measure the time it takes to launch Python, that is, the
> time from when you type `python ENTER` on your shell and the interpreter
> prompt appears. That time is wasted for *every* cgi request, and I bet it
> is much greater than the 95 ms you measure importing a module (be it cgi
> or whatever). You'll gain much more responsiveness if you can switch to
> another protocol, be it FastCGI, WSGI, mod_python or another.

The import of the cgi module takes about 95 milliseconds and the browsers
takes around 260 milliseconds to fetch the xml-page. This is why I thought
it to be important, but I think you are right, I should not worry about
this and switch to another protocol. Is not possible with the current
hosting provider, but I'll switch.
Pointers where to look for in selecting the protocol are apreciated.


> Anyway, comparing the import time between os, sys, and cgi is not very
> meaningful. sys is a builtin module, so "import sys" does very little. os
> is likely to be already imported by the time your script begins, so
> "import os" just verifies that os is already in sys.modules. "import cgi"
> is the only example when Python actually has to load something, so it's
> not a surprise if it takes longer.

Okay, thank you for the explanation.


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


confused on python rpc with apache, is it possible?

2007-01-19 Thread krishnakant Mane
hello all.
I will like to know if the following combination is possible.
I have looked around on google and did not find any thing productive
so bothering the list: sorry.
I am developing a distributed application which will have 3 layers
namely the thin client written in wxpython, an application layer on a
server and a database server of course.  database and application
server will be on same physical machine.
what I want to know is if I can use python as the base for developing
the application layer as an rpc server  and use apache server to
handle http remote procedure requests from the client?
if yes then what basic configuration settings I will need?
I believe I must first have apache recognise python interpreter and
then do some settings in apache so that it knows that what is
happening is not a web page request but an xml-rpc application created
in python.
can some one guide me?
thanks
Krishnakant.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why do I have to call del explicitly for com objects?

2007-01-19 Thread bg_ie

Gabriel Genellina skrev:

> <[EMAIL PROTECTED]> escribió en el mensaje
> news:[EMAIL PROTECTED]
>
> > I'm creating objects in my python script belonging to a COM object
> > which I dispatch using win32com.client.DispatchEx. Hence, dllhost.dll
> > is the concerned process. The problem is that the objects destructor
> > within the com object is not called if the object lives past a certain
> > number of seconds. For example, this function will not call the
> > destructor concerned with obj unless the sleep is commented out.
> >
> > def fnction:
> >  obj = comobj.createACertainObject()
> >  obj.doStuff()
> >  sleep(10)
> >  obj.doMoreStuff()
> >  #del obj
>
> I don't understand the case.
> del does not invoke a destructor, just decrements the object's reference
> count. When the rc reaches zero, the object is a candidate for GC. That is,
> "some time in the future", the GC would destroy it (unless it's part of a
> circular reference chain...)
> So, *inside* your function, there is a reference held by the local variable
> obj. It is decremented automatically when you exit the function (and obj
> gets out of scope) or if you explicitely use del.
> You can use sys.getrefcount() to see how many references an object has. (The
> output is +1 because getrefcount() has a temporary reference to the object
> too).
>
> py> x="Hello World"
> py> sys.getrefcount(x)
> 2
>
> See how many references your obj have. After calling doStuff or doMoreStuff,
> you can have more references if those functions store `self` somewhere, or
> pass it to another method that does so.
>
> > It seems to me that the GC forgets about obj after a certain amount of
> > time. I can force the destructor to be called using del obj at the end
> > of my function, but why do I have to call this explicitly?
> If del obj works at the end, exiting the function should work too. Both ways
> you decrement the rc. There is something *more* in here.
>
> --
> Gabriel Genellina

Thanks for the reply. I tried using a longer sleep before the del but
the destructor wasn't called this time. I guess del is not the issue
here what so ever. As far as I can see, the garbage collector forgets
about my object after a certain period of time. The fix i'm using now
is to use Destruct functions in my CoM object which I call explicitly.

def fnction:
  obj = comobj.createACertainObject()
  obj.doStuff()
  sleep(10)
  obj.doMoreStuff()
  obj.Destruct()

I'd still love to know what the issue is here.

Thanks,

Barry.

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


Re: Asyncore select statement problem

2007-01-19 Thread JamesHoward
Thank you for the responses.  I have learned considerably more about
how Asyncore works because of it.

The problem that I see is that Asyncore's poll function does not seem
to be thread safe.  From what I can tell, I am calling
dispatcher.close() properly and the dispatchers are removed from
asyncore's global map (all except the server itself).  However, it
seems like the error happens when the poll function gets the file
descriptors to run select on and then the thread ticks and removes them
from the global map.  After this the select call is made, but the file
descriptors are not valid anymore.

I guess I have two questions as a result.  First, is this a problem
that anyone else has had and second is there a fix for it?  I have
tried looking for Asyncore thread safe topics in Google, but without
much luck.  If needed I think making the poll function atomic in the
asyncore module might fix this problem, but I wanted to see what other
people thought first.

Thanks again for the help,
Jim Howard


Gabriel Genellina wrote:
> "JamesHoward" <[EMAIL PROTECTED]> escribió en el mensaje
> news:[EMAIL PROTECTED]
>
> >I have a problem with python's asyncore module throwing a bad file
> > descriptor error.  The code might be difficult to copy here, but the
> > problem is essentially:
> >
> > The server wants to sever the connection of an open Asyncore socket.
> > Calling the socket.close() nor the socket.shutdown(2) calls seem to
> > work.  The only way I can close the connection without creating the
> > error below is to have the client close the connection.
>
> You have to use the dispatcher's close() method, else, the asyncore map
> won't be updated, keeping a reference to the closed socket.
> 
> -- 
> Gabriel Genellina

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


Re: confused on python rpc with apache, is it possible?

2007-01-19 Thread Diez B. Roggisch
krishnakant Mane wrote:

> hello all.
> I will like to know if the following combination is possible.
> I have looked around on google and did not find any thing productive
> so bothering the list: sorry.
> I am developing a distributed application which will have 3 layers
> namely the thin client written in wxpython, an application layer on a
> server and a database server of course.  database and application
> server will be on same physical machine.
> what I want to know is if I can use python as the base for developing
> the application layer as an rpc server  and use apache server to
> handle http remote procedure requests from the client?
> if yes then what basic configuration settings I will need?
> I believe I must first have apache recognise python interpreter and
> then do some settings in apache so that it knows that what is
> happening is not a web page request but an xml-rpc application created
> in python.
> can some one guide me?

I'm unclear why you want the apache in there in the first place. Why don't
you just create an e.g. twisted-based XMLRPC-server, and simply let that
run? What is the apache intended for?

Diez


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


Re: More M2Crypto issues

2007-01-19 Thread John Nagle
Gabriel Genellina wrote:
> At Thursday 18/1/2007 04:41, John Nagle wrote:

> On a previous version of M2Crypto that line said: map()[self.ctx] = 
> self, and that failed too ("unhashable object", I think).
> I changed the class _ctxmap (the map() above returns an instance of it) 
> to use str(key) in the 3 places it was used. (That would be equivalent 
> to use str(self.ctx) everywhere, instead of long(self.ctx) as your 
> traceback is showing). All I can say is that no error happened 
> afterwards, but I don't know if that broke something. 
> 
> 
> So using str() appears, at least on the surface, to be reasonable. But 
> someone with more intimate knowledge of the library should confirm that. 
> I don't even understand what's the point for the _ctxmap singleton - 
> it's the same thing as a global dictionary, isn't it?

 I played around with using "str" too, but I was worried about
Python and SWIG version issues.  I'm not sure you can use "str"
on those objects on all versions and platforms.  I think that
SWIG is generating the implementations of __str__ and __long__.

 Incidentally, note in that area that if you never explicitly
call "close" on a Context, it will never be released.  Or so
it looks from the code.

 Actually, at the moment I'm having an M2Crypto problem related
to a SWIG/OpenSSL conflict.  Older versions of OpenSSL have an
include file that needs __i386__ defined, which is something GCC
does based on what platform you're on.  SWIG uses CPP, but
doesn't set the platform defines, so the SWIG phase of the
M2Crypto build fails.  I'm currently trying to get the shared
host where that build took place upgraded to a later version of
OpenSSL, but that requires a server restart, so it may take
a few days.  I'm doing something that requires M2Crypto to
run on a range of machines, which turns out to be rather harder
than expected.

 All this stuff is in the area that Guido was unhappy about
in his "M2Crypto Woes" article.

 http://www.artima.com/weblogs/viewpost.jsp?thread=95863

The worst problems there have been fixed, but we're not out
of the woods yet.  As Guido wrote, using SWIG does complicate
things.

 I'm currently getting good results on Windows 2000 with
Python 2.4 using M2Crypto 0.17; right now, the problems are
on the Linux side.

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


monitor the start and end of applications

2007-01-19 Thread awalter1
Hello,
My purpose is to supervise (from a python program) the launch of some
other programs (python or non python programs) as : "I click on the
button X and the pg X is launched ..."
I want also that my supervision be "wake up" when a pg has exited to
check its status or something like that.
I suppose I need to use thread and I did, I'm trying several solutions
(popen, os.system, commands.getstatusoutput, certainly not correctly) :
generally I am able to launch a pg but when it is ended, the thread
"caller" is still waiting.

Is somebody has encountered similar requirements ?
Thanks a lot for your help

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


Re: when format strings attack

2007-01-19 Thread John Zenger
Perhaps it is not as severe a security risk, but pure Python programs
can run into similar problems if they don't check user input for %
codes.  Example:

>>> k = raw_input("Try to trick me: ")
Try to trick me: How about %s this?
>>> j = "User %s just entered: " + k
>>> print j % "John"
Traceback (most recent call last):
  File "", line 1, in ?
print j % "John"
TypeError: not enough arguments for format string



On Jan 19, 10:44 am, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
> <[EMAIL PROTECTED]> escribió en el mensajenews:[EMAIL PROTECTED]
>
> >http://www.ddj.com/184405774;jsessionid=BDDEMUGJOPXUMQSNDLQCKHSCJUNN2JVN
>
> > I saw a warning from homeland security about this.  I only comment on
> > the because I am trying to use os.system('command1 arg') and it doesn't
> > work but I do see examples with % that is borrowed from the c language.
> > Seems like if I can write a batch file that does something the same
> > behavior should happen in the os module..Pure Python programs are not 
> > affected, but a review of the C implementation
> should be made to see if any (variant of) printf is used without a proper
> format. Anyway I doubt you could find something, because the vulnerability
> is so well known for ages.
> 
> --
> Gabriel Genellina

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


Re: My first try using logger didn't work. Why?

2007-01-19 Thread CedricCicada
Beautiful!  Thank you very much!

One of the problems I was laboring under was that I did not know where
to go to find the official documentation.  Thanks for that link too!

Rob

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


Re: when format strings attack

2007-01-19 Thread Steven D'Aprano
On Fri, 19 Jan 2007 03:51:08 -0800, [EMAIL PROTECTED] wrote:

> http://www.ddj.com/184405774;jsessionid=BDDEMUGJOPXUMQSNDLQCKHSCJUNN2JVN
> 
> I saw a warning from homeland security about this.  I only comment on
> the because I am trying to use os.system('command1 arg') and it doesn't
> work 

What do you mean, doesn't work? It works fine for me, precisely as
expected. What does it do for you? Crash Windows? Crash Python? Raise an
exception? Return an unexpected result?

> but I do see examples with % that is borrowed from the c language.

The "When Format Strings Attack" article isn't relevant to Python. Unlike
C, Python doesn't arbitrary dump bytes from the stack into a string if you
print a string containing %s. In Python, print just prints strings, it
doesn't do any string formatting. String formatting is done by the %
operator, so print "a string containing %s" is safe.

You'd be better off looking at Python examples than C. This is what I'm
guessing you're doing:

>>> command1 = 'dir'
>>> args = '-l text.txt'
>>> os.system('command1 arg')
sh: command1: command not found
32512

os.system doesn't do name-lookups of the string you pass to it. The right
way to do this is some variation on this:

>>> commandline = "%s %s" % (command1, args)
>>> commandline
'dir -l text.txt'
>>> os.system(commandline)
-rw-rw-r-- 1 steve steve 333 Sep 24 16:51 text.txt
0

or even something like this:

os.system('dir -l %s' % 'text.txt')


Now, there is a security risk: you might set command1 yourself, and
allow the user to set args. If command1 is an external application
with a security hole, and the user provides arguments that trigger that
bug, then naturally your application will inherit whatever security
vulnerabilities the external application suffers from. No surprises there.


-- 
Steven.

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


Re: My first try using logger didn't work. Why?

2007-01-19 Thread CedricCicada
Vinay (or anybody else),

Well, now that logging is working, how do I stop it from working?

I'm developing in PythonWin.  When I run my test script, I get one
message.  When I run it a second time, I get two, a third time gets me
three, and so on.

I feel like the Sorceror's Apprentice!

Rob

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


CHINESE TERRORISM 911 REPLAY Re: #Worldwide outcry follows China's sucessful test of a satellite killer

2007-01-19 Thread thermate
GO GET THE NEOCONS TO PUT SOME DEAD CHINESE STUDENTS IN A REMOTE
PILOTED PLANES FLOWN INTO THE NEW WTC OWNED BY LARRY SILVERSTEIN WITH
HEFTY INSURANCE BY SOME JAPANESE COMPANIES AND THEN DECLARE A WAR ON
CHINESE TERROR . LAUGHING OUT LOUD

3027 Dead wrote:
> http://www.guardian.co.uk/international/story/0,,1994236,00.html
>
>
> China hails satellite killer - and stuns its rivals in space
>
>
> · International outcry over first such test since 1985
> · Scientists have warned of dangers of debris in orbit
>
> Suzanne Goldenberg in Washington
> Friday January 19, 2007
> The Guardian
>
> China has given notice of its increasing power in space - and provoked
> widespread international concern - with a successful test of an
> anti-satellite weapon that could be used to knock out enemy
> surveillance and communications craft.
>
> In the first such test since the cold war era, the White House
> confirmed that China had used a medium-range ballistic missile,
> launched from the ground, to destroy an ageing weather satellite more
> than 500 miles into space. "We are aware of it and we are concerned,
> and we made it known," the White House spokesman, Tony Snow, told
> reporters.
>
> Article continues
> The test, on January 11, was the first of its kind since 1985 when
> Washington halted such exercises because of fears of damaging military
> and civilian satellites with large clouds of debris.
>
> The test was especially troubling because it exposed the vulnerability
> of America's dependence on low-orbiting satellites, which are used for
> military communications, smart bombs and surveillance. In theory, last
> week's exercise could give Beijing the capability to knock out such
> satellites - a realisation that underlay the protests from Washington.
>
> Australia and Canada also voiced concerns; Britain, South Korea and
> Japan were expected to follow. "The US believes China's development
> and testing of such weapons is inconsistent with the spirit of
> cooperation that both countries aspire to in the civil space area,"
> Gordon Johndroe, a White House spokesman, said. "We and other
> countries have expressed our concern regarding this action to the
> Chinese."
>
> Scientists have long warned of the dangers of space debris - which can
> remain in orbit for many hundreds of years - on existing space
> programmes. Among the items lost in space are lens caps, tools and
> nuts and bolts. Some former Soviet satellites leak fuel which
> solidifies into balls up to 3cm in diameter. Tiny pieces, including
> flecks of paint from eroding satellites, can travel at 17,000mph, and
> gain enough momentum to damage a medium-sized spacecraft.
>
> Despite yesterday's protests, the Bush administration has opposed a
> global ban on such tests, arguing that America needs to reserve its
> freedom of action in space. Arms control experts said it was not
> immediately clear whether the Chinese test was a ploy to try to press
> the Bush administration into a global weapons treaty, or whether China
> was asserting its own interests in space.
>
> News of the test, first reported by the magazine Aviation Week and
> Space Technology, comes months after the Bush administration unveiled
> a doctrine asserting America's right to take action against any
> perceived threat in space. The missile relied on the force of impact
> rather than an exploding warhead to shatter the satellite.
>
> Estimates said the destroyed Chinese satellite could have shattered
> into tens of thousands of fragments that would remain in orbit for
> more than a decade.
>
> The magazine said on its website: "Details emerging from space sources
> indicate that the Chinese Feng Yun 1C (FY-1C) polar orbit weather
> satellite launched in 1999 was attacked by an asat (anti-satellite)
> system launched from or near the Xichang space centre."
>
> Last August, Mr Bush laid out an even more robust vision of America's
> role in space, asserting Washington's right to deny access to any
> adversary hostile to US interests, and some arms control experts have
> accused the administration of conducting secret research on laser
> weapons to disable and destroy enemy satellites.
>
> In public, Mr Bush has sought to revive the national interest in space
> by calling for Americans to return to the moon in 15 years, and even
> use bases there as a launchpad for Mars. However, almost all of those
> costly military space programmes are over budget and behind schedule.
>
>
> --
> "Now, by the way, any time you hear the United States government
> talking
> about wiretap, it requires -- a wiretap requires a court order.
> Nothing has
> changed, by the way. When we're talking about chasing down terrorists,
> we're
> talking about getting a court order before we do so"
> -George W. Bush, April 20, 2004
>
> Not dead, in jail, or a slave?  Thank a liberal!
> Pay your taxes so the rich don't have to.
>
> http://www.zeppscommentaries.com
> For news feed, http://yahoogroups/subscribe/zepps_news
>

Re: More M2Crypto issues

2007-01-19 Thread Heikki Toivonen
John Nagle wrote:
>   I've been running M2Crypto successfully using Python 2.4 on Windows 2000,
> and now I'm trying to get it to work on Python 2.3.4 on Linux.
> 
>   Attempting to initialize a context results in
> 
> Traceback (most recent call last):
[...]
> map()[long(self.ctx)] = self
> ValueError: invalid literal for long(): _480e1008_p_SSL_CTX

This is almost certainly because of SWIG that is too old. The minimum
required is SWIG 1.3.24. If you cannot upgrade SWIG, the alternative
would be to play around with these values to fit your version of SWIG.

I'm adding this to the FAQ.

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


Re: My first try using logger didn't work. Why?

2007-01-19 Thread Gabriel Genellina

At Friday 19/1/2007 15:59, [EMAIL PROTECTED] wrote:


One of the problems I was laboring under was that I did not know where
to go to find the official documentation.  Thanks for that link too!


You already have it installed; look into your python install 
directory, under "doc"


From inside the interpreter, you can use help():

py> import logging.handlers
py> help(logging.handlers.NTEventLogHandler)
Help on class NTEventLogHandler in module logging.handlers:

class NTEventLogHandler(logging.Handler)
 |  A handler class which sends events to the NT Event Log. Adds a
 |  registry entry for the specified application name. If no dllname is
 |  provided, win32service.pyd (which contains some basic message [...]

Try help("logging"), help("modules logging"), help(any object), help("if")

And you can read the documentation online at http://www.python.org/doc/


--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

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

Re: More M2Crypto issues

2007-01-19 Thread Heikki Toivonen
John Nagle wrote:
> Actually, at the moment I'm having an M2Crypto problem related
> to a SWIG/OpenSSL conflict.  Older versions of OpenSSL have an
> include file that needs __i386__ defined, which is something GCC
> does based on what platform you're on.  SWIG uses CPP, but
> doesn't set the platform defines, so the SWIG phase of the
> M2Crypto build fails.  I'm currently trying to get the shared
> host where that build took place upgraded to a later version of
> OpenSSL, but that requires a server restart, so it may take
> a few days.  I'm doing something that requires M2Crypto to
> run on a range of machines, which turns out to be rather harder
> than expected.

Which version of OpenSSL is that?

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


Re: when format strings attack

2007-01-19 Thread Gabriel Genellina

At Friday 19/1/2007 15:43, John Zenger wrote:


Perhaps it is not as severe a security risk, but pure Python programs
can run into similar problems if they don't check user input for %
codes.  Example:

>>> k = raw_input("Try to trick me: ")
Try to trick me: How about %s this?
>>> j = "User %s just entered: " + k
>>> print j % "John"
Traceback (most recent call last):
  File "", line 1, in ?
print j % "John"
TypeError: not enough arguments for format string


That's not a problem, it's an exception. *This* is a problem: 
printf("Hello, %s")



--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

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

Re: when format strings attack

2007-01-19 Thread Steven D'Aprano
On Fri, 19 Jan 2007 10:43:53 -0800, John Zenger wrote:

> Perhaps it is not as severe a security risk, but pure Python programs
> can run into similar problems if they don't check user input for %
> codes.

Please don't top-post.

A: Because it messes up the order that we read things.
Q: Why?
A: Top-posting.
Q: What is the most annoying newsgroup habit?


> Example:
> 
 k = raw_input("Try to trick me: ")
> Try to trick me: How about %s this?
 j = "User %s just entered: " + k
 print j % "John"
> Traceback (most recent call last):
>   File "", line 1, in ?
> print j % "John"
> TypeError: not enough arguments for format string

That's hardly the same sort of vulnerability the article was talking
about, but it is a potential bug waiting to bite.

In a serious application, you should keep user-inputted strings separate
from application strings, and never use user strings unless they've been
made safe. See Joel Spolsky's excellent article about one way of doing
that:

http://www.joelonsoftware.com/articles/Wrong.html



-- 
Steven.

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


Re: Asyncore select statement problem

2007-01-19 Thread Gabriel Genellina

At Friday 19/1/2007 14:42, JamesHoward wrote:


Thank you for the responses.  I have learned considerably more about
how Asyncore works because of it.

The problem that I see is that Asyncore's poll function does not seem
to be thread safe.  From what I can tell, I am calling
dispatcher.close() properly and the dispatchers are removed from
asyncore's global map (all except the server itself).  However, it
seems like the error happens when the poll function gets the file
descriptors to run select on and then the thread ticks and removes them
from the global map.  After this the select call is made, but the file
descriptors are not valid anymore.

I guess I have two questions as a result.  First, is this a problem
that anyone else has had and second is there a fix for it?  I have
tried looking for Asyncore thread safe topics in Google, but without
much luck.  If needed I think making the poll function atomic in the
asyncore module might fix this problem, but I wanted to see what other
people thought first.


Usually asyncore is used with only one thread - that's one of the 
reasons of using it btw. You can spawn other working threads, but 
they don't usually interact with the networking stuff directly.



--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

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

Re: when format strings attack

2007-01-19 Thread Jeremy Sanders
Steven D'Aprano wrote:
 
> os.system('dir -l %s' % 'text.txt')
> 
> 
> Now, there is a security risk: you might set command1 yourself, and
> allow the user to set args. If command1 is an external application
> with a security hole, and the user provides arguments that trigger that
> bug, then naturally your application will inherit whatever security
> vulnerabilities the external application suffers from. No surprises there.

There are also big risks like this

filename = 'foo; rm importantfile'
cmd = 'ls %s' % filename
os.system(cmd)

oops!

-- 
Jeremy Sanders
http://www.jeremysanders.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: spidering script

2007-01-19 Thread Bernard
4 easy steps to get the links:

1. Download BeautifulSoup and import it in your script file.
2. Use urllib2 to download the html of the url.
3. mash the html using BeautifulSoup
4.
[code]
for tag in BeautifulSoupisedHTML.findAll('a'):
print tag
[/code]

David Waizer a écrit :
> Hello..
>
> I'm  looking for a script (perl, python, sh...)or program (such as wget)
> that will help me get a list of ALL the links on a website.
>
> For example ./magicscript.pl www.yahoo.com and outputs it to a file, it
> would be kind of like a spidering software..
> 
> Any suggestions would be appreciated.
> 
> David

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

Re: Iterator length

2007-01-19 Thread bearophileHUGS
Steven D'Aprano:
> since g is not an arbitrary iterator, one can easily do this:
> print [(h,len(list(g))) for h,g in groupby(s)]
> No need for a special function.

If you look at my first post you can see that I have shown that
solution too, but it creates a list that may be long, that may use a
lot of of memory, and then throws it away each time. I think that's a
bad solution. It goes against the phylosophy of iterators too, they are
things created to avoid managing true lists of items too.


> If you, the iterator
> creator, know enough about the iterator to be sure it has a predictable
> length, you know how to calculate it.

I don't agree, sometimes I know I have a finite iterator, but I may
ignore how many elements it gives (and sometimes they may be a lot).
See the simple example with the groupby.

Bye,
bearophile

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


war with china? a different approach?

2007-01-19 Thread thermate
Coz we have fools in the govt, the downfall of the US has only been
accelerated !!
The are morons who staged 9/11 controlled demolition to kill americans
to start their idiotic war.

Date: Sat, 21 Oct 2006 16:12:20 -0500
Subject: [nsmworld] war with china? a different approach?
From: "J. Knowles" <[EMAIL PROTECTED]>

Greater China
 Apr 20, 2006



SPEAKING FREELY
If it comes to a shooting war ...
By Victor N Corpus

Speaking Freely is an Asia Times Online feature that allows guest
writers to
have their say. Please click here if you are interested in
contributing.

One could call this article a worst-case scenario for the new American
century. Why worst case? Because of the hard lessons from history. The
Romans did not consider the worst-case scenario when Hannibal crossed
the
Alps with his elephants and routed them; or when Hannibal encircled and

annihilated the numerically superior Roman army at the Battle of
Cannae.

The French did not consider the worst-case scenario at Dien Bien Phu
and
when they built the Maginot Line, and the French suffered disastrous
defeats. The Americans did not consider the



worst-case scenario at Pearl Harbor or on September 11, and the results
were
disastrous for the American people. Again, American planners did not
consider the worst-case scenario in its latest war
in Iraq, but instead operated on the "best-case scenario", such as
considering the Iraq invasion a "cake walk" and that the Iraqi people
would
be parading in the streets, throwing flowers and welcoming American
soldiers
as "liberators", only to discover the opposite.

Scenario One: America launches 'preventive war' vs China
Our first objective is to prevent the re-emergence of a new rival. This
is a
dominant consideration underlying the new regional defense strategy and

requires that we endeavor to prevent any hostile power from dominating
a
region whose resources would, under consolidated control, be sufficient
to
generate global power. These regions include Western Europe, East Asia,
the
territory of the former Soviet Union and Southwest Asia.
-Paul Wolfowitz, former US deputy secretary of defense and currently
president of the World Bank
Consider these snapshots of China:

Since 1978, China has averaged 9.4% annual GDP growth

It had a five-fold increase in total output per capita from 1982 to
2002

It had $61 billion in foreign direct investment in 2004 alone and
foreign
trade of $851 billion, the third-largest in the world

The US trade deficit with China exceeded $200 billion in 2005

China has $750 billion in foreign exchange reserves and is the
second-biggest oil importer

Last year it turned out 442,000 new engineers a year; with 48,000
graduates
with master's degrees and 8,000 PhDs annually; compared to only 60,000
new
engineers a year in the US.

China for the first time (2004) surpassed America to export the most
technology wares around the world. China enjoyed a $34 billion trade
surplus
with the US in advanced technology products in 2004 (The Economist,
December
17, 2005). In 2005, the surplus increased to $36 billion

It created 20,000 new manufacturing facilities a year

It holds $252 billion in US Treasury Bonds (plus $48 billion held by
Hong
Kong)

Among the five basic food, energy and industrial commodities -grain
and
meat, oil and coal and steel -consumption in China has eclipsed that
of the
US in all but oil.

China has also gone ahead of the US in the consumption of TV sets,
refrigerators and mobile phones

In 1996, China had 7 million cell phones and the US had 44 million. Now

China has more mobile phone users than the US has people.

China has about $1 trillion in personal savings and a savings rate of
close
to 50%; U.S. has about $158 billion in personal savings and a savings
rate
of about 2% (The Wall Street Journal, Nov 19, 2005)
Shanghai boasts 4,000 skyscrapers - double the number in New York
City (The
Wall Street Journal, Nov 19, 2005)
Songbei, Harbin City in north China is building a city as big as New
York
City

Goldman Sachs predicts that China will surpass the US economy by 2041.

Before China's economy catches up with America, and before China builds
a
military machine that can challenge American superpower status and
world
dominance, America's top strategic planners (Project for the New
American
Century) decide to launch a "preventive war" against China. As a
pretext for
this, the US instigates Taiwan to declare independence.

Taiwan declares independence!
China has anticipated and long prepared itself for this event. After
observing "Operation Summer Pulse -04" when US aircraft carrier
battle
groups converged in the waters off China's coast in mid-July through
August
of 2004, Chinese planners began preparing to face its own worst-case
scenario: the possibility of confronting a total of 15 carrier battle
groups
composed of 12 from America and three from its close British ally.
China's
strategists refer to its counter-strategy to defeat 15 or more aircraft

carrier battle

ANN: Python Molecular Viewer - 1.4.4

2007-01-19 Thread sargis
We are pleased to announce the release of version 1.4.4 of our software
tools including: Python Molecular Viewer (PMV), AutoDockTools (ADT) and
VISION a visual-programming environment.

Installers for binary distributions are available for LINUX, Mac OS X
and Windows at:
http://mgltools.scripps.edu/downloads

The binary distributions contain:
 - a precompiled Python interpreter version 2.4; (except for windows
which requires
   running the Python installer first)
 - PMV, ADT, VISION and all dependent Python packages.

INSTALLERS:
 -  PackageMaker-based installer - Mac OS X  (.dmg extension);
 -  InstallJammer-based installers - Linux and Windows.
Note: the windows installer has to be run after Python 2.4 has been
installed.

LICENSE AGREEMENTS:
--
 The license agreements are provided on the download site at
https://mgltools.scripps.edu/downloads/license-agreements
and can also be found in the LICENSE file of the distribution.

NEW FEATURES:
--
ADT:

 autoanalyzeCommands
  -added new ADanalyze_showBindingSite command as
   Analyze->Dockings->Visualize Docking in context
   This display uses (1)spheres centered on atoms in
closer-than-vdw-radii contact
   (2)hydrogen bonds and (3)sections of secondary structure
   (for sequences of 5 or more adjacent residues in the receptor with
atoms close to the
   ligand) to show the bound ligand in the context of surrounding
receptor.
 autoflexCommands
  -add explicit warning to caution users that the molecule used to
   calculate autogrids for AD4 should contain only the non-moving or
'rigid' residues.
 ConfPlayer
  -added support for updating the 'BindingSite' display
  -added support for showing information about singleton clusters
  -added PopulationPlayer class
 DlgParser:
  -added support for parsing the amount of time involved in the
calculation
  -added support for parsing populations which are written when outlev
is set
   to 4 in the AD4 dpf.
 DockingParameters:
  -added support for reorient keyword (AD4)
  -added dpf_written_filename attribute
 GridParameters:
  -added gpf_written_filename attribute

 Added Web Services commands accessible from Run->Web Services.
 Registered users can now run AutoGrid and AutoDock installed on NBCR
cluster.

 atomTypeTools
  -fixed problem which sometimes occurred in merging nphs.  Previously
   hydrogens not bonded to anything raised an exception. Now the code
checks for
   the existence of bonds before referencing hydrogens' bonds... NB:
now
   non-bonded hydrogens will not raise an error.

 Utilities24:
 prepare_receptor4
  -corrected initialization of 'cleanup' on line 70 to match
documentation
   string
  -improved support for preserving the input atom charge on a
   specified type to AD4ReceptorPreparation
  -fixed bug where 'charges_to_add' was not initialized in some
cases...
 summarize_docking_directory.py
  -new script which reads in all the docking logs in a directory into a
   single Docking. It clusters the results and outputs a
comma-separated
   list showing number of conformations, number of tors, number of
atoms,
   number of clusters, rmstol used for clustering, energy, etc. By
default
   uses c2-specific getRMSD_custom method (line 176) which should be
   commented out if not appropriate.
 summarize_time.py
  -new script which reads in all the docking logs in a directory and
outputs
   the total amount of time taken.

 PMV:

 - New dashboard widget showing a tree representation of molecules and
allowing to
 rapidly execute PMV commands on molecular fragments
 - New Grid3D commands for rendering 3D Grids. Supports adding and
removing grids to Pmv.
   Grid a show in a table widget used for navigating between grids.
Isocontours and
   orthogonal slices can be computed and displayed.
 - New Update command under the Help menu allows the user to update Pmv
with the latest
   version of the tools.
 - New Register button in the About dialog allows a user to register
anytime
 - New BugReport Command to helpCommands. This command is for
submitting bugs to
   Bugzila DataBase from Pmv.
 - New command for reading and playing GROMACS trajectory files(.trr ,
.xtc formats)
 - A new check button in the GUI of the display Sticks and balls
command enable
   licorice representation
 - A new cartoon outlines rendering mode is available and can be turned
on through
   a button on the button bar.
 - New 3D labels allow for more fonts, arbitrary sizes, and optional
billboarding
 - Setting the sphere quality to 0 in display CPK or Sticks And Balls
no adapts the
   sphere quality based on the number of displayed atoms.

 Vision:
 - New node library for MatPlotLib
 - Added 2d texture to geometries
 - Network is now self executable when a user panel is defined
 - Visual editing for network user panels
 - "setmatplotlibparams" node in matpltlibNodes for setting rendering
options
   (such as color, grid, size etc) for axes, figures etc.
 - Added rendering options for H

Re: Determining when a file is an Open Office Document

2007-01-19 Thread Ross Ridge
tubby wrote:
> Now, If only I could something like that on PDF files :)

PDF files should begin with "%PDF-" followed by a version number, eg.
"%PDF-1.4".  The PDF Reference notes that Adobe Acrobat Reader is a bit
more flexiable about what it will accept:

13. Acrobat viewers require only that the header appear
  somewhere within the first 1024 bytes of the file.
14. Acrobat viewers also accept a header of the form
  %!PS-Adobe-N.n PDF-M.m

So identifying PDF files is pretty easy.  If you want to examine the
contents of a PDF file you're better off using Postscript, Ghostscript
specifically, since PDF is essentially Postscript with a special
dictionary of commands.

Ross Ridge

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


OT Annoying Habits (Was: when format strings attack)

2007-01-19 Thread Carroll, Barry
Greetings:

Personally, I don't think top-posting is the most annoying newsgroup
habit.  I think it's making a big fuss about minor inconveniences.  

One of the nicest things about being human is the amazing flexibility of
our brains.  For example, if a block of text isn't arranged in the order
we're used to, we can easily rearrange it mentally and read it anyway.
Oriental and Arabic peoples, for example, do this each time they read
something written in English.  It's EASY, once you get used to it!

It took me about 3 seconds to realize that Mr. D'Aprano' Q&A session was
laid out bottom-to-top instead of top-to-bottom.  After that, it made
perfect sense.  While it was a excellent way to demonstrate his
argument, it failed to prove his point, because, while top-to-bottom may
be the way he reads things, it isn't the way _everyone_ reads things.  

So, as far as I'm concerned, post your posts in whatever manner works
for you.  If it's in English, I'll figure it out.  If not, well, there's
always Babelfish.   ;^)

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


> -Original Message-
> From: Steven D'Aprano [mailto:[EMAIL PROTECTED]
> Sent: Friday, January 19, 2007 11:30 AM
> To: [email protected]
> Subject: Re: when format strings attack
> 
> On Fri, 19 Jan 2007 10:43:53 -0800, John Zenger wrote:
> 
> > Perhaps it is not as severe a security risk, but pure Python
programs
> > can run into similar problems if they don't check user input for %
> > codes.
> 
> Please don't top-post.
> 
> A: Because it messes up the order that we read things.
> Q: Why?
> A: Top-posting.
> Q: What is the most annoying newsgroup habit?
> 
> 
> > Example:
> >
>  k = raw_input("Try to trick me: ")
> > Try to trick me: How about %s this?
>  j = "User %s just entered: " + k
>  print j % "John"
> > Traceback (most recent call last):
> >   File "", line 1, in ?
> > print j % "John"
> > TypeError: not enough arguments for format string
> 
> That's hardly the same sort of vulnerability the article was talking
> about, but it is a potential bug waiting to bite.
> 
> In a serious application, you should keep user-inputted strings
separate
> from application strings, and never use user strings unless they've
been
> made safe. See Joel Spolsky's excellent article about one way of doing
> that:
> 
> http://www.joelonsoftware.com/articles/Wrong.html
> 
> 
> 
> --
> Steven.
> 


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


Re: OT Annoying Habits (Was: when format strings attack)

2007-01-19 Thread Aahz
In article <[EMAIL PROTECTED]>,
Carroll, Barry <[EMAIL PROTECTED]> wrote:
>
>Personally, I don't think top-posting is the most annoying newsgroup
>habit.  I think it's making a big fuss about minor inconveniences. =20

Thing is, nobody will ignore your posts for following standard Usenet
conventions, but some of us will definitely ignore your posts if you
don't.  It's your choice how much attention you want.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

Help a hearing-impaired person: http://rule6.info/hearing.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyMeld for html templates?

2007-01-19 Thread Richie Hindle
[Sean]
> I wonder if anyone has any thoughts on PyMeld as a template
> system for churning out general websites?

I'm doing that (but then I would be wouldn't I? 8-)
http://www.mandant.net is an example - the content of each page comes
from a file containing just the content, the layout and sidebar are
defined in a template HTML file, and the navigation is built by a
Python script.  All that is pulled together using PyMeld into a set of
HTML files and deployed to the web server (there's no need to it on the
fly for that site, but you certainly could).

> I want for a URI request to mysite.com/info
> to pull in a layout.html template which will in turn be populated by
> the info.html template. [...]  how about PyMeld, any ideas on how
> to do it or whether it will even work as I've described?

You'd do something like this:

from PyMeld import Meld

LAYOUT = """The Title
The page information goes here.
The real title
Here is the info, which would in the real world
be read from a file."""

page = Meld(LAYOUT)
info = Meld(INFO)
page.title = info.title._content
page.info = info.info._content
print page

Is that the sort of thing you had in mind?

-- 
Richie Hindle
[EMAIL PROTECTED]

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


How to comment code?

2007-01-19 Thread Martin P. Hellwig
Hi all,

I've been toying with python for about two years now. Not every day, 
just when I encounter something in my job (sysadmin) repetitively dull.
The amazing thing is that like any other language (natural or not) 
learning it more gives you power to express your thoughts better and 
create something from nothing, for me this is something I can only 
compare to freedom.

However since I'm learning more of python I've struggled with 
commenting, how should I've comment my code? I'm not talking about the 
style but more on the concept itself, things that where a couple of 
month ago a bunch of monkey poop is now as easy as reading a comic.

I always give a brief description on what the code is supposed to do and 
  I suppose that any serious coder knows way more then me about 
programming so I don't bother to comment that much since it mostly (in 
my eyes) just clutters up the code and makes it actually harder to read.

Though this makes me uncomfortably, commenting so little, I was thinking 
that perhaps something like doctest (I'm not so much into unit testing 
or the equivalents at this moment) has the side affect to make my code 
more understandable and readable. Any practical experience you'd like to 
share with me, any other comments are welcome too of course :-)

Thanks.

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


Py 2.5 on Language Shootout

2007-01-19 Thread bearophileHUGS
The The Computer Language Shootout has just published results for
Python 2.5 and Psyco 1.5.2. Comparing the old (Python 2.4) Gentoo
Pentium 4 results (now not visible anymore) with the new results, I
have seen that all the tests with Python 2.5 are faster than the ones
with Python 2.4 (some results can't be compared because N is changed):

Gentoo Pentium 4, Python 2.4.3 measurements:
Program & Logs  CPU Time   Memory KB   GZip   N
binary-trees   99.26  15,816402  16
chameneos Timout  5.000.000
cheap-concurrency  23,13   5.252160  15.000
fannkuch   66,38   2.200395  10
fasta  81,62   9.884861   2.500.000
k-nucleotide   15,52  15.580459 250.000
mandelbrot363,86   2.412472   3.000
n-bodyTimout 20.000.000
nsieve  9,79  34.416269   9
nsieve-bits   164,72  42.412320  11
partial-sums   38,64   2.300410   2.500.000
pidigits9,22   2.388391   2.500
recursive 701,64  14.360344  11
regex-dna   6,21  24.160326 500.000
reverse-complement   2,7  46.032272   2.500.000
spectral-norm 696,76   2.456266   2.500
startup 6,38 29 200
sum-file8,08   2.364 61   8.000


Regarding Psyco, two tests only are worse (the sourcecode, CPU and SO
are the same):

Old (Python 2.4.3, older Psyco):
nsieve  4.2222,680  211  9
reverse-complement  1.6649,336  330  2,500,000

New (Python 2.5, Psyco 1.5.2):
nsieve  4.2622,904  211  9
reverse-complement  1.7552,056  330  2,500,000

Bye,
bearophile

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


Re: My first try using logger didn't work. Why?

2007-01-19 Thread Vinay Sajip
[EMAIL PROTECTED] wrote:

> Vinay (or anybody else),
>
> Well, now that logging is working, how do I stop it from working?
>
> I'm developing in PythonWin.  When I run my test script, I get one
> message.  When I run it a second time, I get two, a third time gets me
> three, and so on.
>
> I feel like the Sorceror's Apprentice!
>
> Rob

The way to avoid this is to only call addHandler() once in your script.
PythonWin imports logging and keeps it in memory (something that
wouldn't happen if you ran the script repeatedly from the
command-line), so adding a handler every time results in multiple
handlers logging to the same event sink (e.g. NT Event Log).

So you need to use a flag to indicate whether initialisation has
already happened once, and avoid doing it again. I'm not sure of the
best way of doing this, since I don't know exactly how your app is set
up: if there's no more natural way, you could get a Logger instance and
see if it has any handlers added, before creating a new one and adding
it. This could be done by checking len(logger.handlers) == 0 for that
logger.

Best regards,


Vinay Sajip

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


RE: OT Annoying Habits (Was: when format strings attack)

2007-01-19 Thread Carroll, Barry
Hello again.

First off, Aahz is absolutely right. It is my choice, just as it is his
choice what to read and what to ignore.  My reply was about the fuss,
not the choice.  

Secondly, can someone point me to the Standard Usenet Convention that
mandates against top-posting.  This is not sarcasm; I would really like
to see it.  You see, I recently returned to Usenet after a LONG absence.
When I was last a regular Usenet citizen the Internet was new, GUI
interfaces were experimental and the World Wide Web didn't exist yet.
Newsreader software was text-based.  Top-posting was the common
practice, because it was the most convenient: you didn't have to page
through an arbitrarily large number of messages, most of which you'd
already read umpteen times, to get to the new stuff you were interested
in.  

So I'd really like to know what the standard is now.  I like to know
which rules I'm choosing to break.  ;^)

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed


> -Original Message-
> From: Aahz [mailto:[EMAIL PROTECTED]
> Sent: Friday, January 19, 2007 1:12 PM
> To: [email protected]
> Subject: Re: OT Annoying Habits (Was: when format strings attack)
> 
> In article <[EMAIL PROTECTED]>,
> Carroll, Barry <[EMAIL PROTECTED]> wrote:
> >
> >Personally, I don't think top-posting is the most annoying newsgroup
> >habit.  I think it's making a big fuss about minor inconveniences.
=20
> 
> Thing is, nobody will ignore your posts for following standard Usenet
> conventions, but some of us will definitely ignore your posts if you
> don't.  It's your choice how much attention you want.
> --
> Aahz ([EMAIL PROTECTED])   <*>
> http://www.pythoncraft.com/
> 
> Help a hearing-impaired person: http://rule6.info/hearing.html


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


Re: How to comment code?

2007-01-19 Thread James Stroud
Martin P. Hellwig wrote:
> Hi all,
> 
> I've been toying with python for about two years now. Not every day, 
> just when I encounter something in my job (sysadmin) repetitively dull.
> The amazing thing is that like any other language (natural or not) 
> learning it more gives you power to express your thoughts better and 
> create something from nothing, for me this is something I can only 
> compare to freedom.
> 
> However since I'm learning more of python I've struggled with 
> commenting, how should I've comment my code? I'm not talking about the 
> style but more on the concept itself, things that where a couple of 
> month ago a bunch of monkey poop is now as easy as reading a comic.
> 
> I always give a brief description on what the code is supposed to do and 
>  I suppose that any serious coder knows way more then me about 
> programming so I don't bother to comment that much since it mostly (in 
> my eyes) just clutters up the code and makes it actually harder to read.
> 
> Though this makes me uncomfortably, commenting so little, I was thinking 
> that perhaps something like doctest (I'm not so much into unit testing 
> or the equivalents at this moment) has the side affect to make my code 
> more understandable and readable. Any practical experience you'd like to 
> share with me, any other comments are welcome too of course :-)

I have found it useful to familiarize myself some tool such as epydoc 
and write comments in the function doc-string. For example,

def doit(stuff, beta, cycles):
   """
   Does nothing with I{stuff} in an infinite loop by applying a null
   operation. The I{cycles} parameter is multiplied by infinity.

   @param beta: null operator not to be applied to stuff
   @type beta: callable
   @type cycles: int
   """

This explains paramaters, etc., for you and other users of your API and 
paves the way for automatically generated documentation. Note that it 
would be excessive to comment each and every parameter, etc. Once the 
code is working correctly, a lot of in-line comments can be removed. 
Usually, in python, correctly working code is self explanatory at the 
implementation level, especially if you attempt to code "pythonically" 
(which can roughly be defined as the best practices according to the 
python community or the community subset who post to comp.lang.python).

If you find that your code gets very complicated and needs excessive 
commenting to understand, try to factor it into hierarchically related 
simpler functions and classes and comment each individually using 
doc-strings. In essence, think about commenting the interface rather 
than the implementation.

Use module level doc-strings (comments) to gather usage and explanation 
  notes for the most useful functions. This allows users (for example, 
you) to use your libraries without burrowing into the automatically 
generated documentation for each and every function.

Other tools may be as useful as epydoc, but this is the general strategy 
I have converged upon.

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


RE: OT Annoying Habits (Was: when format strings attack)

2007-01-19 Thread Nick Maclaren

In article <[EMAIL PROTECTED]>,
"Carroll, Barry" <[EMAIL PROTECTED]> writes:
|> 
|> Secondly, can someone point me to the Standard Usenet Convention that
|> mandates against top-posting.  This is not sarcasm; I would really like
|> to see it.  You see, I recently returned to Usenet after a LONG absence.
|> When I was last a regular Usenet citizen the Internet was new, GUI
|> interfaces were experimental and the World Wide Web didn't exist yet.
|> Newsreader software was text-based.  Top-posting was the common
|> practice, because it was the most convenient: you didn't have to page
|> through an arbitrarily large number of messages, most of which you'd
|> already read umpteen times, to get to the new stuff you were interested
|> in. =20

When I started to use this sort of thing, in the early 1970s, top
posting was already deprecated.

And top posting is only more convenient if you are merely adding a
"me, too" or equivalent, and not responding in detail.

But you have been told both of those before.


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


Re: Determining when a file is an Open Office Document

2007-01-19 Thread Robert Marshall
On Fri, 19 Jan 2007, Steven D'Aprano wrote:

> On Fri, 19 Jan 2007 12:22:04 +1100, Ben Finney wrote:
> 
>> tubby <[EMAIL PROTECTED]> writes:
>> 
>>> Silly question, but here goes... what's a good way to determine
>>> when a file is an Open Office document? I could look at the file
>>> extension, but it seems there would be a better way.
>> 
>> The Unix 'file' command determines the type of a file by its
>> contents, not its name. This functionality is essentially a
>> database of "magic" byte patterns mapping to file types,
> 
> Ah, another lousy, unreliable way to make a definite statement about
> the actual contents of a file. Looking at magic bytes inside a file
> is hardly bullet-proof (although file seems to be moderately
> reliable in practice, at least under Linux).
> 
> Simple example: is the file consisting of two bytes "x09x0A" meant
> to be a text file with a tab and a newline, or a binary file
> consisting of a single two-byte int? There's no way to tell just
> from the contents.  

And see for example the problem that development versions of emacs is
(were?) having with C files that started #define and were then treated
as graphics files!

http://thread.gmane.org/gmane.emacs.devel/64823/focus=65228


Robert
-- 
La grenouille songe..dans son château d'eau
Links and things http://rmstar.blogspot.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to comment code?

2007-01-19 Thread Pavel Panchekha
I think that doc strings are the most important way in which you should
be commenting on your code. Once the code works, you can elimainate
most inline comments, leaving only doc string for everything and a few
comments on some particularly confusing parts. Other than that,
comments usually only clutter Python code. But remember that you are
the person who understands your code best, so don't be too fanatical
about deleting inline comments.

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


Re: OT Annoying Habits (Was: when format strings attack)

2007-01-19 Thread Jerry Hill
On 1/19/07, Carroll, Barry <[EMAIL PROTECTED]> wrote:
> Secondly, can someone point me to the Standard Usenet Convention that
> mandates against top-posting.  This is not sarcasm; I would really like
> to see it.

For what (very little) it's worth, see RFC 1855.

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


Re: OT Annoying Habits (Was: when format strings attack)

2007-01-19 Thread Aahz
In article <[EMAIL PROTECTED]>,
Carroll, Barry <[EMAIL PROTECTED]> wrote:
>
>Secondly, can someone point me to the Standard Usenet Convention that
>mandates against top-posting.  This is not sarcasm; I would really like
>to see it.  You see, I recently returned to Usenet after a LONG absence.
>When I was last a regular Usenet citizen the Internet was new, GUI
>interfaces were experimental and the World Wide Web didn't exist yet.
>Newsreader software was text-based.  Top-posting was the common
>practice, because it was the most convenient: you didn't have to page
>through an arbitrarily large number of messages, most of which you'd
>already read umpteen times, to get to the new stuff you were interested
>in. =20

Funny, I've been on Usenet for more than fifteen years, continuously
(and long-windedly -- but that's another matter) and I've never seen a
Usenet group where top-posting was standard.  Anyway, here's a good
resource:

http://www.xs4all.nl/%7ewijnands/nnq/nquote.html
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

Help a hearing-impaired person: http://rule6.info/hearing.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Help with creating processes

2007-01-19 Thread Rod Person
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

I'm trying to create a simple gui wrapper for the handbrake dvd ripper
with python 2.4 on a FreeBSD system.

My problem is this. I want to scan the dvd to see all the titles and
chapters. The handbrake command for this is:

handbrake -i /dev/acd0 -t 0

I've tried:
 cmd = '/usr/local/bin/handbrake -i /dev/acd0 -t 0'
 rtn = os.popen(cmd)

but the script exists before the disk has finished scanning. If I
change cmd to 'ls' it work as I expected. My problem is that the
scanning of the DVD can take upto a minute or more and os.popen doesn't
seem to wait - although I thought it was suppose to?

I've tried using subprocess.call and popen2 etc but nothing seems to
wait for the return. Can someone give me a hint?


- -- 


Rod

"it takes an unusual mind to see the obvious."
- - Alfred Whitehead


-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.5 (FreeBSD)

iD8DBQFFsVWA3rDijyy3LEcRAia4AJ4hWZosgDeFeK4dkKdMg9ZwmAebeACfVqkQ
pGiJ7pL1/d1tVszxF0kzSjQ=
=Jz9+
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Asyncore select statement problem

2007-01-19 Thread JamesHoward
Again, thank you for your help.  With digging through the Asyncore.py
source, I was able to find the poll2 function which is called when the
function asyncore.loop(use_poll = True) is enabled.

This function does not use a select call, but a poll call to do its
looping.  It works well for the problem of threads closing devices at
unknown times.  The reason for this is that the select statement is
called on a series of file descriptors that should not be changed.  If
the file descriptors become invalid, select throws and exception and
the asyncore loop haults.  The use_poll flag sets the asyncore module
to use a poll instead of a select statement.

Within the poll method, there are better ways of dealing with file
descriptors and they seem to be able to discern if a file descriptor
becomes disconnected with the POLLHUP flag.

I am still unsure as to why the select function is used instead of the
poll function, but using poll appears to have solved my problem.

Thanks for all the help,
Jim Howard

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


float comparison confusion

2007-01-19 Thread [EMAIL PROTECTED]
Type "help", "copyright", "credits" or "license" for more information.
>>> cmp(20.10, 20.9)
-1

Why is cmp returning -1 instead of returning positive integer?

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


Re: float comparison confusion

2007-01-19 Thread skip

chrolson> Why is cmp returning -1 instead of returning positive integer?

Last time I checked 20.1 was less than 20.9.

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


Re: OT Annoying Habits

2007-01-19 Thread Jorge Godoy
"Carroll, Barry" <[EMAIL PROTECTED]> writes:

> Secondly, can someone point me to the Standard Usenet Convention that
> mandates against top-posting.  This is not sarcasm; I would really like

You can read RFC 1855.  Section 3.1.3 talks about newsgroups.  

Section 3.1.1 has general guidelines and it includes this:

If you are sending a reply to a message or a posting be sure you
summarize the original at the top of the message, or include just

enough text of the original to give a context. This will make sure
readers understand when they start to read your response. Since
NetNews, especially, is proliferated by distributing the postings from
one host to another, it is possible to see a response to a message
before seeing the original. Giving context helps everyone. But do not
include the entire original. 


I've added the "^" to mark the part where it says what should be on the top of
the message.

You can check it: http://www.dtcc.edu/cs/rfc1855.html


Be seeing you,
-- 
Jorge Godoy  <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to comment code?

2007-01-19 Thread gonzlobo
If it's hard to write, it should be hard to read! :)

On 1/19/07, Martin P. Hellwig <[EMAIL PROTECTED]> wrote:
> Hi all,

(snip)
> However since I'm learning more of python I've struggled with
> commenting, how should I've comment my code
(snip)
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: OT Annoying Habits (Was: when format strings attack)

2007-01-19 Thread Gabriel Genellina

At Friday 19/1/2007 18:43, Carroll, Barry wrote:


Secondly, can someone point me to the Standard Usenet Convention that
mandates against top-posting.  This is not sarcasm; I would really like
to see it.


There are some guidelines, like RFC 1855 (not a real standard, or 
enforced in any way):

http://www.faqs.org/ftp/rfc/rfc1855.txt
"If you are sending a reply to a message or a posting be sure you
  summarize the original AT THE TOP OF THE MESSAGE, or include just
  enough text of the original to give a context (...) But do not 
include the entire original!" (capitals added by me).



You see, I recently returned to Usenet after a LONG absence.
When I was last a regular Usenet citizen the Internet was new, GUI
interfaces were experimental and the World Wide Web didn't exist yet.
Newsreader software was text-based.  Top-posting was the common
practice, because it was the most convenient: you didn't have to page
through an arbitrarily large number of messages, most of which you'd
already read umpteen times, to get to the new stuff you were interested
in.


Really? Top posting a common practice? I'm not a youngster either and 
I've never seen top posting as a *norm* but an exception.
Old newsreaders had a new/quoted ratio, and enforced it to be rather 
high - so it was not easy to forget to trim the quoted text.

http://www.i-hate-computers.demon.co.uk/quote.html
Digging a bit one can find some old recommendations, like the Big 
Dummy's Guide to the Internet (1993):

http://www.cs.indiana.edu/docproject/bdgtti/bdgtti_2.html
Or people puzzled on how this works:
http://groups.google.com/group/news.newusers.questions/browse_thread/thread/a75b1f4cfe470276/b38f62fc633db61e


--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

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

Re: More M2Crypto issues

2007-01-19 Thread John Nagle
Heikki Toivonen wrote:
> John Nagle wrote:
> 
>>Actually, at the moment I'm having an M2Crypto problem related
>>to a SWIG/OpenSSL conflict.  Older versions of OpenSSL have an
>>include file that needs __i386__ defined, which is something GCC
>>does based on what platform you're on.  SWIG uses CPP, but
>>doesn't set the platform defines, so the SWIG phase of the
>>M2Crypto build fails.  I'm currently trying to get the shared
>>host where that build took place upgraded to a later version of
>>OpenSSL, but that requires a server restart, so it may take
>>a few days.  I'm doing something that requires M2Crypto to
>>run on a range of machines, which turns out to be rather harder
>>than expected.
> 
> 
> Which version of OpenSSL is that?

M2Crypto 0.17 requirements:
Python 2.3 or newer
   o m2urllib2 requires Python 2.4 or newer
OpenSSL 0.9.7 or newer
   o Some optional new features will require OpenSSL 0.9.8 or newer
SWIG 1.3.24 or newer

Server in use:
Python version: "Python 2.5 (r25:51908, Jan 18 2007, 10:46:37)"
OpenSSL version: "OpenSSL 0.9.7a Feb 19 2003"
SWIG version: "SWIG Version 1.3.31"
GCC version: "[GCC 3.4.4 20050721 (Red Hat 3.4.4-2)] on linux2"
Computer: Athlon 686 rackmount server.

The actual build failure is:

running build_ext
building 'M2Crypto.__m2crypto' extension
swigging SWIG/_m2crypto.i to SWIG/_m2crypto_wrap.c
swig -python -I/usr/include -o SWIG/_m2crypto_wrap.c SWIG/_m2crypto.i
/usr/include/openssl/opensslconf.h:27: Error: CPP #error ""This openssl-devel 
package does not work your architecture?"". Use the -cpperraswarn option to 
continue swig processing.
error: command 'swig' failed with exit status 1

The problem is that "opensslconf.h" expects the compiler to define __i386__
when running the C preprocessor, and SWIG doesn't do that.  Compare
"opensslconf.h" in different versions of OpenSSL; it's changed considerably.

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


RE: OT Annoying Habits (Was: when format strings attack)

2007-01-19 Thread Carroll, Barry
> -Original Message-
> From: Aahz [mailto:[EMAIL PROTECTED]
> Sent: Friday, January 19, 2007 3:29 PM
> To: [email protected]
> Subject: Re: OT Annoying Habits (Was: when format strings attack)
> 
> In article <[EMAIL PROTECTED]>,
> Carroll, Barry <[EMAIL PROTECTED]> wrote:
> >
> >Secondly, can someone point me to the Standard Usenet Convention that
> >mandates against top-posting.  This is not sarcasm; I would really
like
> >to see it.  
<>
> 
> Funny, I've been on Usenet for more than fifteen years, continuously
> (and long-windedly -- but that's another matter) and I've never seen a
> Usenet group where top-posting was standard.  Anyway, here's a good
> resource:
> 
> http://www.xs4all.nl/%7ewijnands/nnq/nquote.html
> --
> Aahz ([EMAIL PROTECTED])   <*>
> http://www.pythoncraft.com/
> 
> Help a hearing-impaired person: http://rule6.info/hearing.html

My thanks to Aahz and the others who responded.  I also did some
Googling on my own.  I found out that top-posting is the norm in the
e-mail world.  Bottom- and inline-posting are the norm in the newsgroup
world.  

So I concede the point, and I'm bottom-posting like a good citizen.  

Regards,
 
Barry
[EMAIL PROTECTED]
541-302-1107

We who cut mere stones must always be envisioning cathedrals.

-Quarry worker's creed



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


nice one

2007-01-19 Thread Raed
Take a break and try this cool game, this test is apporved by Peugeot
for car parking


http://www.pixelswall.com/Download/peugeot/peugeot.html

Anton
www.pixelswall.com

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


  1   2   >