Re: Send password over TCP connection

2005-10-11 Thread Laszlo Zsolt Nagy
dcrespo wrote:

>¡Beautiful and elegant solution!
>
>Two copies of the password: one on the client, the other on the server.
>
>1. Client wants to connect
>2. Server generates a random_alphanumeric_string and sends it to the
>client
>3. Both Client and Server creates a hash string from
>
>4. Client sends the hash string to the server
>5. Server compares his hash result with the hash string received from
>de client.
>
>I think it is a very good solution, Isn't it?
>  
>
In fact this is almost an OTP but be aware!
A man-in-the-middle attack can crack your algorithm. This is beacuse you 
create a random string only on one side.
You cannot trust in the connection you are using. You can modify you 
algorigthm to be more secure:

1. Client wants to connect
2. Server generates a server_random_alphanumeric_string and sends it to the
client
3. Client generates a client_random_alphanumeric_string and sends it to the
client too
3. Both Client and Server creates a hash string from


4. Client sends the hash string to the server
5. Server compares his hash result with the hash string received from
de client.

This is only a bit difference, but is makes sense. An intuder (who knows 
the your algorithm, because getting the code is not as difficult) could 
make a fake server to you, and send back HIS string (that is not 
random). Suppose we have a weakness in the hash function. The intuder 
can exploit this weakness by sending you his special string. The 
modified version has the advantage of sending two random strings, this 
way the intuder cannot take advantage of possible hash function 
weaknesses, because the hash function will be called on a string that is 
random for sure.

Best,

Les


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

Re: Batteries Included?

2005-10-11 Thread Mike Meyer
"Alex" <[EMAIL PROTECTED]> writes:

> One of the first things I wanted to do when I start learning Python was
> to produce a simple standalone application that I could distribute to
> my users (windows users). Python's moto is "Batteries Included", but
> where are the batteries for making exe files and making an installer
> file? I had to download, install and use py2exe and Inno Setup in order
> to accomplish this. I might be wrong expecting that a language whose
> moto is "Batteries Included" would be able to produce exe files. Are
> there plans to do this in the future version of Python?

Did you try looking through the distutils docs? After you create a
setup.py file for you program, doing

 "python setup.py bdist --formats=wininst"

should do the trick.

Of course, I don't own a Windows box, so I can't check it, but when I
ask a setup file for help on formats, it tells me the wininst format
is a windows installer.

Personally, I think of building a platform-specific bundle for
distribution to end users as more along the lines of shipping than
batteries. Python comes with lots of tools to help you get your
application working - the batteries. Once it's working, you don't need
batteries: you need wrapping paper, and a box, and tape, and so on.

 http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Send password over TCP connection

2005-10-11 Thread Laszlo Zsolt Nagy

>Ignoring all the other issues, any solution which actually requires the 
>password to be stored on the server is a bad solution.  Administrators 
>should not have access to user passwords, and in addition users should 
>not be put in the position of having to trust your server-side security 
>to keep their passwords (which they might have used on other systems) 
>from being grabbed by hackers.
>  
>
Users will always need to trust in the server. The authentication 
process ensures that the
client is really talking with the desired server and vice versa. But 
even if you know that you
are talking to the right server, you need to trust in the server. The 
administrator of the server
has access to all data. Possibly other persons and softwares too. 
Passwords are not different
from this point of view.

  Les

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


Re: Batteries Included?

2005-10-11 Thread Paul Rubin
Sybren Stuvel <[EMAIL PROTECTED]> writes:
> > I might be wrong expecting that a language whose moto is "Batteries
> > Included" would be able to produce exe files.
> 
> Indeed, you're wrong. Why would such an ability be included in Python?

distutils.exe, included in Python, in fact does have the ability to
produce .exe files, just not completely general ones.

> It's a cross platform language. What need would Mac, Linux, BSD,
> Solaris etc. users have for such a feature? 

The same need that they have for msvcrt, winreg, winsound, or the SGI
IRIX specific functions currently in the library.  The same need that
Windows users have for the Unix specific parts which are in the
library.  The same need that non-numeric programmers have for the
cmath module, which is also in the library.

> And why would it have to be included, when there is an easy solution
> just around the corner?  You prooved that it was easy enough to
> install and use by someone who just learned Python. I really don't
> see the problem here.

Um, if the TV ad for some Walkman says "batteries included" and the
batteries aren't included, you have legitimate reason to ask what's
going on.  That it's easy enough for you to go to the store and buy
batteries separately is irrelevant.  You didn't get what was
advertised.

Now a Windows .exe installer wasn't one of the advertised features of
Python and maybe there's good reasons to leave it out, but its
platform specificness is not one of those reasons.  There's already
plenty of platform specific stuff in Python.

Personally I think including a .exe packager in Python would be a
great idea.  As a Linux user I can't easily run Windows-specific
utilities like Inno Setup.  So I don't have a good way to make .exe's
from my Python code that Windows users can easily run.  Having a cross
platform .exe packager included with Python would be useful the same
way cross compilers are useful.  I'm using an x86 computer but I can
easily configure gcc to produce ARM code.  Why shouldn't my Linux
Python installation be able to produce Windows .exe's?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Let My Terminal Go

2005-10-11 Thread Mike Meyer
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:

> Hello,
>
> A user of my application points me to a behavior in gVim,
> the text editor, that I would like to implement in my
> application.
>
> When gVim is launched from a shell terminal, it completely
> frees the terminal. You can continue to use the terminal for
> whatever purpose you wish, including closing and exiting it,
> without any effect on the running gVim instance.
>
> How do I implement this in my application written in python?
> I would like to believe it does not involve me forking my
> application in a new process. Maybe there is signal I can
> send to the operating system to achieve this, right?

Several things need to happen. 

First, you need to take yourself out of the session you are in. To do
that, you use the setsid system call. This is available in python as
os.setsid.

Last, you need to detach your process from the terminal. You do that
by closing all the file descriptors you have that reference it. stdin,
stdout and stderr should do the trick. The standard trick is to set
set them to /dev/null. This has to happen last, so that if there are
problems in the second step, writing to stderr about it does some
good.

Second, you need to tell the shell that launched you that it can
continue. The standard way to do this is to fork your process, and
have the parent exit. That causes the parent shell to think your
process is dead, and so forget about it completely. There are other
ways to do this, but they aren't as reliable.

The easy way to do all these things - from C, anyway - is with
daemon(3). That isn't wrapped as part of the Python library. The
easiest way to solve your problem may be write a wrapper for that
call. If daemon exists on enough systems, submitting your wrapper as a
patch to the os modulee would be appropriate.

http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Batteries Included?

2005-10-11 Thread Michele Simionato
Mike Meyer:
> After you create a setup.py file for you program, doing
>
> "python setup.py bdist --formats=wininst"
>
> should do the trick.
>
> Of course, I don't own a Windows box, so I can't check it, but when I
> ask a setup file for help on formats, it tells me the wininst format
> is a windows installer.

I can confirm that it works (for pure Python applications), since I did
it.

   Michele Simionato

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


Re: Send password over TCP connection

2005-10-11 Thread Laszlo Zsolt Nagy

>If you really want to do it right, use SRP, .
>  
>
This is a bit offtopic here. I read the RFC and I do not see why SRP is 
not vulnerable to dictionary attacks.
If I have a working client software then I can use it to reveal 
passwords. Isn't it a dictionary attack?
Can you please enlighten me?

   Les

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


LINDA WEST (925) 876-7441 of CHIPMAN UNITED VAN LINES likes to commit Fraud & Forgery and she likes to put peoples names on moving contracts with out there Knowledge.Caton Mayflower Moving & Storage D

2005-10-11 Thread Vulvazb
LINDA WEST (925) 876-7441 of CHIPMAN UNITED VAN LINES likes to commit
Fraud & Forgery and she likes to put peoples names on moving contracts
with out there Knowledge.Caton Mayflower Moving & Storage Dublin,ca &
concord,ca (925) 876-7441, 925-887-5515,
925-825-5000, 800-825-3866,800-447-9771, 925-609-1800,
800-447-1771, 925-935-4073, 925-828-3985

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


Re: Batteries Included?

2005-10-11 Thread Marco Aschwanden
> I might be wrong expecting that a language whose
> moto is "Batteries Included" would be able to produce exe files. Are
> there plans to do this in the future version of Python?

Yes, you are wrong expecting that. Creating an exe-cutable is windows  
specific and python _tries_ to be platform neutral. py2exe - a wonderful  
tool which I use myself - is a battery on the shelves. It can be easily  
picked from there.

Furthermore it is not Python's philosophy to create "exe-cutables". But I  
do understand your wish (being a Windows Developper at work myself) and  
Python is not a matter of course within Windows.

Your best bet is ActiveState which bundles a windows specific version. Ask  
them, maybe they are willing to include it. Python should refrain from  
doing so.

Before overloading the "included batteries" an approach as found in Perl  
(CPAN) should be adapted... eg.  
http://peak.telecommunity.com/DevCenter/EasyInstall

Have a nice day,
Marco

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


Re: Send password over TCP connection

2005-10-11 Thread Paul Rubin
Laszlo Zsolt Nagy <[EMAIL PROTECTED]> writes:
> This is a bit offtopic here. I read the RFC and I do not see why SRP
> is not vulnerable to dictionary attacks.
> If I have a working client software then I can use it to reveal
> passwords. Isn't it a dictionary attack?

Dictionary attack in this context means an eavesdropper records a
session, then compares all the hashed passwords against a word list
offline.  If the attacker is allowed to make unlimited online queries,
then he can guess at SRP passwords too.  But the host should notice
that and prevent it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about StringIO

2005-10-11 Thread Frank Millman
Benjamin Niemann wrote:
> Frank Millman wrote:
>
> > I will try to explain my experience with popen() briefly.
> >
> > I run through all the scripts and create a StringIO object with the
> > string I want to pass. It is about 250 000 bytes long. If I run psql
> > using popen(), and pass it the string via stdin, it works fine, but I
> > get all the messages on the screen. If I do the same, but end the
> > command with ' > fjm 2>&1' it works correctly and the messages end up
> > in the file fjm, which is about 40 000 bytes long. If I run it with
> > popen4(), it starts ok, but then hangs about 1/4 of the way through.
> > Exactly the same happens on MSW. It seems to be hitting a limit on the
> > size of the stdout file - is that possible?
> >
>
> That's probably a deadlock as described in
> 
>

Thanks for this pointer. I have read it, but I don't think it applies
to my situation, as it talks about 'reading' from the child's stdout
while the child is 'writing' to stderr. I am not doing that, or at
least not consciously. Here is a code snippet. 's' is a StringIO object
that contains my input. It is about 6000 lines/25 bytes long.

-

sql_stdin,sql_stdout = os.popen4('psql -U %s -d %s' % (user,database))

sql_stdin.writelines(s.readlines())
s.close()
sql_stdin.close()

-

It starts, and then hangs, after processing about 6% of my input.

If I add ' > fjm 2>&1' to the command, it works, so it is definitely
connected with the child writing to stdout/stderr.

I tried storing my input in a list, and passing ''.join(s), but it had
the same result. I also looped over the list and wrote one line at a
time to sql_stdin - same result.

I can work around this, so a solution is not critical. However, it
would be nice to know if this is a limitation of popen4(), or if I am
doing something wrong.

> > BTW, is there an equivalent of /dev/null on MSW?
>
> Dunno - but as a last resort, you could create a tempfile with a unique name
> (to be sure, not to override any existing data), dump your output there and
> later os.unlink() it...
>

A quick google revealed the answer - there is a device called NUL which
achieves the same purpose.

Thanks

Frank

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


Re: Question about StringIO

2005-10-11 Thread Frank Millman
Diez B. Roggisch wrote:
> > Thanks, Steve and Diez, for the replies. I didn't think it was
> > possible, but it was worth asking :-)
> >
> > I will try to explain my experience with popen() briefly.
> >
> > I have some sql scripts to create tables, indexes, procedures, etc. At
> > present there are about 50 scripts, but this number will grow. I have
> > been running them manually so far. Now I want to automate the process.
> >
> > I am supporting PostgreSQL and MS SQL Server, and the syntax is
> > slightly different in some cases. Rather than maintain two sets of
> > scripts, I prefix some lines with -pg- or -ms- to indicate the
> > platform, and then use Python to parse the scripts and generate a
> > correct output for each platform, passing it to 'psql' and 'osql'
> > respectively, using popen().
>
> Why don't youn use te python DB-Api instead?
>
>
> Regards,
>
> Diez

My scripts are used to create the tables in the database. I didn't
think that DB-API covered that. However, even if it did, I don't think
it would handle differences such as the following.

For Unicode support, PostgreSQL uses the character-set specified when
the database is created. SQL Server allows you to specify it for each
column, using the datatype NCHAR and NVARCHAR instead of CHAR and
VARCHAR.

