Re: pyinstaller fails to create exe-File

2007-02-23 Thread Thomas Heller
[EMAIL PROTECTED] schrieb:
> Hi !
> 
> I am trying to create an exe file using pyinstaller. Running the
> created exe-File gives the error message
> ""
> Traceback (most recent call last):
>   File "", line 8, in 
>   File "E:\Documents\mich\job\abs\backup_skript\buildbackup\out1.pyz/
> email", lin
> e 79, in __getattr__
>   File "D:\Programme\pyinstaller\iu.py", line 334, in importHook
> raise ImportError, "No module named %s" % fqname
> ImportError: No module named email.mime.multipart
> ""
> 
> My python-Skript uses the following imports:
> import ConfigParser
> import glob
> import os
> import smtplib
> import time
> import win32api
> import zipfile
> from email.MIMEMultipart import MIMEMultipart
> from email.MIMEBase import MIMEBase
> from email.MIMEText import MIMEText
> from email.Utils import COMMASPACE, formatdate
> from email import Encoders
> 
> Can someone help? Running
>python script.py
> works without any problems.

There have been large changes to the email module in Python 2.5,
see the NEWS.txt file.  email's __init__.py module does some import
hacks to ensure compatibility with previous versions, unfortunately
the packagers cannot handle them automatically.  It /may/ be possible
to write a package hook for pyinstaller, I do not know.

For py2exe at least, the best solution currently is to include the whole
email package; this can be done with '-p email' on the command line, or
by passing the corresponding option to the setup function.

> I have also tried to use py2exe, but
>   python setup.py py2exe
> gives the following error message:
> 
> copying d:\programme\python25\lib\site-packages\py2exe\run.exe -> E:
> \Documents\m
> ich\job\abs\backup_skript\dist\backup.exe
> Traceback (most recent call last):
>   File "setup.py", line 4, in 
> setup(console=["backup.py"])
>   File "d:\programme\python25\lib\distutils\core.py", line 151, in
> setup
> dist.run_commands()
>   File "d:\programme\python25\lib\distutils\dist.py", line 974, in
> run_commands
> self.run_command(cmd)
>   File "d:\programme\python25\lib\distutils\dist.py", line 994, in
> run_command
> cmd_obj.run()
>   File "D:\programme\Python25\Lib\site-packages\py2exe\build_exe.py",
> line 223,
> in run
> self._run()
>   File "D:\programme\Python25\Lib\site-packages\py2exe\build_exe.py",
> line 290,
> in _run
> self.create_binaries(py_files, extensions, dlls)
>   File "D:\programme\Python25\Lib\site-packages\py2exe\build_exe.py",
> line 548,
> in create_binaries
> arcname, target.script)
>   File "D:\programme\Python25\Lib\site-packages\py2exe\build_exe.py",
> line 788,
> in build_executable
> add_resource(unicode(exe_path), script_bytes, u"PYTHONSCRIPT", 1,
> True)
> RuntimeError: EndUpdateResource: Das System kann das angegebene Gerõt
> oder die a
> ngegebene Datei nicht ÷ffnen. (=System cannot find the specified
> device or the file)

That's a different problem; it has nothing to do with the email package.
You should try to clean the dist and build directories that py2exe creates,
sometimes this helps.  If it still does not work, you should try to find
out what the error means.  Is the file readonly?  locked because still in use?

Thomas

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


Re: How can I track/monitor an application and system resources.

2007-02-23 Thread [EMAIL PROTECTED]
Hello,

Many thanks for your advice so far!

The phone reference is actually because the target device is WM 5.0.
I've found a python port Pyce that will run on this platform.  We have
a target application that runs on this platform which we would like to
develop some automated tests for.  The application is written in VC++
and we're using python to stress test it!

Many thanks again!

R.

On 22 Feb, 20:07, Tim Golden <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > Hello All,
>
> > I'm a newbie to Python!
>
> > I am trying to develop a program that monitors the performance of an
> > application.  The kind of information I am interested in is the CPU/
> > Process/Thread and memory performance. Specifically, I would like to
> > track the following
>
> > CPU usage
> > Used Memory on Phone
> > Free Memory on Phone
> > Number of Processes running
> > Number of threads running
> > Number of Filehandles currently open
> > Memory used by a process/thread
> > Process/Thread CPU activity.
>
> > All this under Windows
>
> Not sure about the "... on Phone" bit. Assuming you're
> on a supported platform, sounds like you want to look
> at the WMI stuff, in particular Win32_PerfFormattedData[1].
> There are examples around the web, usually in VBS style.
> They're easy enough to translate into Python, either
> using the win32com module[2] directly, or using my WMI
> helper module[3].
>
> [1]http://msdn2.microsoft.com/en-us/library/aa394253.aspx
> [2]http://pywin32.sf.net
> [3]http://timgolden.me.uk/python/wmi.html
>
> TJG- Hide quoted text -
>
> - Show quoted text -


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


Re: parse HTML by class rather than tag

2007-02-23 Thread gatti
On Feb 23, 8:54 am, [EMAIL PROTECTED] wrote:
> Hello,
>
> i'm would be interested in parsing a HTML files by its corresponding
> opening and closing tags but by taking into account the class
> attributes and its values,
[...]
> so i wondering if i should go with regular expression, but i do not
> think so as i must jumpt after inner closing div, or with a simple
> parser, i've searched and 
> foundhttp://www.diveintopython.org/html_processing/basehtmlprocessor.html
> but i would like the parser not to change anything at all (no
> lowercase).

