Re: Integer division

2007-06-07 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Dan Bishop
wrote:

> On Jun 7, 8:30 pm, Some Other Guy <[EMAIL PROTECTED]> wrote:
>> Since this just involves doubling you can avoid multiplying altogether
>> and just use this:
>>
>> def rounddiv(a,b):
>>   return int((a+a+b)/(b+b))
>>
>> That's 3 integer adds and 1 integer divide.  The int() cast is just
>> there is case somebody passes in floats for a or b; if you know you're
>> only going to have integer arguments you don't need it.
> 
> The // operator was added to the language for a reason.  I'm surprised
> at how few Pythonistas are using it six years later.

It would just document intent here because it still gives `float` results
if used with at least one `float` as operands:

In [1]: 10.0 // 2
Out[1]: 5.0

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


Re: Bragging about Python

2007-06-07 Thread Szabolcs Nagy

Steve Howell wrote:
> --- Georg Brandl <[EMAIL PROTECTED]> wrote:
> > >>
> > >> 15 small programs here:
> > >>
> > >> http://wiki.python.org/moin/SimplePrograms
> > >>
> > >
> > > IMHO a few python goodies are missing there.
> >
> > "It's a Wiki." ;)
> >
>
> Yes indeed.  Please feel free to add to the page, or
> make your own fork.  See link above.

the title of a program shouldn't be part of the code (or it should at
least start with #)
sorry i'm too lazy now to fix it, but imho it needs nicer layout to be
used as 'bragging about python' site

btw nice idea
a good example worth a 100 pages of documentation

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


Re: read xml file from compressed file using gzip