PostgreSQL uses data types called DATE and TIMESTAMP. SQL Server uses
DATETIME (it also uses TIMESTAMP, but that is used for something else).

Both DBMS's have the concept of a column which is automatically
assigned a 'next number' each time a row is created, but the syntax for
defining the column is completely different.

PostgreSQL allows the use of a WHERE clause when creating an INDEX,
which is useful if you only want to index a subset of a table.

SQL Server has the concept of a CLUSTERED INDEX, whereby it stores the
rows physically in index sequence. It defaults to using a clustered
index for the primary key. Often this is not what you want, so it is
desirable to specify the primary key as NONCLUSTERED, and then specify
a CLUSTERED index for a more frequently used column.

These are just a few of the differences, but you get the idea. If there
is a better way to do this in a cross-platform manner, I would love to
know how.

Thanks

Frank

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


Re: Let My Terminal Go

2005-10-11 Thread en.karpachov
On 10 Oct 2005 22:58:08 -0700
[EMAIL PROTECTED] wrote:

> How do I implement this in my application written in python?

Google for "python daemonize".

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


Re: [Info] PEP 308 accepted - new conditional expressions

2005-10-11 Thread Antoon Pardon
Op 2005-10-10, Terry Hancock schreef <[EMAIL PROTECTED]>:
> On Sunday 09 October 2005 07:50 am, phil hunt wrote:
>> On Fri, 7 Oct 2005 01:05:12 -0500, Terry Hancock <[EMAIL PROTECTED]> wrote:
>> >GvR's syntax has the advantage of making grammatical sense in English (i.e.
>> >reading it as written pretty much makes sense).
>> 
>> I know, let's re-write Python to make it more like COBOL! That's 
>> bound to be a winner!
>
> Whereas the "natural order" of "condition affirmative negative" is natural
> for what reason?  That it is so in C?
>
> I don't find that so compelling either, frankly.  Why should it really
> matter in the end?  I've always found C's order (and punctuation) confusing,
> I have to look it up practically everytime I use it or have to read it 
> (which correlates to it being used very rarely, with causality in both
> directions).
>
> Given that situation, choosing a form which is easy to read is surely
> an advantage, and, since it is the way that Python has handled logic
> in the past, it makes sense to continue doing so.

Personnaly I would think some consistency between conditional
expressions and conditional statements would have been a good
thing. I haven't seen a discussion where the following kind of
if statement was discussed.

do:
  return a[0]