Horribly brittle idea. Use a robust HTML parser (e.g.
http://www.crummy.com/software/BeautifulSoup/) to build a document
tree, then visit it top down and look at the value of the 'class'
attributes.

Regards,
Lorenzo Gatti

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


Re: pexpect regex help

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



what about using s.before.split("\r\n")[-1]?

A

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


Re: pexpect regex help

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



result=[x for x in s.before.split("\r\n") if x != ""]
print result[-1]

should cover the blank line problem

A

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


Re: list/get methods/attributes of a class?

2007-02-23 Thread bkamrani
On Feb 22, 5:37 pm, "Jason" <[EMAIL PROTECTED]> wrote:
> On Feb 22, 8:27 am, [EMAIL PROTECTED] wrote:
>
> > Hello,
> > Sorry guys for this newbie questions. But I wonder if there is a
> > standard or build-in method to know the methods of a class?
>
> > I'm not originally a progrommer and I have worked with python/qt in a
> > basic level. Now I work a package which has many predefined classes
> > which I'm going to resue by importing them. I would like to know more
> > about each imported class, what methods exists and so on. Printing the
> > object or type(object) doesn't say so much.
>
> > Any hint or helps is really appreciated!
> > /Ben
>
> Also, try out the built-in help function on the original class.  It'll
> list the class layout, methods, and any associated document strings.
> (It won't list member variables, though.)  To see all elements in an
> instance or class, use the dir() function.
>
> >>> class Dummy(object):
>
> ... "A sample class that can have any given data."
> ... def __init__(self, *args):
> ... self._args = args
> ... def GetArgCount(self):
> ... """Show how many arguments were passed at
> instantiation."""
> ... return len(self._args)
> ...>>> d = Dummy(1, 2, 'three')
> >>> help(d)  # help(Dummy) also works
>
> Help on Dummy in module __main__ object:
>
> class Dummy(__builtin__.object)
>  |  A sample class that can have any given data.
>  |
>  |  Methods defined here:
>  |
>  |  GetArgCount(self)
>  |  Show how many arguments were passed at instantiation.
>  |
>  |  __init__(self, *args)
>  |
>  |
> --
>  |  Data and other attributes defined here:
>  |
>  |  __dict__ = 
>  |  dictionary for instance variables (if defined)
>  |
>  |  __weakref__ = 
>  |  list of weak references to the object (if defined)
>
>
>
>   --Jason

Thanks and regards!

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


Re: Pep 3105: the end of print?

2007-02-23 Thread Jay Tee
On Feb 23, 8:48 am, I V <[EMAIL PROTECTED]> wrote:

> While that's true, C++ compiler vendors, for example, take backwards
> compatibility significantly less seriously, it seems to me. A year or so
> ago, I tried compiling something I'd written for g++ 2, using a
> then-recent-ish g++ 3; it failed spectacularly. Likewise with Visual C++ 6
> and a Visual C++ 2005. The suggestion that "working programmers"
> will reject python if a major version change introduces some backwards
> incompatibilities is not borne out by the experience of any other
> language I am aware of.

The experience with C++ in our project is similar to yours.  I think
the real reason is that the compiler tries to be more true to the
standard than to past implementations; past implementations accepted
incorrect syntax, newer "improved" compilers broke backwards
compatibility by rejecting the incorrect syntax.

Can't blame 'em, C++ syntax is hard ... don't try this at home,
kids ...

On the other hand, C++ is firmly established as a "serious" language
in our community while python is not.  So the programmers tend to be
more forgiving.  There is no perception that compiler developers are
*trying* to be difficult by changing the language to break backwards
compatibility.  That's the difference I think.

JT

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


Re: How can I track/monitor an application and system resources.

2007-02-23 Thread Tim Golden
[EMAIL PROTECTED] wrote:
> The phone reference is actually because the target device is WM 5.0.
> I've found a python port Pyce that will run on this platform.  We have
> a target application that runs on this platform which we would like to
> develop some automated tests for.  The application is written in VC++
> and we're using python to stress test it!

You'll have to investigate a bit to see what APIs are
available for the platform. I'm afraid I've no experience
with portable devices, but some of my colleagues who've
done embedded database work on GPRS scanners tell me that
the API is quite cut-back.

Apart from WMI -- which could well not be there -- there
are also the Performance APIs which are exposed by pywin32
in the win32pdh module. Again, though, you'd have to check
if they're supported.

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


Re: Europe Tests Established Chemicals on Millions of Animals

2007-02-23 Thread Laurent Pointal
You help nothing by posting subjects unrelated to the *programming
language* Python into a usenet group about this language.

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


The truth about the SigEx Foundry and the SigEx Ventures

2007-02-23 Thread [EMAIL PROTECTED]
First of all, I'd like to appologise for the noise and for
cross-posting. This is my first and last e-mail on this list.
  As you may have noticed from the subject of the e-mail, I'm about
to speak about the SigEx Ventures company, an organisation that
appoints itself as the liaison between strategic investors and young
tallented people in IT&C. It originates in the US but currently
operates in Europe. Specifically in Pau, France.
  On their website (www.sigex.com, now www.thefoundryschool.tv) they
speak fluent Corporatese. I must admit, I'm not a native English
speaker, but even so my ear is trained well enough for me to be able
to tell spam from ham. They present some glossy products, that nobody
ever actually saw working. They're all vaporware.
  On the same website they speak about fantastic opportunities
offered to young talented fellows in the IT&C field, in the shape of
internship at their fantastic research centre in Pau. Unfortunately,
it's all in the demo because the real deal is nothing like it. There's
no such thing as opportunity to work with cutting-edge technologies or
leading researchers in the branch. It's all smoke and mirrors.
  As a former intern there, I feel that the truth should be made
available, as neither of their statements really hold true. My best
bet is that they attract investors and suck up their cash without ever
producing anything.

  I'm gathering all sorts of information, starting with my own
experience, on http://sigexfoundry.blogspot.com. Feel free to read
more there.

  Why am I doing this? There is a term for my action, called
whistleblowing. I'd like to underline the fact that I'm by no means
affected by SigEx's past or current actions, I went there as an intern
for merely satisfying my own curiosity about them. But I know that
many of the subscribers of this list are scholars, professors, people
with strong positions in the branch, most of which can easily pass as
models for younger enthusiasts. They're the ones I'd like this mail to
reach. It'd be a real pity if more people suffered from SigEx's
dubious practices.

   Once again, here is the link to the blog: http://sigexfoundry.blogspot.com
   And, once again, sorry for the noise.

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


Re: pexpect regex help

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

Re: Convert to binary and convert back to strings

2007-02-23 Thread Mikael Olofsson


Neil Cerutti wrote:
> Woah! You better quadruple it instead.
> How about Double Pig Latin?
> No, wait! Use the feared UDPLUD code.
> You go Ubbi Dubbi to Pig Latin, and then Ubbi Dubbi again.
> Let's see here... Ubububythubububonubpubay
> That's what I call ubububeautubububifubububulbubay.

That looks slightly like the toy language that Swedish kids refer to as 
the robbers language: You double each consonant, and place an o between 
each such double consonant. So, applying that to Python, you would get 
popytothohonon. Actually, one of the largest Swedish telecom companies 
has used this toy language in one of their commercials.

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


Re: connection pool in python?

2007-02-23 Thread elGringo
On 23 fév, 08:44, "Eric CHAO" <[EMAIL PROTECTED]> wrote:
> Connection Pool is necessary in web applications with Java and JDBC.
> So does python have something like that?
>
> Thanks.

Look at http://www.sqlalchemy.org/

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


CSV(???)

2007-02-23 Thread David C.Ullrich
Is there a csvlib out there somewhere?

And/or does anyone see any problems with
the code below?

What csvline does is straightforward: fields
is a list of strings. csvline(fields) returns
the strings concatenated into one string
separated by commas. Except that if a field
contains a comma or a double quote then the
double quote is escaped to a pair of double
quotes and the field is enclosed in double
quotes.

The part that seems somewhat hideous is
parsecsvline. The intention is that
parsecsvline(csvline(fields)) should be
the same as fields. Haven't attempted
to deal with parsecsvline(data) where
data is in an invalid format - in the
intended application data will always
be something that was returned by
csvline. It seems right after some
testing... also seems blechitudinous.

(Um: Believe it or not I'm _still_ using
python 1.5.7. So comments about iterators,
list comprehensions, string methods, etc
are irrelevent. Comments about errors in
the algorithm would be great. Thanks.)

The code:

from string import replace, join

def csvescape(s):
  if ',' in s or '"' in s or '\n' in s:
res = replace(s, '"', '""')
return '"%s"' % res
  else:
return s

def csvline(fields):
  return join(map(csvescape, fields), ',')

class indexedstring:
  def __init__(self, s):
self.s = s
self.index = 0

  def current(self):
return self[self.index]

  def inc(self):
self.index = self.index + 1

  def next(self):
self.inc()
return self.current()

  def __getitem__(self, j):
return self.s[j]

  def __len__(self):
return len(self.s)

  def eos(self):
return self.index >= len(self)

  def lookahead(self):
return self[self.index + 1]

  def getfield(self):
if self.eos():
  return None
if self.current() == '"':
  return self.quotedfield()
else:
  return self.rawfield()

  def rawfield(self):
"""Read until comma or eos."""
start = self.index
while not (self.eos() or (self.current() == ',')):
  self.inc()

res = self.s[start:self.index]

self.inc()

return res

  def quotedfield(self):
"""Read until '",' or '" followed by eos.
Replace "" in result with "."""

start = self.index

while 1:
  self.inc()
  if self.current() == '"':
self.inc()
if (self.eos() or (self.current()==',')):
  break

res = self.s[start + 1:self.index - 1]

self.inc()

return replace(res, '""', '"') 

def parsecsvline(csvline):
  """Inverts csvline(). Assumes csvline is valid, ie
  is something as returned by csvline(); output undefined
  if csvline is in invalid format"""

  s = indexedstring(csvline)
  res = []

  while not s.eos():
   res.append(s.getfield())

  return res



David C. Ullrich
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: TimedRotatingFileHandler() isn't rotating at midnight?

2007-02-23 Thread Vinay Sajip
On 9 Feb, 14:14, [EMAIL PROTECTED] wrote:
> Right.  Check out the logrotate facility on your system.

This can be used together with the WatchedFileHandler recently checked
into SVN trunk - this (Unix/Linux-only) handler checks to see if the
dev or inode have changed, and if they have (because of rotation by
e.g. logrotate), reopens the file before writing to it.

Regards,

Vinay Sajip

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


What is bad with "Relative imports"

2007-02-23 Thread Alexander Eisenhuth
Hi,

PyLint says that "Relative imports" ... are worth to be warned .

And I ask myself why?

- Example directory structure -
Sound/  Top-level package
   __init__.py  Initialize the sound package
   Utils/   Subpackage
 __init__.py
 iobuffer.py
errors.py
 misc.py
...
   Formats/ 

Let's say in misc.py exist the class Player(). What could be bad to expose it 
in 
  Utils.__init__() like:

-- __init__.py -
import misc # provoke PyLint warning
Player = misc.Player
...


with
Sound.Utils.Player() ??

Thaks for your experience and comments

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


Re: Reading mails from Outlook

2007-02-23 Thread beeswax
On 22 feb, 15:45, Larry Bates <[EMAIL PROTECTED]> wrote:
> beeswax wrote:
> > Hi,
>
> > Does anyone knows how to read e-mails from a specific folders in
> > outlook?
> > I only found out how to read the mails from the inbox folder and how
> > to list all available folder.
> > I just don't found a way to access my mails from the other folders.
>
> > Can anyone help me?
>
> > Regards,
 >
> > Sam
>
> I'll bet that some of the best information you can get about interacting
> with Outlook is going to be by looking at the sourcecode to SpamBayes
> plug-in.  You can get it from here:
>
> https://sourceforge.net/project/showfiles.php?group_id=61702&package_...
>
> -Larry

Hi again,

I found the solution myself, the next code will iterate all folders,
sub folders and their mails.
I just needed to understand what I could do with the folders objects.
But, this code will trow an error when trying to connect to shared
folders (exchange folders etc).

Btw does anyone knows a good API for this, or a way to get all the
properties from an object?


# Create instance of Outlook
o = win32com.client.gencache.EnsureDispatch("Outlook.Application")
# Dump all folders recursive, starting from root
DumpFoldersRecursive(o.GetNamespace("MAPI").Folders,0)
o = None

def DumpFoldersRecursive(folders,indent):
# Note: the com indexes start from 1
for i in range(1,folders.Count+1):
folder = folders[i]
print '%sFolder %d: "%s"' %
('\t'*indent,i,DecodeUnicodeString(folder.Name))

# if a folder has no subfolders, its Folders.Count will be
zero, so this is safe.
for i in range(len(folder.Items)):
   message = folder.Items[i+1]
   print message.Subject

DumpFoldersRecursive(folder.Folders,indent+1)



Regards,

Sam

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


Module trouble [newbie]

2007-02-23 Thread Boris Ozegovic
Can somebody explaint this to me:

I have module a.py
A = 100
import b
print "A printing"
print "B is %s" % b.B

and module b.py
B = 2000
import a
print "B printing"
print "A is %s" % a.A

I thought that output would be:
B printing
A is 100
A printing
B is 2000

Because import b would execute b.py, and in b.py line "import a" would be
ignored, but my output is:

>>> import a
100
A printing
B is 100

??

:)

-- 
http://www.nacional.hr/articles/view/23894/23
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: CSV(???)

2007-02-23 Thread Philipp Pagel
David C. Ullrich <[EMAIL PROTECTED]> wrote:
> Is there a csvlib out there somewhere?

How about csv in the standard library?

> (Um: Believe it or not I'm _still_ using
> python 1.5.7.

I have no idea if csv was part of the standard library backin those
days...

But even if not: either upgrade to something less outdated or see if you
can get todays csv to work with the oldtimer.

cu
Philipp

-- 
Dr. Philipp Pagel  Tel. +49-8161-71 2131
Dept. of Genome Oriented BioinformaticsFax. +49-8161-71 2186
Technical University of Munich
http://mips.gsf.de/staff/pagel
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: CSV(???)

2007-02-23 Thread Tim Golden
Philipp Pagel wrote:
> David C. Ullrich <[EMAIL PROTECTED]> wrote:
>> Is there a csvlib out there somewhere?
> 
> How about csv in the standard library?
> 
>> (Um: Believe it or not I'm _still_ using
>> python 1.5.7.
> 
> I have no idea if csv was part of the standard library backin those
> days...
> 
> But even if not: either upgrade to something less outdated or see if you
> can get todays csv to work with the oldtimer.

You might have a look at the Object Craft CSV module, from
which the stdlib one is loosely descended, but you'd have to
compile it yourself if you're on 1.5.2.

http://www.object-craft.com.au/projects/csv/

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


Re: Module trouble [newbie]

2007-02-23 Thread Diez B. Roggisch
Boris Ozegovic wrote:

> Can somebody explaint this to me:
> 
> I have module a.py
> A = 100
> import b
> print "A printing"
> print "B is %s" % b.B
> 
> and module b.py
> B = 2000
> import a
> print "B printing"
> print "A is %s" % a.A
> 
> I thought that output would be:
> B printing
> A is 100
> A printing
> B is 2000
> 
> Because import b would execute b.py, and in b.py line "import a" would be
> ignored, but my output is:
> 
 import a
> 100
> A printing
> B is 100

Are you sure the above is what you really used for your test? Because your
output features a single 100, which the above lacks a print-statement for.


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


Re: Module trouble [newbie]

2007-02-23 Thread Boris Ozegovic
Diez B. Roggisch wrote:

> Are you sure the above is what you really used for your test? Because your
> output features a single 100, which the above lacks a print-statement for.

Yeah, I cancelled the message, but synchronization allready happened.  :)

Problem was in some other place.

One more question: is calling import inside function definition poor
design?  e.g.

def foo():
   doSomething:
   import someModule
   someModule.doSomethin

-- 
http://www.nacional.hr/articles/view/23894/23
-- 
http://mail.python.org/mailman/listinfo/python-list


python float-point problem

2007-02-23 Thread unidevel
I just compiled python 2.4.2 using openembedded for my zaurus C750.
I test some comparison for float-pointing number, for example:
3.1<3.0 True
3.2<3.0 True
3.3<3.0 False
8.4<4.0 True
I use the cross compiler that compiled python to make a simple C
program,
got correct results.
Anyone have some idea about that?

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

Re: Module trouble [newbie]

2007-02-23 Thread Diez B. Roggisch
Boris Ozegovic wrote:

> Diez B. Roggisch wrote:
> 
>> Are you sure the above is what you really used for your test? Because
>> your output features a single 100, which the above lacks a
>> print-statement for.
> 
> Yeah, I cancelled the message, but synchronization allready happened.  :)
> 
> Problem was in some other place.
> 
> One more question: is calling import inside function definition poor
> design?  e.g.
> 
> def foo():
>doSomething:
>import someModule
>someModule.doSomethin

I use it sometimes myself, to avoid otherwise circular imports. However, I
don't like it very much. Try to go without it I'd say, but that is just a
gut-feeling.

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


Re: Finding a tuple in a tuple

2007-02-23 Thread Duncan Booth
Philipp Pagel <[EMAIL PROTECTED]> wrote:

> Another way to go instead of using sets, although probably less elegant:
> 
 True in [x in t1 for x in t2]
> True
 True in [x in t1 for x in t3]
> True
 True in [x in t1 for x in t4]
> False
 True in [x in t1 for x in t5]
> False

Slightly more elegant for Python 2.5 users:

>>> any(x in t1 for x in t2)
True
>>> any(x in t1 for x in t3)
True
>>> any(x in t1 for x in t4)
False
>>> any(x in t1 for x in t5)
False


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


Re: jython import search path

2007-02-23 Thread Diez B. Roggisch
> Accepted strategy? It doesn't seem very portable. It assumes that
> everyone puts their library
> modules in the exact same place. Or do they just figure that changing
> the sys.path.append
> line is easy enough?

Portability has nothing to do with it. If you arrange your project in a way
that these paths can be figured out at runtime, it's fine.

If not, you might need some installation routine that will figure them out
when installing the software, hard-coding such paths in some way (as
parameter lists or whatsoever)
 
>> java -Dpython.path=
> 
> I'm not using Java at all. I just want to generate Java bytecode for
> purposes of code analysis
> by existing tools.

If you are using jython, you are using java. 

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


Re: Local class variables? (mod_python problem)

2007-02-23 Thread Diez B. Roggisch
> It is not desirable for the class variable to keep incrementing outside
> of invocations of '__main__', as is the case when it is loaded under
> mod_python under apache2 on linux.
> 

I'm still not clear on what you want to accomplish. In the end it boils down
to who is supposed to share that information in the variables, or in other
words: which scope has it.

Is it per request? Then using some thread-local storage would be in order,
or "abusing" a possible request-object.

Is it per user, over several requests? Then you need a session-mechanism.

Is it per application, for several users, over several requests? Then your
approach is ok, but needs guarding against concurrrent access using
threading.Lock for example. However, I presume that is not the desired
usecase, from what I can extract from your posts I presume it's case two.

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


Re: Module trouble [newbie]

2007-02-23 Thread Boris Ozegovic
Diez B. Roggisch wrote:

> I use it sometimes myself, to avoid otherwise circular imports. 

Circular imports are the reason why I have module issues.  Last question:
if I put modules in some package and then try to import one I get
"AttributeError: 'module' object has no attribute 'a'

Code is:

a.py
A = 756
import someFolder.b as b
print "A printing"
print "B is %s" % b.B

b.py
B = 2000
import someFolder.a as a
print "B printing"
print "A is %s" % a.A

How can I do circular imports if I use packages?  Darn.  I don't remeber
this module gothcas when reading Learning Python.

-- 
http://www.nacional.hr/articles/view/23894/23
-- 
http://mail.python.org/mailman/listinfo/python-list


compile python with sqlite3

2007-02-23 Thread Nader Emami
L.S.,

I have to compile (install) locally Python 2.5, because I don't have 
'root' permission. Besides I would use 'sqlite3' as a database for 
TurboGears/Django. I have installed 'sqlite3' somewhere on my Linux 
(/path/to/sqlite'). What do I have to do if I want to compile 'Python' 
with 'sqlite3'? I would appreciate if somebody tells me to solve this 
problem.

With regards,
Nader
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Creating a daemon process in Python

2007-02-23 Thread Nick Craig-Wood
Eirikur Hallgrimsson <[EMAIL PROTECTED]> wrote:
>  def daemonize():
>  if (not os.fork()):
>  # get our own session and fixup std[in,out,err]
>  os.setsid()
>  sys.stdin.close()
>  sys.stdout = NullDevice()
>  sys.stderr = NullDevice()

That doesn't close the underlying file descriptors...

Here is another method which does :-

  null = os.open(os.devnull, os.O_RDWR)
  os.dup2(null, sys.stdin.fileno())
  os.dup2(null, sys.stdout.fileno())
  os.dup2(null, sys.stderr.fileno())
  os.close(null)


>  if (not os.fork()):
>  # hang around till adopted by init
>  ppid = os.getppid()
>  while (ppid != 1):
>  time.sleep(0.5)
>  ppid = os.getppid()

Why do you need hang around until adopted by init?  I've never see
that in a daemonize recipe before?

>  else:
>  # time for child to die
>  os._exit(0)
>  else:
>  # wait for child to die and then bail
>  os.wait()
>  sys.exit()

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


Finding non ascii characters in a set of files

2007-02-23 Thread bg_ie
Hi,

I'm updating my program to Python 2.5, but I keep running into
encoding problems. I have no ecodings defined at the start of any of
my scripts. What I'd like to do is scan a directory and list all the
files in it that contain a non ascii character. How would I go about
doing this?

Thanks,

Barry.

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


Re: What is the best queue implemetation in Python?

2007-02-23 Thread Szabolcs Nagy
> For that purpose I have used the good deque that you can find in
> collections in the standard library. It's very good for queues, and
> it's a bit faster than regular lists for stacks too.

you mean *much* faster (since a list is a reference array so pop(0) is
O(n) operation)

never use a list as queue if len(queue) > 1

=== benchmark

$ time ./deque_queue.py
34359607296

real0m0.286s
user0m0.264s
sys 0m0.016s

$ time ./list_queue.py
34359607296

real1m20.915s
user1m18.649s
sys 0m0.396s


=== the sources

--- deque_queue.py:
#!/usr/bin/python2.5

from collections import deque

def f(n):
sum = 0
queue = deque()
for i in range(n):
queue.append(i)
while queue:
sum += queue.popleft()
print sum

if __name__=='__main__':
f(1<<18)

--- list_queue.py:
#!/usr/bin/python2.5

def f(n):
sum = 0
queue = list()
for i in range(n):
queue.append(i)
while queue:
sum += queue.pop(0)
print sum

if __name__=='__main__':
f(1<<18)

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


Re: Creating a daemon process in Python

2007-02-23 Thread Jean-Paul Calderone
On Fri, 23 Feb 2007 08:30:07 -0600, Nick Craig-Wood <[EMAIL PROTECTED]> wrote:
>Eirikur Hallgrimsson <[EMAIL PROTECTED]> wrote:
>
> [snip]
>
>>  if (not os.fork()):
>>  # hang around till adopted by init
>>  ppid = os.getppid()
>>  while (ppid != 1):
>>  time.sleep(0.5)
>>  ppid = os.getppid()
>
>Why do you need hang around until adopted by init?  I've never see
>that in a daemonize recipe before?
>

I think it simplifies some signal handling logic.  I'd never seen it before
in a deamonizer either, but it caught my eye in this one.  I haven't had time
to investigate further though.  I hope Eirikur will explain. :)

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


With PIL... paste image on top of other with dropshadow

2007-02-23 Thread Peter Bengtsson
I love the dropshadow effect I managed to make with this recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/474116

Here's what it can look like:
http://www.peterbe.com/test/188-tequilacat.2.jpg

It takes a background as a parameter but it's just a colour. What I
want is to put the image on top of another but doing so with a
dropshadow. I guess the solution would be something like putting the
dropshadow on the first image without a background colour but instead
a transparant background and then paste this onto another image.

I just have no idea to do that?

The final result I want is something like programmtically fake that a
picture (the foreground) is hanging on a wall (the background) with a
dropshadow so that it looks like it's hanging in a inch-deep frame.

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


Re: Finding non ascii characters in a set of files

2007-02-23 Thread Peter Bengtsson
On Feb 23, 2:38 pm, [EMAIL PROTECTED] wrote:
> Hi,
>
> I'm updating my program to Python 2.5, but I keep running into
> encoding problems. I have no ecodings defined at the start of any of
> my scripts. What I'd like to do is scan a directory and list all the
> files in it that contain a non ascii character. How would I go about
> doing this?
>

How about something like this:
content = open('file.py').read()
try:
content.encode('ascii')
except UnicodeDecodeError:
print "file.py contains non-ascii characters"


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


Re: Module trouble [newbie]

2007-02-23 Thread Goldfish
On Feb 23, 6:44 am, Boris Ozegovic <[EMAIL PROTECTED]>
wrote:
> Can somebody explaint this to me:
>
> I have module a.py
> A = 100
> import b
> print "A printing"
> print "B is %s" % b.B
>
> and module b.py
> B = 2000
> import a
> print "B printing"
> print "A is %s" % a.A
>
> I thought that output would be:
> B printing
> A is 100
> A printing
> B is 2000
>
> Because import b would execute b.py, and in b.py line "import a" would be
> ignored, but my output is:
>
> >>> import a
>
> 100
> A printing
> B is 100
>
> ??
>
> :)
>
> --http://www.nacional.hr/articles/view/23894/23