2007-06-07 Thread Stefan Behnel
flebber wrote:
> I was working at creating a simple program that would read the content
> of a playlist file( in this case *.k3b") and write it out . the
> compressed "*.k3b" file has two file and the one I was trying to read
> was maindata.xml.

Consider using lxml. It reads in gzip compressed XML files transparently and
provides loads of other nice XML goodies.

http://codespeak.net/lxml/dev/

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


Re: How Can I Increase the Speed of a Large Number of Date Conversions

2007-06-07 Thread Josiah Carlson
Some Other Guy wrote:
> vdicarlo wrote:
>> I am a programming amateur and a Python newbie who needs to convert
>> about 100,000,000 strings of the form "1999-12-30" into ordinal dates
>> for sorting, comparison, and calculations. Though my script does a ton
>> of heavy calculational lifting (for which numpy and psyco are a
>> blessing) besides converting dates, it still seems to like to linger
>> in the datetime and time libraries.  (Maybe there's a hot module in
>> there with a cute little function and an impressive set of
>> attributes.)
> ...
>> dateTuple = time.strptime("2005-12-19", '%Y-%m-%d')
>> dateTuple = dateTuple[:3]
>> date = datetime.date(dateTuple[0], dateTuple[1],
>> dateTuple[2])
>> ratingDateOrd = date.toordinal()
> 
> There's nothing terribly wrong with that, although strptime() is overkill
> if you already know the date format.  You could get the date like this:
> 
>date = apply(datetime.date, map(int, "2005-12-19".split('-')))
> 
> But, more importantly... 100,000,000 individual dates would cover 274000
> years!  Do you really need that much??  You could just precompute a
> dictionary that maps a date string to the ordinal for the last 50 years
> or so. That's only 18250 entries, and can be computed in less than a second.
> Lookups after that will be near instantaneous:
> 
> 
>  import datetime
> 
>  days = 365*50 # about 50 years worth
>  dateToOrd = {} # dict. of date string to ordinal
...

Then there's the argument of "why bother using real dates?"  I mean, all 
that is necessary is a mapping of date -> number for sorting.  Who needs 
accuracy?

for date in inp:
 y, m, d = map(int, date.split('-'))
 ordinal = (y-1990)*372 + (m-1)*31 + d-1

Depending on the allowable range of years, one could perhaps adjust the 
1990 up, and get the range of date ordinals down to about 12 bits (if 
one packs netflix data properly, you can get everything in memory). 
With a bit of psyco, the above is pretty speedy.

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


Re: Integer division

2007-06-07 Thread Terry Reedy

"Some Other Guy" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| [EMAIL PROTECTED] wrote:
|
| > Hello all,
| >  I have two integers and I want to divide one by another, and want to
| > get an integer result which is the higher side whenever the result is
| > a fraction.
| >  3/2 => 1 # Usual behavior
| >  some_func(3, 2) => 2 # Wanted
|
| Are you trying to accomplish int((a/b) + 0.5), but cheaply?

No, the OP wanted 'ceiling' division rather than 'floor' division.
In other words, always round up instead of down.

| If so, consider that that is the same as (a/b) + (b/2b),
| which is (2a/2b) + (b/2b), which is (2a+b)/2b.

This is nice for rounded division.

tjr



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


read xml file from compressed file using gzip

2007-06-07 Thread flebber
I was working at creating a simple program that would read the content
of a playlist file( in this case *.k3b") and write it out . the
compressed "*.k3b" file has two file and the one I was trying to read
was maindata.xml . I cannot however seem to use the gzip module
correctly. Have tried the program 2 ways for no success, any ideas
would be appreciated.

Attempt 1

#!/usr/bin/python

import os
import gzip
playlist_file = open('/home/flebber/oddalt.k3b')
class GzipFile([playlist_file[decompress[9, 'rb']]]);

os.system(open("/home/flebber/tmp/maindata.xml"));

for line in maindata.xml:
print line

playlist_file.close()

Attempt 2 - largely just trying to get gzip to work

#!/usr/bin/python

import gzip
fileObj = Gzipfile("/home/flebber/oddalt.k3b", 'rb');
fileContent = fileObj.read()
for line in filecontent:
print line

fileObj.close()

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


have a look at my blog site for asp.net .. there is microsoft contest also ( u can win so much)

2007-06-07 Thread justpratik
hi please a have a look at my site http://justpratik.blogspot.com
and there's link for contest so
hurry before 15th june

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


have a look at my blog site for asp.net .. there is microsoft contest also ( u can win so much)have a look at my blog site for asp.net .. there is microsoft contest also ( u can win so much)

2007-06-07 Thread justpratik
hi please a have a look at my site http://justpratik.blogspot.com
and there's link for contest so
hurry before 15th june

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


compiling python and calling it from C/C++

2007-06-07 Thread Russ
Is it possible to compile python code into a library (on unix), then
link to it and call it from C/C++? If so, where can I learn how.
Thanks.

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


Re: How Can I Increase the Speed of a Large Number of Date Conversions

2007-06-07 Thread Larry Bates
James T. Dennis wrote:
> Some Other Guy <[EMAIL PROTECTED]> wrote:
>> vdicarlo wrote:
>>> I am a programming amateur and a Python newbie who needs to convert
>>> about 100,000,000 strings of the form "1999-12-30" into ordinal dates
>>> for sorting, comparison, and calculations. Though my script does a ton
>>> of heavy calculational lifting (for which numpy and psyco are a
>>> blessing) besides converting dates, it still seems to like to linger
>>> in the datetime and time libraries.  (Maybe there's a hot module in
>>> there with a cute little function and an impressive set of
>>> attributes.)
>> ...
>>> dateTuple = time.strptime("2005-12-19", '%Y-%m-%d')
>>> dateTuple = dateTuple[:3]
>>> date = datetime.date(dateTuple[0], dateTuple[1],
>>> dateTuple[2])
>>> ratingDateOrd = date.toordinal()
> 
>> There's nothing terribly wrong with that, although strptime() is overkill
>> if you already know the date format.  You could get the date like this:
> 
>>   date = apply(datetime.date, map(int, "2005-12-19".split('-')))
> 
>> But, more importantly... 100,000,000 individual dates would cover 274000
>> years!  Do you really need that much??  You could just precompute a
>> dictionary that maps a date string to the ordinal for the last 50 years
>> or so. That's only 18250 entries, and can be computed in less than a second.
>> Lookups after that will be near instantaneous:
> 
>  For that matter why not memoize the results of each conversion
>  (toss it in a dictionary and precede each conversion with a
>  check like: if this_date in datecache: return datecache[this_date]
>  else: ret=convert(this_date); datecache[this_date]=ret; return ret)
> 
>  (If you don't believe that will help, consider that a memo-ized
>  implementation of a recursive Fibonacci function runs about as quickly
>  as iterative approach).
> 
> 
Even better do something like (not tested):

try: dateord=datedict[cdate]
except KeyError:
dateord=datetime.date(*[int(x) for x in "2005-12-19".split('-'))
datedict[cdate]=dateord


hat way you build the cache on the fly and there is no penalty if
lookup key is already in the cache.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Integer division

2007-06-07 Thread Dan Bishop
On Jun 7, 8:30 pm, Some Other Guy <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > Hello all,
> >  I have two integers and I want to divide one by another, and want to
> > get an integer result which is the higher side whenever the result is
> > a fraction.
> >  3/2 => 1 # Usual behavior
> >  some_func(3, 2) => 2 # Wanted
>
> Are you trying to accomplish int((a/b) + 0.5), but cheaply?
>
> If so, consider that that is the same as (a/b) + (b/2b),
> which is (2a/2b) + (b/2b), which is (2a+b)/2b.
>
> Since this just involves doubling you can avoid multiplying altogether
> and just use this:
>
> def rounddiv(a,b):
>   return int((a+a+b)/(b+b))
>
> That's 3 integer adds and 1 integer divide.  The int() cast is just
> there is case somebody passes in floats for a or b; if you know you're
> only going to have integer arguments you don't need it.

The // operator was added to the language for a reason.  I'm surprised
at how few Pythonistas are using it six years later.

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


mysqlimport error

2007-06-07 Thread moishyyehuda
whey when I execute this statment
cursor.execute("""mysqlimport merchandise 1.txt""")
I get this error
ProgrammingError: (1064, "You have an error in your SQL syntax. Check
the manual that corresponds to your MySQL server version for the right
syntax to use near 'mysqlimport merchandise 1.txt' at line 1")
  args = (1064, "You have an error in your SQL syntax. Check
the...se near 'mysqlimport merchandise 1.txt' at line 1")

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


Re: How does os.walk work?

2007-06-07 Thread [EMAIL PROTECTED]
On Jun 7, 5:13 pm, Gary Herron <[EMAIL PROTECTED]> wrote:
> Simple:  os.walk builds the list to contain all the subdirectories.
> After giving you a chance to modify that list, ow.walk then goes through
> the list (whatever contents it has at that point) and visits any
> subdirectory.
>
> I'd guess your trouble with understanding this has to do with wondering
> how the modified list gets from your code back to os.walk.  But in fact
> they are not two separate lists, but one list, passed by reference from
> os.walk into your code.
>
Thanks, that does make sense now.

-Greg


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


Re: How Can I Increase the Speed of a Large Number of Date Conversions

2007-06-07 Thread James T. Dennis
Some Other Guy <[EMAIL PROTECTED]> wrote:
> vdicarlo wrote:
>> I am a programming amateur and a Python newbie who needs to convert
>> about 100,000,000 strings of the form "1999-12-30" into ordinal dates
>> for sorting, comparison, and calculations. Though my script does a ton
>> of heavy calculational lifting (for which numpy and psyco are a
>> blessing) besides converting dates, it still seems to like to linger
>> in the datetime and time libraries.  (Maybe there's a hot module in
>> there with a cute little function and an impressive set of
>> attributes.)
> ...
>> dateTuple = time.strptime("2005-12-19", '%Y-%m-%d')
>> dateTuple = dateTuple[:3]
>> date = datetime.date(dateTuple[0], dateTuple[1],
>> dateTuple[2])
>> ratingDateOrd = date.toordinal()

> There's nothing terribly wrong with that, although strptime() is overkill
> if you already know the date format.  You could get the date like this:

>   date = apply(datetime.date, map(int, "2005-12-19".split('-')))

> But, more importantly... 100,000,000 individual dates would cover 274000
> years!  Do you really need that much??  You could just precompute a
> dictionary that maps a date string to the ordinal for the last 50 years
> or so. That's only 18250 entries, and can be computed in less than a second.
> Lookups after that will be near instantaneous:

 For that matter why not memoize the results of each conversion
 (toss it in a dictionary and precede each conversion with a
 check like: if this_date in datecache: return datecache[this_date]
 else: ret=convert(this_date); datecache[this_date]=ret; return ret)

 (If you don't believe that will help, consider that a memo-ized
 implementation of a recursive Fibonacci function runs about as quickly
 as iterative approach).


-- 
Jim Dennis,
Starshine: Signed, Sealed, Delivered

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


Re: Bug/Weak Implementation? popen* routines can't handle simultaneous read/write?

2007-06-07 Thread dmoore
thanks for all of your responses. i'll look more closely at pexpect
(The version I originally saw was much much older). I do want a cross-
platform solution. I'm pretty busy so getting the wxProcess magic into
useful shape will take me some time (at least on the order of weeks)
so other interest parties feel free to step up.

cheers
Damien

On Jun 7, 8:59 pm, Noah <[EMAIL PROTECTED]> wrote:
> On Jun 7, 9:01 am, dmoore <[EMAIL PROTECTED]> wrote:
>
> popen and friends will never do what you want it to do. Down that path
> lies bitter disappointment.
> You need pseduo-ttys and non-blocking IO. I don't know how to do this
> on Windows, but I know it's possible.
> Cygwin does it.
>
> > Anybody have any thoughts on this? Do I have my story straight? (the
> > popen variants can't handle this case and there are no other
> > alternatives in the standard python distro) Is there some place I can
> > submit this as a feature request? (Python dev?)
>
> Try Pexpecthttp://pexpect.sourceforge.net/
> It's been around for a long time and is quite complete and stable.
>
> The catch is that it's UNIX-only. If you want to tease out the magic
> code from wxProcess that
> does non-blocking reads on win32 then I'd be happy to integrate that
> into the current development branch
> of Pexpect. If someone can provide a pure Python drop-in replacement
> for the read_nonblocking() function
> I use for UNIX systems then it would be easy. I have a whole test
> framework that I can run it through to
> see if it performs the same as the UNIX flavor.
>
> I'm sure this is feasible without any C extensions -- it might require
> some ctypes hacking.
> I know Windows has pretty decent async IO, but I don't know what they
> have as an equivalent for a pty.
> Maybe it isn't necessary. A pty is only necessary on UNIX because the
> standard c library, stdio, behaves
> differently when it's talking to a plain pipe versus a terminal -- it
> switches buffering
> between block and line oriented buffer. You don't want block buffering
> on interactive applications.
> This is why popen eventually breaks down. No, there is no way to
> select this behavior from
> the calling side... unless you can trick it into dynamically linking
> to your specially hacked libc.
> But that's getting ahead because that's what happens on UNIX -- it
> might be a non-issue on Windows.
>
> The read_nonblocking() function I use has an interface like this:
> 
> def read_nonblocking (self, size = 1, timeout = -1):
>
> """This reads at most size characters from the child
> application. It
> includes a timeout. If the read does not complete within the
> timeout
> period then a TIMEOUT exception is raised. If the end of file
> is read
> then an EOF exception will be raised. If a log file was set
> using
> setlog() then all data will also be written to the log file.
>
> If timeout is None then the read may block indefinitely. If
> timeout is -1
> then the self.timeout value is used. If timeout is 0 then the
> child is
> polled and if there was no data immediately ready then this
> will raise
> a TIMEOUT exception.
>
> The timeout refers only to the amount of time to read at least
> one
> character. This is not effected by the 'size' parameter, so if
> you call
> read_nonblocking(size=100, timeout=30) and only one character
> is
> available right away then one character will be returned
> immediately.
> It will not wait for 30 seconds for another 99 characters to
> come in.
>
> This is a wrapper around os.read(). It uses select.select() to
> implement the timeout. """
> 
>
> Yours,
> Noah


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


How Can I Increase the Speed of a Large Number of Date Conversions

2007-06-07 Thread vdicarlo
I am a programming amateur and a Python newbie who needs to convert
about 100,000,000 strings of the form "1999-12-30" into ordinal dates
for sorting, comparison, and calculations. Though my script does a ton
of heavy calculational lifting (for which numpy and psyco are a
blessing) besides converting dates, it still seems to like to linger
in the datetime and time libraries.  (Maybe there's a hot module in
there with a cute little function and an impressive set of
attributes.)

Anyway, others in this group have said that the date and time
libraries are a little on the slow side but, even if that's true, I'm
thinking that the best code I could come up with to do the conversion
looks so clunky that I'm probably running around the block three times
just to go next door. Maybe someone can suggest a faster, and perhaps
simpler, way.

Here's my code, in which I've used a sample date string instead of its
variable name for the sake of clarity. Please don't laugh loud enough
for me to hear you in Davis, California.

dateTuple = time.strptime("2005-12-19", '%Y-%m-%d')
dateTuple = dateTuple[:3]
date = datetime.date(dateTuple[0], dateTuple[1],
dateTuple[2])
ratingDateOrd = date.toordinal()

P.S. Why is an amateur newbie trying to convert 100,000,000 date
strings into ordinal dates? To win try to win a million dollars, of
course! In case you haven't seen it, the contest is at www.netflixprize.com.
There are currently only about 23,648 contestants on 19,164 teams from
151 different countries competing, so I figure my chances are pretty
good. ;-)

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


Re: pickling problem

2007-06-07 Thread Pomato

Brian Blais wrote:
> Hello,
>
> I have a somewhat nested dict that I want to pickle, but it (sometimes) 
> contains some
> no-no's  (specifically, in this case, functions).  I know I can't pickle 
> them, but I
> would like to be able to pickle the rest of the dict.  Is there a good way to 
> be able
> to walk through a dict, and take out all of the non-pickleable objects?  I 
> could
> replace them with something else (a tag of some sort, for me to reconstruct 
> things
> later).
>
>
>   thanks,
>
>   Brian Blais
>
> --
> -
>
>   [EMAIL PROTECTED]
>   http://web.bryant.edu/~bblais

One way to do that could be:

>> d = {1:functionA, 2:functionB, 3:"String"}
>> for key in d:
>> if callable(key): d[key] = "tag"

That would work for the functions in your dictionary.

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


Re: Bug/Weak Implementation? popen* routines can't handle simultaneous read/write?

2007-06-07 Thread Noah
On Jun 7, 9:01 am, dmoore <[EMAIL PROTECTED]> wrote:

popen and friends will never do what you want it to do. Down that path
lies bitter disappointment.
You need pseduo-ttys and non-blocking IO. I don't know how to do this
on Windows, but I know it's possible.
Cygwin does it.

> Anybody have any thoughts on this? Do I have my story straight? (the
> popen variants can't handle this case and there are no other
> alternatives in the standard python distro) Is there some place I can
> submit this as a feature request? (Python dev?)

Try Pexpect http://pexpect.sourceforge.net/
It's been around for a long time and is quite complete and stable.

The catch is that it's UNIX-only. If you want to tease out the magic
code from wxProcess that
does non-blocking reads on win32 then I'd be happy to integrate that
into the current development branch
of Pexpect. If someone can provide a pure Python drop-in replacement
for the read_nonblocking() function
I use for UNIX systems then it would be easy. I have a whole test
framework that I can run it through to
see if it performs the same as the UNIX flavor.

I'm sure this is feasible without any C extensions -- it might require
some ctypes hacking.
I know Windows has pretty decent async IO, but I don't know what they
have as an equivalent for a pty.
Maybe it isn't necessary. A pty is only necessary on UNIX because the
standard c library, stdio, behaves
differently when it's talking to a plain pipe versus a terminal -- it
switches buffering
between block and line oriented buffer. You don't want block buffering
on interactive applications.
This is why popen eventually breaks down. No, there is no way to
select this behavior from
the calling side... unless you can trick it into dynamically linking
to your specially hacked libc.
But that's getting ahead because that's what happens on UNIX -- it
might be a non-issue on Windows.

The read_nonblocking() function I use has an interface like this:

def read_nonblocking (self, size = 1, timeout = -1):

"""This reads at most size characters from the child
application. It
includes a timeout. If the read does not complete within the
timeout
period then a TIMEOUT exception is raised. If the end of file
is read
then an EOF exception will be raised. If a log file was set
using
setlog() then all data will also be written to the log file.

If timeout is None then the read may block indefinitely. If
timeout is -1
then the self.timeout value is used. If timeout is 0 then the
child is
polled and if there was no data immediately ready then this
will raise
a TIMEOUT exception.

The timeout refers only to the amount of time to read at least
one
character. This is not effected by the 'size' parameter, so if
you call
read_nonblocking(size=100, timeout=30) and only one character
is
available right away then one character will be returned
immediately.
It will not wait for 30 seconds for another 99 characters to
come in.

This is a wrapper around os.read(). It uses select.select() to
implement the timeout. """


Yours,
Noah

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


Re: Bragging about Python

2007-06-07 Thread Steve Howell
--- Georg Brandl <[EMAIL PROTECTED]> wrote:
> >> 
> >> 15 small programs here:
> >> 
> >> http://wiki.python.org/moin/SimplePrograms
> >> 
> > 
> > IMHO a few python goodies are missing there.
> 
> "It's a Wiki." ;)
> 

Yes indeed.  Please feel free to add to the page, or
make your own fork.  See link above.








 

Bored stiff? Loosen up... 
Download and play hundreds of games for free on Yahoo! Games.
http://games.yahoo.com/games/front
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Running a process every N days

2007-06-07 Thread kaens
On 6/7/07, David Bear <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
>
> > What's the best way to run either an entire python process or a python
> > thread every N days. I'm running Python 2.4.3 on Fedora Core 5 Linux.
> > My code consists of a test and measurement system that runs 24/7 in a
> > factory setting. It collects alot of data and I'd like to remove all
> > data older than 30 days. My ideal solution would be something that
> > runs in the background but only wakes up to run every few days to
> > check for old data.
> >
> > Thanks,
> >
> > Dan McLeran
>
>
> And you can use cron to launch your python program?
>
> --
> David Bear
> -- let me buy your intellectual property, I want to own your thoughts --
> --
> http://mail.python.org/mailman/listinfo/python-list
>

yes.
man cron
man crontab
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Python 2.5.1 - sqlite3.dll issue

2007-06-07 Thread Delaney, Timothy (Tim)
Delaney, Timothy (Tim) wrote:

> Josh Ritter wrote:
> 
>> A number of our Windows customers have an issue with the sqlite3
>> module included with Python 2.5.1
>> 
>> We've tracked the problem down to the sqlite3.dll included with the
>> Python 
>> 2.5.1 distrubtion.  It is stripped and thus cannot be relocated. 
>> This causes the following exception on computers where something is
>> already loaded into the address the sqlite3.dll wants to use:
>> 
>> File "sqlite3\__init__.pyc", line 24, in 
>> File "sqlite3\dbapi2.pyc", line 27, in 
>> ImportError: DLL load failed: Invalid access to memory location.
>> 
>> I downloaded the latest sqlite3.dll from http://www.sqlite.org and
>> this fixes the problem.  (This dll isn't stripped)
> 
> Could you raise a bug report on SourceForge please?
> http://sourceforge.net/tracker/?group_id=5470&atid=105470&func=add

OK - I've raised bug report 1733134 for this. I would strongly encourage
people though to get their own SourceForge account so they can
participate in the Python development process.

Cheers,

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


Re: Bragging about Python

2007-06-07 Thread Steve Howell
Programs like this were posted on this thread:

>def fib():
>generation, parent_rabbits, baby_rabbits = 1,
> 1, 1
>while True:
>yield generation, baby_rabbits
>generation += 1
>parent_rabbits, baby_rabbits = \
>   baby_rabbits, parent_rabbits +
> baby_rabbits
> 
> for pair in fib():
> if pair[0] > 100:
> break
> print "Generation %d has %d (baby) rabbits."
> % pair
> 

One goal behind the SimplePrograms page is to give
people that are new to Python a *gentle* immersion
into Python code.  I prefer simple:

parent_rabbits, baby_rabbits = (1, 1)
while baby_rabbits < 100:
print 'This generation has %d rabbits' %
baby_rabbits
parent_rabbits, baby_rabbits = (baby_rabbits,
parent_rabbits + baby_rabbits)

Somebody commented in another reply that they'd prefer
the variable names "a" and "b," but other than that, I
think it's hard to simplify this.

The problem of counting rabbits is not sufficiently
rich to motivate a solution with generator functions,
and "yield" statements are just gonna scare people
away from the Python, unless they've had a chance to
see simpler idioms first.

I do think there's a place on the page for a good
generators example, but it needs to solve a
sufficiently complex problem that the use of
generators actually simplifies the solution.

So I'm throwing down the gauntlet--can somebody write
a short program (maybe 10 to 20 lines) where you solve
a problem more simply than a similar
non-generator-using solution would solve it?  Maybe
something like Eight Queens?

-- Steve

P.S.  FWIW the page does already include examples of
generator expressions and the itertools module, but it
does not yet show any code that actually implements a
generator.  I would greatly welcome the addition of a
good example.





   

Yahoo! oneSearch: Finally, mobile search 
that gives answers, not web links. 
http://mobile.yahoo.com/mobileweb/onesearch?refer=1ONXIC
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Running a process every N days

2007-06-07 Thread David Bear
[EMAIL PROTECTED] wrote:

> What's the best way to run either an entire python process or a python
> thread every N days. I'm running Python 2.4.3 on Fedora Core 5 Linux.
> My code consists of a test and measurement system that runs 24/7 in a
> factory setting. It collects alot of data and I'd like to remove all
> data older than 30 days. My ideal solution would be something that
> runs in the background but only wakes up to run every few days to
> check for old data.
> 
> Thanks,
> 
> Dan McLeran


And you can use cron to launch your python program?

-- 
David Bear
-- let me buy your intellectual property, I want to own your thoughts --
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bragging about Python

2007-06-07 Thread Steve Howell

--- Szabolcs Nagy <[EMAIL PROTECTED]> wrote:
> 
> actually i don't like when a tutorial uses over
> complicated cute names
> if the context is obvious (fibonacci) then we don't
> need to add
> 'parent_rabbits' and such identifiers

I still prefer the use of "rabbits," but I don't mind
if people change that, as I understand the brevity argument.


   

Pinpoint customers who are looking for what you sell. 
http://searchmarketing.yahoo.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: howto obtain directory where current (running) py-file is placed?

2007-06-07 Thread Stef Mientki
Gerard Flanagan wrote:
> On Jun 7, 8:39 am, dmitrey <[EMAIL PROTECTED]> wrote:
>> Hi all,
>> I guess this question was asked many times before, but I don't know
>> keywords for web search.
>>
>> Thank you in advance, D.
> 
> import os
> 
> d1 = os.path.dirname(__file__)
here I get an error "__file__" is not defined ??
> d2 = os.path.dirname(os.__file__)
here I get a completely different path ??
> 
> print d1
> print d2

This seems to work (but I doubt it's always working !! )
print os.getcwd()

so what's the real answer ?

thanks,
Stef Mientki

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


Re: Running a process every N days

2007-06-07 Thread Diez B. Roggisch
[EMAIL PROTECTED] schrieb:
> What's the best way to run either an entire python process or a python
> thread every N days. I'm running Python 2.4.3 on Fedora Core 5 Linux.
> My code consists of a test and measurement system that runs 24/7 in a
> factory setting. It collects alot of data and I'd like to remove all
> data older than 30 days. My ideal solution would be something that
> runs in the background but only wakes up to run every few days to
> check for old data.

Use cron, the periodic task scheduler of your OS.

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


Re: Running a process every N days

2007-06-07 Thread Klaas
On Jun 7, 3:27 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
wrote:
> What's the best way to run either an entire python process or a python
> thread every N days. I'm running Python 2.4.3 on Fedora Core 5 Linux.
> My code consists of a test and measurement system that runs 24/7 in a
> factory setting. It collects alot of data and I'd like to remove all
> data older than 30 days. My ideal solution would be something that
> runs in the background but only wakes up to run every few days to
> check for old data.

google "cron"

-Mike

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


Re: Running a process every N days

2007-06-07 Thread Grant Edwards
On 2007-06-07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

> What's the best way to run either an entire python process or a python
> thread every N days.

man cron
man 5 crontab

-- 
Grant Edwards   grante Yow! It don't mean a
  at   THING if you ain't got
   visi.comthat SWING!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter custom drawing

2007-06-07 Thread James Stroud
Xavier Bérard wrote:
> Hello everyone,
> 
> I am wondering if there is a way to use custom drawing in Tkinter.
> I've been using it for few months, and all I know about custom drawing
> is to draw directly on a Canvas with such methods as "create_line",
> "create_rectangle", etc.
> 
> Now, the problem, is that I have already plenty of widgets on my
> screen. I just want to draw over them, which is a bit difficult in my
> comprehension of things.
> 
> My perfect solution was to put temporary invisible Canvas when I want
> do use draw methods, but such thing doesn't exist (as far as I could
> search in this community's posts).
> 
> Anyone have a clue ?
> 
> Thanks,
> Xavier Berard
> 

Are you sure you are spelling it right? The C is not capitalized:

from Tkinter import Invisiblecanvas

etc.

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


Re: running a random function

2007-06-07 Thread Neil Cerutti
On 2007-06-07, Dustan <[EMAIL PROTECTED]> wrote:
> On Jun 7, 1:30 pm, Neil Cerutti <[EMAIL PROTECTED]> wrote:
>> On 2007-06-07, Stebanoid <[EMAIL PROTECTED]> wrote:
>>
>> > if you have a list of functions you can try this:
>>
>> > import random
>> > import math
>> > m[int(math.floor(len(m)*random.random()))]()  # seems like Lisp
>>
>> Or rather m[random.randint(0, len(m))]()
>
> Or rather random.choice(m)() # seems like Python

Sweet!

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


Re: Bragging about Python

2007-06-07 Thread Szabolcs Nagy

Cameron Laird wrote:
> In article <[EMAIL PROTECTED]>,
> Mathias Panzenboeck  <[EMAIL PROTECTED]> wrote:
>def fib():
>generation, parent_rabbits, baby_rabbits = 1, 1, 1
>while True:
>yield generation, baby_rabbits
>generation += 1
>parent_rabbits, baby_rabbits = \
>   baby_rabbits, parent_rabbits + baby_rabbits
>
> for pair in fib():
> if pair[0] > 100:
> break
> print "Generation %d has %d (baby) rabbits." % pair
>
> as more appealing to non-Pythoneers.  I'm still suspicious about
> how they're going to react to itertools.islice().  Now, though,
> I've begun to question my own sense of style ...

actually i don't like when a tutorial uses over complicated cute names
if the context is obvious (fibonacci) then we don't need to add
'parent_rabbits' and such identifiers
eg i find more readable and clear the following:

def fib():
a, b = 0, 1
while True:
yield a
a, b = b, a + b

for (n, fn) in enumerate(fib()):
if n > 100:
break
print "F[%d] = %d" % (n, fn)

ymmv

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


RE: Python 2.5.1 - sqlite3.dll issue

2007-06-07 Thread Delaney, Timothy (Tim)
Josh Ritter wrote:

> A number of our Windows customers have an issue with the sqlite3
> module included with Python 2.5.1
> 
> We've tracked the problem down to the sqlite3.dll included with the
> Python 
> 2.5.1 distrubtion.  It is stripped and thus cannot be relocated.  This
> causes the following exception on computers where something is already
> loaded into the address the sqlite3.dll wants to use:
> 
> File "sqlite3\__init__.pyc", line 24, in 
> File "sqlite3\dbapi2.pyc", line 27, in 
> ImportError: DLL load failed: Invalid access to memory location.
> 
> I downloaded the latest sqlite3.dll from http://www.sqlite.org and
> this fixes the problem.  (This dll isn't stripped)

Could you raise a bug report on SourceForge please?
http://sourceforge.net/tracker/?group_id=5470&atid=105470&func=add

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


Running a process every N days

2007-06-07 Thread [EMAIL PROTECTED]
What's the best way to run either an entire python process or a python
thread every N days. I'm running Python 2.4.3 on Fedora Core 5 Linux.
My code consists of a test and measurement system that runs 24/7 in a
factory setting. It collects alot of data and I'd like to remove all
data older than 30 days. My ideal solution would be something that
runs in the background but only wakes up to run every few days to
check for old data.

Thanks,

Dan McLeran

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


RE: lists - append - unique and sorted

2007-06-07 Thread Delaney, Timothy (Tim)
Terry Reedy wrote:

> "Dan Bishop" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
>> If you don't need the list to be sorted until you're done building
>> it, you can just use: 
>> 
>> lst = sorted(set(lst))
> 
> ?? looks same as
> lst.sort()

You missed that the OP wants only unique values from the original list.

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


Re: url to image

2007-06-07 Thread sononix
On Jun 7, 7:49 pm, Szabolcs  Nagy <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > just wondering are there any snippets out there where you can convert
> > a url to an image using python
>
> you mean render a webpage as an image?
> does not sound a simple task
> maybe you can use oss web rendering engines like gecco, khtml or
> webcore

This can be done(very primitive) using the PIL library though the
problem is that I havent found a means of firing an event when the
page had been loaded

Is there any means of firing an event in firefox or checking some
variable maybe in the urllib2 library to check this

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


EuroPython 2007: Early Registration Deadline and Draft Timetable

2007-06-07 Thread Paul Boddie
EuroPython is the European Python and Zope Conference, taking place
this year in Vilnius, Lithuania from Monday 9th July to Wednesday 11th
July.

The last day of EuroPython's early registration period is upon us:
reduced rates will only be available until the end of today, Friday
8th June; after this date, normal rates will apply. More information
on registration can be found here:

 * http://www.europython.org/sections/registration_issues/how-to-register

Help with issues related to registration is provided here:

 * http://www.europython.org/sections/registration_issues/help-on-registration

In addition, a draft timetable of talks has now been made available on
the EuroPython Web site:

 * http://www.europython.org/sections/tracks_and_talks/draft-timetable

Act now to ensure your place at EuroPython and secure yourself a
generous discount on the registration fee!

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


Re: How does os.walk work?

2007-06-07 Thread Gary Herron
[EMAIL PROTECTED] wrote:
> In the example from help(os.walk) it lists this:
>
> from os.path import join, getsize
> for root, dirs, files in walk('python/Lib/email'):
> print root, "consumes",
> print sum([getsize(join(root, name)) for name in files]),
> print "bytes in", len(files), "non-directory files"
> if 'CVS' in dirs:
> dirs.remove('CVS')  # don't visit CVS directories
>
> What I'm wondering is how does the "dirs.remove('CVS')" line prevent
> os.walk from visiting that directory?  how does the walk function know
> what you do to the dirs variable?  I tried looking at the code in
> os.py but it wasn't clear to me there either.
>   
Simple:  os.walk builds the list to contain all the subdirectories. 
After giving you a chance to modify that list, ow.walk then goes through
the list (whatever contents it has at that point) and visits any
subdirectory. 

I'd guess your trouble with understanding this has to do with wondering
how the modified list gets from your code back to os.walk.  But in fact
they are not two separate lists, but one list, passed by reference from
os.walk into your code. 

Gary Herron
> Thanks,
>
> Greg
>
>   

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


How does os.walk work?

2007-06-07 Thread [EMAIL PROTECTED]
In the example from help(os.walk) it lists this:

from os.path import join, getsize
for root, dirs, files in walk('python/Lib/email'):
print root, "consumes",
print sum([getsize(join(root, name)) for name in files]),
print "bytes in", len(files), "non-directory files"
if 'CVS' in dirs:
dirs.remove('CVS')  # don't visit CVS directories

What I'm wondering is how does the "dirs.remove('CVS')" line prevent
os.walk from visiting that directory?  how does the walk function know
what you do to the dirs variable?  I tried looking at the code in
os.py but it wasn't clear to me there either.

Thanks,

Greg

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


Re: running a random function

2007-06-07 Thread Dustan
On Jun 7, 1:30 pm, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> On 2007-06-07, Stebanoid <[EMAIL PROTECTED]> wrote:
>
> > if you have a list of functions you can try this:
>
> > import random
> > import math
> > m[int(math.floor(len(m)*random.random()))]()  # seems like Lisp
>
> Or rather m[random.randint(0, len(m))]()

Or rather random.choice(m)() # seems like Python

> --
> Neil Cerutti
> Caution: Cape does not enable user to fly. --Kenner's Batman costume


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


Re: subprocess call acts differently than command line call?

2007-06-07 Thread Jim
On Jun 7, 2:30 pm, Rob Wolfe <[EMAIL PROTECTED]> wrote:
> That's really strange. Have you got only *one* version of ``file``
> program on your machine?
Thank you, Rob.  I thought I had that kind of thing covered in
specifying the -m but obviously there was something I wasn't getting,
and you found it.

Hope I can return the favor sometime,
Jim

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


Python 2.5.1 - sqlite3.dll issue

2007-06-07 Thread Josh Ritter
A number of our Windows customers have an issue with the sqlite3 module 
included with Python 2.5.1

We've tracked the problem down to the sqlite3.dll included with the Python 
2.5.1 distrubtion.  It is stripped and thus cannot be relocated.  This 
causes the following exception on computers where something is already 
loaded into the address the sqlite3.dll wants to use:

File "sqlite3\__init__.pyc", line 24, in 
File "sqlite3\dbapi2.pyc", line 27, in 
ImportError: DLL load failed: Invalid access to memory location.

I downloaded the latest sqlite3.dll from http://www.sqlite.org and this 
fixes the problem.  (This dll isn't stripped)


-Josh Ritter
President
Prairie Games, Inc
http://www.prairiegames.com 

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


Re: Bragging about Python

2007-06-07 Thread Georg Brandl
Mathias Panzenboeck schrieb:
> Steve Howell schrieb:
>> --- "[EMAIL PROTECTED]"
>> <[EMAIL PROTECTED]> wrote:
>> 
>>> Is there a resource somewhere on the net that can be
>>> used to quickly
>>> and effectively show Python's strengths to
>>> non-Python programmers?
>>> Small examples that will make them go "Wow, that
>>> _is_ neat"?
>>>
>> 
>> 15 small programs here:
>> 
>> http://wiki.python.org/moin/SimplePrograms
>> 
> 
> IMHO a few python goodies are missing there.

"It's a Wiki." ;)

Georg

-- 
Thus spake the Lord: Thou shalt indent with four spaces. No more, no less.
Four shall be the number of spaces thou shalt indent, and the number of thy
indenting shall be four. Eight shalt thou not indent, nor either indent thou
two, excepting that thou then proceed to four. Tabs are right out.

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


Re: Bragging about Python

2007-06-07 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Mathias Panzenboeck  <[EMAIL PROTECTED]> wrote:
>Steve Howell schrieb:
>> --- "[EMAIL PROTECTED]"
>> <[EMAIL PROTECTED]> wrote:
>> 
>>> Is there a resource somewhere on the net that can be
>>> used to quickly
>>> and effectively show Python's strengths to
>>> non-Python programmers?
>>> Small examples that will make them go "Wow, that
>>> _is_ neat"?
>>>
>> 
>> 15 small programs here:
>> 
>> http://wiki.python.org/moin/SimplePrograms
>> 
>
>IMHO a few python goodies are missing there.
>e.g. generator functions:
>
># generic fibonacci without upper bound:
>def fib():
>parent_rabbits, baby_rabbits = 1, 1
>while True:
>yield baby_rabbits
>parent_rabbits, baby_rabbits = baby_rabbits, parent_rabbits +
>baby_rabbits
>
>
># only calculate and print the first 100 fibonacci numbers:
>from itertools import islice
>
>for baby_rabbits in islice(fib(),100):
>print 'This generation has %d rabbits' % baby_rabbits

Good point.

This example intrigues me.  When I saw the first couple of lines,
I expected

   def fib():
   generation, parent_rabbits, baby_rabbits = 1, 1, 1
   while True:
   yield generation, baby_rabbits
   generation += 1
   parent_rabbits, baby_rabbits = \
  baby_rabbits, parent_rabbits + baby_rabbits

for pair in fib():
if pair[0] > 100:
break
print "Generation %d has %d (baby) rabbits." % pair

as more appealing to non-Pythoneers.  I'm still suspicious about
how they're going to react to itertools.islice().  Now, though,
I've begun to question my own sense of style ...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: url to image

2007-06-07 Thread Szabolcs Nagy

[EMAIL PROTECTED] wrote:
> just wondering are there any snippets out there where you can convert
> a url to an image using python

you mean render a webpage as an image?
does not sound a simple task
maybe you can use oss web rendering engines like gecco, khtml or
webcore

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


Re: Who uses Python?

2007-06-07 Thread Stef Mientki
Hendrik van Rooyen wrote:
> "Stef Mientki" <[EMAIL PROTECTED]> wrote:
> 
>> I use Python as  a replacement for MatLab,
>> and intend to use it as replacement for Delphi, AutoIt, PHP, VB.
>> And I'ld love to use it as a replacement for micro controller programming.
> 
> If you have a little sub - 64k micro this is not really practical.
> 
> What we have done is to define a limited virtual machine with
> a simple "assembler" language and used Python to write the
> "compiler" for it.
> 
> Then you have to write the interpreter for the virtual machine
> in the native micro's code - Either using C or assembler, and
> you are away from the hardware, into a useful layer of abstraction.
> 
> ... well sort of - in such a small thing, you are never really far from
> the hardware, as that is what its supposed to be controlling - but
> what it definitely buys you is that your apps written in your special
> language become portable between disparate processors like say
> an ARM at the upper end and an 8031/8051 at the lower...
> 
> Such "interpreters" are surprisingly little code, and they work
> well - faster than what one would expect. - often outperforming
> C code that does pass by value...
> 
> - Hendrik
> 
hello Hendrik,

I use even smaller micro controllers (PIC) and
as I'm just writing a functional simulator for it in Python,
(see 
http://oase.uci.kun.nl/~mientki/data_www/pic/jalcc/python/jal_simulation.html
and even a small movie: (600 kB) 
http://oase.uci.ru.nl/~mientki/download/jal_simulator1.htm

I would love to see your code,
not directly to use it (I want JAL),
but it might give me some good ideas.

cheers,
Stef Mientki
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: recursion error using setattr and getattr

2007-06-07 Thread Gabriel Genellina
En Thu, 07 Jun 2007 08:23:48 -0300, Nathan Harmston  
<[EMAIL PROTECTED]> escribió:

> I m trying to implement an object which contains lazy" variables. My
> idea is to alter the getattr and the setattr methods. However I keep
> on getting a recursion error.

Instead of setattr/getattr, use a property, and you'll get much cleaner  
code.

-- 
Gabriel Genellina

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


Re: ftplib error- Large file

2007-06-07 Thread half . italian
On Jun 7, 8:54 am, Facundo Batista <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > Why would storbinary throw an exception even when the file transfer
> > was successful?  Why would the exception not be thrown until after the
> > file was sent?  Shouldn't ftplib return something like (104,
> > "Connection reset by peer") instead of throwing an error?  Is my
> > reasoning off somewhere?
>
> There was an error, the connection was reset by peer. The error code is
> 104. As it *was* an error, an exception is correct.
>
> You always can hide it yourself, with try/except...
>
> Regards,
>
> --
> .   Facundo
> .
> Blog:http://www.taniquetil.com.ar/plog/
> PyAr:http://www.python.org/ar/

Ok.  I guess that makes sense.  But what about the other
questions...mainly: Why would it throw an exception even though the
file was properly transferred?

I guess this could be blamed on the FTP server.

~Sean

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


Re: running a random function

2007-06-07 Thread Neil Cerutti
On 2007-06-07, Stebanoid <[EMAIL PROTECTED]> wrote:
> if you have a list of functions you can try this:
>
> import random
> import math
> m[int(math.floor(len(m)*random.random()))]()  # seems like Lisp

Or rather m[random.randint(0, len(m))]()

-- 
Neil Cerutti
Caution: Cape does not enable user to fly. --Kenner's Batman costume
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bug/Weak Implementation? popen* routines can't handle simultaneousread/write?

2007-06-07 Thread Terry Reedy

"dmoore" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| alternatives in the standard python distro) Is there some place I can
| submit this as a feature request? (Python dev?)

http://sourceforge.net/tracker/?group_id=5470

But don't hold your breath for a volunteer to respond.  Discussion here is 
good until you have a concrete request and support/rationale.




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


Re: subprocess call acts differently than command line call?

2007-06-07 Thread Rob Wolfe
Jim <[EMAIL PROTECTED]> writes:

> Hello,
>
> I need a program that will traverse a directory tree to ensure that
> there
> are unix-style line endings on every file in that tree that is a text
> file.
> To tell text files from others I want to use the unix "file" command
> (Python's "mimetypes" is not so good for me).  But I am stuck on
> something about getting that output, and I'd greatly appreciate any
> pointers.
>
> Both the command line "file" and the python libmagic binding give the
> same behavior, but I'll illustrate with "file".  It sometimes acts
> differently when run from the command line than when run using
> the subprocess module (with the same user).  For example, it
> sometimes
> gives output when run from the command line but no output when run as
> a subprocess.
>
> Below is a short program to demo.  (I use this on a test file tree
> that is at ftp://joshua.smcvt.edu/pub/hefferon/a.zip if anyone
> is interested.)

[...]

> I've put a transcript of what happens at the bottom of this message.
> One file (in the test tree it is "eqchange.txt") gives no output from
> the above program, but does give an output when I use "file" at the
> command line.

[...]

> -transcript (edited to shorten)
> $ python test.py
> result:  acrotex/readme.txt: ASCII English text, with CRLF line
> terminators
>
> result:  acrotex/eq2db.ins: ASCII English text, with CRLF line
> terminators
>
> result:  acrotex/eqchange.txt:
>
> result:  acrotex/exerquiz.dtx: ISO-8859 English text, with CRLF line
> terminators
> result:  acrotex/doc: directory
>
> done
>
> $ file acrotex/eqchange.txt
> acrotex/eqchange.txt: ISO-8859 English text, with CRLF line

That's interesting. I've checked this eqchange.txt file from
your a.zip on my machine and the result is:

$ file acrotex/readme.txt
acrotex/readme.txt: ASCII English text, with CRLF line terminators
$ file acrotex/eqchange.txt
acrotex/eqchange.txt:
$ file acrotex/exerquiz.dtx
acrotex/exerquiz.dtx: ISO-8859 English text, with CRLF line terminators

$ file -v
file-4.17
magic file from /etc/magic:/usr/share/file/magic
$ uname -orvm
2.6.18-4-k7 #1 SMP Wed May 9 23:42:01 UTC 2007 i686 GNU/Linux

That's really strange. Have you got only *one* version of ``file``
program on your machine?

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


Re: open function fail after running a day

2007-06-07 Thread Vinay Sajip
Try the following (Python 2.5.x):

import logging

t=open(filename,'rb')
try:
data=t.read()
#processing data...
except:
logging.exception("Failed to process %r", filename)
finally:
t.close()

For earlier versions of Python, you will need to nest the try blocks:

import logging

t=open(filename,'rb')
try:
try:
data=t.read()
#processing data...
except:
logging.exception("Failed to process %r", filename)
finally:
t.close()

Regards,


Vinay Sajip

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


Re: Where can I suggest an enchantment for Python Zip lib?

2007-06-07 Thread Larry Bates
durumdara wrote:
> Hi!
> 
> Where can I ask it?
> 
> I want to ask that developers change the Python's Zip lib in the next
> versions.
> The Zip lib not have a callback procedure. When I zip something, I don't
> know, what is the actual position of the processing, and how many bytes
> remaining.
> It is simply rewriteable, but when I get new Python, it is forget this
> thing again...
> 
> So some callback needed for it, if possible. With this I can abort
> processing and I can show the actual state when I processing a large file.
> 
> See this thread:
> http://groups.google.com.kh/group/comp.lang.python/browse_thread/thread/c6069d12273025bf/18b9b1c286d9af7b?lnk=st&q=python+zip+callback&rnum=1#18b9b1c286d9af7b
> 
> 
> Thanks for your help:
> dd
> 
> 
You can easily find out roughly how many bytes are in your .ZIP archive
by using following:

zipbytes=Zobj.fp.tell()

Where Zobj is your zipfile instance.  You don't need a callback.

Problem is ill defined for a better solution.  You don't know how much
the "next" file will compress.  It may compress a lot, not at all or
in some situations actually grow.  So it is difficult (impossible?) to
know how many bytes are remaining.  I have a rough calculation where
I limit the files to 2Gb, but you must set aside some space for the
table of contents that gets added at the end (whose size you don't
actually know either). So I use:

maxzipbytesupperlimit=int((1L<<31)-(8*(1<<20)))

That is 2Gb-8Mb maximum TOC limit of a zip file.

I look at zipbytes add the uncompressed size of the next file, if it
exceeds maxzipbytesupperlimit, I close the file and move to the next
zip archive.  If it is smaller, I add the file to the archive.

Hope this helps.

-Larry



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


Re: Where can I suggest an enchantment for Python Zip lib?

2007-06-07 Thread Terry Reedy

"durumdara" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| Hi!
|
| Where can I ask it?
|
| I want to ask that developers change the Python's Zip lib in the next
| versions.

On the sourceforge tracker,

http://sourceforge.net/tracker/?group_id=5470

 there is a Feature Request category. 



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


Re: open function fail after running a day

2007-06-07 Thread Vinay Sajip
Try the following:

import logging

t=open(filename,'rb')
try:
data=t.read()
#processing data...
except:
logging.exception("Failed to process %r", filename)
finally:
t.close()




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


Re: TLSAbruptCloseError

2007-06-07 Thread Gabriel Genellina
En Tue, 05 Jun 2007 14:22:48 -0300, Todd Hopfinger <[EMAIL PROTECTED]>  
escribió:

> I am using TLS Lite and J2ME SecureConnection for the purposes of  
> encrypting
> traffic to/from a Java Midlet client and a multithreaded Python server.
> However, I encounter a TLSAbruptCloseError. I have tried to determine the
> cause of the exception to no avail. I understand that it has to do with
> close_notify alerts. My abbreviated code follows.
>
>
> // Server
>
>
> def sslSockRecv(conn, num):
>
> data = ''
>
> while len(data) < num:
>
> data = conn.recv(num - len(data)) #
> TLSAbruptCloseError thrown here
>
> if len(data) == 0:
>
> raise NotEnoughBytes  
> ('Too
> few bytes from client. Expected ' + str(num) + '; got ' + str(len(data)),
> num, len(data))
>
> return data

Without much analysis, shouldn't be: data += conn.recv(num - len(data)) or  
something like that?
Else you are discarding the previously received data.

-- 
Gabriel Genellina

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


Re: Integer division

2007-06-07 Thread Terry Reedy

"Sion Arrowsmith" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
| > 3/2 => 1 # Usual behavior
| > some_func(3, 2) => 2 # Wanted
|
| def some_func(a, b):
|return -(-a/b)
|
| And people complain about Python's behaviour regarding division of
| negative integers.

Nice.  This goes on my 'why didn't I think of that' list;-)

I was thinking of the rather pedestrian

d,r = divmod(a,b)
if r: d+=1

tjr



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


Re: lists - append - unique and sorted

2007-06-07 Thread Terry Reedy

"Dan Bishop" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| If you don't need the list to be sorted until you're done building it,
| you can just use:
|
| lst = sorted(set(lst))

?? looks same as
lst.sort() 



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


Re: Who uses Python?

2007-06-07 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Hendrik van Rooyen <[EMAIL PROTECTED]> wrote:
>
>"Stef Mientki" <[EMAIL PROTECTED]> wrote:
>
>> I use Python as  a replacement for MatLab,
>> and intend to use it as replacement for Delphi, AutoIt, PHP, VB.
>> And I'ld love to use it as a replacement for micro controller programming.
>
>If you have a little sub - 64k micro this is not really practical.
>
>What we have done is to define a limited virtual machine with
>a simple "assembler" language and used Python to write the
>"compiler" for it.
>
>Then you have to write the interpreter for the virtual machine
>in the native micro's code - Either using C or assembler, and
>you are away from the hardware, into a useful layer of abstraction.
>
>... well sort of - in such a small thing, you are never really far from
>the hardware, as that is what its supposed to be controlling - but
>what it definitely buys you is that your apps written in your special
>language become portable between disparate processors like say
>an ARM at the upper end and an 8031/8051 at the lower...
>
>Such "interpreters" are surprisingly little code, and they work
>well - faster than what one would expect. - often outperforming
>C code that does pass by value...
>
>- Hendrik
>

Amen!  That is, while it is indeed easy to construct examples
where Python computes a numerical result only a hundredth as 
fast as the corresponding C code, what I find far more interesting
to discuss are the (surprisingly frequent) cases where Python and
litte languages result in solutions which are *faster* at run-time,
along with being more maintainable and quick to develop.

Yet more chatter on a role for Python with specialized hardware ap-
pears in http://www.unixreview.com/documents/s=9133/ur0404e/ >.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python for embedded systems with memory constraints

2007-06-07 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
vishnu  <[EMAIL PROTECTED]> wrote:
>Hi there,
>
>I am embedding python 2.5 on embedded system running on RTOS where I
>had strict memory constraints.
>As python is a huge malloc intensive application, I observed huge
>memory fragmentation in my system which is leading to out of memory
>after running few scripts.
>So I decided to re-initialise the python with out restarting the whole python.
>I tried to use Py_Finalise() after completion of each script , then
>call Py_Initialise as is done in below link.
>http://mail.python.org/pipermail/python-list/2001-November/114253.html
>Which in every loop it causes a leak of 10K and after some iterations
>it leaks of 200K etc. After few more runs this crashes. I read some
>where this leak was solved in 2.5, but with 2.5 also I am having
>problems
>And also I found Py_Finalise does not completely cleanup the memory,
>So how do I re-initialise my memory pool?
>
>Does anybody faced this problem earlier and got any solution hack to
>run the python for a embedded system within own managed memory pool of
>say 10MB?
>
>Any help/ideas are greatly appreciated!. Thanks in advance.

Your report is interesting and important--and surprising!  I thought
Python memory allocation is "cleaner" than you seem to be observing.

I hope one of the core Python maintainers can address this.  I haven't
worked at this level recently enough to speculate on why it's happen-
ing, nor will I soon be in a position to volunteer to research it on 
my own (although I'd eagerly contract to do so on a modestly paid
basis).  

Depending on your schedule and technology, there are lots of technical
fixes that might apply:
A.  quick-starting Python variations that encourage you
to manage memory on a whole-process level;
B.  use of one of the many Python variants (even PyPy?)
that might give you a more favorable memory profile;
C.  switch to Lua or Tcl as more easily embeddable 
alternative languages;
D.  custom memory allocator;
...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: running a random function

2007-06-07 Thread Stebanoid
On 7, 19:56, David Bear <[EMAIL PROTECTED]> wrote:
> I would like to write some code that would randomly select a function from a
> list of functions and call it. I was looking in the globals names space and
> randomly selecting items that were of type function.. but I didn't see a
> way of actually running the function.
>
> Any pointers?
>
> --
> David Bear
> -- let me buy your intellectual property, I want to own your thoughts --

if you have a list of functions you can try this:

import random
import math
m[int(math.floor(len(m)*random.random()))]()  # seems like Lisp
code :D

where m - is list of functions.
but what about functions arguments?
Strange task.. Very strange...

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


Re: MySQL InterfaceError

2007-06-07 Thread BartlebyScrivener
On Jun 7, 10:09 am, "Joe" <[EMAIL PROTECTED]> wrote:
>
> And, yes, printing the error message returns absolutely nothing.  The tuple
> following InterfaceError is both the error code and message.  Unfortunately,
> it will only give me (0, '') which isn't much help.
>

I'm on Google groups and can't see the first part of your original
message, so don't know what query you are using. But I get that
interface error when I attempt to interpolate values from something
other than a tuple.

E.g.

SELECT item from table where item like %s

If you try to use a string, say, instead of a string in a tuple,
you'll get an interface error.

That's the only time I've gotten it.

rd

> Thanks again!
>
> Jough


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


pyExcelerator Protection insert_bitmap

2007-06-07 Thread pythonwin pythonwin

Good evening!

say, please, as in *.xls to insert an unscreened picture?

example: image.py

but a picture in OpenOficce is not represented :(
OS - windows XP, debian etch
pyExcelerator 0.6.3a-1
#!/usr/bin/env python
# -*- coding: windows-1251 -*-
# Copyright (C) 2005 Kiseliov Roman

__rev_id__ = """$Id: image.py,v 1.3 2005/03/27 12:47:06 rvk Exp $"""


from pyExcelerator import *

w = Workbook()
ws = w.add_sheet('Image')



class Protection(Formatting.Protection):
def __init__(self, cell_locked,formula_hidden):
self.cell_locked = cell_locked
self.formula_hidden = formula_hidden

protection = Protection(0,0)

t = ((protection.cell_locked & 0x01) << 0) | ((protection.formula_hidden & 0x01) << 1)

print t


style = XFStyle()
style.protection = protection


ws.write(2, 2, '1',  style)
ws.insert_bitmap('python.bmp', 2, 2)
ws.insert_bitmap('python.bmp', 10, 2)


ws.protect = False
ws.wnd_protect = False
ws.obj_protect = False
ws.scen_protect = False

w.protect = False
w.wnd_protect = False
w.obj_protect = False


w.save('image.xls')
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: running a random function

2007-06-07 Thread Stebanoid
On 7, 19:56, David Bear <[EMAIL PROTECTED]> wrote:
> I would like to write some code that would randomly select a function from a
> list of functions and call it. I was looking in the globals names space and
> randomly selecting items that were of type function.. but I didn't see a
> way of actually running the function.
>
> Any pointers?
>
> --
> David Bear
> -- let me buy your intellectual property, I want to own your thoughts --

if you have a list of functions you can try this:

import random
import math
m[int(math.ceil(random.random()))]() #seems like Lisp code :)

but what about functions arguments?
Strange task... Very strange

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


Re: Bug/Weak Implementation? popen* routines can't handle simultaneous read/write?

2007-06-07 Thread Nick Craig-Wood
dmoore <[EMAIL PROTECTED]> wrote:
>  I've seen the following issue come up in multiple posts to this
>  mailing list:
> 
>  I have a python program that spawns a child process with popen or
>  popen2 or popen3 or popen2.popen2 etc.
>  the child process is interactive: it asks for input then spits out
>  some output, asks for more input then spits out some output. for
>  example, consider the trivial child program:
> 
>  print "welcome"
>  print ">",
>  s=raw_input()
>  while s!='exit':
>  print "you entered:",s
>  print ">",
>  s=raw_input()
> 
>  Now I may be completely wrong about this (I did play with popen for a
>  very long time before writing this message), but it appears that none
>  of the popen variants allow for a sequence of reads and writes to/from
>  this child. that is, if I read from the open pipe's output I will
>  never be able to write the input for the child because the parent
>  program will block on read until eof (I will have similar blocking
>  problems if I start with write - using readline does not seem to
>  help).

You are correct.

>  the standard proposed remedy I have seen on this list is to use Unix-
>  only select/fctl, or otherwise dig into the bowls of the win32 api, or
>  download some half-complete sourceforge process control project.

If you are referring to pexpect I've found it works well - unix only
though.  I've not noticed it being half complete.

There is also a recipe for a non-blocking subprocess - see

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440554

> All well and good, but unsatisfying for writing platform independent code.
> 
>  it turns out that there is at least one open source multi-platform
>  (read: win32/linux) api that does handle synchronous I/O with the
>  child: wxWidgets and wxPython using the class wxProcess. Now the
>  wxWidgets implementation is far from perfect, but it at least allows a
>  program to test for new input on the child's stdout and read stdout/
>  write stdout in a non-blocking way.

Interesting I didn't know about that - I shall try it!

>  However, I find it frustrating
>  that I have to import wx just to have useable interactive pipes in my
>  python scripts when I would expect this to be part of the native
>  python implementation.
> 
>  Anybody have any thoughts on this? Do I have my story straight? (the
>  popen variants can't handle this case and there are no other
>  alternatives in the standard python distro) Is there some place I can
>  submit this as a feature request? (Python dev?)

The non-blocking subprocess would make a good start for a stdlib
submission.

It should really optionally use ptys under unix too otherwise you'll
never be able to script passwd etc.  An interface a bit like pexpect
wpuld be useful too (ie scan for these regexps or timeout and return a
match object).

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


Re: running a random function

2007-06-07 Thread Roberto Bonvallet
On 7 jun, 11:56, David Bear <[EMAIL PROTECTED]> wrote:
> I would like to write some code that would randomly select a function from a
> list of functions and call it. I was looking in the globals names space and
> randomly selecting items that were of type function.. but I didn't see a
> way of actually running the function.

Try this:

def f(x):
print "Calling f with arg %s" % x
def g(x):
print "Calling g with arg %s" % x
def h(x):
print "Calling h with arg %s" % x

import random
functions = [f, g, h]
for i in range(10):
random.choice(functions)(25)

HTH, cheers.
--
Roberto Bonvallet

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


Re: open function fail after running a day

2007-06-07 Thread Vinay Sajip
On Jun 7, 3:33 pm, alexteo21 <[EMAIL PROTECTED]> wrote:
> I have created a script using python that will batch process data
> files every hour
> The script is running on Solaris.  Python version 2.3.3
>
> t=open(filename,'rb')
> data=t.read()
> #processing data...
> t.close()

Try the following approach:

t=open(filename,'rb')
try:
  data=t.read()
  #processing data...
finally:
  t.close()

and see if that improves matters. If you want to add logging for a
quick check, then...

import logging

t=open(filename,'rb')
try:
  data=t.read()
  #processing data...
except:
  logging.exception("Failed to process file %r", filename)
finally:
  t.close()

Regards,

Vinay Sajip

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


easiest way to count memory eaten by call to Python func?

2007-06-07 Thread dmitrey
hi all,
which way is the simplest for now to obtain the memory amount eaten by
call to Python  'myfunc' function?
Thx, D

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


Re: running a random function

2007-06-07 Thread Dustan
On Jun 7, 10:56 am, David Bear <[EMAIL PROTECTED]> wrote:
> I would like to write some code that would randomly select a function from a
> list of functions and call it. I was looking in the globals names space and
> randomly selecting items that were of type function..

Careful!!! You don't want to destroy your computer by accident.

> but I didn't see a
> way of actually running the function.

What do you mean? foo is a function; here's how you run it:

foo()

> Any pointers?

Given a list of functions, it would simply be, given the list of
functions bar (untested):

import random
random.choice(bar)()

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


Re: Baffled on Windows.

2007-06-07 Thread Neil Cerutti
On 2007-06-07, Robin Becker <[EMAIL PROTECTED]> wrote:
> BartlebyScrivener wrote:
>> On Jun 7, 8:17 am, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> 
>> A good habit for naming your scripts: If you have a script and you
>> want to name it text.py, or list.py or new.py or old.py or some common
>> name that might be found in the thousand and one other modules and
>> programs in your various installations, just use my_text.py or
>> my_list.py or neil_new.py or something to reduce the chances that
>> you'll be shadowing without knowing it.
>> 
>> rick
>
> using your advice we will start getting problems where my_new
> is shadowed so then we start having to recur and we'll have
> names like
>
> my_my_new.py my_my_list.py .. my_my_my_new.py .
>
> I leave as an exercise the algorithm which chooses the
> appropriate version of new/list to use :)

Thanks all for the helpful replies.

I'll just memorize the names of all the Python modules in
existence to eliminate this source of errors once and for all.

Or possibly I'll just rename my scripts things whenever this
happens. ;)

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


Re: running a random function

2007-06-07 Thread Matimus
How are you making the list of functions? Something like this:

[code]
fs = []
for k,f in globals():
if callable(f):
fs.append(f)
[/code]

Then to call a random one (assuming they all take no parameters):

[code]
import random
random.choice(fs)()
[/code]

Or maybe you only have the name of the function, this should work:

[code]
globals()[name]()
[/code]

Does this help? I'm not really clear on what you are asking for.

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


Re: running a random function

2007-06-07 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, David Bear wrote:

> I would like to write some code that would randomly select a function from a
> list of functions and call it. I was looking in the globals names space and
> randomly selecting items that were of type function.. but I didn't see a
> way of actually running the function.

If you have a function or callable you call it with the "call operator",
which are parenthesis:

In [8]: int
Out[8]: 

In [9]: int()
Out[9]: 0

For a random selection of an element from a list look at the
`random.choice()` function.

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


updating db with csv

2007-06-07 Thread moishyyehuda
#1 If any one familiar with godaddy hosting. They have apparently have
a hosing server i.e.(scripts, html files etc.), and a server for
databases. How can I import from my script,  with a csv. if the db is
on a different server than the script server.

#2 I would like to update and insert with the same csv file. Is there
a way to tell the database for some lines to update, and for some
lines to insert.

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


Re: MySQL InterfaceError

2007-06-07 Thread kaens
On 6/7/07, Joe <[EMAIL PROTECTED]> wrote:
> > Huh the only thing I can find on InterfaceError is "Errors related to
> > the database interface and not the database itself." You might be able
> > to get some info from connection.info() . . .
>
> Yeah, I wish there was more documentation about this type of error.  The
> only thing info() tells me is that the connection is open through id ##.
>
> > Are you using utf8? MySQLdb seems to have some problems with that.
> > Also, I assume you've tried catching the error and printing the error
> > message, right?
>
> Yes, we are using utf8.  What kind of problems can be seen with it?  This is
> all I have run across so far.  What type of encoding would you suggest?  I
> am still new at some of this stuff, so if you could possibly explain
> (off-topic, so a link is fine) the differences between database encodings I
> would be grateful.
>
> And, yes, printing the error message returns absolutely nothing.  The tuple
> following InterfaceError is both the error code and message.  Unfortunately,
> it will only give me (0, '') which isn't much help.
>
> Thanks again!
>
> Jough
>
>

I really don't know what kinds of errors have cropped up with utf8, or
what encoding you should use. The one utf8 error I saw online was
related to the character_set_name() call - you could try commenting
that out, and all the references to the variable set, and see if your
queries work then.

I don't know if that's your problem or not.

I guess you should go to the MySQLdb site and open a bug report there
or something. Wish I knew enough about it to help you out more, but
really, I just use it, and I've yet to have a problem with it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: running a random function

2007-06-07 Thread Brian van den Broek
David Bear said unto the world upon 06/07/2007 11:56 AM:
> I would like to write some code that would randomly select a function from a
> list of functions and call it. I was looking in the globals names space and
> randomly selecting items that were of type function.. but I didn't see a
> way of actually running the function.
> 
> Any pointers?
> 

Unless I've missed your meaning:

 >>> import random
 >>> def f(): print 42
...
 >>> def g(): print 24
...
 >>> funcs = [f,g]
 >>> random.choice(funcs)()
24


Best,

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


running a random function

2007-06-07 Thread David Bear
I would like to write some code that would randomly select a function from a
list of functions and call it. I was looking in the globals names space and
randomly selecting items that were of type function.. but I didn't see a
way of actually running the function.

Any pointers?

-- 
David Bear
-- let me buy your intellectual property, I want to own your thoughts --
-- 
http://mail.python.org/mailman/listinfo/python-list


Bug/Weak Implementation? popen* routines can't handle simultaneous read/write?

2007-06-07 Thread dmoore
Hi folks,

I've seen the following issue come up in multiple posts to this
mailing list:

I have a python program that spawns a child process with popen or
popen2 or popen3 or popen2.popen2 etc.
the child process is interactive: it asks for input then spits out
some output, asks for more input then spits out some output. for
example, consider the trivial child program:

print "welcome"
print ">",
s=raw_input()
while s!='exit':
print "you entered:",s
print ">",
s=raw_input()

Now I may be completely wrong about this (I did play with popen for a
very long time before writing this message), but it appears that none
of the popen variants allow for a sequence of reads and writes to/from
this child. that is, if I read from the open pipe's output I will
never be able to write the input for the child because the parent
program will block on read until eof (I will have similar blocking
problems if I start with write - using readline does not seem to
help).

the standard proposed remedy I have seen on this list is to use Unix-
only select/fctl, or otherwise dig into the bowls of the win32 api, or
download some half-complete sourceforge process control project. All
well and good, but unsatisfying for writing platform independent code.

it turns out that there is at least one open source multi-platform
(read: win32/linux) api that does handle synchronous I/O with the
child: wxWidgets and wxPython using the class wxProcess. Now the
wxWidgets implementation is far from perfect, but it at least allows a
program to test for new input on the child's stdout and read stdout/
write stdout in a non-blocking way. However, I find it frustrating
that I have to import wx just to have useable interactive pipes in my
python scripts when I would expect this to be part of the native
python implementation.

Anybody have any thoughts on this? Do I have my story straight? (the
popen variants can't handle this case and there are no other
alternatives in the standard python distro) Is there some place I can
submit this as a feature request? (Python dev?)

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


Re: Why can not catch the inner exception

2007-06-07 Thread kelvin.you
On 6 7 ,   10 53 , "Mark T" <[EMAIL PROTECTED]> wrote:
> "   " <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]
>
>
>
>
>
> > Please see the follow code,  I can not catch the exception " IOError"
> > raised from shutil.copyfile() , why?
> >try:
> >if (DEST_TYPE & TYPE_FTP):
> >fn = oname
> >ftpc.UploadFile(f, fn)
> >else:
> >fn = os.path.join(dst, oname)
> >shutil.copyfile(f, fn)
>
> > other code
>
> >except [IOError, FtpcException],why:
> >num = 0
> >print >>sys.stderr, "can not copy '%s' to '%s':
> > %s"%(f, fn, why)
> >ERR_NUM += 1
>
> > I must do like this:
> >try:
> >if (DEST_TYPE & TYPE_FTP):
> >fn = oname
> >ftpc.UploadFile(f, fn)
> >else:
> >fn = os.path.join(dst, oname)
> >try:
> > shutil.copyfile(f, fn)
> >except IOError:
> >   
>
> > other code
>
> >except [IOError, FtpcException],why:
> >num = 0
> >print >>sys.stderr, "can not copy '%s' to '%s':
> > %s"%(f, fn, why)
> >ERR_NUM += 1
>
> > Thanks!
>
>   ,
>
> Use a tuple (IOError,FtpcException) instead of a list in the except
> statement and it works.
>
> --  - -
>
> - -

Thank you!
  :-)

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


Re: Help a C++ escapee!

2007-06-07 Thread Jason
On Jun 7, 1:59 am, "Simon Pickles" <[EMAIL PROTECTED]> wrote:
> Hi,
>
> Can someone help me leave the murky c++ world and enter shiny pythonland?
>
> I have a problem with importing and global variables, here's my code:
[snip!]
> When run, I come unstuck here:
>
> self.clientSocket, self.clientAddress = network.accept()
>
> I get a nameError on 'network', yet it is one in the global namespace,
> defined in server.py before CServerThread.Listen() is called.
>
> In c++, I understood how to declare variables, here I have a problem. Its
> like I need an extern statement from c++.
>
> Can anyone clarify this for me?

The others have covered your problem.  I'd just like to add a little
detail.

As the others have mentioned, global variables reside in their module
namespace.  There is no truly "global" namespace, and that hasn't
really shown up as a problem in Python.  There are two tricks to this:

  1)  Modules are only executed once, at the first import.  Every
additional import merely gets the module object, but does not execute
the code again.  Try adding a print statement outside all class and
function statements in a module, then import it multiple times.
You'll only see the results of the print statement once.

You can also start up python with the "-v" flag.  Python will then
tell you whenever it executes a module.

This means that you can have a "global" module.  Create a Python
module with all the variables that you want, and just import that
module in all places that need those variables.  If you find yourself
stuffing a huge number of variables into your global module, you
probably need to rethink your program design.

Otherwise, put the global data in the various modules that create and
update it.  Usually, your other code will only need to access that
data under more rare conditions.

If you absolutely need a module to be re-executed, the "reload"
function will do what you want.

  2)  Modules do not have to be imported at the start of the file.  A
module import statement can occur any time code is executed.  By
convention, we place the import statement at the beginning of the
block where we use it.

Remember that Python isn't C++.  If you place an import statement in a
function, Python doesn't try to import that statement until the
function is called.  This is very different from C/C++'s #include
preprocessor statements.

If you're having problems with circular references, the import
statement can usually
be moved inside of functions or methods that need them, or the files
can be refactored to  get rid of the circular reference.

Here's something that shows both points.  I started python by typing
in "python -v".  There's a large number of imported modules that
Python automatically loads.  After that finishes:
>>> def spam(x):
... x = 5 * x
... import math   # Math won't be imported until this function is
called
... return math.pow(x, 2)
...
>>> spam(1) # This should import the math module, executing its contents
import math # builtin
25.0
>>> spam(2) # spam() will now use the previously import math module.  (This is 
>>> fast)
100.0