if a[0] < a[1] else:
  return a[1[

> No doubt, ANY choice of ternary operator for Python will be
> criticized, and no doubt, ANY choice would nevertheless be
> usable.

Agreed, I think having it is more important than what form
it comes in. My preference has more to do with consistency
with the statement.

> OTOH, I think this choice is consistent with the rest of Python's
> design. The general choice to use keyword operators for LOGIC
> and symbolic operators for MATH is retained, and so long as we're
> describing the logic in words, it makes sense for the wording
> to sound natural.
>
> Consistency certainly does make it easier for me to remember.

I think that a consistency within the language would have
made more sense than consistency with someone's mother
tongue. When I program I program in python or some other
programming language. Not in english, dutch, french or
some other natural language.

But for me this is just style talk. I don't care that much
for style, I'm more concerned with functionality and I'm
glad this functionality will become available.

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


mod_python

2005-10-11 Thread Python_it
Today I was busy to install mod_python.

I have put the line

LoadModule python_module libexec/mod_python.so

into the httpd.conf file.
It Works!
Apache load mod_python /3.2.2.b Python2.4

But my problem is where I have to place te following code in de
httpd.conf?


AddHandler mod_python .py
PythonHandler mptest
PythonDebug On


Because al the tutorials write this. But where?

If I try to put the code some where,
apache give the following message by testing the configure:
Multiple  arguments not (yet) supported
But what i have to change or replace.

I test with the next file:

C:\Program Files\Apache Group\Apache2\htdocs\project\
mptest.py

from mod_python import apache

def handler(req):
   req.content_type = 'text/plain'
   req.send_http_header()
   req.write('mptest.py\n')
   return apache.OK

Is this code enough for testing?

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


Re: Send password over TCP connection

2005-10-11 Thread Laszlo Zsolt Nagy
Paul Rubin wrote:

>Laszlo Zsolt Nagy <[EMAIL PROTECTED]> writes:
>  
>
>>This is a bit offtopic here. I read the RFC and I do not see why SRP
>>is not vulnerable to dictionary attacks.
>>If I have a working client software then I can use it to reveal
>>passwords. Isn't it a dictionary attack?
>>
>>
>
>Dictionary attack in this context means an eavesdropper records a
>session, then compares all the hashed passwords against a word list
>offline.  If the attacker is allowed to make unlimited online queries,
>then he can guess at SRP passwords too.  But the host should notice
>that and prevent it.
>  
>
I see. So the eavesdropper records the random strings and the password 
hash value sent.
Having these values, he can try to find a suitable password in his list 
that will result in the same communication.
He can do this without having to connect to the server again, just by 
replaying the algorithm for a given password
(and the same 'random' strings).

The difference in SRP is that the random strings are private, they will 
never be sent over the network.
So they cannot be eavesdropped. Cracking SRP would require to calculate 
the dividers of a product of
two very big primes (like in RSA). This is why it is hard to use 
dictionary attacks - you cannot replay the
algorithm for a given password.

Thank you, I think I understand now.

   Les



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


Re: mod_python

2005-10-11 Thread deelan
Python_it wrote:
(...)
> But my problem is where I have to place te following code in de
> httpd.conf?
> 
> 
> AddHandler mod_python .py
> PythonHandler mptest
> PythonDebug On
> 
> 
> Because al the tutorials write this. But where?

try put it at the end of your http.conf file.

 >
 > If I try to put the code some where,
 > apache give the following message by testing the configure:
 > Multiple  arguments not (yet) supported
 > But what i have to change or replace.

just an idea, try:


...


because it sounds like apache parser gets confused
with all those slashes.

> 
> I test with the next file:
> 
> C:\Program Files\Apache Group\Apache2\htdocs\project\
> mptest.py
> 
> from mod_python import apache
> 
> def handler(req):
>req.content_type = 'text/plain'
>req.send_http_header()
>req.write('mptest.py\n')
>return apache.OK
> 
> Is this code enough for testing?
> 

i believe so.

also check this:
"Getting mod_python Working"


-- 
deelan 




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


Re: Question about StringIO

2005-10-11 Thread Diez B. Roggisch
> Thanks for this pointer. I have read it, but I don't think it applies
> to my situation, as it talks about 'reading' from the child's stdout
> while the child is 'writing' to stderr.

But that is exactly the point: the psql blocks because you don't read 
away the buffered data. Start a thread, read that stdout/stderr and see 
if things go smoothly.

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


SOAPpy, WSDL, non-standard types and my graying hair

2005-10-11 Thread Miki Tebeka
Hello,

I'm trying to use SOAPpy with WSDL (talking to 
http://www.seapine.com/ttpro.html).

proxy.show_methods for getRecordListForTable is:

Method Name: getRecordListForTable

   In #0: cookie  ((u'http://www.w3.org/2001/XMLSchema', u'long'))
   In #1: tablename  ((u'http://www.w3.org/2001/XMLSchema', u'string'))
   In #2: filtername  ((u'http://www.w3.org/2001/XMLSchema', u'string'))
   In #3: columnlist  ((u'urn:testtrack-interface', u'ArrayOfCTableColumn'))

   Out #0: recordlist  ((u'urn:testtrack-interface', u'CRecordListSoap'))

I know how to prepare the first three arguments (using SOAPpy.stringType and
SOAPpy.longType). I can't find the documentation on how to prepare the last
argument.

Any ideas? pointers? ...

Thanks.
--

Miki Tebeka <[EMAIL PROTECTED]>
http://tebeka.bizhat.com
The only difference between children and adults is the price of the toys


pgpmRrBPnFq5x.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Question about StringIO

2005-10-11 Thread Diez B. Roggisch
> My scripts are used to create the tables in the database. I didn't
> think that DB-API covered that. 

The DB-Api covers executin arbirary SQL - either DDL or DML. It is 
surely centered around DML, but that doesn't mean that its not usabel to 
issue "create ..." statements.

 >However, even if it did, I don't think
> it would handle differences such as the following.



All that has nocthing to do with teh API - you'd still need your 
differentiated DDL - but the communication with the programs would go away.

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


Re: mod_python

2005-10-11 Thread Python_it
Thanks for your replay.
I put the handler code at the end of the file.
No error!
But if I go to my localhost\project\mptest.py
The code of my function appears.
I solve this by put the following code in the confige file:


AllowOverride FileInfo


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


Re: Question about StringIO

2005-10-11 Thread Frank Millman

Diez B. Roggisch wrote:
> > Thanks for this pointer. I have read it, but I don't think it applies
> > to my situation, as it talks about 'reading' from the child's stdout
> > while the child is 'writing' to stderr.
>
> But that is exactly the point: the psql blocks because you don't read
> away the buffered data. Start a thread, read that stdout/stderr and see
> if things go smoothly.
>
> Diez

Of course (kicks himself), it is obvious now that you have explained
it. I tried your suggestion and it works perfectly.

Many thanks

Frank

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


Re: Looking for info on Python's memory allocation

2005-10-11 Thread Lasse Vågsæther Karlsen
Sybren Stuvel wrote:
> Steven D'Aprano enlightened us with:
> 
>>he says that every time you try to append to a list that is already
>>full, Python doubles the size of the list. This wastes no more than

> If, on the other hand, you double the memory every time you run out,
> you have to copy much less data, and in the end it turns out you need
> roughly N steps to add N items to the list. That's a lot better, isn't
> it?

This begs a different question along the same lines.

If I have a generator or other iterable producing a vast number of 
items, and use it like this:

s = [k for k in iterable]

if I know beforehand how many items iterable would possibly yield, would 
a construct like this be faster and "use" less memory?

s = [0] * len(iterable)
for i in xrange(len(iterable)):
 s[i] = iterable.next()

-- 
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:[EMAIL PROTECTED]
PGP KeyID: 0x2A42A1C2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Learning Python

2005-10-11 Thread Chris Dewin
On Mon, 10 Oct 2005 17:20:35 +, dannypatterso wrote:

[snip]

>> I'm a hobby programmer using mostly BASIC(s) and some Java.  I know
>> procedural programming and I know what encapsulation, inheritance and
>> polymorphism are but I have very little experience in using them as
>> I've written just a few Java programs (i.e., I guess I could use a
>> primer in OO programming).

There was an excellent such primer on devshed, by Icarus, but they appear
to have taken it down.

I saved a copy of it to my HD. Would there be anything morally, or legally
wrong with me uploading it to my site?

-- 
www.wintergreen.in

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


Re: Question about StringIO

2005-10-11 Thread Frank Millman

Diez B. Roggisch wrote:
> > My scripts are used to create the tables in the database. I didn't
> > think that DB-API covered that.
>
> The DB-Api covers executin arbirary SQL - either DDL or DML. It is
> surely centered around DML, but that doesn't mean that its not usabel to
> issue "create ..." statements.
>
>  >However, even if it did, I don't think
> > it would handle differences such as the following.
>
> 
>
> All that has nocthing to do with teh API - you'd still need your
> differentiated DDL - but the communication with the programs would go away.
>
> Diez

I understand. It certainly gives me an alternative approach - I will
experiment to see which suits my purpose best.

Many thanks for your assistance.

Frank

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


A faster shutil.rmtree or maybe a command.

2005-10-11 Thread martijn
H!

Sometimes I must delete 2 very big directory's.
The directory's have a very large tree with much small file's in it.

So I use shutil.rmtree()
But its to slow.

Is there a faster method ?

I use FreeBsd 5.4.

---
is it maybe faster to walking in the directy en delete each file?

Thanks,
GC-Martijn

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


Re: Learning Python

2005-10-11 Thread Paul Rubin
"Chris Dewin" <[EMAIL PROTECTED]> writes:
> There was an excellent such primer on devshed, by Icarus, but they appear
> to have taken it down.
> 
> I saved a copy of it to my HD. Would there be anything morally, or legally
> wrong with me uploading it to my site?

A little googling shows it's still up at:

http://www.melonfire.com/community/columns/trog/print.php?id=94  part 1
http://www.melonfire.com/community/columns/trog/print.php?id=96  part 2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A faster shutil.rmtree or maybe a command.

2005-10-11 Thread Giovanni Bajo
[EMAIL PROTECTED] wrote:

> Sometimes I must delete 2 very big directory's.
> The directory's have a very large tree with much small file's in it.
>
> So I use shutil.rmtree()
> But its to slow.
>
> Is there a faster method ?


Is os.system("rm -rf %s" % directory_name) much faster?
-- 
Giovanni Bajo


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


A problem while using urllib

2005-10-11 Thread Johnny Lee
Hi,
   I was using urllib to grab urls from web. here is the work flow of
my program:

1. Get base url and max number of urls from user
2. Call filter to validate the base url
3. Read the source of the base url and grab all the urls from "href"
property of "a" tag
4. Call filter to validate every url grabbed
5. Continue 3-4 until the number of url grabbed gets the limit

   In filter there is a method like this:

--
# check whether the url can be connected
def filteredByConnection(self, url):
   assert url

   try:
  webPage = urllib2.urlopen(url)
   except urllib2.URLError:
  self.logGenerator.log("Error: " + url + " ")
  return False
   except urllib2.HTTPError:
  self.logGenerator.log("Error: " + url + " not found")
  return False
   self.logGenerator.log("Connecting " + url + " successed")
   webPage.close()
   return True


   But every time when I ran to the 70 to 75 urls (that means 70-75
urls have been tested via this way), the program will crash and all the
urls left will raise urllib2.URLError until the program exits. I tried
many ways to work it out, using urllib, set a sleep(1) in the filter (I
thought it was the massive urls crashed the program). But none works.
BTW, if I set the url from which the program crashed to base url, the
program will still crashed at the 70-75 url. How can I solve this
problem? thanks for your help

Regards,
Johnny

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


Idle bytecode query on apparently unreachable returns

2005-10-11 Thread sxanth
>What puzzles me, though, are bytecodes 17, 39 and 42 - surely these aren't 
>reachable? Does the compiler just throw in a default 'return None' 
>epilogue, with routes there from every code path, even when it's not 
>needed? If so, why?

Hi.

pyc (http://freshmeat.net/projects/pyc) can already remove that
unused code since June.

As for "why", I guess that there is a lot of room for optimizing
the bytecode but it's a PITA doing all of it in the current internal
compiler. And so developers simply don't care about it.
Maybe the ast-branch would make it easier to start generating
optimal bytecode. On the other hand, the 'compiler module'
produces bad bytecode (for example it miscalculates the 'stacksize'
of functions and as a result the generated functions are slow), it
doesn't use LIST_APPEND, and it doesn't even do the simple peephole
optimizations of the intenal compiler!


In the latest version 0.8 to-be-released, pyc does many more bytecode
optimizations that give a +5% to pystone and it can also bring
generator expressions and decorators to python 2.3.

[OT]
0.8 is stuck on the conditional. We can bring the conditional expression
from the __future__ to users of 2.3/2.4 but I'm not sure people really
like the "T if C else F" syntax over "C ? T : F".

The argument: "python uses 'and'/'or' instead of &&/|| and therefore
it should also use 'if-else' instead of '?:'", just doesn't apply.
And generally this is one of those things that you will never find
the argument that proves which is the right choice. In these cases
you do what you *LIKE* more.

Perhaps a vote would be in order considering the this-or-that
nature of the conditional expression :)


st.


This message was sent through the TEI of ATHENS by means of NOC. 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Batteries Included?

2005-10-11 Thread en.karpachov
On 11 Oct 2005 00:10:01 -0700
Paul Rubin wrote:

> Personally I think including a .exe packager in Python would be a
> great idea.  As a Linux user I can't easily run Windows-specific
> utilities like Inno Setup.  So I don't have a good way to make .exe's
> from my Python code that Windows users can easily run.  Having a cross
> platform .exe packager included with Python would be useful the same
> way cross compilers are useful.  I'm using an x86 computer but I can
> easily configure gcc to produce ARM code.  Why shouldn't my Linux
> Python installation be able to produce Windows .exe's?

Because you can't run it yourself? If you cannot run the freshly-made exe
yourself, why would you want to distrubute it, without even trying? But if
you can, then you can run the InnoSetup as well.

But, for me, I don't care whether such an option will be included or not. I
won't object anyway.

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


Re: A faster shutil.rmtree or maybe a command.

2005-10-11 Thread martijn
A little.

I think its yust to big to handle it.
I'm going to ask it in a freebsd forum, maybe they know how to speed
up.

Thanks.

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


Re: mod_python

2005-10-11 Thread Peter
deelan wrote:

>Python_it wrote:
>(...)
>  
>
>>But my problem is where I have to place te following code in de
>>httpd.conf?
>>
>>
>>AddHandler mod_python .py
>>PythonHandler mptest
>>PythonDebug On
>>
>>
>>Because al the tutorials write this. But where?
>>
>>
>
>try put it at the end of your http.conf file.
>
> >
> > If I try to put the code some where,
> > apache give the following message by testing the configure:
> > Multiple  arguments not (yet) supported
> > But what i have to change or replace.
>
>  
>
>just an idea, try:
>
>
>...
>
>
>because it sounds like apache parser gets confused
>with all those slashes.
>
>  
>
I could be wrong, but i think i read something about apache expecting 
you to use forward slashes instead of backslashes when i was using 
windows...
I seem to recall it being in the readme. ...?

>>I test with the next file:
>>
>>C:\Program Files\Apache Group\Apache2\htdocs\project\
>>mptest.py
>>
>>from mod_python import apache
>>
>>def handler(req):
>>   req.content_type = 'text/plain'
>>   req.send_http_header()
>>   req.write('mptest.py\n')
>>   return apache.OK
>>
>>Is this code enough for testing?
>>
>>
>>
>
>i believe so.
>
>also check this:
>"Getting mod_python Working"
>
>
>  
>
HTH,
Peter

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


strange import error with Python-2.4.1

2005-10-11 Thread Robin Becker
Whilst testing the excellent xlrd http://www.python.org/pypi/xlrd/0.3a1
I came across the following strangeness when trying to add an import of os to 
assist with debugging/tracing.


At line 66 I replaced

import sys

with import sys, os

and then ran python runxlrd.py --help and got this error which is not a real 
syntax problem

Traceback (most recent call last):
   File "runxlrd.py", line 5, in ?
 import xlrd
   File "C:\python24\lib\site-packages\xlrd\__init__.py", line 552
 if DEBUG: print >> self.logfile, "SST Processing"

if I remove the , os then the run produces the expected

usage: runxlrd.py [options] command input-file-patterns

options:
   -h, --helpshow this help message and exit
   -l LOGFILENAME, --logfilename=LOGFILENAME
 contains error messages
   -v VERBOSITY, --verbosity=VERBOSITY
 level of information and diagnostics provided

I also am able to change the line to

import sys
import os

without error.

This behaviour doesn't occur with 2.4.2 or 2.4 only with 2.4.1. I looked for 
some bug fix in the recently released 2.4.2 that related, but couldn't find 
anything obvious. My system doesn't have psyco so xlrd's attempted psyco use 
shouldn't be an issue. Thanks for 2.4.2, but is this one of the fixed bugs or 
has it just got harder to induce?
-- 
Robin Becker

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


Re: Looking for info on Python's memory allocation

2005-10-11 Thread Peter Otten
Lasse Vågsæther Karlsen wrote:

> If I have a generator or other iterable producing a vast number of
> items, and use it like this:
> 
> s = [k for k in iterable]
> 
> if I know beforehand how many items iterable would possibly yield, would
> a construct like this be faster and "use" less memory?
> 
> s = [0] * len(iterable)
> for i in xrange(len(iterable)):
>  s[i] = iterable.next()

You can easily answer the speed aspect of your question using the timeit
module:

~ $ python2.4 -m timeit -s'iterable=range(1000)' '[k for k in iterable]'
1 loops, best of 3: 111 usec per loop

~ $ python2.4 -m timeit -s'iterable=range(1000)' 's = [0]*len(iterable); it
= iter(iterable)' 'for i in xrange(len(iterable)): s[i] = it.next()'
1000 loops, best of 3: 513 usec per loop

~ $ python2.4 -m timeit -s'iterable=range(1000)' 's = [0]*len(iterable)'
'for i, v in enumerate(iterable): s[i] = v'
1000 loops, best of 3: 269 usec per loop

~ $ python2.4 -m timeit -s'iterable=range(1000)' 'list(iterable)'
10 loops, best of 3: 7.33 usec per loop

Peter

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

Re: Batteries Included?

2005-10-11 Thread Paul Rubin
<[EMAIL PROTECTED]> writes:
> Because you can't run it yourself? If you cannot run the
> freshly-made exe yourself, why would you want to distrubute it,
> without even trying? But if you can, then you can run the InnoSetup
> as well.

Obviously I'd want someone to test the .exe before putting it in wide
distribution.  That doesn't solve the problem of how to make the .exe.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Let My Terminal Go

2005-10-11 Thread Mystilleef
Hello,

Thank you. That's all I needed. For some reason, I had always assumed
forking was an expensive process. I guess I was ill-informed.

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


Re: Let My Terminal Go

2005-10-11 Thread Mystilleef
Hello,

Thanks to all the responders and helpers on the group. I'm learning
everyday.

Thanks

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


Re: strange import error with Python-2.4.1

2005-10-11 Thread Steve Holden
Robin Becker wrote:
> Whilst testing the excellent xlrd http://www.python.org/pypi/xlrd/0.3a1
> I came across the following strangeness when trying to add an import of os to 
> assist with debugging/tracing.
> 
> 
> At line 66 I replaced
> 
> import sys
> 
> with import sys, os
> 
> and then ran python runxlrd.py --help and got this error which is not a real 
> syntax problem
> 
> Traceback (most recent call last):
>File "runxlrd.py", line 5, in ?
>  import xlrd
>File "C:\python24\lib\site-packages\xlrd\__init__.py", line 552
>  if DEBUG: print >> self.logfile, "SST Processing"
> 
> if I remove the , os then the run produces the expected
> 
> usage: runxlrd.py [options] command input-file-patterns
> 
> options:
>-h, --helpshow this help message and exit
>-l LOGFILENAME, --logfilename=LOGFILENAME
>  contains error messages
>-v VERBOSITY, --verbosity=VERBOSITY
>  level of information and diagnostics provided
> 
> I also am able to change the line to
> 
> import sys
> import os
> 
> without error.
> 
> This behaviour doesn't occur with 2.4.2 or 2.4 only with 2.4.1. I looked for 
> some bug fix in the recently released 2.4.2 that related, but couldn't find 
> anything obvious. My system doesn't have psyco so xlrd's attempted psyco use 
> shouldn't be an issue. Thanks for 2.4.2, but is this one of the fixed bugs or 
> has it just got harder to induce?

Robin:

Can I ask if you are specifying a source encoding in your file with a 
pragma (?) like

# -*- coding: iso-8859-15 -*-

I've noticed what appear to be spurious syntax errors from time to time 
on such files, and have been attempting to debug the problem for some 
time without any apparent success.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: strange import error with Python-2.4.1

2005-10-11 Thread Fredrik Lundh
Steve Holden wrote:

> Can I ask if you are specifying a source encoding in your file with a
> pragma (?) like
>
> # -*- coding: iso-8859-15 -*-
>
> I've noticed what appear to be spurious syntax errors from time to time
> on such files, and have been attempting to debug the problem for some
> time without any apparent success.

http://www.python.org/sf/1175396

 



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


Re: strange import error with Python-2.4.1

2005-10-11 Thread Richard Brodie

"Robin Becker" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]

> This behaviour doesn't occur with 2.4.2 or 2.4 only with 2.4.1. I looked for
> some bug fix in the recently released 2.4.2 that related, but couldn't find
> anything obvious.

One of the various codecs fixes, I think. Bug #1175396, perhaps.


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


Re: Idle bytecode query on apparently unreachable returns

2005-10-11 Thread Raymond Hettinger
[Tom Anderson]:
> What puzzles me, though, are bytecodes 17, 39 and 42 - surely these aren't
> reachable? Does the compiler just throw in a default 'return None'
> epilogue, with routes there from every code path, even when it's not
> needed? If so, why?

Since unreachable code is never executed, there is no performance
payoff for optimizing it away.  It is not hard to write a dead-code
elimination routine, but why bother?  It would save a few bytes, slow
down compilation time, save nothing at runtime, and make the compiler
more complex/fragile.

FWIW, the peephole optimizer in Python/compile.c is mature -- the low
hanging fruit has already been harvested, leaving the field of
remaining optimizations somewhat barren.


Raymond

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


Re: Python's Performance

2005-10-11 Thread Peter Hansen
Steve Holden wrote:
> And we definitely need "agile" in there. Bugger, I'll go out and come in 
> again ...

Used in the same breath as the word "bugger", I'm not sure the phrase 
"go out and come in again" is entirely appropriate for a family forum. ;-)

But I'm also not sure I ought to post that to the group, so I'll spare 
them and just inflict the thought on you!

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


Re: Merging sorted lists/iterators/generators into one stream of values...

2005-10-11 Thread Lasse Vågsæther Karlsen


Another idea for this method would be that in some cases I noticed that 
it was useful to know which source each element would come from as well, 
as well as removing duplicates from the results.

For instance