a.py
===
A = 100
import b
print "A printing"
print "B is %s" % b.B

b.py
===
B = 2000
import a
print "B printing"
print "A is %s" % a.A

Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)]
on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import a
B printing
A is 100
A printing
B is 2000
>>>

Looks okay to me.

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


Re: CSV(???)

2007-02-23 Thread John Machin
On Feb 23, 10:11 pm, David C. Ullrich <[EMAIL PROTECTED]>
wrote:
> Is there a csvlib out there somewhere?

I can make available the following which should be capable of running
on 1.5.2 -- unless they've suffered bitrot :-)

(a) a csv.py which does simple line-at-a-time hard-coded-delimiter-etc
pack and unpack i.e. very similar to your functionality *except* that
it doesn't handle newline embedded in a field. You may in any case be
interested to see a different way of writing this sort of thing: my
unpack does extensive error checking; it uses a finite state machine
so unexpected input in any state is automatically an error.

(b) an extension module (i.e. written in C) with the same API. The
python version (a) imports and uses (b) if it exists.

(c) an extension module which parameterises everything including the
ability to handle embedded newlines.

The two extension modules have never been compiled & tested on other
than Windows but they both should IIRC be compilable with both gcc
(MinGW) and the free Borland 5.5 compiler -- in other words vanilla C
which should compile OK on Linux etc.

If you are interested in any of the above, just e-mail me.

>
> And/or does anyone see any problems with
> the code below?
>
> What csvline does is straightforward: fields
> is a list of strings. csvline(fields) returns
> the strings concatenated into one string
> separated by commas. Except that if a field
> contains a comma or a double quote then the
> double quote is escaped to a pair of double
> quotes and the field is enclosed in double
> quotes.
>
> The part that seems somewhat hideous is
> parsecsvline. The intention is that
> parsecsvline(csvline(fields)) should be
> the same as fields. Haven't attempted
> to deal with parsecsvline(data) where
> data is in an invalid format - in the
> intended application data will always
> be something that was returned by
> csvline.

"Always"? Famous last words :-)

> It seems right after some
> testing... also seems blechitudinous.

I agree that it's bletchworthy, but only mildly so. If it'll make you
feel better, I can send you as a yardstick csv pack and unpack written
in awk -- that's definitely *not* a thing of beauty and a joy
forever :-)

I presume that you don't write csvline() output to a file, using
newline as a record terminator and then try to read them back and pull
them apart with parsecsvline() -- such a tactic would of course blow
up on the first embedded newline. So as a matter of curiosity, where/
how are you storing multiple csvline() outputs?

>
> (Um: Believe it or not I'm _still_ using
> python 1.5.7. So comments about iterators,
> list comprehensions, string methods, etc
> are irrelevent. Comments about errors in
> the algorithm would be great. Thanks.)

1.5.7 ?
[big snip]

Cheers,
John

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


Re: Finding non ascii characters in a set of files

2007-02-23 Thread John Machin
On Feb 24, 2:12 am, "Peter Bengtsson" <[EMAIL PROTECTED]> wrote:
> On Feb 23, 2:38 pm, [EMAIL PROTECTED] wrote:
>
> > Hi,
>
> > I'm updating my program to Python 2.5, but I keep running into
> > encoding problems. I have no ecodings defined at the start of any of
> > my scripts. What I'd like to do is scan a directory and list all the
> > files in it that contain a non ascii character. How would I go about
> > doing this?
>
> How about something like this:
> content = open('file.py').read()
> try:
> content.encode('ascii')
> except UnicodeDecodeError:
> print "file.py contains non-ascii characters"


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


Rational numbers

2007-02-23 Thread Martin Manns
Hi,

I am starting to use rationals and since I found no batteries included,
I tried out the mxNumber package.

However, I get strange warnings on comparison operations
(which however seem to yield correct results):