Hope this helps!

  --Jason

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


Re: ftplib error- Large file

2007-06-07 Thread Facundo Batista
[EMAIL PROTECTED] wrote:

> Why would storbinary throw an exception even when the file transfer
> was successful?  Why would the exception not be thrown until after the
> file was sent?  Shouldn't ftplib return something like (104,
> "Connection reset by peer") instead of throwing an error?  Is my
> reasoning off somewhere?

There was an error, the connection was reset by peer. The error code is
104. As it *was* an error, an exception is correct.

You always can hide it yourself, with try/except...

Regards,

-- 
.   Facundo
.
Blog: http://www.taniquetil.com.ar/plog/
PyAr: http://www.python.org/ar/


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


Re: Tkinter custom drawing

2007-06-07 Thread Kevin Walzer
Xavier Bérard wrote:
> 
> Now, the problem, is that I have already plenty of widgets on my
> screen. I just want to draw over them, which is a bit difficult in my
> comprehension of things.
> 

What are you trying to achieve by "drawing over" widgets?

-- 
Kevin Walzer
Code by Kevin
http://www.codebykevin.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Designing a graph study program

2007-06-07 Thread andrea
On 10 Mag, 16:52, Alexander Schliep <[EMAIL PROTECTED]> wrote:
> andrea <[EMAIL PROTECTED]> writes:
> > On 9 Mag, 09:10, Alexander Schliep <[EMAIL PROTECTED]> wrote:
> >> Check outhttp://gato.sf.net(LGPLlicense). It does exactly what you
> >> want to do and there is a binary for MacOS X. Algorithms are implemented
> >> using Gato's graph class and rudimentary visualizations you get for free
> >> by replacing standard data structures (e.g., a vertex queue) by
> >> animated ones (AnimatedVertexQueue).
>
> > Very very nice well done!
>
> Thanks.
>
> > I'd like to do something similar, just to learn something new...
>
> Gato is open source and I'd be happy to collaborate. There are quite a
> few areas (e.g. SVG export, displays for data structure contents, more
> complete 3D support, polygon edges, running backwards?) which need
> work.
>
> > Could you explain me how you designed it?? How is the step mechanism
> > done??
>
> The algorithm is executed by a subclass of the Python debugger (see
> Gato.py).  A Tk event mechanism is used to step to the next line if
> you are in running mode. Otherwise the user steps manually. The
> visualizations are done with animated data structures, which animate
> changes to their internal state with respect to the graph: e.g., when
> you add or remove v to/from an AnimatedVertexQueue it changes v's
> color.
>
> Tk has a canvas which does object-oriented drawing. A line is not
> just a bunch of pixels but rather an object which you can move,
> scale, has callbacks. I dislike Tcl, but Tk is amazing, even it
> it looks 1980s.
>
> There is a 
> paperhttp://algorithmics.molgen.mpg.de/preprints/2000-CATBox-MTCM.pdf
> describing the ideas.
>
> Best,
> Alexander