s1 = [1, 3, 5, 7]
s2 = [2, 3, 4]

for k, s in merge_by_sort(s1, s2):
 print k, "from source", s

this would print:

1 from source 0
2 from source 1
3 from source 1
3 from source 0
4 from source 1
5 from source 0
7 from source 0

and the above list has 3 twice, so possibly:

1 from sources [0]
2 from sources [1]
3 from sources [0, 1]
4 from sources [1]
5 from sources [0]
7 from sources [0]

This latter one would be a slightly more heavy method as it would have 
to compare the N first elements of the list or heap to figure out what 
indices to yield as well.

However, the previous solution could be:

def merge_by_sort(*sources, **options):
 if "cmp" in options:
 comparison = options["cmp"]
 else:
 comparison = cmp

 iterables = []
 for index, source in enumerate(sources):
 try:
 source = iter(source)
 iterables.append([source.next(), index, source])
 except StopIteration:
 pass

 iterables.sort(cmp=comparison, key=lambda x: x[0], reverse=True)
 while iterables:
 yield iterables[-1][0], iterables[-1][1]
 try:
 iterables[-1][0] = iterables[-1][2].next()
 if len(iterables) > 1 and comparison(iterables[-1][0], 
iterables[-2][0]) > 0:
 iterables.sort(comparison, key=lambda x: x[0], 
reverse=True)
 except StopIteration:
 iterables.pop(-1)

-- 
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:[EMAIL PROTECTED]
PGP KeyID: 0x2A42A1C2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Send password over TCP connection

2005-10-11 Thread Peter Hansen
Laszlo Zsolt Nagy wrote:
 > Peter Hansen wrote:
>> Ignoring all the other issues, any solution which actually requires 
>> the password to be stored on the server is a bad solution.  
>> Administrators should not have access to user passwords, and in 
>> addition users should not be put in the position of having to trust 
>> your server-side security to keep their passwords (which they might 
>> have used on other systems) from being grabbed by hackers.
>>
> Users will always need to trust in the server. The authentication 
> process ensures that the
> client is really talking with the desired server and vice versa. But 
> even if you know that you
> are talking to the right server, you need to trust in the server. The 
> administrator of the server
> has access to all data. Possibly other persons and softwares too. 
> Passwords are not different from this point of view.

If you're saying that people have no choice but to trust that their 
passwords, stored in the clear on the server of some idiot who didn't 
know better, are safe from casual administrator observation and safe 
from hackers stealing the password file, then you shouldn't be allowed 
anywhere near a supposedly secure system...

If you're just saying that one has to trust that the server you are 
talking to at this instant in time is really the one you thought it was, 
then that's an entirely different issue and I agree.

But storing passwords in the clear, thus allowing administrators full 
access to users' passwords, is absolutely *not* necessary.  That's my 
point, regardless of what other issues this thread spawns.  If the OP 
implements strictly the sequence he mentioned in the posting to which I 
was replying, he'll be the aforementioned idiot...

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


Re: Python's Performance

2005-10-11 Thread Peter Hansen
Peter Hansen wrote:
> But I'm also not sure I ought to post that to the group, so I'll spare 
> them and just inflict the thought on you!

Or, maybe I'll just fail to trim the newsgroup line and accidentally 
post to the group anyway.  Yes, that's just what I'll do.

Sorry folks. :-)

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


Re: strange import error with Python-2.4.1

2005-10-11 Thread Steve Holden
Fredrik Lundh wrote:
> Steve Holden wrote:
> 
> 
>>Can I ask if you are specifying a source encoding in your file with a
>>pragma (?) like
>>
>># -*- coding: iso-8859-15 -*-
>>
>>I've noticed what appear to be spurious syntax errors from time to time
>>on such files, and have been attempting to debug the problem for some
>>time without any apparent success.
> 
> 
> http://www.python.org/sf/1175396
> 
Thanks!

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: subprocess and non-blocking IO (again)

2005-10-11 Thread Nick Craig-Wood
Marc Carter <[EMAIL PROTECTED]> wrote:
>  import subprocess,select,sys
> 
>  speakers=[]
>  lProc=[]
> 
>  for machine in ['box1','box2','box3']:
>   p = subprocess.Popen( ('echo '+machine+';sleep 2;echo goodbye;sleep 
>  2;echo cruel;sleep 2;echo world'), stdout=subprocess.PIPE, 
>  stderr=subprocess.STDOUT, stdin=None, universal_newlines=True )
>   lProc.append( p )
>   speakers.append( p.stdout )
> 
>  while speakers:
>   speaking = select.select( speakers, [], [], 1000 )[0]
>   for speaker in speaking:
>   speech = speaker.readlines()
>   if speech:
>   for sentence in speech:
>   print sentence.rstrip('\n')
>   sys.stdout.flush() # sanity check
>   else: # EOF
>   speakers.remove( speaker )
>  - SNIP -
>  The problem with the above is that the subprocess buffers all its output 
>  when used like this and, hence, this automation is not informing me of 
>  much :)

The problem with the above is that you are calling speaker.readlines()
which waits for all the output.

If you replace that with speaker.readline() or speaker.read(1) you'll
see that subprocess hasn't given you a buffered pipe after all!

In fact you'll get partial reads of each line - you'll have to wait
for a newline before processing the result, eg

import subprocess,select,sys

speakers=[]
lProc=[]

for machine in ['box1','box2','box3']:
 p = subprocess.Popen( ('echo '+machine+';sleep 2;echo goodbye;sleep 2;echo 
cruel;sleep 2;echo world'), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, 
stdin=None, universal_newlines=True, shell=True)
 lProc.append( p )
 speakers.append( p.stdout )

while speakers:
 speaking = select.select( speakers, [], [], 1000 )[0]
 for speaker in speaking:
 speech = speaker.readline()
 if speech:
 for sentence in speech:
 print sentence.rstrip('\n')
 sys.stdout.flush() # sanity check
 else: # EOF
 speakers.remove( speaker )

gives

b
o
x
1

b
o
x
3

b
o
x
2

pause...

g
o
o
d
b
y
e

etc...

I'm not sure why readline only returns 1 character - the pipe returned
by subprocess really does seem to be only 1 character deep which seems
a little inefficient! Changing bufsize to the Popen call doesn't seem
to affect it.
-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess and non-blocking IO (again)

2005-10-11 Thread Marc Carter
Donn Cave wrote:
> If you want to use select(), don't use the fileobject
> functions. Use os.read() to read data from the pipe's file
> descriptor (p.stdout.fileno().)  This is how you avoid the
> buffering.
Thankyou, this works perfectly.  I figured it would be something simple.

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


How to do *args, **kwargs properly

2005-10-11 Thread Lasse Vågsæther Karlsen
I must be missing something but what is the proper way to do a function 
using such arguments ?

Specifically I'm looking for:

- ability to take an unspecified number of "positional arguments"
- ability to take optional named arguments that follows the first arguments
- raise appropriate errors if I use the wrong named arguments

for instance:

fn(1, 2, 3)
fn(1, 2, 3, cmp=lambda x, y: y-x)
fn(1, 2, 3, cpm=lambda x, y: y-x) # TypeError on this

Is the following the way to go ?

def fn(*values, **options):
 comparison = cmp
 for key, value in options.iteritems():
 if key == "cmp":
 comparison = value
 else:
 raise TypeError, "'%s' is an invalid keyword argument for 
this function" % key
 # rest of function here

or is the "proper python" way simply this:

def fn(*values, **options):
 if "cmp" in options: comparison = options["cmp"]
 else: comparison = cmp
 # rest of function here

and thus ignoring the wrong parameter names?

-- 
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:[EMAIL PROTECTED]
PGP KeyID: 0x2A42A1C2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A problem while using urllib

2005-10-11 Thread Alex Martelli
Johnny Lee <[EMAIL PROTECTED]> wrote:
   ...
>try:
>   webPage = urllib2.urlopen(url)
>except urllib2.URLError:
   ...
>webPage.close()
>return True
> 
> 
>But every time when I ran to the 70 to 75 urls (that means 70-75
> urls have been tested via this way), the program will crash and all the
> urls left will raise urllib2.URLError until the program exits. I tried
> many ways to work it out, using urllib, set a sleep(1) in the filter (I
> thought it was the massive urls crashed the program). But none works.
> BTW, if I set the url from which the program crashed to base url, the
> program will still crashed at the 70-75 url. How can I solve this
> problem? thanks for your help

Sure looks like a resource leak somewhere (probably leaving a file open
until your program hits some wall of maximum simultaneously open files),
but I can't reproduce it here (MacOSX, tried both Python 2.3.5 and
2.4.1).  What version of Python are you using, and on what platform?
Maybe a simple Python upgrade might fix your problem...


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


Re: How to do *args, **kwargs properly

2005-10-11 Thread Paul Rubin
Lasse Vågsæther Karlsen <[EMAIL PROTECTED]> writes:
> or is the "proper python" way simply this:
> 
> def fn(*values, **options):
>  if "cmp" in options: comparison = options["cmp"]
>  else: comparison = cmp
>  # rest of function here
> 
> and thus ignoring the wrong parameter names?

I don't know about "proper" but it's pretty common.  You could also
use a positional arg:

  def fn(cmp, *values):
 # blah blah

   fn(cmp, 1, 2, 3) # call the function

You could check for invalid keys a little more concisely than in your
example.  For example with sets:
  def fn(*values, **options):
if Set(options.keys()) - Set(('cmp')):
  raise error...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to do *args, **kwargs properly

2005-10-11 Thread Alex Martelli
Lasse Vågsæther Karlsen <[EMAIL PROTECTED]> wrote:
   ...
> fn(1, 2, 3)
> fn(1, 2, 3, cmp=lambda x, y: y-x)
> fn(1, 2, 3, cpm=lambda x, y: y-x) # TypeError on this

I assume these are your specs.

> or is the "proper python" way simply this:
> 
> def fn(*values, **options):
>  if "cmp" in options: comparison = options["cmp"]
>  else: comparison = cmp
>  # rest of function here
> 
> and thus ignoring the wrong parameter names?

Errors should not pass silently, unless explicitly silenced.

So, I would code:

def fn(*values, **opts):
  cmp = opts.pop('cmp', cmp)
  if opts: raise ValueError, 'Unknown option(s): %s' % opts.keys()
  # rest of function here

There are some cases where ignoring extra options, or just warning about
them, may be more appropriate, but normally I would check...


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


Re: Wanted: Python module allowing direct access to raw sectors ofharddrives (MFT, boot sector, etc.) in MS Windows

2005-10-11 Thread Claudio Grondi
Thank you for your reply, even if currently not
that interesting for me because after the first
CD writer for IDE were available I stopped to
use SCSI and didn't come back to it since then.

Does the Python open() command not work the
same way for SCSI drives as for IDE or USB
drives (I can't try it myself, because of above)?

Claudio
P.S. for those who are interested I have uploaded a
Python script I wrote for myself to have a reference to
this subject to:
http://people.freenet.de/AiTI-IT/Python/HowTo_AccessRawSectorsOfPhysicalDrives.py
:-)

"sam" <[EMAIL PROTECTED]> schrieb im Newsbeitrag
news:[EMAIL PROTECTED]
> The following site contains my routines to access information from the
> Microsoft SCSIPASSTHROUGH layer under windows. These routines allow you
> to access the storage devices mounted under windows using SCSI
> commands. The dll that I provide will work with Python 2.3
>
> http://starship.python.net/crew/samschul/
>
> Sam Schulenburg
>
> Claudio Grondi wrote:
> > Thank you Jeff very much for your quick reply.
> > It saved me really much time of digging in the wrong direction.
> >
> > <[EMAIL PROTECTED]> wrote in
> > news:<[EMAIL PROTECTED]>...
> > >> I took the advice from this web page:
> > >> http://support.microsoft.com/kb/q100027/
> > Ok, I had found this page myself during Googling, but I have missed just
> > to try to use the described way of addressing physical devices with file
> > opening in Python.
> > It works as expected with harddrives so you are right that you are
getting
> > the MBR with the proposed code.
> >
> > After some not always happy end adventures with Python
> > scripting I am impressed by the power of the concept behind
> > the language once again.
> >
> > Claudio
> >
> > >>(I don't know how this extends to floppies, and the 9x family of OSes
> > isn't
> > >>listed in "applies to", so this may not help your case)
> > >>Here, I open "physical drive 0" and see that the magic number
indicates a
> > valid
> > >>boot record. I believe it is the MBR.
> > > f = open('.\\PhysicalDrive0', 'rb')
> > > f.read(512)[-2:]
> > >>'U\xaa' # that is, hex 55 AA
> > >>I don't know much about low-level filesystem or partition details--I
got
> > the
> > >>tidbit about the 55 AA magic number from
> >
>>http://www-uxsup.csx.cam.ac.uk/pub/doc/suse/sles9/adminguide-sles9/ch08.ht
> > ml
> > >>Jeff
> > >><[EMAIL PROTECTED]> schrieb im Newsbeitrag
> > news:[EMAIL PROTECTED]
>




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