---
$ python
Python 2.4.3 (#1, Jan 15 2007, 15:46:19) 
[GCC 4.1.1 (Gentoo 4.1.1-r3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from mx.Number import *
>>> a=Rational(0,1)
>>> a
0/1
>>> str(a)
'0.0'
>>> b=-50
>>> b
-50L
>>> a==b
__main__:1: RuntimeWarning: tp_compare didn't return -1, 0 or 1
False
>>> 
---

How do I get rid of these warnings?

Is there any rational number library around that
1) is comparably fast for large denominators
2) allows deriving types from Rationals without wrapping?

Regards

Martin

P.S. The respective mailing list does not like me, so that I try my
luck here.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert to binary and convert back to strings

2007-02-23 Thread Eric Pederson
Harlin Seritt wrote:

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

To my mind, the more sensible job you do at programming this the worse 
off you are, unless you use strong encryption.  There are nearly 
infinite approaches, so the random approach you use will be part of the 
"security" of the obfuscation.

OK, I am not really taking this so seriously, but it is a fun question 
(Python makes these minor things fun).  Is there anyway to do this in 
Python?  You bet, so many ways... here's another:

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

s0=s+"$"
s2="0 ".join([str(ord(c)) for c in s])
s1="".join([chr(int(i[:-1])) for i in s2.split(" 
")[:-1]])+chr(int(s2[-1]))[:-1]

def codeMe(s):
s0=s+"$"
return "0 ".join([str(ord(c)) for c in s0])

def uncodeMe(s):
return "".join([chr(int(i[:-1])) for i in s.split(" 
")[:-1]])+chr(int(s[-1]))[:-1]

def testit(s):
s2=codeMe(s)
s1=uncodeMe(s2)
strings={"original":s, "obfuscated":s2, "decoded":s1}
for k in strings.keys():
print k,":  ","\n",strings[k], "\n\n"
   
testit(s)

-
the obfuscated looks like this:

730 320 1190 1110 1170 1080 1000 320 1080 1050 1070 1010 320 1160 1110 
320 1160 970 1070 1010 320 970 320 1150 1160 1140 1050 1100 1030 320 
1080 1050 1070 1010 320 390 1150 1170 1120 1010 1140 990 970 1080 1050 
1020 1140 970 1030 1050 1080 1050 1150 1160 1050 990 1010 1200 1120 1050 
970 1080 1050 1000 1110 990 1050 1170 1150 390 100 970 1100 1000 320 
1190 1140 1050 1160 1010 320 1050 1160 320 1160 1110 320 970 320 1020 
1050 1080 1010 320 1050 1100 320 980 1050 1100 970 1140 1210 320 1020 
1110 1140 1090 1150 320 450 450 320 1160 1040 1050 1150 320 1190 970 
1210 320 970 320 1170 1150 1010 1140 320 990 970 1100 1100 1110 1160 320 
1140 1010 970 1000 100 1160 1040 1010 320 1150 1160 1140 1050 1100 1030 
320 1050 1100 320 990 970 1150 1010 320 1160 1040 1010 1210 320 1190 
1010 1140 1010 320 1160 1140 1210 320 1160 1110 320 1110 1120 1010 1100 
320 1050 1100 320 1150 1110 1090 1010 1160 1040 1050 1100 1030 320 1080 
1050 1070 1010 320 970 1150 990 1050 1050 320 1160 1010 1200 1160 100 
1010 1000 1050 1160 1110 1140 460 320 730 390 1000 320 970 1080 1150 
1110 320 1080 1050 1070 1010 320 1160 1110 320 980 1010 320 970 980 1080 
1010 320 1160 1110 320 1140 1010 970 1000 320 1160 1040 1010 320 980 
1050 1100 970 1140 1210 320 1020 1110 1140 1090 1010 1000 320 1000 970 
1160 970 320 980 970 990 1070 100 1050 1100 1160 1110 320 1150 1160 1140 
1050 1100 1030 320 1020 1110 1140 1090 970 1160 320 1150 1110 320 1160 
1040 970 1160 320 1050 1160 320 1150 1040 1110 1190 1150 320 1160 1040 
1010 320 1110 1140 1050 1030 1050 1100 970 1080 320 1180 970 1080 1170 
1010 460 320 730 1150 320 1160 1040 1010 1140 1010 320 970 1100 1210 100 
1190 970 1210 320 1160 1110 320 1000 1110 320 1160 1040 1050 1150 320 
1050 1100 320 800 1210 1160 1040 1110 1100 630 36

Of course some overly curious application user may note the pattern of 
"0" endings, strip those off, concatenate the numbers, and try several 
conversions on them, at which point they may figure this out-  and 
contact you to gloat that they have hacked the file.

That's when you recruit them onto your development team and give them 
some real work.  :-)

Have fun


EP

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


Re: Creating a daemon process in Python

2007-02-23 Thread Eirikur Hallgrimsson
I didn't actually write this module.  I believe I found it in a 
discussion in ASPN at Active State.

Thanks for the input, and when I get a chance I will try these alternate 
approaches.  This module has been working fine for me as is--so far.

Eirikur


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


Re: Finding non ascii characters in a set of files

2007-02-23 Thread Larry Bates
Peter Bengtsson wrote:
> On Feb 23, 2:38 pm, [EMAIL PROTECTED] wrote:
>> Hi,
>>
>> I'm updating my program to Python 2.5, but I keep running into
>> encoding problems. I have no ecodings defined at the start of any of
>> my scripts. What I'd like to do is scan a directory and list all the
>> files in it that contain a non ascii character. How would I go about
>> doing this?
>>
> 
> How about something like this:
> content = open('file.py').read()
> try:
> content.encode('ascii')
> except UnicodeDecodeError:
> print "file.py contains non-ascii characters"
> 
> 
The next problem will be that non-text files will contain non-ASCII
characters (bytes).  The other 'issue' is that OP didn't say how large
the files were, so .read() might be a problem.

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


Apache Cgi (70007)The timeout specified has expired

2007-02-23 Thread naima . mans
Hello,

When i run my python script, it works a moment and then stop with this
message in the log:

(70007)The timeout specified has expired: ap_content_length_filter:
apr_bucket_read() failed refers to ..

I think my script is too long therefore the server stop it...

how can i do to run all my python script?

thanks for your help

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


Re: Finding non ascii characters in a set of files

2007-02-23 Thread John Machin
On Feb 24, 2:35 am, "John Machin" <[EMAIL PROTECTED]> wrote:
> On Feb 24, 2:12 am, "Peter Bengtsson" <[EMAIL PROTECTED]> wrote:
>
> > On Feb 23, 2:38 pm, [EMAIL PROTECTED] wrote:
>
> > > Hi,
>
> > > I'm updating my program to Python 2.5, but I keep running into
> > > encoding problems. I have no ecodings defined at the start of any of
> > > my scripts. What I'd like to do is scan a directory and list all the
> > > files in it that contain a non ascii character. How would I go about
> > > doing this?
>
> > How about something like this:
> > content = open('file.py').read()
> > try:
> > content.encode('ascii')
> > except UnicodeDecodeError:
> > print "file.py contains non-ascii characters"

Sorry, I fell face down on the Send button :-)

To check all .py files in the current directory, modify Peter's code
like this:

import glob
for filename in glob.glob('*.py'):
   content = open(filename).read()

maybe that UnicodeDecodeError should be ...Encode...
and change the print statement to cater for filename being variable.

If you have hundreds of .py files in the same directory, you'd better
modify the code further to explicitly close each file.

HTH,
John

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


Re: Apache Cgi (70007)The timeout specified has expired

2007-02-23 Thread abubakerkiter2003

[EMAIL PROTECTED] أرسلت:
> Hello,
>
> When i run my python script, it works a moment and then stop with this
> message in the log:
>
> (70007)The timeout specified has expired: ap_content_length_filter:
> apr_bucket_read() failed refers to ..
>
> I think my script is too long therefore the server stop it...
>
> how can i do to run all my python script?
>
> thanks for your help

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

Re: Apache Cgi (70007)The timeout specified has expired

2007-02-23 Thread abubakerkiter2003

[EMAIL PROTECTED] أرسلت:
> Hello,
>
> When i run my python script, it works a moment and then stop with this
> message in the log:
>
> (70007)The timeout specified has expired: ap_content_length_filter:
> apr_bucket_read() failed refers to ..
>
> I think my script is too long therefore the server stop it...
>
> how can i do to run all my python script?
>
> thanks for your help

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

Re: Rational numbers

2007-02-23 Thread Larry Bates
Martin Manns wrote:
> Hi,
> 
> I am starting to use rationals and since I found no batteries included,
> I tried out the mxNumber package.
> 
> However, I get strange warnings on comparison operations
> (which however seem to yield correct results):
> 
> ---
> $ python
> Python 2.4.3 (#1, Jan 15 2007, 15:46:19) 
> [GCC 4.1.1 (Gentoo 4.1.1-r3)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
 from mx.Number import *
 a=Rational(0,1)
 a
> 0/1
 str(a)
> '0.0'
 b=-50
 b
> -50L
 a==b
> __main__:1: RuntimeWarning: tp_compare didn't return -1, 0 or 1
> False
> ---
> 
> How do I get rid of these warnings?
> 
> Is there any rational number library around that
> 1) is comparably fast for large denominators
> 2) allows deriving types from Rationals without wrapping?
> 
> Regards
> 
> Martin
> 
> P.S. The respective mailing list does not like me, so that I try my
> luck here.

I quick search of Google turned up:

http://books.google.com/books?id=1Shx_VXS6ioC&pg=PA625&lpg=PA625&dq=python+rational+number+library&source=web&ots=BA8_4EXdQ4&sig=aDEnYA99ssKe7PSweVNyi8cS2eg
http://calcrpnpy.sourceforge.net/clnum.html
http://gmpy.sourceforge.net/

-Larry

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


Re: Local class variables? (mod_python problem)

2007-02-23 Thread Rory Campbell-Lange
On 23/02/07, Diez B. Roggisch ([EMAIL PROTECTED]) wrote:
> > It is not desirable for the class variable to keep incrementing outside
> > of invocations of '__main__', as is the case when it is loaded under
> > mod_python under apache2 on linux.
> > 
> 
> I'm still not clear on what you want to accomplish. In the end it boils down
> to who is supposed to share that information in the variables, or in other
> words: which scope has it.
> 
> Is it per request? Then using some thread-local storage would be in order,
> or "abusing" a possible request-object.
> 
> Is it per user, over several requests? Then you need a session-mechanism.
> 
> Is it per application, for several users, over several requests? Then your
> approach is ok, but needs guarding against concurrrent access using
> threading.Lock for example. However, I presume that is not the desired
> usecase, from what I can extract from your posts I presume it's case two.

Many thanks for your reply. The use case is per request, and I would be
grateful to learn more about thread-local storage.

Kind regards
Rory

-- 
Rory Campbell-Lange 
<[EMAIL PROTECTED]>

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


Re: Rational numbers

2007-02-23 Thread Martin Manns
On Fri, 23 Feb 2007 09:52:06 -0600
Larry Bates <[EMAIL PROTECTED]> wrote:
> I quick search of Google turned up:
> 
> http://books.google.com/books?id=1Shx_VXS6ioC&pg=PA625&lpg=PA625&dq=python+rational+number+library&source=web&ots=BA8_4EXdQ4&sig=aDEnYA99ssKe7PSweVNyi8cS2eg
> http://calcrpnpy.sourceforge.net/clnum.html
> http://gmpy.sourceforge.net/

Sorry that I did not point these out initially.

+ clnum seems to be slower and for speed may be compiled to wrap gmp so
that it is just an additional layer between python and gmp .

+ gmpy is looking pretty unmaintained (dead) to me (newest update of
cvs 10 months ago).

+ boost indeed is a quite nice C++ library. However, I fear that I
would end up writing the python wrappers for operators (+ - * / min
max cmp etc.) myself. I would like to avoid this since these operators
should work correctly for any type (not just int and float) and I have
little experience with verifying such generic code. The problems
encountered in the mxNumber wrapper support this notion.

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


Re: Finding non ascii characters in a set of files

2007-02-23 Thread John Machin
On Feb 24, 2:44 am, Larry Bates <[EMAIL PROTECTED]> wrote:
> Peter Bengtsson wrote:
> > On Feb 23, 2:38 pm, [EMAIL PROTECTED] wrote:
> >> Hi,
>
> >> I'm updating my program to Python 2.5, but I keep running into
> >> encoding problems. I have no ecodings defined at the start of any of
> >> my scripts. What I'd like to do is scan a directory and list all the
> >> files in it that contain a non ascii character. How would I go about
> >> doing this?
>
> > How about something like this:
> > content = open('file.py').read()
> > try:
> > content.encode('ascii')
> > except UnicodeDecodeError:
> > print "file.py contains non-ascii characters"
>
> The next problem will be that non-text files will contain non-ASCII
> characters (bytes).  The other 'issue' is that OP didn't say how large
> the files were, so .read() might be a problem.
>
> -Larry

The way I read it, the OP's problem is to determine in one big hit
which Python source files need a

# coding: whatever

line up the front to stop Python 2.5 complaining ... I hope none of
them are so big as to choke .read()

Cheers,
John

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


c_string missing from ctypes?

2007-02-23 Thread Jacob Rael
Hello,

I was following along with this site:

http://www.brunningonline.net/simon/blog/archives/000659.html

and I got a error. It boils down to:



In [9]: import ctypes
In [10]: dir(ctypes.c_string)
---
Traceback (most recent call
last)

P:\ in ()

: 'module' object has no attribute
'c_string'




I google ctypes.c_string and many people use it.

I am using python 2.5 with ctypes version: 1.0.1  on a windows
machine.

I have to admit I don't know where ctypes came from. I tried to re-
install it but the window binaries only support 2.4.

Also:

http://starship.python.net/crew/theller/ctypes/tutorial.html

seems dead.

An info is greatly appreciated.

jr

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


Re: c_string missing from ctypes?

2007-02-23 Thread Chris Mellon
On 23 Feb 2007 09:03:21 -0800, Jacob Rael <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I was following along with this site:
>
> http://www.brunningonline.net/simon/blog/archives/000659.html
>
> and I got a error. It boils down to:
>
> 
>
> In [9]: import ctypes
> In [10]: dir(ctypes.c_string)
> ---
> Traceback (most recent call
> last)
>
> P:\ in ()
>
> : 'module' object has no attribute
> 'c_string'
>
> 

The tutorial is out of date, ctypes.c_string was removed somewhere
around version 0.6 (theres a comment to this effect in the comments
under the tutorial). You want ctypes.c_buffer instead.

>
>
> I google ctypes.c_string and many people use it.
>
> I am using python 2.5 with ctypes version: 1.0.1  on a windows
> machine.
>
> I have to admit I don't know where ctypes came from. I tried to re-
> install it but the window binaries only support 2.4.
>

As of Python 2.5 ctypes is part of the standard library.

> Also:
>
> http://starship.python.net/crew/theller/ctypes/tutorial.html
>
> seems dead.
>
> An info is greatly appreciated.
>
> jr
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: c_string missing from ctypes?

2007-02-23 Thread Simon Brunning
On 23 Feb 2007 09:03:21 -0800, Jacob Rael <[EMAIL PROTECTED]> wrote:
> I was following along with this site:
>
> http://www.brunningonline.net/simon/blog/archives/000659.html

You don't want to be messing around with that old rubbish. I should
know - I wrote it.

Instead, take a look at .

> In [9]: import ctypes
> In [10]: dir(ctypes.c_string)
> ---
> Traceback (most recent call
> last)
> : 'module' object has no attribute
> 'c_string'

I think that c_string has been replaced by c_buffer in recent versions
of ctypes.

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


Re: Finding non ascii characters in a set of files

2007-02-23 Thread Tim Arnold
"Peter Bengtsson" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> On Feb 23, 2:38 pm, [EMAIL PROTECTED] wrote:
>> Hi,
>>
>> I'm updating my program to Python 2.5, but I keep running into
>> encoding problems. I have no ecodings defined at the start of any of
>> my scripts. What I'd like to do is scan a directory and list all the
>> files in it that contain a non ascii character. How would I go about
>> doing this?
>>
>
> How about something like this:
> content = open('file.py').read()
> try:
>content.encode('ascii')
> except UnicodeDecodeError:
>print "file.py contains non-ascii characters"
>
Here's what I do (I need to know the line number).

import os,sys,codecs
def checkfile(filename):
f = codecs.open(filename,encoding='ascii')

lines = open(filename).readlines()
print 'Total lines: %d' % len(lines)
for i in range(0,len(lines)):
try:
l = f.readline()
except:
num = i+1
print 'problem: line %d' % num

f.close()



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


Re: Rational numbers / alternatives to mxNumber

2007-02-23 Thread Martin Manns
On Fri, 23 Feb 2007 11:39:11 -0500
Martin Manns <[EMAIL PROTECTED]> wrote:

> + boost indeed is a quite nice C++ library. However, I fear that I
> would end up writing the python wrappers for operators (+ - * / min
> max cmp etc.) myself. I would like to avoid this since these operators
> should work correctly for any type (not just int and float) and I have
> little experience with verifying such generic code. The problems
> encountered in the mxNumber wrapper support this notion.


I just saw the pyboost-linux-0.1.1 package and tried it out.

ImportError: /home/mn/notes/libboost_python.so.1.34.0: undefined
symbol: PyUnicodeUCS4_FromEncodedObject

It seems to have problems with UCS2 compiled python.
Any robust rational wrapper out there?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Local class variables? (mod_python problem)

2007-02-23 Thread Diez B. Roggisch
> 
> Many thanks for your reply. The use case is per request, and I would be
> grateful to learn more about thread-local storage.

There are several ways. I'm not familiar with mod_python, but I guess you
get a dict-like object for the request parameters. In python, this is
usually writable (in contrast to the darn J2EE-spec'ed HttpRequest)

So just add a new key, e.g. "working_state", to it. Under that, file those
variables.

Alternatively, there are recipes out there
(http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302088
)

that give you basically a dictionary keyed with the current thread.

That is helpful if you have computations deeper in code that can't get a
hold on the request object. Might be the case in mod_python - in cherrypy,
the request itself is thread-locally stored, so you can get it whereever
you need.

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


Re: CSV(???)

2007-02-23 Thread Neil Cerutti
On 2007-02-23, David C  Ullrich <[EMAIL PROTECTED]> wrote:
> Is there a csvlib out there somewhere?
>
> And/or does anyone see any problems with
> the code below?
>
> What csvline does is straightforward: fields
> is a list of strings. csvline(fields) returns
> the strings concatenated into one string
> separated by commas. Except that if a field
> contains a comma or a double quote then the
> double quote is escaped to a pair of double
> quotes and the field is enclosed in double
> quotes.
>
> The part that seems somewhat hideous is
> parsecsvline. The intention is that
> parsecsvline(csvline(fields)) should be
> the same as fields. Haven't attempted
> to deal with parsecsvline(data) where
> data is in an invalid format - in the
> intended application data will always
> be something that was returned by
> csvline. It seems right after some
> testing... also seems blechitudinous.
>
> (Um: Believe it or not I'm _still_ using python 1.5.7. So
> comments about iterators, list comprehensions, string methods,
> etc are irrelevent. Comments about errors in the algorithm
> would be great. Thanks.)

Two member functions of indexedstring are not used: next and
lookahead. __len__ and __getitem__ appear to serve no real
purpose.

> def parsecsvline(csvline):
>   """Inverts csvline(). Assumes csvline is valid, ie
>   is something as returned by csvline(); output undefined
>   if csvline is in invalid format"""
>
>   s = indexedstring(csvline)
>   res = []
>
>   while not s.eos():
>res.append(s.getfield())
>
>   return res

You'll be happy to know that iterators and list comprehensions
will make your code better after you upgrade. ;-)

In the meantime, I think your (relative lack of) error handling
is OK. GIGO, as they say (garbage in, garbage out).

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


Re: Rational numbers

2007-02-23 Thread bearophileHUGS
Martin Manns:
> + gmpy is looking pretty unmaintained (dead) to me (newest update of
> cvs 10 months ago).

I have used it on Py2.5, so it seems to work anyway, and it's fast
enough for my purposes. And probably soon some alex-shaped life will
show up elsewhere.

Bye,
bearophile

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


Re: Rational numbers

2007-02-23 Thread [EMAIL PROTECTED]
On Feb 23, 10:39 am, Martin Manns <[EMAIL PROTECTED]> wrote:
> On Fri, 23 Feb 2007 09:52:06 -0600
>
> Larry Bates <[EMAIL PROTECTED]> wrote:
> > I quick search of Google turned up:
>
> >http://books.google.com/books?id=1Shx_VXS6ioC&pg=PA625&lpg=PA625&dq=p...
> >http://calcrpnpy.sourceforge.net/clnum.html
> >http://gmpy.sourceforge.net/
>
> Sorry that I did not point these out initially.
>
> + clnum seems to be slower and for speed may be compiled to wrap gmp so
> that it is just an additional layer between python and gmp .
>
> + gmpy is looking pretty unmaintained (dead) to me (newest update of
> cvs 10 months ago).

Actually, gmpy is being maitained even if SourceForge isn't up to
date.

I got my gmpy 1.04a for Python 2.5 Windows binary from



I haven't used the rationals all that much, but been very
happy with them when I have.


>
> + boost indeed is a quite nice C++ library. However, I fear that I
> would end up writing the python wrappers for operators (+ - * / min
> max cmp etc.) myself. I would like to avoid this since these operators
> should work correctly for any type (not just int and float) and I have
> little experience with verifying such generic code. The problems
> encountered in the mxNumber wrapper support this notion.
>
> Martin


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


Re: Rational numbers

2007-02-23 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Martin Manns wrote:

> + gmpy is looking pretty unmaintained (dead) to me (newest update of
> cvs 10 months ago).

What CSV activities do you expect?  This package seems to be pretty
stable.  As long as there is no bug or incompatible changes in the
underlying library I would not expect changes to that package.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding non ascii characters in a set of files

2007-02-23 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Tim Arnold wrote:

> Here's what I do (I need to know the line number).
> 
> import os,sys,codecs
> def checkfile(filename):
> f = codecs.open(filename,encoding='ascii')
> 
> lines = open(filename).readlines()
> print 'Total lines: %d' % len(lines)
> for i in range(0,len(lines)):
> try:
> l = f.readline()
> except:
> num = i+1
> print 'problem: line %d' % num
> 
> f.close()

I see a `NameError` here.  Where does `i` come from?  And there's no need
to read the file twice.  Untested:

import os, sys, codecs

def checkfile(filename):
f = codecs.open(filename,encoding='ascii')

try:
for num, line in enumerate(f):
pass
except UnicodeError:
print 'problem: line %d' % num

f.close()

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding non ascii characters in a set of files

2007-02-23 Thread Tim Arnold
"Marc 'BlackJack' Rintsch" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> In <[EMAIL PROTECTED]>, Tim Arnold wrote:
>


>   Untested:
>
> import os, sys, codecs
>
> def checkfile(filename):
>f = codecs.open(filename,encoding='ascii')
>
>try:
>for num, line in enumerate(f):
>pass
>except UnicodeError:
>print 'problem: line %d' % num
>
>f.close()
>
> Ciao,
> Marc 'BlackJack' Rintsch

Thanks Marc,
That looks much cleaner. I didn't know the 'num' from the enumerate would 
persist so the except block could report it.

thanks again,
--Tim


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


Who has not attended these free tutorial courses ?

2007-02-23 Thread stj911
"President Bush ... you are under arrest" - 911 truth video by Dr
Morgan Reynolds, Former Chief Economist under Bush

You can also save them by right clicking the
links and saving them as flv files and download a free flv player.
google is your best friend.

"Bush Administration Insider Says U.S. Government Behind 911.flv"
"http://ash-v31.ash.youtube.com/get_video?video_id=HkpOsUmp-9w";  <---
key video

"911 Truth, Scott Forbes describes power-downs in WTC.flv" "http://
youtube-609.vo.llnwd.net/d1/04/D1/fEJmcvTzYfo.flv"

"911 Truth, Consequences of Revealing the Truth about 911.flv"
"http://
youtube-609.vo.llnwd.net/d1/04/D1/fEJmcvTzYfo.flv"

"U.S. Army General Says Flight 77 Did Not Hit Pentagon.flv"
"http://lax-v8.lax.youtube.com/get_video?video_id=Zsn4JA450iA";

"911 Truth, Bush Administration Lied About Iraq 911.flv" "http://lax-
v8.lax.youtube.com/get_video?video_id=Zsn4JA450iA"

"Bush gets caught off guard on 9/11 prior knowledge question.flv"
"http://lax-v222.lax.youtube.com/get_video?video_id=0eH5qbrpwlM";

"Bush gets caught off guard on 911 prior knowledge question.flv"
"http://lax-v222.lax.youtube.com/get_video?video_id=0eH5qbrpwlM";

"World Trade Center -- Controlled Demolition.flv" "http://
v187.youtube.com/get_video?video_id=87fyJ-3o2ws"

"911 Truth, The Moles, the Patsies, State-Sponsored Terror.flv"
"http://chi-v43.chi.youtube.com/get_video?video_id=u0K9BM9oo90";

The Answer: Why do they hate our freedoms :

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


Re: What is the best queue implemetation in Python?

2007-02-23 Thread sunheaver
On Feb 22, 12:40 pm, hg <[EMAIL PROTECTED]> wrote:
> John Machin wrote:
> > On Feb 23, 11:12 am, "John" <[EMAIL PROTECTED]> wrote:
> >> I want to write a code for Breadth First Traveral for Graph, which needs
> >> a queue to implement.
>
> >> I wonder that for such a powerful language as Python, whether there is a
> >> better and simpler implementation for a traditional FIFO queue?
>
> > Better and simpler than *WHAT*?
>
> Sorry, but you do that all the time ... "ask the question as you know the
> answer, otherwise shut the f u ..."
>
> Can't you assume for a second that other people do not have your wonderful
> brain and still have to make it through 60+ years of life of learning ?
>
> hg



Um... first off, you have to admit that a lot of what is posted
on the internet in general and even on groups like this is rambling,
poorly thought out, missing necessary context, and just generally a
mess and hard to understand.

So maybe a little peer pressure on folks to clean up their posts and
try
to express themselves clearly isn't such a bad thing.

And finally, let's face it: if the internet ever does cease to be a
place
where you can see crotechety know-it-all programmers roasting clueless
noobs,
then, honestly, what is the point of owning a computer?

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


Re: With PIL... paste image on top of other with dropshadow

2007-02-23 Thread Matimus
two things,

change the following line:
[code]
  back = Image.new(image.mode, (totalWidth, totalHeight), background)
[/code]
To:
[code]
  back = Image.new("RGBA", (totalWidth, totalHeight), background)
[/code]

and then do something like this:
[code]
  import sys

  bg = Image.open(sys.argv[1])
  image = Image.open(sys.argv[2])

  image = dropShadow(image,shadow=(0x00,0x00,0x00,0xff))
  bg.paste( image, (50,50), image )

  bg.show()
[/code]

Where the shadow color specifies an alpha transparency value.

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


Re: Rational numbers

2007-02-23 Thread casevh
On Feb 23, 10:34 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> On Feb 23, 10:39 am, Martin Manns <[EMAIL PROTECTED]> wrote:
>
> > On Fri, 23 Feb 2007 09:52:06 -0600
>
> > Larry Bates <[EMAIL PROTECTED]> wrote:
> > > I quick search of Google turned up:
>
> > >http://books.google.com/books?id=1Shx_VXS6ioC&pg=PA625&lpg=PA625&dq=p...
> > >http://calcrpnpy.sourceforge.net/clnum.html
> > >http://gmpy.sourceforge.net/
>
> > Sorry that I did not point these out initially.
>
> > + clnum seems to be slower and for speed may be compiled to wrap gmp so
> > that it is just an additional layer between python and gmp .
>
> > + gmpy is looking pretty unmaintained (dead) to me (newest update of
> > cvs 10 months ago).

I worked with Alex Martelli (gmpy's maintainer) to fix a bug found by
mensanator. With Alex's permission, I released it as gmpy 1.04a. Alex
has not updated cvs with the fix.

gmpy 1.04a compiles cleanly with the latest releases of Python and
GMP, so I consider it stable.

>
> Actually, gmpy is being maitained even if SourceForge isn't up to
> date.
>
> I got my gmpy 1.04a for Python 2.5 Windows binary from
>
> 
>
> I haven't used the rationals all that much, but been very
> happy with them when I have.
>

casevh

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


Re: Finding non ascii characters in a set of files

2007-02-23 Thread Martin v. Löwis
Tim Arnold schrieb:
> That looks much cleaner. I didn't know the 'num' from the enumerate would 
> persist so the except block could report it.

It's indeed guaranteed that the for loop index variables will keep the
value they had when the loop stopped (either through regular
termination, break, or an exception) (unlike list comprehensions, where
the variable also stays, but only as a side effect of the implementation
strategy).

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


Re: Found a product for running Python-based websites off CDROM -have anybody tried it?

2007-02-23 Thread David Wishnie
Hello,

Thank you for your input!

We've looked at XAMPP, and it has the following disadvantages compared
to Stunnix:

* it's not targeted for putting to CDs at all (it's "unzip and run apache and
   stuff"type of thing). This means it probably can't autochoose
port numbers
   for mysql and http. It has no functionality for easy stopping of webserver
   and stuff from inside a script (that allows to release media on Linux and
   OSX). It's seems not to be tested for running from read-only media. It has
   no "showing logo at startup" functionality.

* XAMPP for Linux and OSX is considered beta

* XAMPP is unsupported as a whole

* XAMPP for Linux and OSX seem not to support Tomcat and mod_python

* XAMPP for OSX won't work on OSX 10.3

* Even if one will be able to somehow create a CD with XAMPP, the database
  files and content of document root needs to be replicated for each platform.

The only advantage of XAMPP is the price. But given a time needed for
highly-skilled
enginer (with good programming skills) to spend on XAMPP to make it ready for
creating commercial CDs for Windows, Mac OSX - cost of Stunnix tool is
very attractive, and don't forget about updates and support.

-David



On 2/20/07, Don Taylor <[EMAIL PROTECTED]> wrote:
> David Wishnie wrote:
> > Hello,
> >
> > Recently I've found a product that allows to create CDs or DVDs with
> > mod_python  -based websites
> > (and CGI python of  course) so that apache-based webserver, python and
> > mod_python are run directly
> > off CD on  Windows, MacOS X  and Linux at the same time (also it seems
> > to support perl, java,
> > php and mysql + SQLite as databases).
> >
> > http://www.stunnix.com/prod/aws/overview.shtml
> >
> > Have anybody tried it? I'm considering to use it for several projects.
> >
> > Thanks,
> >   David
> >
> That is an expensive product ($789) especially considering it mostly
> consists of FOSS pieces.
>
> I found XAMPP, a FOSS, that is almost the same thing:
>
> http://portableapps.com/apps/development/xampp
>
> and this thread for getting mod_python running (scroll down a bit to the
> second post):
>
> http://www.apachefriends.org/f/viewtopic.php?t=21169&highlight=python
>
> I have not tried this yet.
>
> Don.
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding non ascii characters in a set of files

2007-02-23 Thread Tim Arnold
"Marc 'BlackJack' Rintsch" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> In <[EMAIL PROTECTED]>, Tim Arnold wrote:
>
>> Here's what I do (I need to know the line number).
>>
>> import os,sys,codecs
>> def checkfile(filename):
>> f = codecs.open(filename,encoding='ascii')
>>
>> lines = open(filename).readlines()
>> print 'Total lines: %d' % len(lines)
>> for i in range(0,len(lines)):
>> try:
>> l = f.readline()
>> except:
>> num = i+1
>> print 'problem: line %d' % num
>>
>> f.close()
>
> I see a `NameError` here.  Where does `i` come from?  And there's no need
> to read the file twice.  Untested:
>
> import os, sys, codecs
>
> def checkfile(filename):
>f = codecs.open(filename,encoding='ascii')
>
>try:
>for num, line in enumerate(f):
>pass
>except UnicodeError:
>print 'problem: line %d' % num
>
>f.close()
>
> Ciao,
> Marc 'BlackJack' Rintsch

well, I take it backthat code doesn't work, or at least it doesn't for 
my test case.
but thanks anyway, I'm sticking to my original code. the 'i' came from for i 
in range.
--Tim


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


Re: Rational numbers

2007-02-23 Thread Martin Manns
On 23 Feb 2007 12:00:10 -0800
[EMAIL PROTECTED] wrote:
> 
> I worked with Alex Martelli (gmpy's maintainer) to fix a bug found by
> mensanator. With Alex's permission, I released it as gmpy 1.04a. Alex
> has not updated cvs with the fix.
> 
> gmpy 1.04a compiles cleanly with the latest releases of Python and
> GMP, so I consider it stable.
> 
> >
> > Actually, gmpy is being maitained even if SourceForge isn't up to
> > date.
> >
> > I got my gmpy 1.04a for Python 2.5 Windows binary from
> >
> > 
> >
> > I haven't used the rationals all that much, but been very
> > happy with them when I have.
> >
> 
> casevh
> 

Thank you for all the replies.

I think that I am going to switch to gmpy.

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


Re: Who has not attended these free tutorial courses ?

2007-02-23 Thread kilian heckrodt
[EMAIL PROTECTED] wrote:

Please note that this is a math newsgroup and
not a i-post-my-favoured-conspiracy-theory newsgroup


> "President Bush ... you are under arrest" - 911 truth video by Dr
> Morgan Reynolds, Former Chief Economist under Bush
> 
> You can also save them by right clicking the
> links and saving them as flv files and download a free flv player.
> google is your best friend.
> 
> "Bush Administration Insider Says U.S. Government Behind 911.flv"
> "http://ash-v31.ash.youtube.com/get_video?video_id=HkpOsUmp-9w";  <---
> key video
> 
> "911 Truth, Scott Forbes describes power-downs in WTC.flv" "http://
> youtube-609.vo.llnwd.net/d1/04/D1/fEJmcvTzYfo.flv"
> 
> "911 Truth, Consequences of Revealing the Truth about 911.flv"
> "http://
> youtube-609.vo.llnwd.net/d1/04/D1/fEJmcvTzYfo.flv"
> 
> "U.S. Army General Says Flight 77 Did Not Hit Pentagon.flv"
> "http://lax-v8.lax.youtube.com/get_video?video_id=Zsn4JA450iA";
> 
> "911 Truth, Bush Administration Lied About Iraq 911.flv" "http://lax-
> v8.lax.youtube.com/get_video?video_id=Zsn4JA450iA"
> 
> "Bush gets caught off guard on 9/11 prior knowledge question.flv"
> "http://lax-v222.lax.youtube.com/get_video?video_id=0eH5qbrpwlM";
> 
> "Bush gets caught off guard on 911 prior knowledge question.flv"
> "http://lax-v222.lax.youtube.com/get_video?video_id=0eH5qbrpwlM";
> 
> "World Trade Center -- Controlled Demolition.flv" "http://
> v187.youtube.com/get_video?video_id=87fyJ-3o2ws"
> 
> "911 Truth, The Moles, the Patsies, State-Sponsored Terror.flv"
> "http://chi-v43.chi.youtube.com/get_video?video_id=u0K9BM9oo90";
> 
> The Answer: Why do they hate our freedoms :
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


How to build Hierarchies of dict's? (Prototypes in Python?)

2007-02-23 Thread Charles D Hixson
I'm sure I've read before about how to construct prototypes in Python, 
but I haven't been able to track it down (or figure it out).

What I basically want is a kind of class that has both class and 
instance level dict variables, such that descendant classes 
automatically create their own class and instance level dict variables.  
The idea is that if a member of this hierarchy looks up something in 
it's local dict, and doesn't find it, it then looks in the class dict, 
and if not there it looks in its ancestral dict's.  This is rather like 
what Python does at compile time, but I want to do it at run time.

I'm sure I've seen how to do it...but have no idea where, or what it was 
called, or when (probably around the time Prothon was being discussed, 
as I have the idea of prototype associated with it for no clear reason).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for contract developer(s) - where can I find them?

2007-02-23 Thread John J. Lee
[EMAIL PROTECTED] writes:

> On Feb 21, 9:51 pm, Scott SA <[EMAIL PROTECTED]> wrote:
> >
> > I've just sent a job listing to python.org and posted this message on
> > comp.lang.python,
> 
> Interesting, so [email protected] and comp.lang.python are
> _related_. I guess that means I'm the new guy on the block. Well I
> guess this joke is on me this time ... LOL!

Yes, there's a bidirectional gateway between the two -- post to one
and it shows up on the other.


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


Re: BDFL in wikipedia

2007-02-23 Thread John J. Lee
Robin Becker <[EMAIL PROTECTED]> writes:

> Carl Banks wrote:
> ..
> > Since when is Larry Wall benevolent?  He should be called the SDFL.
> >
> .
> 
> even the great leader has been referred to as the MDFL :)
[...]

By you?-)


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


Question about idiomatic use of _ and private stuff.

2007-02-23 Thread Steven W. Orr
I understand that two leading underscores in a class attribute make the 
attribute private. But I often see things that are coded up with one 
underscore. Unless I'm missing something, there's a idiom going on here.

Why do people sometimes use one leading underscore?

TIA

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


Re: Question about idiomatic use of _ and private stuff.

2007-02-23 Thread Troy Melhase
> Why do people sometimes use one leading underscore?

Many folks like to use the single leading underscore to emphasize that
the attribute isn't part of the normal way to use the class or
instance.

It's bad style in my opinion, but I'm probably in the minority.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: timeout in urllib.open()

2007-02-23 Thread John J. Lee
Steve Holden <[EMAIL PROTECTED]> writes:
[...]
> This has recently been discussed on python-dev. It's likely that
> certain libraries will acquire a timeout keyword argument in the next
> release, but only if someone is concerned enough to develop the
> appropriate patches - the principle appears to be accepted.

I didn't read the recent python-dev thread, but ISTM this has been
true since the socket timeout feature was added (Python 2.3?).
Apparently so far nobody wanted it enough to actually implement it.


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


Re: timeout in urllib.open()

2007-02-23 Thread John J. Lee
Paul Rubin  writes:

> Stefan Palme <[EMAIL PROTECTED]> writes:
> > is there a way to modify the time a call of
> > 
> >   urllib.open(...)
> > 
> > waits for an answer from the other side? Have a tool which
> > automatically checks a list of websites for certain content. The
> > tool "hangs" when one of the contacted websites behaves badly and
> > "never" answers...
> 
> Other than by using socket timeouts, at least in Un*x, you can also
> use signal.alarm.  You can only have one OS-provided alarm pending at
> a time, so if you want multiple overlapping timeouts you have to
> schedule them yourself with a single alarm.

Note that neither of these is guaranteed to time out urllib.open(),
though usually they will.

Another way to solve the underlying problem is not to try to time out
the network operation(s) at all, but to use threads or non-blocking
sockets (e.g. using Twisted).


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


Re: Found a product for running Python-based websites off CDROM -have anybody tried it?

2007-02-23 Thread Paul Boddie
David Wishnie wrote:
>
> We've looked at XAMPP, and it has the following disadvantages compared
> to Stunnix:

I've only read the Stunnix Web site, and I've only seen XAMPP in
passing. However...

> * it's not targeted for putting to CDs at all (it's "unzip and run apache and
>stuff"type of thing). This means it probably can't autochoose port 
> numbers
>for mysql and http. It has no functionality for easy stopping of webserver
>and stuff from inside a script (that allows to release media on Linux and
>OSX). It's seems not to be tested for running from read-only media. It has
>no "showing logo at startup" functionality.

I guess XAMPP isn't what you're looking for. But then, if it's just an
issue of having Apache in a filesystem on a CD, the distance between
convenient installation/unpacking of an Apache instance onto a normal
disk and the preparation of a ready-to-run instance isn't that great:
the two activities overlap, with the former perhaps providing the
means to enable the latter. I do wonder how database writes are
handled, though, or are bundled databases read-only?

> * XAMPP for Linux and OSX is considered beta

It shouldn't be too hard to work with anything UNIX-like. CD-ROMs are
just read-only filesystems, and we're not even talking about live CD
magic here.

> * XAMPP is unsupported as a whole
>
> * XAMPP for Linux and OSX seem not to support Tomcat and mod_python

Yes, but do we really care about Tomcat? ;-)

> * XAMPP for OSX won't work on OSX 10.3
>
> * Even if one will be able to somehow create a CD with XAMPP, the database
>   files and content of document root needs to be replicated for each platform.

Doesn't everything understand ISO-9660 plus various extensions these
days?

> The only advantage of XAMPP is the price. But given a time needed for
> highly-skilled enginer (with good programming skills) to spend on XAMPP
> to make it ready for creating commercial CDs for Windows, Mac OSX -
> cost of Stunnix tool is very attractive, and don't forget about updates and 
> support.

It's up to everyone to decide themselves how they spend their money,
but remember that software like Apache doesn't require rocket science
to set up in arbitrary locations, and database systems aren't that
difficult to install in various places either. Perhaps the most
difficult bit might be binary compatibility, and there'd be some
discipline required in making sure the library dependencies could be
satisfied on the target systems. Either that or you could give up and
distribute a virtual machine image - there was a Python Web
development image publicised a while back, in fact.

Paul

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


Having multiple instances of a single application start a single instance of another one

2007-02-23 Thread buffinator
I have two applications that should work together, let's call them A and B.

The first time A starts, it should open a B process and start 
communicating with it. All other times an A instance starts it should 
simply talk with the B that already is open.

The problem here is, if I start say 40 A applications at once... how do 
I check if a B is open "fast enough" so that the other A's (not the 
first one) won't spawn new B's?

Im programming this in windows and am currently using the horrible 
solution in A

if not win32gui.FindWindow(None, "Name of B"):
spawn_B_here()

This only works well if there is a small time between the A's started 
first...

What would the best solution for my problem be?

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


Re: Rational numbers

2007-02-23 Thread [EMAIL PROTECTED]
On Feb 23, 2:00 pm, [EMAIL PROTECTED] wrote:
> On Feb 23, 10:34 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
>
>
>
>
>
> > On Feb 23, 10:39 am, Martin Manns <[EMAIL PROTECTED]> wrote:
>
> > > On Fri, 23 Feb 2007 09:52:06 -0600
>
> > > Larry Bates <[EMAIL PROTECTED]> wrote:
> > > > I quick search of Google turned up:
>
> > > >http://books.google.com/books?id=1Shx_VXS6ioC&pg=PA625&lpg=PA625&dq=p...
> > > >http://calcrpnpy.sourceforge.net/clnum.html
> > > >http://gmpy.sourceforge.net/
>
> > > Sorry that I did not point these out initially.
>
> > > + clnum seems to be slower and for speed may be compiled to wrap gmp so
> > > that it is just an additional layer between python and gmp .
>
> > > + gmpy is looking pretty unmaintained (dead) to me (newest update of
> > > cvs 10 months ago).
>
> I worked with Alex Martelli (gmpy's maintainer) to fix a bug found by
> mensanator. With Alex's permission, I released it as gmpy 1.04a. Alex
> has not updated cvs with the fix.
>
> gmpy 1.04a compiles cleanly with the latest releases of Python and
> GMP, so I consider it stable.

Am I hallucinating? Didn't I see at least some version
of gmpy for Python 2.5 on SourceForge awhile back?
I distinctly remember thinking that I don't have to
direct people to your site, but SourceForge is not
showing anything beyond vesion 1.01 for Python 2.4.


>
> > Actually, gmpy is being maitained even if SourceForge isn't up to
> > date.
>
> > I got my gmpy 1.04a for Python 2.5 Windows binary from
>
> > 
>
> > I haven't used the rationals all that much, but been very
> > happy with them when I have.
>
> casevh

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


Re: Question about idiomatic use of _ and private stuff.

2007-02-23 Thread James Stroud
Troy Melhase wrote:
>> Why do people sometimes use one leading underscore?
> 
> 
> Many folks like to use the single leading underscore to emphasize that
> the attribute isn't part of the normal way to use the class or
> instance.
> 
> It's bad style in my opinion, but I'm probably in the minority.

I've increasingly found that leading underscores are unnecessary as well 
if not using a "magic" attribute with the bounding double underscores.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Having multiple instances of a single application start a single instance of another one

2007-02-23 Thread Troy Melhase
> The first time A starts, it should open a B process and start
> communicating with it. All other times an A instance starts it should
> simply talk with the B that already is open.

B should write its process id to a location known by both
applications.  When A starts, it should read that PID from the file
and attempt to communicate with the process having that PID.

When B starts, it should also check for the file.  If it's found and
if the PID in it is present in the process table, then B should exit.
Otherwise, it should start normally and write its own PID to the file.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: IbPy 0.7.0-9.00 - Interactive Brokers Python API

2007-02-23 Thread vj
Cool. Why is python 2.5 required, will it not work with python 2.4?

VJ

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


Re: Question about idiomatic use of _ and private stuff.

2007-02-23 Thread Chris Mellon
On 2/23/07, James Stroud <[EMAIL PROTECTED]> wrote:
> Troy Melhase wrote:
> >> Why do people sometimes use one leading underscore?
> >
> >
> > Many folks like to use the single leading underscore to emphasize that
> > the attribute isn't part of the normal way to use the class or
> > instance.
> >
> > It's bad style in my opinion, but I'm probably in the minority.
>
> I've increasingly found that leading underscores are unnecessary as well
> if not using a "magic" attribute with the bounding double underscores.
> --

I use the single underscore a lot and should use it more. It indicates
something that you shouldn't look at unless you understand and are
willing to bind yourself to the class internals.

For example, I have a network interface that buffers data as it's
being parsed. The internal buffer is a list named _buffer, and messing
with the buffer is a good way to break the parser.

There's an exterior interface, which is a guaranteed consistent buffer
called "message", but (even for me, the author) it's easy to get
confused about which one is the safe, public attribute and which one
is private. The underscore disambiguates.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Having multiple instances of a single application start a single instance of another one

2007-02-23 Thread buffinator
Troy Melhase wrote:
>> The first time A starts, it should open a B process and start
>> communicating with it. All other times an A instance starts it should
>> simply talk with the B that already is open.
> 
> B should write its process id to a location known by both
> applications.  When A starts, it should read that PID from the file
> and attempt to communicate with the process having that PID.
> 
> When B starts, it should also check for the file.  If it's found and
> if the PID in it is present in the process table, then B should exit.
> Otherwise, it should start normally and write its own PID to the file.

Three very simple questions then.

1. How do I find out a running applications process ID

2. How do I check if a process ID is bound to a running application.

3. There won't be any issues with different applications trying to read 
and write the same file doing this?

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


Re: ANN: IbPy 0.7.0-9.00 - Interactive Brokers Python API

2007-02-23 Thread Troy Melhase
On 23 Feb 2007 14:36:24 -0800, vj <[EMAIL PROTECTED]> wrote:
> Cool. Why is python 2.5 required, will it not work with python 2.4?

Short answer:  because java2python produces python 2.5 syntax.

Long answer:

I wrote java2python specifically to translate the IB reference code.
That reference code makes heavy use of the java ternary operator, and
I wanted the most direct representation of that -- which is the
conditional expression provided in python 2.5.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Rational numbers

2007-02-23 Thread casevh

> Am I hallucinating? Didn't I see at least some version
> of gmpy for Python 2.5 on SourceForge awhile back?
> I distinctly remember thinking that I don't have to
> direct people to your site, but SourceForge is not
> showing anything beyond vesion 1.01 for Python 2.4.

Alex released versions 1.02 and 1.03 as CVS updates only. I think he
may have made an announcement that 1.02 included alpha support for
Python 2.5. 1.04a is 1.03 with one additional fix. I don't think there
has been an official release, though.

casevh

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


Re: Having multiple instances of a single application start a single instance of another one

2007-02-23 Thread Troy Melhase
> Three very simple questions then.
>
> 1. How do I find out a running applications process ID

import os
mypid = os.getpid()

> 2. How do I check if a process ID is bound to a running application.

this is os-specific.  i'm sure there's a windows api provided for it.

> 3. There won't be any issues with different applications trying to read
> and write the same file doing this?

shouldn't be any problem:  only the first app started will write to the file.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regex Speed

2007-02-23 Thread garrickp
On Feb 21, 10:34 am, [EMAIL PROTECTED] wrote:
> On Feb 20, 6:14 pm, Pop User <[EMAIL PROTECTED]> wrote:
> >http://swtch.com/~rsc/regexp/regexp1.html

Going back a bit on a tangent, the author of this citation states that
any regex can be expressed as a  DFA machine. However, while
investigating this more I appear to have found one example of a regex
which breaks this assumption.

"ab+c|abd"

Am I correct? Can you think of a deterministic method of computing
this expression? It would be easier with a NFA machine, but given that
the Python method of computing RE's involves pre-compiling a re
object, optimizing the matching engine would make the most sense to
me.

Here's what I have so far:

class State(object):
def __init__(self):
self.nextState = {}
self.nextStateKeys = []
self.prevState = None
self.isMatchState = True
def setNextState(self, chars, iNextState):
self.nextState[chars] = iNextState
self.nextStateKeys = self.nextState.keys()
self.isMatchState = False
def setPrevState(self, iPrevState):
self.prevState = iPrevState
def moveToNextState(self, testChar):
if testChar in self.nextStateKeys:
return self.nextState[testChar]
else:
return None

class CompiledRegex(object):
def __init__(self, startState):
self.startState = startState
def match(self, matchStr):
match_set = []
currentStates = [self.startState]
nextStates = [self.startState]
for character in matchStr:
for state in currentStates:
nextState = state.moveToNextState(character)
if nextState is not None:
nextStates.append(nextState)
if nextState.isMatchState:
print "Match!"
return
currentStates = nextStates
nextStates = [self.startState]
print "No Match!"

def compile(regexStr):
startState = State()
currentState = startState
backRefState = None
lastChar = ""
for character in regexStr:
if character == "+":
currentState.setNextState(lastChar, currentState)
elif character == "|":
currentState = startState
elif character == "?":
backRefState = currentState.prevState
elif character == "(":
# Implement "("
pass
elif character == ")":
# Implement ")"
pass
elif character == "*":
currentState = currentState.prevState
currentState.setNextState(lastChar, currentState)
else:
testRepeatState = currentState.moveToNextState(character)
if testRepeatState is None:
newState = State()
newState.setPrevState(currentState)
currentState.setNextState(character, newState)
if backRefState is not None:
backRefState.setNextState(character, newState)
backRefState = None
currentState = newState
else:
currentState = testRepeatState
lastChar = character
return CompiledRegex(startState)

>>> a = compile("ab+c")
>>> a.match("abc")
Match!
>>> a.match("abbc")
Match!
>>> a.match("ac")
No Match!
>>> a = compile("ab+c|abd")
>>> a.match("abc")
Match!
>>> a.match("abbc")
Match!
>>> a.match("ac")
No Match!
>>> a.match("abd")
Match!
>>> a.match("abbd")
Match!
>>>

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


Re: Rational numbers

2007-02-23 Thread Gabriel Genellina
En Fri, 23 Feb 2007 12:35:19 -0300, Martin Manns <[EMAIL PROTECTED]> escribió:

> I am starting to use rationals and since I found no batteries included,
> I tried out the mxNumber package.
>
> However, I get strange warnings on comparison operations
> (which however seem to yield correct results):

mx.Number.Rational is horribly broken. They break this rule:

a==b => hash(a)==hash(b)

so they can'b be used as dictionary keys, by example.
Try the other packages suggested. I've used clnum without problems.

-- 
Gabriel Genellina

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


Re: Rational numbers

2007-02-23 Thread aleaxit
On Feb 23, 12:00 pm, [EMAIL PROTECTED] wrote:
   ...
> > > + gmpy is looking pretty unmaintained (dead) to me (newest update of
> > > cvs 10 months ago).
>
> I worked withAlex Martelli(gmpy's maintainer) to fix a bug found by
> mensanator. With Alex's permission, I released it as gmpy 1.04a. Alex
> has not updated cvs with the fix.

Heh, I see why one might get that impression -- I'm in the process of
moving gmpy from sourceforge (where I find it harder and harder, and
ever more problematic, to work) to code.google.com 's new hosting
facility -- gmpy 1.02 prerelease (more updated than that "1.04a", and
particularly including your fix, Case) is already available at
http://code.google.com/p/gmpy/ but I have made no official
announcement yet (partly because what's available is yet limited:
sources, and binaries for Python 2.3, 2.4 and 2.5 but only for MacOSX
10.4 on Macs with intel processors)... building binaries for Windows
(not having a Windows machine or development system) or Universal
binaries for the Mac (due to problems building Universal versions of
the underlying GMP in its latest, 4.2 incarnation... I'm running out
of PPC-based Macs, and have none left with MaxOSX 10.3...) is much
more problematic for me.

To call this (Google Code) release 1.02, with a "1.04" (?) out from
another source, may be confusing, but I'd rather not "force" the
number upwards

I do have one new co-owner on the Google Code "version" of gmpy (Chip
Turner, once author of a similar GMP wrapper for perl, now a Python
convert and a colleague of mine) but I suspect that won't make the
building of Windows (and Universal Mac) binaries much easier.  If
anybody who has easy access to Microsoft's MSVC++.NET (and is willing
to try building GMP 4.2 with/for it), or a PPC Mac with XCode
installed (possibly with MacOSX 10.3...), wants to volunteer to build
"the missing binaries" for the platforms that the current owners of
gmpy can't easily support, we could complete, test and release the
definitive 1.02, and move on with the development (I could get
enthusiastic about this again, if I could develop just the sources,
and the binaries for the one architecture I really use -- Macs w/intel
-- rather than strive each time with binaries for architectures that
are quite a pain for me...!-).

Anybody who's interested in helping out is welcome to mail me and/or
use the "wiki" and "issues" entry of the Google Code gmpy site...


Thanks,

Alex

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


Re: Rational numbers

2007-02-23 Thread aleaxit
On Feb 23, 2:52 pm, [EMAIL PROTECTED] wrote:
> > Am I hallucinating? Didn't I see at least some version
> > of gmpy for Python 2.5 on SourceForge awhile back?
> > I distinctly remember thinking that I don't have to
> > direct people to your site, but SourceForge is not
> > showing anything beyond vesion 1.01 for Python 2.4.
>
> Alex released versions 1.02 and 1.03 as CVS updates only. I think he
> may have made an announcement that 1.02 included alpha support for
> Python 2.5. 1.04a is 1.03 with one additional fix. I don't think there
> has been an official release, though.

Right: apparently sourceforce doesn't want me to do "releases" any
more (quite apart from the utter mess that doing a "release" on
sourceforce always was and still is), though I can still update the
cvs repository -- that's part of why I'm moving to Google Code
hosting.


Alex

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


Re: Having multiple instances of a single application start a single instance of another one

2007-02-23 Thread Jerry Hill
On 2/23/07, buffinator <[EMAIL PROTECTED]> wrote:
> 2. How do I check if a process ID is bound to a running application.

Under windows, this should work:
>>> import win32process
>>> running_pids = win32process.EnumProcesses()
>>> running_pids
(0, 4, 1048, 1496, 1656, 1836, 1896, 756, 988, 1712, 220, 1156, 240,
1600, 1932, 428, 1100, 1880, 1152, 1444, 296, 624, 536, 412, 1812,
3384, 2064, 2164, 2344, 2516, 2816, 2992, 3412, 3628, 2836, 3168,
3420, 3408, 816, 1676, 504, 3244, 2404, 452, 1624, 3924, 2660, 3736,
3608, 1304)

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


Re: How to build Hierarchies of dict's? (Prototypes in Python?)

2007-02-23 Thread Larry Bates
Charles D Hixson wrote:
> I'm sure I've read before about how to construct prototypes in Python,
> but I haven't been able to track it down (or figure it out).
> 
> What I basically want is a kind of class that has both class and
> instance level dict variables, such that descendant classes
> automatically create their own class and instance level dict variables. 
> The idea is that if a member of this hierarchy looks up something in
> it's local dict, and doesn't find it, it then looks in the class dict,
> and if not there it looks in its ancestral dict's.  This is rather like
> what Python does at compile time, but I want to do it at run time.
> 
> I'm sure I've seen how to do it...but have no idea where, or what it was
> called, or when (probably around the time Prothon was being discussed,
> as I have the idea of prototype associated with it for no clear reason).

What you describe is exactly how Zope works so you might want to spend
some time looking at it.

http://www.zope.org

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


Re: Rational numbers

2007-02-23 Thread casevh
On Feb 23, 3:27 pm, [EMAIL PROTECTED] wrote:
> On Feb 23, 12:00 pm, [EMAIL PROTECTED] wrote:
>...
>
> > > > + gmpy is looking pretty unmaintained (dead) to me (newest update of
> > > > cvs 10 months ago).
>
> > I worked withAlex Martelli(gmpy's maintainer) to fix a bug found by
> > mensanator. With Alex's permission, I released it as gmpy 1.04a. Alex
> > has not updated cvs with the fix.
>
> Heh, I see why one might get that impression -- I'm in the process of
> moving gmpy from sourceforge (where I find it harder and harder, and
> ever more problematic, to work) to code.google.com 's new hosting
> facility -- gmpy 1.02 prerelease (more updated than that "1.04a", and
> particularly including your fix, Case) is already available 
> athttp://code.google.com/p/gmpy/but I have made no official
> announcement yet (partly because what's available is yet limited:
> sources, and binaries for Python 2.3, 2.4 and 2.5 but only for MacOSX
> 10.4 on Macs with intel processors)... building binaries for Windows
> (not having a Windows machine or development system) or Universal
> binaries for the Mac (due to problems building Universal versions of
> the underlying GMP in its latest, 4.2 incarnation... I'm running out
> of PPC-based Macs, and have none left with MaxOSX 10.3...) is much
> more problematic for me.
>
> To call this (Google Code) release 1.02, with a "1.04" (?) out from
> another source, may be confusing, but I'd rather not "force" the
> number upwards
>
> I do have one new co-owner on the Google Code "version" of gmpy (Chip
> Turner, once author of a similar GMP wrapper for perl, now a Python
> convert and a colleague of mine) but I suspect that won't make the
> building of Windows (and Universal Mac) binaries much easier.  If
> anybody who has easy access to Microsoft's MSVC++.NET (and is willing
> to try building GMP 4.2 with/for it), or a PPC Mac with XCode
> installed (possibly with MacOSX 10.3...), wants to volunteer to build
> "the missing binaries" for the platforms that the current owners of
> gmpy can't easily support, we could complete, test and release the
> definitive 1.02, and move on with the development (I could get
> enthusiastic about this again, if I could develop just the sources,
> and the binaries for the one architecture I really use -- Macs w/intel
> -- rather than strive each time with binaries for architectures that
> are quite a pain for me...!-).
>
> Anybody who's interested in helping out is welcome to mail me and/or
> use the "wiki" and "issues" entry of the Google Code gmpy site...
>
> Thanks,
>
> Alex

I can keep building gmpy for Windows. I actually use MINGW since
getting GMP compiled under MSVC is "challanging". I should be able to
build new binaries for Windows this weekend. And I would be happy to
point everyone to a real release.

casevh

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


Re: How to build Hierarchies of dict's? (Prototypes in Python?)

2007-02-23 Thread Gabriel Genellina
En Fri, 23 Feb 2007 17:53:59 -0300, Charles D Hixson  
<[EMAIL PROTECTED]> escribió:

> I'm sure I've read before about how to construct prototypes in Python,
> but I haven't been able to track it down (or figure it out).
>
> What I basically want is a kind of class that has both class and
> instance level dict variables, such that descendant classes
> automatically create their own class and instance level dict variables.
> The idea is that if a member of this hierarchy looks up something in
> it's local dict, and doesn't find it, it then looks in the class dict,
> and if not there it looks in its ancestral dict's.  This is rather like
> what Python does at compile time, but I want to do it at run time.

Well, the only thing on this regard that Python does at compile time, is  
to determine whether a variable is local or not. Actual name lookup is  
done at runtime.
You can use instances and classes as dictionaries they way you describe.  
Use getattr/setattr/hasattr/delattr:

py> class A:
...   x = 0
...   y = 1
...
py> class B(A):
...   y = 2
...
py> a = A()
py> setattr(a, 'y', 3) # same as a.y = 3 but 'y' may be a variable
py> print 'a=',vars(a)
a= {'y': 3}
py>
py> b = B()
py> print 'b=',vars(b)
b= {}
py> setattr(b,'z',1000)
py> print 'b=',vars(b)
b= {'z': 1000}
py> print 'x?', hasattr(b,'x')
x? True
py> print 'w?', hasattr(b,'w')
w? False


-- 
Gabriel Genellina

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


Re: Having multiple instances of a single application start a single instance of another one

2007-02-23 Thread Larry Bates
buffinator wrote:
> I have two applications that should work together, let's call them A and B.
> 
> The first time A starts, it should open a B process and start
> communicating with it. All other times an A instance starts it should
> simply talk with the B that already is open.
> 
> The problem here is, if I start say 40 A applications at once... how do
> I check if a B is open "fast enough" so that the other A's (not the
> first one) won't spawn new B's?
> 
> Im programming this in windows and am currently using the horrible
> solution in A
> 
> if not win32gui.FindWindow(None, "Name of B"):
> spawn_B_here()
> 
> This only works well if there is a small time between the A's started
> first...
> 
> What would the best solution for my problem be?
> 
> /buffis

Others have answered your specific question on the forum, I thought
I would make a suggestion.  You should consider writing application B
as a Windows Service that gets started once (maybe even auto start
when the machine boots) and runs forever in the background.  Then have
all your A's bind to it and communication (via sockets, pipes, filesystem,
database, ...).  That way your A's won't have the problem you describe.

Just a suggestion.

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


Re: Possible to set cpython heap size?

2007-02-23 Thread Andrew MacIntyre
Chris Mellon wrote:
> On 22 Feb 2007 11:28:52 -0800, Andy Watson <[EMAIL PROTECTED]> wrote:
>> On Feb 22, 10:53 am, a bunch of folks wrote:
>>
>>> Memory is basically free.
>> This is true if you are simply scanning a file into memory.  However,
>> I'm storing the contents in some in-memory data structures and doing
>> some data manipulation.   This is my speculation:
>>
>> Several small objects per scanned line get allocated, and then
>> unreferenced.  If the heap is relatively small, GC has to do some work
>> in order to make space for subsequent scan results.  At some point, it
>> realises it cannot keep up and has to extend the heap.  At this point,
>> VM and physical memory is committed, since it needs to be used.  And
>> this keeps going on.  At some point, GC will take a good deal of time
>> to compact the heap, since I and loading in so much data and creating
>> a lot of smaller objects.
>>
>> If I could have a heap that is larger and does not need to be
>> dynamically extended, then the Python GC could work more efficiently.
>>
> 
> I haven't even looked at Python memory management internals since 2.3,
> and not in detail then, so I'm sure someone will correct me in the
> case that I am wrong.
> 
> However, I believe that this is almost exactly how CPython GC does not
> work. CPython is refcounted with a generational GC for cycle
> detection. There's a memory pool that is used for object allocation
> (more than one, I think, for different types of objects) and those can
> be extended but they are not, to my knowledge, compacted.
> 
> If you're creating the same small objects for each scanned lines, and
> especially if they are tuples or new-style objects with __slots__,
> then the memory use for those objects should be more or less constant.
> Your memory growth is probably related to the information you're
> saving, not to your scanned objects, and since those are long-lived
> objects I simple don't see how heap pre-allocation could be helpful
> there.

Python's internal memory management is split:
- allocations up to 256 bytes (the majority of objects) are handled by
a custom allocator, which uses 256kB arenas malloc()ed from the OS on
demand.  With 2.5 some additional work was done to allow returning
completely empty arenas to the OS; 2.3 and 2.4 don't return arenas at
all.
- all allocations over 256 bytes, including container objects that are
extended beyond 256 bytes, are made by malloc().

I can't recall off-hand whether the free-list structures for ints (and
floats?) use the Python allocator or direct malloc(); as the free-lists
don't release any entries, I suspect not.

The maximum allocation size and arena size used by the Python allocator
are hard-coded for algorithmic and performance reasons, and cannot be
practically be changed, especially at runtime.  No active compaction
takes place in arenas, even with GC.  The only time object data is
relocated between arenas is when an object is resized.

If Andy Watson is creating loads of objects that aren't being managed
by Python's allocator (by being larger than 256 bytes, or in a type 
free-list), then the platform malloc() behaviour applies.  Some platform
allocators can be tuned via environment variables and the like, in which
case review of the platform documentation is indicated.