Ok thanks a lot for the explanation Alexander...

Well I changed my implementation of edges and nodes to this:

class node:
"""nodi di un grafo"""
def __init__(self, label, color=None, parent=None, distance=None):
self.label = label
self.color = color
self.parent = parent
self.distance = distance

def __eq__(self,y):
"""uguaglianza fra nodi"""
return self.label == y.label

def __repr__(self):
"""docstring for __repr__"""
return str(self.label)


class edge: # CHANGED tutta la gestione di nodi e lati
"""lato di un grafo"""
def __init__(self, u, v, directed=False, w=1):
"due lati ed eventualmente il peso associato"
self.u = u
self.v = v
self.w = w
self.directed = directed


def __repr__(self):
"""docstring for __repr__"""
if self.directed:
sym = " --> "
else:
sym = " --- "
return str(self.u) + sym + str(self.v)

def __eq__(self,y):
if self.directed != y.directed:
return False
r = (self.u == y.u and self.v == y.v)
l = (self.v == y.u and self.u == y.v)
if self.directed: # gia controllato che non siano diversi
return r
else:
return r or l


Does it make sense??
But now I have some troubles with all the rest ;)
For example this code

def make_adj_list(self,nodes,edges):
"""crea la lista di adiacenza"""
adj_list = {}
for v in nodes:
adj_list[v] = []
   ...