Re: Let My Terminal Go

2005-10-11 Thread Ivan Voras
Mike Meyer wrote:

> The easy way to do all these things - from C, anyway - is with
> daemon(3). That isn't wrapped as part of the Python library. The
> easiest way to solve your problem may be write a wrapper for that
> call. If daemon exists on enough systems, submitting your wrapper as a
> patch to the os modulee would be appropriate.

I think the deamon() library call only exists on the BSDs. Anyway, there 
it is implemented with a fork() call and some additional code to close 
std descriptors, so there's no practical difference between calling 
deamon() and fork() by yourself...
-- 
http://mail.python.org/mailman/listinfo/python-list


XMS .NET: IBM Message Service Client for .NET Beta

2005-10-11 Thread rungta
IronPython and Boo developers may find this interesting:

The second refresh of the IBM Message Service Client for .NET Beta is
now
available:

http://www14.software.ibm.com/webapp/download/search.jsp?go=y&rs=message

The key enhancements in this refresh are:

- The supported messaging environments have been extended to include
IBM
WebSphere MQ 5.3 and 6 (for point to point messaging only) and WBI
Message
Broker 6.
- Several updates have been made to remove API restrictions and fix
minor
defects reported since the previous refresh or during continued
testing.
- The first full draft of the user documentation has been completed.

Further details can be found in the products readme.txt.

Any feedback or queries are welcomed at:
news://news.software.ibm.com/ibm.software.websphere.mq.beta.
But please prefix your XMS-related posts to this Beta newsgroup with
'XMS .NET:'.

About XMS .NET:

XMS .NET can connect to WebSphere MQ, The default messaging provider in

WebSphere Application Server v6 and WebSphere Business Integration
Event/Message Brokers.

An XMS application can exchange messages with any of the following
types
of application - An XMS application, a WebSphere MQ JMS application, a
native WebSphere MQ application and a JMS application that is using the

WebSphere default messaging provider. XMS applications may use
different
IBM messaging servers with little or no change.

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


Re: How to do *args, **kwargs properly

2005-10-11 Thread Max M
Lasse Vågsæther Karlsen wrote:
> I must be missing something but what is the proper way to do a function 
> using such arguments ?

> - ability to take an unspecified number of "positional arguments"

You should probably pass a sequence to the method instead. You can do it 
the other way, but it's poor coding style in most cases.


> - ability to take optional named arguments that follows the first arguments

Setting the default value to a value that cannot exist as an argument is 
the normal way. Eg. None.

def fn(vals, cmp=None)


> - raise appropriate errors if I use the wrong named arguments

def fn(*values, cmp=None):
 if cmp is None:
 raise TypeError, "'%s' is an invalid keyword argument for this 
function" % key


If you insist on doing it the other way:

FN_LEGAL_ARGS = set( ('cmp',) )

def fn(*values, **options):
 for key in options.keys():
 if not key in FN_LEGAL_ARGS:
 raise TypeError, "'%s' is an invalid keyword argument for 
this function" % key


-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


datetime and daylight savings problem

2005-10-11 Thread James
I need to import a bunch of data into our database for which there's a
single entry each day which occurs at the same time every day in local
time - so I need to convert this to UTC taking into account local
daylight savings. However daylight savings just don't seem to be
working at all...