Some platform allocators are notorious for poor behaviour in certain 
circumstances, and coalescing blocks while deallocating is one 
particularly nasty problem for code that creates and destroys lots
of small variably sized objects.

-- 
-
Andrew I MacIntyre "These thoughts are mine alone..."
E-mail: [EMAIL PROTECTED]  (pref) | Snail: PO Box 370
[EMAIL PROTECTED] (alt) |Belconnen ACT 2616
Web:http://www.andymac.org/   |Australia
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about idiomatic use of _ and private stuff.

2007-02-23 Thread Gabriel Genellina
En Fri, 23 Feb 2007 13:12:20 -0300, Steven W. Orr <[EMAIL PROTECTED]>  
escribió:

> I understand that two leading underscores in a class attribute make the
> attribute private. But I often see things that are coded up with one
> underscore. Unless I'm missing something, there's a idiom going on here.
>
> Why do people sometimes use one leading underscore?

Just a single leading underscore means "not for public usage".
Double leading underscore (without trailing underscores), means that  
Python will "mangle" the name in an attempt to make the name unique along  
the class hierarchy (so two classes in the same hierarchy may use the same  
attribute name without conflicting).
Double leading and trailing underscores are used by the Python interpreter  
itself.

__names have some pitfalls so better avoid them except on the specific use  
case for which they were designed.  
http://docs.python.org/ref/atom-identifiers.html

-- 
Gabriel Genellina

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


  1   2   >