builds an adjacency list of the graph, but now the object Node is not
hashable of course!
How do I manage this? I think I can use the label
adj_list[v.label] = [u.label, etc etc]
but then I need another dictionary to go from labels to objects, it's
not difficult but look ugly to me, other solutions??

Thanks a lot

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


Re: Baffled on Windows.

2007-06-07 Thread Robin Becker
BartlebyScrivener wrote:
> On Jun 7, 8:17 am, Neil Cerutti <[EMAIL PROTECTED]> wrote:

> A good habit for naming your scripts: If you have a script and you
> want to name it text.py, or list.py or new.py or old.py or some common
> name that might be found in the thousand and one other modules and
> programs in your various installations, just use my_text.py or
> my_list.py or neil_new.py or something to reduce the chances that
> you'll be shadowing without knowing it.
> 
> rick

using your advice we will start getting problems where my_new is shadowed so 
then we start having to recur and we'll have names like

my_my_new.py my_my_list.py .. my_my_my_new.py .

I leave as an exercise the algorithm which chooses the appropriate version of 
new/list to use :)
-- 
Robin Becker

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


Re: ctypes: error passing a list of str to a fortran dll

2007-06-07 Thread luis
On 5 jun, 06:15, Charles Sanders <[EMAIL PROTECTED]>
wrote:
> luis wrote:
> > I'm using ctypes to call afortrandllfrom python. I have no problems
> > passing integer and double arryas, but I have an error with str arrys.
> > For example:
>
> [snip]
>
> I do not know about MicrosoftFortrancompilers (your mention
> ofdllindicates you are probably using MS), nor much about
> Python, but the C equivalent of a givenFortrancall is operating
> system and compiler dependent. You should consult theFortran
> compiler manual for the compiler used to create theDLL.
>
> Despite this, many (but not all) C toFortraninterfaces have
> the following characteristics
>
> + C name isFortranname in lower case
> +FortranREAL, DOUBLE PRECISION, INTEGER etc parameters
>   are pointers to the parameter in C, ie float*, etc
> +FortranREAL etc arrays are pointers in C (same as
>   C arrays decay to pointers).
> +FortranCHARACTER and CHARACTER arrays are passed as TWO
>   parameters, one a pointer to the start of the variable
>   or array, and the other the length as an integer, not
>   a pointer. The length parameters follow all other
>   parameters, in order of the character variables/arrays.
>
> Variations I have seen (all on Unix) include using upper case
> instead of lower, prepending (or postpending) an underscore (or
> other character(s)) to the subroutine or function name, and
> using special "character descriptors" (packing address and
> length into one "word") for character variables. There are
> almost certainly more variations that I have not seen.
>
> For example, given aFORTRANdeclaration
>
> SUBROUTINE X( CV, RV, CA, N )
> CHARACTER*(*) CV
> REAL  RV
> CHARACTER*(*) CA(*)
> INTEGER   N
>
> The C equivalent is likely to be
>
> void x( char *pcv, float *prv, char *pca, int *pn,
> int lv, int la)
>
> Where lv will hold the length  of cv and la the length of
> each element of ca (required to be the same for all elements
> of the array).Fortranuses fixed length character strings,
> padded with blanks.
>
> Given the error message
>
>  > ValueError: Procedure probably called with not enough
>  > arguments (4 bytes missing)
>
> I suspect that yourFortrancompiler is one of the many which
> do this, and the missing 4 bytes are the integer length of
> each element of the character array.
>
> Also, I noticed you seem to be passing an array of character
> pointers rather than an array of characters. It is doubtful thatFortrancan 
> handle this. You will probably have to pad the strings
> to a maximal length with spaces, concatanate then into one big
> string, and pass this by reference together with their padded
> length. YourFortranmay (but probably won't) have extensions
> that allow you to pass an array of character pointers.
>
> Charles

The solution proposed by Jugoslav Dujic, from comp lang fortran is

#Python script calling fortran subroutine
from ctypes import *
ap = windll.LoadLibrary(self.locationDll)
ap.TEST_02.restype=None
myCadena='D:\BBDD\PythonScripts\pru.txt'
strLen=len(myCadena)
pf_myCadena = c_char_p(myCadena)
pf_srLen = c_int(strLen)
ap.TEST_02(pf_myCadena,pf_srLen)

!fortran dll
subroutine TEST_02(s)
  !DEC$ ATTRIBUTES DLLEXPORT :: TEST_02
  !DEC$ATTRIBUTES REFERENCE:: s
  !INTEGER(4):: n
  CHARACTER(*):: s

  open (unit=31,file=trim(s))
  write(31,'(f0.1)') 1.0
  write(31,*) trim(s)
  write(31,'(i0)') len_trim(s)
  close(31)
  return
END subroutine

Regards

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


Re: Integer division

2007-06-07 Thread Sion Arrowsmith
Hamish Moffatt  <[EMAIL PROTECTED]> wrote:
>[EMAIL PROTECTED] wrote:
> def div_ceil(a, b):
>> ... if a%b:
>> ... return ((a/b)+1)
>> ... else:
>> ... return (a/b)
>
>Yes, although it's not as short or as fast (probably as my version):
>
>def div_ceil(a, b):
> return ((a+(b-1))/b)

If that's what you care about:

$ python -mtimeit -s 'def divc1(a,b): return (a+b-1)/b' 'divc1(3,2)'
100 loops, best of 3: 0.443 usec per loop
$ python -mtimeit -s 'def divc2(a,b): return -(-a/b)' 'divc2(3,2)'
100 loops, best of 3: 0.331 usec per loop

Also, note:

>>> divc2(sys.maxint, 2)
1073741824
>>> divc1(sys.maxint, 2)
1073741824L

which is going to cause problems with sys.version_info < (2, 3) .
(Or do I mean (2, 2)? I don't have a 2.2 to hand.)

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
   "Frankly I have no feelings towards penguins one way or the other"
-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Baffled on Windows.

2007-06-07 Thread BartlebyScrivener
On Jun 7, 8:17 am, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> I have the following Python program:
>
> Running this program with 2.5.1 causes another Python script in
> the same directory to be loaded . . . 'new.py'

A good habit for naming your scripts: If you have a script and you
want to name it text.py, or list.py or new.py or old.py or some common
name that might be found in the thousand and one other modules and
programs in your various installations, just use my_text.py or
my_list.py or neil_new.py or something to reduce the chances that
you'll be shadowing without knowing it.

rick


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


Re: Lack of += and -= operators in Pyrex?

2007-06-07 Thread Skip Montanaro
> ... I noticed it complains
> about the use of the += and -= assignment operators.  The fix is
> obviously pretty trivial.  I didn't notice any mention in the Pyrex
> docs as a difference between Python and Pyrex though.  Was I mistaken?

Never mind.  I missed the bit where it said they haven't yet been implemented.

Sorry for the noise...

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


RE: MySQL InterfaceError

2007-06-07 Thread Joe
> Huh the only thing I can find on InterfaceError is "Errors related to
> the database interface and not the database itself." You might be able
> to get some info from connection.info() . . .

Yeah, I wish there was more documentation about this type of error.  The
only thing info() tells me is that the connection is open through id ##.

> Are you using utf8? MySQLdb seems to have some problems with that.
> Also, I assume you've tried catching the error and printing the error
> message, right?

Yes, we are using utf8.  What kind of problems can be seen with it?  This is
all I have run across so far.  What type of encoding would you suggest?  I
am still new at some of this stuff, so if you could possibly explain
(off-topic, so a link is fine) the differences between database encodings I
would be grateful.

And, yes, printing the error message returns absolutely nothing.  The tuple
following InterfaceError is both the error code and message.  Unfortunately,
it will only give me (0, '') which isn't much help.

Thanks again!

Jough 

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


Re: open function fail after running a day

2007-06-07 Thread Nikita the Spider
In article <[EMAIL PROTECTED]>,
 alexteo21 <[EMAIL PROTECTED]> wrote:

> The script is working fine on the day of execution.
> It is able to process the data files very hour.  However, the
> processing fail one day later i.e. the date increment by 1.
> 
> Traceback (most recent call last):
>   File "./alexCopy.py", line 459, in processRequestModule
> sanityTestSteps(reqId,model)
>   File "./alexCopy.py", line 699, in sanityTestSteps
> t = open(filename, 'rb')
> IOError: [Errno 24] Too many open files:
> 
> I have explicitly closed the file.  Is there something else I need to
> do?

Sounds like the .close() isn't getting executed as you think. Try using 
the logging module to log a line immediately before each open and close 
so that you can ensure you're really closing all the files. 
Alternatively, some other bit of code my be the guilty party. A utility 
like fstat can show you who has files open.

Good luck

-- 
Philip
http://NikitaTheSpider.com/
Whole-site HTML validation, link checking and more
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why can not catch the inner exception

2007-06-07 Thread Mark T


"人言落日是天涯,望极天涯不见家" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

Please see the follow code,  I can not catch the exception " IOError"
raised from shutil.copyfile() , why?
   try:
   if (DEST_TYPE & TYPE_FTP):
   fn = oname
   ftpc.UploadFile(f, fn)
   else:
   fn = os.path.join(dst, oname)
   shutil.copyfile(f, fn)

    other code

   except [IOError, FtpcException],why:
   num = 0
   print >>sys.stderr, "can not copy '%s' to '%s':
%s"%(f, fn, why)
   ERR_NUM += 1

I must do like this:
   try:
   if (DEST_TYPE & TYPE_FTP):
   fn = oname
   ftpc.UploadFile(f, fn)
   else:
   fn = os.path.join(dst, oname)
   try:
shutil.copyfile(f, fn)
   except IOError:
  

    other code

   except [IOError, FtpcException],why:
   num = 0
   print >>sys.stderr, "can not copy '%s' to '%s':
%s"%(f, fn, why)
   ERR_NUM += 1

Thanks!



你好,

Use a tuple (IOError,FtpcException) instead of a list in the except 
statement and it works.


--马克

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

open function fail after running a day

2007-06-07 Thread alexteo21
I have created a script using python that will batch process data
files every hour
The script is running on Solaris.  Python version 2.3.3

t=open(filename,'rb')
data=t.read()
#processing data...
t.close()

The script is working fine on the day of execution.
It is able to process the data files very hour.  However, the
processing fail one day later i.e. the date increment by 1.

Traceback (most recent call last):
  File "./alexCopy.py", line 459, in processRequestModule
sanityTestSteps(reqId,model)
  File "./alexCopy.py", line 699, in sanityTestSteps
t = open(filename, 'rb')
IOError: [Errno 24] Too many open files:

I have explicitly closed the file.  Is there something else I need to
do?

Appreciate your comments

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


url to image

2007-06-07 Thread sononix
just wondering are there any snippets out there where you can convert
a url to an image using python

I have be trying to use

webbrowser.open("www.mypage.com")

with printscreen but I have no means of finding out when the page url
is fully loaded

any tips

tks
M

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


Re: Bragging about Python

2007-06-07 Thread Mathias Panzenboeck
Steve Howell schrieb:
> --- "[EMAIL PROTECTED]"
> <[EMAIL PROTECTED]> wrote:
> 
>> Is there a resource somewhere on the net that can be
>> used to quickly
>> and effectively show Python's strengths to
>> non-Python programmers?
>> Small examples that will make them go "Wow, that
>> _is_ neat"?
>>
> 
> 15 small programs here:
> 
> http://wiki.python.org/moin/SimplePrograms
> 

IMHO a few python goodies are missing there.
e.g. generator functions:

# generic fibonacci without upper bound:
def fib():
parent_rabbits, baby_rabbits = 1, 1
while True:
yield baby_rabbits
parent_rabbits, baby_rabbits = baby_rabbits, parent_rabbits + 
baby_rabbits


# only calculate and print the first 100 fibonacci numbers:
from itertools import islice

for baby_rabbits in islice(fib(),100):
print 'This generation has %d rabbits' % baby_rabbits
-- 
http://mail.python.org/mailman/listinfo/python-list


pickling problem

2007-06-07 Thread Brian Blais
Hello,

I have a somewhat nested dict that I want to pickle, but it (sometimes) 
contains some
no-no's  (specifically, in this case, functions).  I know I can't pickle them, 
but I
would like to be able to pickle the rest of the dict.  Is there a good way to 
be able
to walk through a dict, and take out all of the non-pickleable objects?  I could
replace them with something else (a tag of some sort, for me to reconstruct 
things
later).


thanks,

Brian Blais

-- 
-

  [EMAIL PROTECTED]
  http://web.bryant.edu/~bblais

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


Tkinter custom drawing

2007-06-07 Thread Xavier Bérard
Hello everyone,

I am wondering if there is a way to use custom drawing in Tkinter.
I've been using it for few months, and all I know about custom drawing
is to draw directly on a Canvas with such methods as "create_line",
"create_rectangle", etc.

Now, the problem, is that I have already plenty of widgets on my
screen. I just want to draw over them, which is a bit difficult in my
comprehension of things.

My perfect solution was to put temporary invisible Canvas when I want
do use draw methods, but such thing doesn't exist (as far as I could
search in this community's posts).

Anyone have a clue ?

Thanks,
Xavier Berard

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


Lack of += and -= operators in Pyrex?

2007-06-07 Thread Skip Montanaro
I'm experimenting a bit with Pyrex and like it pretty well so far.
While converting a module from Python to Pyrex I noticed it complains
about the use of the += and -= assignment operators.  The fix is
obviously pretty trivial.  I didn't notice any mention in the Pyrex
docs as a difference between Python and Pyrex though.  Was I mistaken?

In case it makes any difference, the structure of the couple
statements I needed to change was

obj.attr.subattr += self.attr

Thx,

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


Re: subprocess leaves child living

2007-06-07 Thread Thomas Dybdahl Ahle
Den Thu, 07 Jun 2007 07:00:53 + skrev reed:

> On Jun 5, 7:58 am, Thomas Dybdahl Ahle <[EMAIL PROTECTED]> wrote:
>> Hi, When I do a small program like
>>
>> from subprocess import Popen
>> popen = Popen(["ping", "google.com"]) from time import sleep
>> sleep(100)
>>
>> start it and kill it, the ping process lives on. Is there a way to
>> ensure that the ping process is always killed when the python process
>> is?
>> I can't use atexit, as ping then isn't killed when python is killed "in
>> the hard way"
> 
> 
> 
> pid = popen.pid
> pidfile = open('/usr/local/var/somefile.pid', 'w') pidfile.write('pid')
> pidfile.close()

> then you can check if it is still running when your ?program? restarts
> and can kill it.

If it restarts yeah.

> maybe not the perfect answer, but it answers an imperfect question.

Any details you need?
-- 
http://mail.python.org/mailman/listinfo/python-list


FTPLIB fails to retreive the remote file

2007-06-07 Thread Hrusikesa Patro
Hi All,

I'm trying to download a remote file through FTP. Here's the script:

###
#!/usr/bin/env python
import ftplib
import os
import time

ddir="C:\\ftp"
os.chdir(ddir)
f=ftplib.FTP("10.2.2.1", "user", "user123")
f.cwd("/home/protocol/cccdb/dumps/")

# define filename
day=time.strftime("%Y.%d.%m")
file2="mq20-%s-cdbdump.xml.md5" % (day)

#To debug
pwd = f.pwd()
print pwd
print file2

# get the remote file to the local directory
f.retrbinary('RETR %s' % file2, open(file2,"wb").write)
f.close()
###


*Output:*
>>> execfile("ftp.py")
/home/protocol/cccdb/dumps
mq20-2007.07.06-cdbdump.xml.md5
Traceback (most recent call last):
  File "", line 1, in ?
  File "ftp.py", line 44, in ?
f.retrbinary('RETR %s' % file2, open(file2,"wb").write)
  File "t:\Python23\lib\ftplib.py", line 379, in retrbinary
conn = self.transfercmd(cmd, rest)
  File "t:\Python23\lib\ftplib.py", line 345, in transfercmd
return self.ntransfercmd(cmd, rest)[0]
  File "t:\Python23\lib\ftplib.py", line 324, in ntransfercmd
conn.connect(sa)
  File "", line 1, in connect
socket.error: (10060, 'Operation timed out')
>>>

What's gone wrong?

Rgs,
Hrusi

***  Aricent-Unclassified   ***
"DISCLAIMER: This message is proprietary to Aricent and is intended solely for 
the use of 
the individual to whom it is addressed. It may contain privileged or 
confidential information and should not be 
circulated or used for any purpose other than for what it is intended. If you 
have received this message in error, 
please notify the originator immediately. If you are not the intended 
recipient, you are notified that you are strictly
prohibited from using, copying, altering, or disclosing the contents of this 
message. Aricent accepts no responsibility for 
loss or damage arising from the use of the information transmitted by this 
email including damage from virus."
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Baffled on Windows.

2007-06-07 Thread Tim Golden
Neil Cerutti wrote:
> I have the following Python program:
> 
> import win32com.client
> print 'Huh?' # Actually, it says something profain.
> 
> 
> Running this program with 2.5.1 causes another Python script in
> the same directory to be loaded and run (specifically the import
> causes it), and a .pyc file is created from that list.
> 
> The 'other' program is called 'new.py'. Is that what's causing
> my problem?

A useful technique on these occasions is to use the -v
switch when starting python. If I do nothing more than
import win32com.client, watch what happens:

python -v -c "import win32com.client" 2> python-startup.txt
grep "new" python-startup.txt
.
.
# c:\python24\lib\new.pyc matches c:\python24\lib\new.py
import new # precompiled from c:\python24\lib\new.pyc
# cleanup[2] new

So somewhere in there a module called "new" is being
imported from standard library and, yes, you are
shadowing that module by your own one of the same
name.

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

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


Re: Integer division

2007-06-07 Thread Hamish Moffatt
[EMAIL PROTECTED] wrote:
> On Jun 7, 2:15 pm, Hamish Moffatt <[EMAIL PROTECTED]> wrote:
>> [EMAIL PROTECTED] wrote:
>>> Hello all,
>>>  I have two integers and I want to divide one by another, and want to
>>> get an integer result which is the higher side whenever the result is
>>> a fraction.
>>>  3/2 => 1 # Usual behavior
>>>  some_func(3, 2) => 2 # Wanted
>>> Any easier solution other than int(math.ceil(float(3)/2))
>> The normal solution is to add (divisor-1) to the dividend before division.
>>
>> Ie ceil(3/2) = floor((3+(2-1))/2) = 2. Correct.
>> But ceil(4/2) = floor((4+(2-1))/2) = 2 also. Correct.
> 
> What about this?
> 
 def div_ceil(a, b):
> ... if a%b:
> ... return ((a/b)+1)
> ... else:
> ... return (a/b)

Yes, although it's not as short or as fast (probably as my version):

def div_ceil(a, b):
 return ((a+(b-1))/b)



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


Baffled on Windows.

2007-06-07 Thread Neil Cerutti
I have the following Python program:

import win32com.client
print 'Huh?' # Actually, it says something profain.


Running this program with 2.5.1 causes another Python script in
the same directory to be loaded and run (specifically the import
causes it), and a .pyc file is created from that list.

The 'other' program is called 'new.py'. Is that what's causing
my problem?

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


  1   2   >