Python 2.3.5 (#2, May  4 2005, 08:51:39)
[GCC 3.3.5 (Debian 1:3.3.5-12)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from pytz import timezone
>>> from datetime import datetime
>>> t=timezone("Europe/Paris")
>>> utc=timezone("UTC")
>>> d=datetime(2005,01,24,16,59,tzinfo=t)
>>> d
datetime.datetime(2005, 1, 24, 16, 59, tzinfo=)
>>> d.astimezone(utc)
datetime.datetime(2005, 1, 24, 16, 59, tzinfo=)
>>> d2=datetime(2005,06,01,16,59,tzinfo=t)
>>> d2
datetime.datetime(2005, 6, 1, 16, 59, tzinfo=)
>>> d2.astimezone(utc)
datetime.datetime(2005, 6, 1, 16, 59, tzinfo=)

One of these should be in DST, the other shouldn't, I'm not sure why.
Additional oddness here

>>> d.astimezone(utc).astimezone(t)
datetime.datetime(2005, 1, 24, 18, 59, tzinfo=)
>>> d2.astimezone(utc).astimezone(t)
datetime.datetime(2005, 6, 1, 17, 59, tzinfo=)

I'm not sure if it's just something I'm doing completely wrong here...

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


Re: How to do *args, **kwargs properly

2005-10-11 Thread Lasse Vågsæther Karlsen
Max M wrote:
> Lasse Vågsæther Karlsen wrote:
> 
>> I must be missing something but what is the proper way to do a 
>> function using such arguments ?
> 
> 
>> - ability to take an unspecified number of "positional arguments"
> 
> 
> You should probably pass a sequence to the method instead. You can do it 
> the other way, but it's poor coding style in most cases.

So what you're saying is that instead of:

def fn(*values, **options):

I should use:

def fn(values, cmp=cmp):

in this specific case?

and then instead of:

fn(1, 2, 3, cmp=...)

this:

fn([1, 2, 3], cmp=...)



I think I'll re-write to use a list instead.

-- 
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:[EMAIL PROTECTED]
PGP KeyID: 0x2A42A1C2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparing lists

2005-10-11 Thread Scott David Daniels
Christian Stapfer wrote:
> "Steve Holden" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
> 
>>Christian Stapfer wrote:
>>
>>>"George Sakkis" <[EMAIL PROTECTED]> wrote in message 
>>>news:[EMAIL PROTECTED]
>>>
>>>
"Christian Stapfer" <[EMAIL PROTECTED]> wrote:

><[EMAIL PROTECTED]> wrote:
>>try to use set.
A reasonable suggestion.  A set must have the trade-offs involved.
The abstraction itself brings to mind the issues, and the performance
can, at least in theory, be handled there.  If that is true (that
the "set" abstraction "sees" the problem), then you can rely on the
Python implementation of "set" to either now, or eventually, have
a "good" implementation -- one not too far off efficient.  The Python
gang is good at this stuff; a "better" set implementation will win if
it can show better performance without related down-sides.

As to the "either now, or eventually;"  if you _must_ have performance
now, not in some abstract future, then it behooves you to _test_,
_test_, _test_!

>>> If the documentation stated the order-of-magnitude
>>>behavior of those basic operations up front, then
>>>I (and *anyone* else who ever wanted to use those
>>>operations on large lists / large sets) could do
>>>a quick order-of-magnitude estimation of how
>>>a certain program design will behave, performance
>>>wise.
And, if the proper documentation is in place, and it
says "dictionary lookup is O(N)" (and you avoid using
it for exactly that reason), how surprised will you be
to discover that the O(N) is only reached if the hash
values of the keys are all equal?

Oh, maybe you expect "O(N)" to really mean "\Theta(N)".
Then, if you are a dweeb like me, you will respond that
"This is not possible, a dictionary of size N must take at
least 'O(lg N)' to read the key, never mind processing it."
But, it turns out, that given a bound on the size of a
process, processing an address is "O(1)", not "O(lg N)".
Is that too practical for you, or not enough?

>>>  *Experimenting* is not necessarily as easy to
>>>do as you seem to believe. 


>>>How do you, for example, hit upon the worst-case 
 >>>behavior with your test data?
Are you saying the documentation should characterize the
cases that achieve worst-case behavior?  This is a stiff
burden indeed, not one I am used to in even the most rigorous
classes I've seen.  If there is such a characterization,
how burned will you feel if a case is overlooked and that
case is the one that you sold to your customer?  Are you
willing to provide the same guaranteed performance and
documentation of performance to your customer that you
you expect of the Python system?  Would you mind if the
quality is proportional to the price you paid?

>>You are, of course, either assuming that there's a
>>single implementation of Python,
> Of course not!
> 
>>or that all implementations have the same behaviour.
> Of course not!

> But it is reasonable, anyway, to ask for information
> about a specific implementation (that one is *forced*
> to use). 
You are not _forced_ to use any implementation of Python.
You are free to implement your own Python system.

>   And if the implementer wants to complain that
> giving such information would break his wonderful
> abstraction then I can only answer: It is *reality*
> that *will* break your abstraction as regards
> performance! It is, therefore, absolutely *no*
> use to *pretend* you *can* avoid this form of "breaking
> the abstraction" by simply avoiding to mention it
> in the documentation...
I simply repeat: I have never seen a paper characterizing
the performance of an algorithm as "O(expr(N))" that described
in details _all_ cases that reached that limit.  At most such
papers describe _one_ such cases.  Nor have I ever seen papers
describing the performance of an algorithm as "\Theta(expr(N))"
that characterized the cases that broke the "\Theta" performance.
If you provide me the papers, provide me a C compiler with
equivalent docs on all C expressions, and provide me the funding
to update the Python docs, I will be happy to do so for a single
version of Python and a since version of CPython.  I expect I
will have an easier time of it than the IronPython people will
have.

> I consider it the job of the implementer to know
> about the trade-offs that he has been making in
> choosing one particular implementation, and to
> know what computational complexity therefore
> attaches to the various operations exposed in
> its interface.
Am I to take it you provide this to all of your customers?

> How reasonable is it to ask me, or anyone else
> for that matter, to extract, experiment-wise
> (if it can be done at all with reasonable effort)
> information that properly belongs to the implementer
> and really should have been exposed in the
> documentation in the first place?
Not at all reasonable.  How reasonable is it to ask
me to provide you support information for free?

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org

Re: Send password over TCP connection

2005-10-11 Thread dcrespo
then, what you proppose?

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


Python Doc Problem Example: sort() (reprise)

2005-10-11 Thread Xah Lee
Python Doc Problem Example: sort()

Xah Lee, 200503
Exhibit: Incompletion & Imprecision

Python doc “3.6.4 Mutable Sequence Types” at
http://python.org/doc/2.4/lib/typesseq-mutable.html

in which contains the documentation of the “sort” method of a list.
Quote:

«
Operation   Result  Notes
s.sort([cmp[, key[, reverse]]]) sort the items of s in place(7),
(8), (9), (10)

(7) The sort() and reverse() methods modify the list in place for
economy of space when sorting or reversing a large list. To remind you
that they operate by side effect, they don't return the sorted or
reversed list.

(8) The sort() method takes optional arguments for controlling the
comparisons.

cmp specifies a custom comparison function of two arguments (list
items) which should return a negative, zero or positive number
depending on whether the first argument is considered smaller than,
equal to, or larger than the second argument: "cmp=lambda x,y:
cmp(x.lower(), y.lower())"

key specifies a function of one argument that is used to extract a
comparison key from each list element: "cmp=str.lower"

reverse is a boolean value. If set to True, then the list elements
are sorted as if each comparison were reversed.

In general, the key and reverse conversion processes are much
faster than specifying an equivalent cmp function. This is because cmp
is called multiple times for each list element while key and reverse
touch each element only once.

Changed in version 2.3: Support for None as an equivalent to
omitting cmp was added.

Changed in version 2.4: Support for key and reverse was added.

(9) Starting with Python 2.3, the sort() method is guaranteed to be
stable. A sort is stable if it guarantees not to change the relative
order of elements that compare equal -- this is helpful for sorting in
multiple passes (for example, sort by department, then by salary
grade).

(10) While a list is being sorted, the effect of attempting to
mutate, or even inspect, the list is undefined. The C implementation of
Python 2.3 and newer makes the list appear empty for the duration, and
raises ValueError if it can detect that the list has been mutated
during a sort.
»


As a piece of documentation, this is a lousy one.

The question Python doc writers need to ask when evaluating this piece
of doc are these:

• can a experienced programer who is expert at several languages but
new to Python, and also have read the official Python tutorial, can he,
read this doc, and know exactly how to use sort with all the options?

• can this piece of documentation be rewritten fairly easily, so that
the answer to the previous question is a resounding yes?

To me, the answers to the above questions are No and Yes. Here are some
issues with the doc:

• In the paragraph about the “key” parameter, the illustration
given is: “cmp=str.lower”. It should be be “key=str.lower”

• This doc lacks examples. One or two examples will help a lot,
especially to less experienced programers. (which comprises the
majority of readers) In particular, it should give a full example of
using the comparison function and one with the “key” parameter.
Examples are particularly needed here because these parameteres are
functions, often with the “lambda” construct. These are unusual and
advanced constructs among imperative programers.

• This doc fails to mention what happens when the predicate and the
shortcut version conflicts. e.g. “myList.sort(cmp=lambda x,y:
cmp(x[0], y[0]), key=lambda x: str(x[1]) )”

• The syntax notation Python doc have adopted for indicating optional
parameters, does not give a clear view just exactly what combination of
optional parameters can be omitted. The notation: “s.sort([cmp[,
key[, reverse]]])” gives the impression that only trailing arguments
can be omitted, which is not true.

• The doc gives no indication of how to omit a optional arg. Should
it be “nul”, “Null”, 0, or left empty? Since it doesn't give
any examples, doc reader who isn't Python experts is left to guess at
how true/false values are presented in Python.

• On the whole, the way this doc is written does not give a clear
picture of the roles of the supplied options, nor how to use them.

Suggested Quick Remedy: add a example of using the cmp function. And a
example using the “key” function. Add a example of Using one of
them and with reverse. (the examples need not to come with much
explanations. One sentence annotation is better than none.)

Other than that, the way the doc is layed out with a terse table and
run-on footnotes (employed in several places in Python doc) is not
inductive. For a better improvement, there needs to be a overhaul of
the organization and the attitude of the entire doc. The organization
needs to be programing based, as opposed to implementation or computer
science based. (in this regard, one can learn from the Perl folks). As
to attitude, the writing needs to be Python-as-is, as opposed to
computer science framework, as in

Where is the error

2005-10-11 Thread enas khalil


hello,

when i run the following code to Read and tokenize data from a tagged text as follows :
from nltk.corpus import brownfrom nltk.tagger import TaggedTokenizerfrom nltk.tokenizer import *tagged_txt_str=open('corpus.txt' ).read()tagged_txt_token=Token(TEXT=tagged_txt_str)TaggedTokenizer.tokenize(tagged_txt_token)print tagged_txt_token
 
i got the following error :Traceback (most recent call last):File "C:\My Documents\TAGGING.PY", line 3, in -toplevel-from nltk.tagger import TaggedTokenizerImportError: cannot import name TaggedTokenizer
 
 
 
could anyone help me thanks in advanceenas
		 Yahoo! Music Unlimited - Access over 1 million songs. Try it free.-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Function decorator that caches function results

2005-10-11 Thread Piet van Oostrum
> Paul Rubin  (PR) wrote:

>PR> Tom Anderson <[EMAIL PROTECTED]> writes:

>PR> That's misleading, I'd say a closure is a combination of a function
>PR> (executable code) and a lexical environment 
[snip]
>PR> This is all described in SICP (mitpress.mit.edu/sicp).  

Where the word closure is used for something completely different (it
mentions that others use the word closure as we do here).
:=(
-- 
Piet van Oostrum <[EMAIL PROTECTED]>
URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4]
Private email: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


python server?

2005-10-11 Thread Francesco Marchetti-Stasi
Hello everybody,

I am the happy yet unsatisfied owner of an ipaq 3760. I am writing a
python+pygtk editor optimized for an handheld, and in the future I'd
like to write more applications (to-do-list and agenda are on top of
my priorities, since the existing ones don't fit my needs).

I was now thinking of a way to improve memory usage. Any python
application I launch takes 9-10 MB, and this risks to be a major
blocking factor, since the memory I have is only 64 MB.

So I'd like to share the memory between programs, sort of an
emacs-server mode. I have a vague idea of the way to implement this,
with a python-server.py script which would take over programs from a
launcher.py script, or maybe a single script which would run into the
background, the first time it is launched, and feed the programs to an
already running copy,  when finding an already running instance. Since
I am mainly interested to GUI applications, the resulting threads
should cohexist nicely.

I was wondering if something similar already existed, to use as-is or
to adapt to my needs.
I did a little googling, which pointed me to interesting, but rather
different projects. Has anybody ever seen or heard something of this
kind? Or maybe there is something almost-ready in the amazing python
library (as you understand, I am rather new to python), and I missed
it?

Thanks,
Francesco.
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: WMI - Restore Setting in Python

2005-10-11 Thread Tim Golden
[saw huan chng]

> I am beginner in Python. I have some questions on WMI Service in Python. 
> I was able to use properties of Class Restore in WMI, but not able to 
> use the method. Here is the sample code that I done, anyone can help me?

[... snip code ...]

OK, I don't actually use XP (and the SystemRestore doesn't exist on 2000)
but I *strongly* suggest that if you're going to do anything with WMI you
(** blows own trumpet **) use this module:

http://timgolden.me.uk/python/wmi.html

It does some of the dirty work you'd otherwise have to do.

Effectively, the answer to your question is that Method-calling in
WMI is a bit of a messy process. That's why I wrote the module to
cover up the messiness. Unfortunately, there are some new areas
of WMI-ness in XP which I've never really used, so the module's
a bit weak in these areas.

Using the wmi module, you'll have to do this (effectively untested):


import wmi

connection = wmi.connect_server (".", namespace=r"root\DEFAULT")

sequence_number = 11

#
# Bit of a hack; I need to improve the module here
#
system_restore = wmi._wmi_object (connection.Get ("SystemRestore"))
system_restore.Restore (sequence_number)




If you really want to do it yourself, you need to do something like
this: (*very* untested)


import win32com.client

wmi_service = win32com.client.Dispatch ("WbemSripting.SWbemLocator")
wbem_services = wmi_service.ConnectServer (".", r"root\DEFAULT")
test_obj = wbem_services.Get ("SystemRestore")

sequence_number = 11

restore_method = test_obj.Methods_ ("Restore")
restore_params = restore_method.InParameters
restore_params.Properties_ ("SequenceNumber").Value = sequence_number
test_obj.ExecMethod_ ("Restore", restore_params)


Hope that helps a bit

TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

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


Re: Python's Performance

2005-10-11 Thread Piet van Oostrum
> Terry Hancock <[EMAIL PROTECTED]> (TH) wrote:

>TH> He's got to be talking about runtime name-binding.  In
>TH> other words, when you refer to:

>TH> a.spam

>TH> the Python interpreter actually knows you labeled that attribute 'spam',
>TH> and the string is stored in a.__dict__ , so you can also access it as

>TH> getattr(a, 'spam')

>TH> etc.

>TH> I'm pretty sure this is what string "internment" is for, though, and
>TH> that such lookups are optimized out pretty much whenever possible.

In the case of getattr(a, 'spam') a string comparison for 'spam' has to be
done. AFAIK, in the case of a.spam the string 'spam' has been interned, so
that no string comparison is necessary at lookup, only a pointer
comparison. Due to hash collisions probably multiple comparisons could be
necessary. 
-- 
Piet van Oostrum <[EMAIL PROTECTED]>
URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4]
Private email: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Function decorator that caches function results

2005-10-11 Thread Fredrik Lundh
Tom Anderson wrote:

> Okay, a crack at a definition: a closure is a function in which some of
> the variable names refer to variables outside the function. And i don't
> mean global variables - i mean somebody else's locals; call them 'remote
> variables'.

in Python, the global variables are someone else's locals.

 



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


win32com, generating the cache programaticaly?

2005-10-11 Thread Andrew Markebo

Hello!

I am messing around with communicating between LabVIEW and Python, got
it to work by a small 'fix' (grabbing the generated file, and
importing it by hand)

What I might want to do, is to automatically generate the data done by
executing makepy.py and run by it.

What I select in makepy.py is a library "LabVIEW data 7.1", I would
like to do this from my program. Any hints?

Then, is it possible making this on a minor mode, basically I have
only to dig out the CLSID of "LabVIEW data 7.1" and put it into the
generated file.. sort of?? 

  /Andy

-- 
 "I do not agree with what you say, but I will defend to the death
your right to say it."

-- Francois Marie Arouet Voltaire (1694-1778), French philosopher,
   writer, "Candide"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Learning Python

2005-10-11 Thread Paul DiRezze
These are all great suggestions.

Thanks to all who replied.

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


Re: Merging sorted lists/iterators/generators into one stream of values...

2005-10-11 Thread Lasse Vågsæther Karlsen
Lasse Vågsæther Karlsen wrote:
> 
> 
> Another idea for this method would be that in some cases I noticed that 
> it was useful to know which source each element would come from as well, 
> as well as removing duplicates from the results.
> 


The "removing duplicates" problem would probably be best as a separate 
function and it occurs to me that perhaps Python has such a function 
already.

Again, this function would need the following criteria:

1. Be able to iterate through something other than a list
2. Yield the values, not return a list
3. Take an arbitrary cmp function to determine what is a duplicate

As sugar, perhaps also the following criteria:

- Ability to "combine" the duplicates through a special function

A simple first-version function I hacked together does this:

def unique(source, cmp=cmp, key=None, combine=None):
 it = iter(source)
 first = True
 value = it.next()
 values = [value]
 while True:
 try:
 value = it.next()
 if key is not None:
 cmp_result = cmp(values[0][key], value[key])
 else:
 cmp_result = cmp(values[0], value)
 if cmp_result == 0:
 values.append(value)
 else:
 if combine is not None:
 yield combine(values)
 else:
 yield values[0]
 values = [value]
 except StopIteration:
 if combine is not None:
 yield combine(values)
 else:
 yield values[0]
 break
 raise StopIteration

Note that this function does not do any sorting so if the source that it 
gets the values from is not sorted, the result will be very wrong. This 
is again due to my criteria of being able to handle cursors retrieving 
data from a database and thus avoid loading everything into memory.

The combine function is passed a list of "duplicate" values and must 
return a value that will be yielded out of unique.

Example of usage:

def sum_counts(values):
 value = values[0][0]
 sum = 0
 for row in values:
 sum += row[1]
 return value, sum

fruits = [["Apple", 10], ["Apple", 15], ["Banana", 23], ["Orange", 17], 
["Orange", 17]]
for fruit, total_sum in unique(fruits, key=0, combine=sum_counts):
 print fruit, "has a sum of", total_sum

This will produce:

Apple has a sum of 25
Banana has a sum of 23
Orange has a sum of 34

Function name is perhaps not the best one. It occurs to me that this is 
the GROUP BY function in SQL so perhaps a different name is better, but 
then again this might be moot if such a function already exists somewhere :)

-- 
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:[EMAIL PROTECTED]
PGP KeyID: 0x2A42A1C2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to do *args, **kwargs properly

2005-10-11 Thread George Sakkis
"Lasse Vågsæther Karlsen" <[EMAIL PROTECTED]> wrote:

> So what you're saying is that instead of:
>
> def fn(*values, **options):
>
> I should use:
>
> def fn(values, cmp=cmp):
>
> in this specific case?
>
> and then instead of:
>
> fn(1, 2, 3, cmp=...)
>
> this:
>
> fn([1, 2, 3], cmp=...)
>
> 
>
> I think I'll re-write to use a list instead

Actually in most cases you don't need to assume it's a list; any
iterable is usually good enough. You can always turn it into a list (or
a tuple or a set or..) in the function if you really have to. So when
you do have to and when you don't ? You don't have to if all you do is
iterate over the elements. This is true even if you want to iterate
more than once; just use the itertools.tee() function to create N
independent iterators. To sum up, a better signature for your function
is likely to be "def fn(iterable, cmp=cmp)".

George

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


Re: Python's Performance

2005-10-11 Thread Steven D'Aprano
On Mon, 10 Oct 2005 16:47:35 -0700, Paul Boddie wrote:

>> The difficulty is that the target architecture in not realized in hardware.
> 
> Or isn't perhaps feasible/viable for hardware realisation: one of the
> EuroPython speakers dangled the promise of hardware support for
> high-level languages (the classic "Python on a chip" concept), but
> there are probably plenty of areas where hardware support can assist
> software virtual machines without going to all the trouble of
> implementing such virtual machines in hardware completely.

I remember back in the mid 1980s, Apple and Texas Instruments collaborated
to build a hybrid dual-processor machine. It had a standard Motorola
68000 CPU like the Macintosh, plus a custom TI processor that executed
Lisp code in hardware. I'm told that the reason they never sold was that
the Lisp machine was considerably slower than the software Lisp solution
of the time.

On the other hand, there were Forth enthusiasts who hacked their
Macintoshes with Forth chips, and they went like a rocket.

-- 
Steven.

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


Re: How to do *args, **kwargs properly

2005-10-11 Thread Lasse Vågsæther Karlsen
George Sakkis wrote:
> "Lasse Vågsæther Karlsen" <[EMAIL PROTECTED]> wrote:

>>I think I'll re-write to use a list instead
> 
> 
> Actually in most cases you don't need to assume it's a list; any
> iterable is usually good enough. You can always turn it into a list (or
> a tuple or a set or..) in the function if you really have to. So when
> you do have to and when you don't ? You don't have to if all you do is
> iterate over the elements. This is true even if you want to iterate
> more than once; just use the itertools.tee() function to create N
> independent iterators. To sum up, a better signature for your function
> is likely to be "def fn(iterable, cmp=cmp)".

Yep, that sounds like a plan :)

-- 
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:[EMAIL PROTECTED]
PGP KeyID: 0x2A42A1C2
-- 
http://mail.python.org/mailman/listinfo/python-list


REMINDER: BayPIGgies: October 13, 7:30pm (IronPort)

2005-10-11 Thread Aahz
The next meeting of BayPIGgies will be Thurs, October 13 at 7:30pm at
IronPort.

Tim Thompson will describe and demonstrate the interaction between
Burning Man and Python using two applications, Radio Free Quasar and
Ergo.

BayPIGgies meetings alternate between IronPort (San Bruno, California)
and Google (Mountain View, California).  For more information and
directions, see http://www.baypiggies.net/


Before the meeting, we sometimes meet at 6pm for dinner.  Discussion of
dinner plans is handled on the BayPIGgies mailing list.  

Advance notice:  We've got some options on the plate for November 10 but
haven't settled anything yet.  Please send e-mail to
[EMAIL PROTECTED] if you want to suggest an agenda (or volunteer
to give a presentation).  The meeting agenda for December 8 has been set.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"If you think it's expensive to hire a professional to do the job, wait
until you hire an amateur."  --Red Adair
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Learning Python

2005-10-11 Thread Steven D'Aprano
On Tue, 11 Oct 2005 18:26:58 +0900, Chris Dewin wrote:

> On Mon, 10 Oct 2005 17:20:35 +, dannypatterso wrote:
> 
> [snip]
> 
>>> I'm a hobby programmer using mostly BASIC(s) and some Java.  I know
>>> procedural programming and I know what encapsulation, inheritance and
>>> polymorphism are but I have very little experience in using them as
>>> I've written just a few Java programs (i.e., I guess I could use a
>>> primer in OO programming).
> 
> There was an excellent such primer on devshed, by Icarus, but they appear
> to have taken it down.
> 
> I saved a copy of it to my HD. Would there be anything morally, or legally
> wrong with me uploading it to my site?

What licence was the primer published under? Unfortunately, under
copyright law, it isn't enough for the copyright owner to merely not
prohibit redistribution, but they must explicitly allow it, e.g. under a
Creative Commons licence.

That is because when you redistribute it, you are effectively making a
copy.

I should also point out that copyright infringement not only opens you to
law suits, but in many countries is now a felony crime. For instance, here
in Australia thanks to the  wonderful  "Free" Trade
Agreement with the USA, the BSAA (our local branch of the American
Business Software Alliance) is trumpeting the fact that they can now have
company CEOs jailed for not buying enough software licences -- or, as the
case may be, buying them but not being able to find them when the BSAA
comes a knocking.

Having said all that, if you are aware of the risks, you may make a value
judgement that the copyright owner won't mind if you republish the work,
e.g. because they were giving it away for free to start with. If so, I see
nothing morally wrong with putting it up on your website. (The law may
disagree.)

-- 
Steven.

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


Re: Merging sorted lists/iterators/generators into one stream of values...

2005-10-11 Thread George Sakkis
> Function name is perhaps not the best one. It occurs to me that this
> is the GROUP BY in SQL so perhaps a different name is better, but
> then again this might be moot if such a already exists somewhere :)

Amazing, you keep reinventing things, even with the exact same name :)

from itertools import imap,groupby
from operator import itemgetter

for fruit,group in groupby(fruits, itemgetter(0)):
print fruit, "has a sum of", sum(imap(itemgetter(1),group))

For this to work as intended, fruits has to be already sorted by the
same key given to grouby; otherwise just replace fruits with
sorted(fruits, itemgetter(0)).

By the way, read all the functions in the itertools module
(http://docs.python.org/lib/itertools-functions.html), it will save you
a lot of time.

George

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


Re: Python's Performance

2005-10-11 Thread Charles Krug
On Mon, 10 Oct 2005 11:21:18 -0700, Donn Cave <[EMAIL PROTECTED]>
wrote:
>> Iron-
>> Python).  is it still an interpreter if it generates machine code?
> 
> Is what an interpreter?
> 
> I am not very well acquainted with these technologies, but it sounds
> like variations on the implementation of an interpreter, with no
> really compelling distinction between them.  

An important point made by Tannenbaum is this:

Once you have a machine that executes instructions (what he called
hardware or "Level Zero Machine", then you can create higher level
machines that execute code written in the language of that machine.

For the purposes of writing C, for example, we pretend that we have this
magical machine that "runs C code," or more typically, "the machine that
runs (insert OS name) C code."

When the Level n machine isn't fast enough, we go to the level n-1
machine . . . C or Java for us, or assembly, but the model remains valid
until the point where you bump up against the underlying logic gates.

While we don't talk about the "Virtual Machine" the way Java folks do,
Tannenbaum's model is still useful for thinking about such things.

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


Re: Merging sorted lists/iterators/generators into one stream of values...

2005-10-11 Thread Lasse Vågsæther Karlsen
George Sakkis wrote:
>>Function name is perhaps not the best one. It occurs to me that this
>>is the GROUP BY in SQL so perhaps a different name is better, but
>>then again this might be moot if such a already exists somewhere :)
> 
> 
> Amazing, you keep reinventing things, even with the exact same name :)
> 
> from itertools import imap,groupby
> from operator import itemgetter
> 
> for fruit,group in groupby(fruits, itemgetter(0)):
> print fruit, "has a sum of", sum(imap(itemgetter(1),group))
> 
> For this to work as intended, fruits has to be already sorted by the
> same key given to grouby; otherwise just replace fruits with
> sorted(fruits, itemgetter(0)).
> 
> By the way, read all the functions in the itertools module
> (http://docs.python.org/lib/itertools-functions.html), it will save you
> a lot of time.
> 
> George
> 

Itertools, meh, there's that wheel again :)

Didn't know about this one so thank you :)

-- 
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:[EMAIL PROTECTED]
PGP KeyID: 0x2A42A1C2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: When someone from Britain speaks, Americans hear a "British accent"...

2005-10-11 Thread Charles Krug
On Mon, 10 Oct 2005 15:46:34 -0500, Terry Hancock
<[EMAIL PROTECTED]> wrote:
> On Saturday 08 October 2005 04:35 am, Steve Holden wrote:
>> I must have been working at NASA at the time; they are well known for 
>> embiggening prices.
> 
> Not nearly as much as the DoD, from what I hear.
> 
> Truthfully, I think those stories are bit exaggerated -- I think the
> real problem is somebody making a bad make/buy decision. They decide
> to make something that they could easily have bought at the hardware
> store.
> 

Typically, it was a $30 hammer with $270 worth of paperwork attached.

The famous "$10k Toilet Seat" is actually a bit of an interesting tale.

The part in question is the toilet from a C5A transport . . not
something you can purchase at the local Home Depot.

Being an aircraft toilet, it's crammed into a tiny space and has to be
as light as possible and all the things you associate with aircraft
toilets.

When they were speccing the project, the airframe manufacturer included
some number of spare toilet seats in the bid, given the expected life of
the airframe.  Some faceless bureaucrat decided that they didn't NEED
any spare toilet seats and cancelled that line item.

Lo and Behold, they eventually needed spare toilet seats.  But because
of Another Good Regulation (tm) the tooling had been recycled.

Recreating the tooling to make the spares was, amortized over the number
ordered, around $10k/seat.  Compared to the tooling costs, subsequent
orders of the same seat are pretty much "free" . . . at least until some
bozo in Ring A decides to toss the tooling again.

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


HELP: Searching File Manager written in Python

2005-10-11 Thread anton
Hi,

I am googeling some hours now ... still without result.

So I have a question:

Does somebody know a filemanager:

 - which looks like Norton Commander/7-Zip Filemanager

 - where I can add python scripts which I can execute
   on a selected file


I already looked at wxpyatol but its not what I search, and its no
more developped.

Thanks 


 Stephane

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


Can module access global from __main__?

2005-10-11 Thread Neal Becker
Suppose I have a main program, e.g., A.py.  In A.py we have:

X = 2
import B

Now B is a module B.py.  In B, how can we access the value of X?


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


Re: Looking for info on Python's memory allocation

2005-10-11 Thread Steven D'Aprano
On Tue, 11 Oct 2005 11:22:39 +0200, Lasse Vågsæther Karlsen wrote:

> This begs a different question along the same lines.

Er, no it doesn't. "Begs the question" does _not_ mean "asks the question"
or "suggests the question". It means "assumes the truth of that which
needs to be proven".

http://en.wikipedia.org/wiki/Begging_the_question
http://www.worldwidewords.org/qa/qa-beg1.htm

(Both of these sources are far more forgiving of the modern mis-usage than
I am. Obviously.)


> If I have a generator or other iterable producing a vast number of
> items, and use it like this:
> 
> s = [k for k in iterable]
> 
> if I know beforehand how many items iterable would possibly yield, would
> a construct like this be faster and "use" less memory?
> 
> s = [0] * len(iterable)
> for i in xrange(len(iterable)):
>  s[i] = iterable.next()

Faster? Maybe. Only testing can tell -- but I doubt it. But as for less
memory, look at the two situations.

In the first, you create a list of N objects.

In the second, you end up with the same list of N objects, plus an xrange
object, which may be bigger or smaller than an ordinary list of N
integers, depending on how large N is.

So it won't use *less* memory -- at best, it will use just slightly more.

Is there a way from within Python to find out how much memory a single
object uses, and how much memory Python is using in total?


-- 
Steven.

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


Re: date reformatting

2005-10-11 Thread Magnus Lycka
Bell, Kevin wrote:
> Anyone aware of existing code to turn a date string "8-15-05" into the
> number 20050815?

 >>> import datetime
 >>> s = "8-15-05"
 >>> month,day,year = map(int, s.split('-'))
 >>> date = datetime.date(2000+year,month,day)
 >>> date.strftime('%Y%m%d')
'20050815'

Of course, if you really want the *number* 20050815 you'd
have to do
 >>> int(date.strftime('%Y%m%d'))

Using a datetime.date object means that you have good
support for a lot of arithmetic on and formatting of
dates without writing a lot of new code.

If you really mean that you want the number 20050815, I
assume this is because some legacy system beyond you control
need to have dates in that format. It's not a particularly
good format for dates. If you just want a numeric storage of
dates, I'd suggest using datetime.date.toordinal/fromordinal.
Those numbers aren't as easy to decipher manually, but at
least they work right if you subtract dates or add or subtract
days from a date.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to do *args, **kwargs properly

2005-10-11 Thread Max M
Lasse Vågsæther Karlsen wrote:
> Max M wrote:

> So what you're saying is that instead of:
> 
> def fn(*values, **options):
> 
> I should use:
> 
> def fn(values, cmp=cmp):
> 
> in this specific case?
> 
> and then instead of:
> 
> fn(1, 2, 3, cmp=...)
> 
> this:
> 
> fn([1, 2, 3], cmp=...)

Precisely. Sometimes you need different interfaces for a method. In that 
case it is fine.

But if you are just doing it instead of passing sequences, you are just 
(ab)using the * and ** operators.

The method definition, like any python code, is made for humans not 
machines. The more obvious you can make the function definition, the 
happier anyone will be.

-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: strange import error with Python-2.4.1

2005-10-11 Thread Robin Becker
Fredrik Lundh wrote:
> Steve Holden wrote:
> 
> 
>>Can I ask if you are specifying a source encoding in your file with a
>>pragma (?) like
>>
>># -*- coding: iso-8859-15 -*-
>>
>>I've noticed what appear to be spurious syntax errors from time to time
>>on such files, and have been attempting to debug the problem for some
>>time without any apparent success.
> 
> 
> http://www.python.org/sf/1175396
> 
>  

thanks that looks like it, the __init__.py had


# -*- coding: cp1252 -*-

at the start.
-- 
Robin Becker

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


how to(can we ?) pass argument to .py script ?

2005-10-11 Thread quiteblack
howdy~

i wrote a .py file and it works fine, my goal is to pass argument to
that py file when it get executed, and accept that argument within py
file, eg. i prefer a command like below:

python test.py -t

and then, i may get "-t" within test.py for later use.

i have no ideas how to do and i'm really stuck, can anyone help ?

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


ANN: Kamaelia 0.3.0 released!

2005-10-11 Thread Michael Sparks
Kamaelia 0.3.0 has been released!

Introduction


Kamaelia is a networking/communications infrastructure for innovative
multimedia systems. Kamaelia uses a component architecture designed to
simplify creation and testing of new protocols and large scale media
delivery systems. A subset of the system has been tested on series 60
phones.

General feedback is welcome either directly, mailing lists or via IRC
(#kamaelia, freenode). People are also more than welcome to use the
system and suggest improvements not directly related to our specific
goals, because we recognise the system can be used in more areas, not
just networked multimedia. A diversity of systems built improves the
system (for all users of course!) as a whole.


What's New & Changed?
=

*NOTE* Kamaelia 0.3.0 requires Axon-1.1.2 to run for some newer
components
  (which has also just been released).

Full release notes and change log:
* http://kamaelia.sourceforge.net/Kamaelia-0.3.0-ReleaseNotes.html

New Examples - 7 new examples including:
* Simple reliable multicast based streamer using Ogg Vorbis.
* Dirac Player
* Dirac encode & playback.
* Simple bouncing images game. Designed for very small children who
  are amused by things take beep and react when you press left/right
  mouse buttons.
* Simple example showing how to use the ticker (First developed for
  showing subtitles).
* Demonstration system showing how to use the new software chassis
  facility in the context of multiple chassis. 

New Tools, Notable Additions

* Visual tool for building Kamaelia pipelines
* Tk Support
* Video encode, decode and playback. (dirac)

New Packages & Subsystems

These names should provide you with a flavour of the new subsystems that
have been added:

* Kamaelia.Codec
* Kamaelia.Chassis
* Kamaelia.File
* Kamaelia.UI.Tk
* Kamaelia.Internet.Simulate

Other Highlights

* Software chassis (software backplane will be coming in
Kamaelia-NEXT)
* Tk integration. (The pipeline builder is a nice example of a tool
this
  enables)
* Dirac encoded video decoders and encoders
* Support for video playback. (dirac & YUV)
* Variety of pygame based components, including
* Tools for greater control over the pygame surface managed
environment
* Tools for building simple games. (controlling sprite behaviour for
  example)
* Much richer tools for file reading and writing
* Includes re-usable file readers.
* More utilities for message filters and splitting of messages
* Basic tools for simuluating error conditions and failure rates
  for delivery of messages (Sufficient for simulating an unstable
  underlying internet infrastructure).


What is Kamaelia?
=

The project aims to make it easy to build networked multimedia
systems (eg audio, video, interactive systems). The result is systems
which are naturally componentised. Also, the resulting systems are
/naturally concurrent/ allowing quick and fast reuse in the same way
as Unix pipelines do. 

It is designed as a practical toolkit, such that you can build systems
such as:
   * Ogg Vorbis streaming server/client systems (via vorbissimple)
   * Create Video players & streaming systems (for dirac).
   * With subtitles.
   * Simple network aware games (via pygame)
   * Quickly build TCP & Multicast based network servers and clients
   * Presentation tools
   * A networked audio mixer matrix (think multiple audio sources over
 network connections mixed and sent on to multiple locations with
 different mixes)
   * Look at graph topologies & customise the rules of display &
 particle types.
 Mix and match all of the above.

You can also do a lot of this *visually* using the new PipeBuilder
application in Tools.

Essentially if the system you want to build involves audio or moving
pictures, and you want to be able to make the system network aware,
then this should be quick and easy to do using Kamaelia. (If it isn't,
then a) it's a bug b) needs improving :-)

It runs on Linux, Window, Mac OS X with a subset running on Series 60
phones.

The basic underlying metaphor of a component us like an office worker
with inboxes and outboxes, with deliveries occuring between desks,
offices, and depts. The component can thus do work anyway it likes but
only communicates with these inboxes and outboxes. Like office workers,
components run in parallel, and to achieve this are generally
implemented using python generators, but can also used threads.

The rationale behind the project is to provide a toolkit enabling the
development of new protocols, including streaming, for large scale
media delivery. The license essentially allows use in proprietary
systems without change, but all changes to the system itself must be
shared.

Oh, and due to things like the visual editor, the use of pygame in
a lot of examples, the use of dirac & vorbis, it's qu

Re: Can module access global from __main__?

2005-10-11 Thread Steve Holden
Neal Becker wrote:
> Suppose I have a main program, e.g., A.py.  In A.py we have:
> 
> X = 2
> import B
> 
> Now B is a module B.py.  In B, how can we access the value of X?
> 
> 
Without trying in any way to dodge the question, why do you want to do that?

There's a property of software called "coupling" that's used to describe 
the way that communications take place between different components of a 
piece of software. Ideally modules should be loosely-coupled, which is 
usually achieved by passing values in as function or method arguments 
and receiving the results as the return values of said functions or methods.

When a module is loosely-coupled in this way it's possible to revise the 
structure of one component completely (while maintaining the same 
interface specification) without affecting any other component.

By introducing some magic "load a variable from the namespace of the 
importing module" you make your modules tightly-coupled, which is very 
bad for maintainability: what happens if you now import B.py into a 
module that doesn't create an X in its namespace?

The fact that you ask the question implies that you really need to think 
a little harder about the structure of your program. If you tell us the 
*real* problem (back to my "why do you want to do that" question ...) 
perhaps we can suggest a better-structured solution.

regards
  Steve

PS: If A is the main program (the module that you have run) then you 
should be able to access it as __main__.X, but you'd be *very naughty* 
to do so :-)
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: how to(can we ?) pass argument to .py script ?

2005-10-11 Thread Simon Brunning
On 11 Oct 2005 07:07:44 -0700, [EMAIL PROTECTED]
<[EMAIL PROTECTED]> wrote:
> i wrote a .py file and it works fine, my goal is to pass argument to
> that py file when it get executed, and accept that argument within py
> file, eg. i prefer a command like below:
>
> python test.py -t
>
> and then, i may get "-t" within test.py for later use.
>
> i have no ideas how to do and i'm really stuck, can anyone help ?

Short answer:

import sys
print sys.argv

You might also want to take to butchers at the optparse module.

--
Cheers,
Simon B,
[EMAIL PROTECTED],
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


how to execute .exe file ?

2005-10-11 Thread quiteblack
hi all~

i used to drive .exe file working by writing a simple batch file, i
thin python may do this as well bu i dunno how to, any help ?

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


Re: Jargons of Info Tech industry

2005-10-11 Thread axel
In comp.lang.perl.misc Roedy Green <[EMAIL PROTECTED]> wrote:
>>HTML is a problem on *other* peoples crappy software as well. It
>>wasn't designed to carry code content, but has been hacked up to do
>>that.
 
> It seems to me it goes without saying that you cannot trust code from
> strangers, especially anonymous strangers.  You simply don't run code
> sent in email except from highly trusted individuals.  If you do, that
> is YOUR fault for being such a silly ass not the mail system's ability
> to deliver code.  It is as stupid as running code that came as an
> attachment.
 
> One of the ideas I play with in my essay  is that you could insist
> your correspondents have digital id certificate signed by Thawte or
> other CA attesting to their identity, thus giving you legal recourse
> against them if they send you spam, Trojans etc.
 
> This would slow them down with requests for permission to send. they
> could send only one per certificate.  The  cost and hassle of getting
> the certificate could deter tem, and uniquely identify them for
> blocking and public black lists.

Plus being a total pain for legitimate correspondents and also expensive.

I don't know how much spam other people receive but on one account I
hardly receive any as I reserve it for friends and business. On another
I had about 40 spam messages which took all of ten seconds to delete.
Hardly a serious matter.

Axel

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


Re: When someone from Britain speaks, Americans hear a "British accent"...

2005-10-11 Thread Grant Edwards
On 2005-10-10, Terry Hancock <[EMAIL PROTECTED]> wrote:

>> I must have been working at NASA at the time; they are well known for 
>> embiggening prices.
>
> Not nearly as much as the DoD, from what I hear.
>
> Truthfully, I think those stories are bit exaggerated -- I think the
> real problem is somebody making a bad make/buy decision. They decide
> to make something that they could easily have bought at the hardware
> store.

That and the combination of low volumes and the cost of
testing. They want something seemingly simple (say a hammer),
but they want it tested and certified to a particular set of
functional and environmental specs.  That takes literally
man-years of effort, and then they only end up buying 3 of
them.  The cost of the testing gets divided by three and added
onto the unit cost.

-- 
Grant Edwards   grante Yow!  Jesus is my
  at   POSTMASTER GENERAL...
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: When someone from Britain speaks, Americans hear a "British accent"...

2005-10-11 Thread Grant Edwards
On 2005-10-10, Terry Hancock <[EMAIL PROTECTED]> wrote:

>> Cool.  While we're on the topic, has anybody else noticed that
>> "guys" is acceptible and commonly used to refer to a group of
>> women, 
>
> Yeah, though it depends on where you are.

I assumed you could tell that from my accent. :)

>> Likewise, "dude" is often used when addressing a female but
>> almost never when speaking about one in the third person.

>
> This I have never witnessed.  That's bizarre.

At least in the upper midwest it seems quite common for
teen-age boys/girls to address each other as "dude".  For
example

"Dude, you have got to go to the concert with us".

But, if somebody refers to "that dude over there in the blue
jaket," the "dude" is invariably a male.

-- 
Grant Edwards   grante Yow!  I am NOT a nut
  at   
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to(can we ?) pass argument to .py script ?

2005-10-11 Thread Giovanni Dall'Olio

[EMAIL PROTECTED] wrote:


> howdy~
>
> i wrote a .py file and it works fine, my goal is to pass argument to
> that py file when it get executed, and accept that argument within py
> file, eg. i prefer a command like below:
>
> python test.py -t
>
> and then, i may get "-t" within test.py for later use.


sys.argv and getopt module:
http://diveintopython.org/scripts_and_streams/command_line_arguments.html

bye!

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


Re: Can module access global from __main__?

2005-10-11 Thread Neal Becker
Everything you said is absolutely correct.  I was being lazy.  I had a main
program in module, and wanted to reorganize it, putting most of it into a
new module.  Being python, it actually only took a small effort to fix this
properly, so that in B.py, what were global variables are now passed as
arguments to class constructors and functions.

Still curious about the answer.  If I know that I am imported from __main__,
then I can do access X as sys.modules[__main__].X.  In general, I don't
know how to determine who is importing me.

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


Re: Send password over TCP connection

2005-10-11 Thread Laszlo Zsolt Nagy

>If you're saying that people have no choice but to trust that their 
>passwords, stored in the clear on the server of some idiot who didn't 
>know better, are safe from casual administrator observation and safe 
>from hackers stealing the password file, then you shouldn't be allowed 
>anywhere near a supposedly secure system...
>  
>
Of course I would not say this. :-)

>If you're just saying that one has to trust that the server you are 
>talking to at this instant in time is really the one you thought it was, 
>then that's an entirely different issue and I agree.
>  
>
Not just this.
"one has to trust that the server you are talking to at this instant in 
time is really the one you thought it was" - this is just authentication.
I'm saying that even if the authentication is secure and the server is 
really the one that you wanted to talk with, the server can still be 
vulnerable to other kinds of attacks. Since users are storing data on 
the server, they need to trust in its security. Storing the clear 
passwords is not a good idea, I agree. But having a secure 
authentication method and not storing clear passwords doesn't 
automatically mean that the server is secured. :-)

I'm sorry, I was not clear. I think we were talking about the same thing.

   Les


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


Re: Python reliability

2005-10-11 Thread John Waycott
Ville Voipio wrote:
> In article <[EMAIL PROTECTED]>, Thomas Bartkus wrote:
> 
>>All in all, it would seem that the reliability of the Python run time is the
>>least of your worries.  

I agree - design of the application, keeping it simple and testing it 
thoroughly is more important for reliability than implementation 
language. Indeed, I'd argue that in many cases you'd have better 
reliability using Python over C because of easier maintainability and 
higher-level data constructs.

> 
> Well, let's put it this way. I have seen many computers running
> Linux with a high load of this and that (web services, etc.) with
> uptimes of years. I have not seen any recent Linux crash without
> faulty hardware or drivers.
> 
> If using Python does not add significantly to the level of 
> irreliability, then I can use it. If it adds, then I cannot
> use it.
> 

I wrote a simple Python program that acts as a buffer between a 
transaction network and a database server, writing the transaction logs 
to a file that the database reads the next day for billing. The simple 
design decoupled the database from network so it wasn't stresed during 
high-volume times. The two systems (one for redundancy) that run the 
Python program have been running for six years.

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


Re: how to(can we ?) pass argument to .py script ?

2005-10-11 Thread quiteblack
hey i got it ! tks guys !

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


Re: Best way to share a python list of objects

2005-10-11 Thread Magnus Lycka
kyle.tk wrote:
> So I have a central list of python objects that I want to be able to
> share between different process that are possibly on different
> computers on the network. Some of the processes will add objects to
> list and another process will be a GUI that will view objects in the
> list. I want this all to happen in real-time (e.g once a processes adds
> an object to the list the GUI will see it.)
> 
> What would be the best way to accomplish this. Some of my ideas:
> - An XML file r/w-able by all processes
> - Send pickled objects between all processes and each keeps it own list
> locally
> - A ascii type protocol akin to ftp the hands out all the info to the
> processes
> 
> Any other ideas? What would work the best

Relational database are useful for sharing data in a controlled way.
A better option for arbirary Python objects might be ZODB with ZEO.

http://www.zope.org/Wikis/ZODB/FrontPage
http://www.zope.org/Wikis/ZODB/FrontPage/guide/index.html
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >