Re: Finding the instance reference of an object

2008-11-05 Thread Hendrik van Rooyen
 "Joe Strout" <[EMAIL PROTECTED]> wrote:


> 4. You now see how a mutating an object within a function tells you
> NOTHING about how the reference to that object was passed.

> 5. You see that the first three languages above are passing a
> reference by value and using that to mutate and object, yet for
> reasons still mysterious, the Python example (which has exactly the
> same behavior) must be doing something different.

This is dialectic nit picking - WTF makes "passing a reference by value"
different from "passing a reference" - the salient point is that its a reference
that is passed - would you expect another level of indirection - a reference to
the
reference, or what, before you admit that the thing that is passed is a
reference
and not a copied value of the OBJECT that is of interest.

Looks to me that even if there were ten levels of indirection you would still
insist that its a "pass by value" because in the end, its the actual memory
address of the first pointer in the queue that is passed.  If that is what you
mean,
it is obviously trivially true - but then ALL calling can only be described as
"call by value" - which makes nonsense of what the CS people have been
doing all these years.

"Calling by value" is not a useful definition of Pythons behaviour.

- Hendrik



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


Re: Django or TurboGears or Pylons? for python web framework.

2008-11-05 Thread Aspersieman
On Wed, 05 Nov 2008 08:35:23 +0200, 3000 billg <[EMAIL PROTECTED]>  
wrote:



Hi Senior,


Hi

There was a case for web site that will be public to Internet for me. I  
like

python so I do not consider the use of Ruby on Rails.


Excellent choice :)

I searched more web framework of python from Google. The good solution  
just

only there are Django, TurboGears and Pylons.


I would recommend web2py [1].

Just from my preferences, I want to use Django but the AJAX support will  
be
a problem. Also I need to select a JavaScript framework and lean it,  
maybe

JQuery, mootools or other. And I can not write python as it is written in
general javascript. I need to learn a different syntax.


It supports (and comes with) jquery, has awesome ajax integration.


TurboGears or Pylons, I am worried that the issue of performance because
CherryPy.


I have read (somewhere - I can't find the link now, you can probably  
google it) that it runs as fast or faster than django (and some other  
frameworks).



Could everybody give me a hand for your select? Django or Turbegears or
Pylons? and Why?


For Django VS web2py see [2]
For Turbogears VS web2py see [3]


If Django, how to do Ajax support for you? and why?


For info on web2py and ajax see [4].

Also web2py supports SQLite, MySQL, PostgreSQL, MSSQL, FireBird and Oracle  
databases - which is very cool for me as I often need to work on different  
RDBMS's. Internationalisation is also a cinch. Plus - you can run the  
whole framework from a USB drive and it includes a administrative  
interface with a text editor so you can code your project *entirely* in a  
web browser. It also runs on almost anything that supports python :  
windows, unix/linux, OS X etc. I also has a very active and helpful  
mailing list


I have tried a couple of other frameworks but only web2py gave me that  
'just right' feel. Don't, however take only my word for it - and try other  
frameworks to find the one that works for you. One is, fortunately, spoilt  
for choice with all the cool python frameworks these days. :)



thanks eveybody first.


HTH

Nicol

[1] http://www.web2py.com/
[2] http://mdp.cti.depaul.edu/AlterEgo/default/show/101
[3] http://mdp.cti.depaul.edu/AlterEgo/default/show/102
[4] http://mdp.cti.depaul.edu/AlterEgo/default/show/80

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


Extract frame from wmv

2008-11-05 Thread Martin

Hi,

I need to extract a frame from a wmv file and save it as a jpg. In fact 
I need to extract a frame from each one of a collection of several 
thousand wmv files, but that's beside the point.


I've actually written a script that does exactly this using the pyglet 
module. But while it works fine on my local machine running Python 2.5, 
my host is only on 2.4.3. They've installed pyglet for me, but it won't 
run without ctype, and they don't suport it.


Can anyone suggest an alternative way to achieve this using a module 
that will run on a standard 2.4.3 installation?


Thanks,

Martin

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


Re: Extract frame from wmv

2008-11-05 Thread Tim Golden

Martin wrote:
I need to extract a frame from a wmv file and save it as a jpg. In fact 
I need to extract a frame from each one of a collection of several 
thousand wmv files, but that's beside the point.


I've actually written a script that does exactly this using the pyglet 
module. But while it works fine on my local machine running Python 2.5, 
my host is only on 2.4.3. They've installed pyglet for me, but it won't 
run without ctype, and they don't suport it.


Can anyone suggest an alternative way to achieve this using a module 
that will run on a standard 2.4.3 installation?


Pretty sure pymedia can do this kind of thing, possibly
with a bit of work.

http://pymedia.org/tut/src/dump_video.py.html

I used it recentlyish to do the reverse: combine a series
of still shots into a time-lapse movie.

Alternatively, you might be able to commandline control
mencoder or ffmpeg itself to do this. Not sure, but there
must be *something* among those millions of command-line
options!

TJG

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


Re: Is there a better/simpler way to filter blank lines?

2008-11-05 Thread Marc 'BlackJack' Rintsch
On Wed, 05 Nov 2008 14:39:36 +1100, Ben Finney wrote:

> Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> writes:
> 
>> On Wed, 05 Nov 2008 13:18:27 +1100, Ben Finney wrote:
>> 
>> > Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> writes:
>> > 
>> > Your example shows only that they're important for grouping the
>> > expression from surrounding syntax. As I said.
>> > 
>> > They are *not* important for making the expresison be a generator
>> > expression in the first place. Parentheses are irrelevant for the
>> > generator expression syntax.
>> 
>> Okay, technically correct but parenthesis belong to generator
>> expressions because they have to be there to separate them from
>> surrounding syntax with the exception when there are already enclosing
>> parentheses.  So parenthesis are tied to generator expression syntax.
> 
> No, I think that's factually wrong *and* confusing.
> 
> >>> list(i + 7 for i in range(10))
> [7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
> 
> Does this demonstrate that parentheses are “tied to” integer literal
> syntax? No.

You can use integer literals without parenthesis, like the 7 above, but 
you can't use generator expressions without them.  They are always 
there.  In that way parenthesis are tied to generator expressions.

If I see the pattern ``f(x) for x in obj if c(x)`` I look if it is 
enclosed in parenthesis or brackets to decide if it is a list 
comprehension or a generator expression.  That may not reflect the formal 
grammar, but it is IMHO the easiest and pragmatic way to look at this as 
a human programmer.

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


subprocess and PPID

2008-11-05 Thread Michele Petrazzo

Hi all,
I believe that this is a *nix question, but since I'm developing in
python, I'm here.

I have a code that execute into a "Popen" a command (ssh). I need that,
if the python process die, the parent pid (PPID) of the child don't
become 1 (like I can seen on /proc/$pid$/status ), but it has to die,
following it's parent
It's possible in linux and with subprocess?

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


Re: Is there a better/simpler way to filter blank lines?

2008-11-05 Thread Jorgen Grahn
On Tue, 04 Nov 2008 15:36:23 -0600, Larry Bates <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
>> tmallen:
>>> I'm parsing some text files, and I want to strip blank lines in the
>>> process. Is there a simpler way to do this than what I have here?
>>> lines = filter(lambda line: len(line.strip()) > 0, lines)
...

> Of if you want to filter/loop at the same time, or if you don't want all the 
> lines in memory at the same time:

Or if you want to support potentially infinite input streams, such as
a pipe or socket.  There are many reasons this is my preferred way of
going through a text file.

> fp = open(filename, 'r')
> for line in fp:
>  if not line.strip():
>  continue
>
>  #
>  # Do something with the non-blank like:
>  #
>
>
> fp.close()

Often, you want to at least rstrip() all lines anyway,
for other reasons, and then the extra cost is even less:

   line = line.rstrip()
   if not line: continue
   # do something with the rstripped, nonblank lines

/Jorgen

-- 
  // Jorgen Grahn   R'lyeh wgah'nagl fhtagn!
--
http://mail.python.org/mailman/listinfo/python-list


socket.getaddrinfo: flags |= AI_ADDRCONFIG

2008-11-05 Thread Karl Chen

I've discovered that since glibc 2.3.2, getaddrinfo(3) supports a
useful flag called AI_ADDRCONFIG.  It turns off  lookups if
the machine isn't configured for IPv6 (and similarly for IPv4,
theoretically).  This is especially important when behind gateways
whose DNS forwarder silently filter  requests.  Without
AI_ADDRCONFIG, every DNS request has to wait for 4  request
timeouts before it even attempts an A request.

Passing hints=NULL to getaddrinfo (the C function) means
hints->flags = AI_V4MAPPED | AI_ADDRCONFIG.  I.e., not the same as
hints->hints->flags = 0.  (Don't ask me why the default isn't 0, I
don't like this API either.  It means if you wish to specify only
some hint parameters you have to carefully get the flags right.)

Python's socketmodule.c, especially socket_getaddrinfo, uses 0 as
the default flags.  So AI_ADDRCONFIG is turned off by default.

I propose:
1) mimic glibc default behavior, i.e. if flags is unspecified or
   None, treat it as the default value of AI_V4MAPPED |
   AI_ADDRCONFIG).

Alternatively:
2) add these flags to callers of socket.getaddrinfo in various
   standard libs, e.g. httplib.


(AI_V4MAPPED isn't as important since it only applies if you
explicitly choose AF_INET6, a conscious decision.)

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


Re: False and 0 in the same dictionary

2008-11-05 Thread bearophileHUGS
Ben Finney:
> Is there a later PEP that I've missed which
> finally makes ‘bool’ a type independent from ‘int’?

In a tidy language like an ObjectPascal or Java bools and integers are
different types.

In Python if bools become distinct from integers you have to rewrite
things like:
sum(el == val for el in iterable)
as:
sum(1 for el in iterable if el == val)

In the past here I have stated that boolean operators should return
only boolean values, and I believe it still. Because doing otherwise
is quite confusing.

But in practice I have seen that while being a little untidy, having
bools as subtype of int doesn't lead to much bugs, and it has few
practical advantages. So purity isn't that useful here.

Having an iterable that contains both ints and bools isn't too much
common, because while Python isn't statically typed, in practice most
of the times in most Python programs types are uniform and predictable
(that's why ShedSkin can work).

And even if you have a list that contains bools and integers mixed,
then having to tell them apart (by hashing, etc) is quite uncommon, I
think I have never had to do it in 2-3 years. So maybe is that code
that is doing something messy, so maybe is that code that has to
change and become more tidy, and not the language itself :-)

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: False and 0 in the same dictionary

2008-11-05 Thread bearophileHUGS
Prateek:
> How do I make a dictionary which has distinct key-value pairs for 0,
> False, 1 and True.

Why do you have to do that? What's the problem you have to solve?
Maybe (probably) there are better or more clean alternative solutions.

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


Re: Extract frame from wmv

2008-11-05 Thread Martin

Tim Golden wrote:

Martin wrote:
I need to extract a frame from a wmv file and save it as a jpg. In 
fact I need to extract a frame from each one of a collection of 
several thousand wmv files, but that's beside the point.


I've actually written a script that does exactly this using the pyglet 
module. But while it works fine on my local machine running Python 
2.5, my host is only on 2.4.3. They've installed pyglet for me, but it 
won't run without ctype, and they don't suport it.


Can anyone suggest an alternative way to achieve this using a module 
that will run on a standard 2.4.3 installation?


Pretty sure pymedia can do this kind of thing, possibly
with a bit of work.

http://pymedia.org/tut/src/dump_video.py.html

I used it recentlyish to do the reverse: combine a series
of still shots into a time-lapse movie.

Alternatively, you might be able to commandline control
mencoder or ffmpeg itself to do this. Not sure, but there
must be *something* among those millions of command-line
options!

TJG



Hi Tim,

I've looked at Pymedia but I have to admit I couldn't work it out.

Commandline might be good, but I'm really hoping someone can point me in 
the right direction, as this is not my area of expertise.


Thanks,

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


Re: Extract frame from wmv

2008-11-05 Thread Tim Golden

Martin wrote:

I've looked at Pymedia but I have to admit I couldn't work it out.

Commandline might be good, but I'm really hoping someone can point me in 
the right direction, as this is not my area of expertise.



Nor mine :) Just so people can help you out, can you
be more precise in your requirement? Do you want just
the first frame (eg to act as an img placeholder for
an embedded video). Or do you want to extract one or
more arbitrary frames, eg for screen cap purposes?

This page:

 http://stream0.org/2008/02/howto-extract-images-from-a-vi.html

looks helpful from the ffmpeg pov, but I assume you're
as capable of using Google as I am. I had a very quick
go with the copy of pymedia I have installed here, but
it couldn't read a (fairly recent) .wmv file so that
might be a problem in any case.

UPDATE: Just tried:

 ffmpeg -i bacardi.wmv -r 1 -f image2 images%05d.png

from that page and it produced useful stuff. Worth a try?

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


Re: False and 0 in the same dictionary

2008-11-05 Thread Carl Banks
On Nov 4, 3:48 pm, Prateek <[EMAIL PROTECTED]> wrote:
> I've been using Python for a while (4 years) so I feel like a moron
> writing this post because I think I should know the answer to this
> question:
>
> How do I make a dictionary which has distinct key-value pairs for 0,
> False, 1 and True.
> As I have learnt, 0 and False both hash to the same value (same for 1
> and True).
>
> >>> b = {0:'xyz', False:'abc'}
> >>> b
>
> {0: 'abc'}  # Am I the only one who thinks this is weird?
>
> This obviously stems from the fact that 0 == False but 0 is not False
> etc. etc.
>
> That doesn't help my case where I need to distinguish between the two
>
> The same issue applies in a list:
>
> Suppose I do:
>
> >>> a = [0, 1, True, False]
> >>> a.index(False)
>
> 0
>
> Wha??? Help.


Let me suggest using surrogate objects instead of True and False:

class TrueObject(object):
def __nonzero__(self):
return True

class FalseObject(object):
def __nonzero__(self):
return False

DistinctTrue = TrueObject()
DistinctFalse = FalseObject()


If that doesn't work and you really need the actual True and False
objects to be distinct, it's not too hard to special case a dict to
get it:

class special_dict(dict):
def __init__(self,*args,**kwargs):
self.true_surrogate = object()
self.false_surrogate = object()
super(special_dict,self).__init__(*args,**kwargs)
def __getitem__(self,value):
if value is True:
value = self.true_surrogate
elif value is False:
value = self.false_surrogate
super(special_dict,self).__getitem__(value)
## etc.


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


Red Hat 32 bit RPM for python 2.4+

2008-11-05 Thread James Prav
Hi ,

Could anybody please point to any available Red Hat 32 bit RPM for python
2.4 or greater version on Net. I searched a lot but could find for other
flavour and not Red hat.

Thanks in advance,
James
--
http://mail.python.org/mailman/listinfo/python-list


Question concerning array.array and C++

2008-11-05 Thread Fabio

Hi All,
I have a question concerning the use of array.array inside of C++ code I 
wrote.


I am working with _big_ data files but some entries in these files are
usually bounded say between -5 to 40. Returning a Python list makes no 
sense. In Python I always work with the array.array module which does 
the trick. But now that I wrote my own C++ module for some preprocessing 
I need the return array.array objects.


Consider the object

array.array('c',[40,40,40])

Can I create such an object from within the C++ layer and pass it to the 
Python layer?


I already looked at arraymodule.c and tried to link the arraymodule.o 
file to my code but then I have to mess around with extern "C" and the 
like and it gets really messy.


Any help would be great!

Fabio

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


Re: push-style templating - an xml-like way to process xhtml

2008-11-05 Thread lkcl
On Nov 2, 11:19 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:

> Push-style though enhances the risk of mixing program logic with
> presentation-logic (as simple print-statements do), and makes it a
> precondition that anybody who's supposed to tinker with the softare
> needs to be knowledgable in Python as well as in HTML.

 i'd like to add perhaps a different perspective.  i've developed and
used the following:

 * xmlvl (http://sf.net/projects/virgule) - it's a (non-NP-complete)
XML-based programming language, which was derived from advogato's
codebase.  it outputs XHTML, is "template-based" and implements what
is best described as an XML-based lattice-like, "crystalline" and
hierarchical OO database (!!).  i understood it while i was writing
it, but woudldn't dare go near it, ever again.

 the lessons learned from this were: don't take templating to extremes
(i.e. do the absolute minimum), and never ever write programming
languages in XML.

 * python-htmltmpl (http://htmltmpl.sourceforge.net/) - it's a simple,
utterly simple, HTML-syntax-like templating language, which can do
"substitution", "if/else statements", and "loops".  that's about it.
the nice thing about htmltmpl is that it can do pre-compilation of its
templates, inserting jump-points (which are used to seek() to the next
precompiled statement) into the .tmplc files.  this saves a _great_
deal of time and CPU cycles.

 the lesson from this one is hard to get across, because htmltmpl
basically... works.  it doesn't _need_ developing, it's complete, it
works, it's never going to get up in the sourceforge "rankings"
because... it does everything that it's designed to do.

so it drops off of people's radar, and they reinvent the wheel.

if you think you need anything more than htmltmpl, which separates out
html from programming, think again.  you can pass in a list of
dictionaries into htmltmpl, that generates the table content, form
content, whatever-content.

job done.

* pyjamas (http://pyjs.org) - this is treating the web page and the
web browser as a desktop "canvas", i.e. turning the web browser
concept on its head, and allowing you to program it in exactly the
same way that you would if you were writing a desktop app with PyQt4
or PyGtk2.

no kidding about, here.

why on earth would you want to do something like this?  it's very
simple: HTML "programming" is madness.  it's madness from two angles:

1) CSS abortions.  as an example: i tried doing a centred-box, once.
it took two weeks, and it still was a failure: worked fine in firefox,
but in IE6 if you squashed the browser size, so that normally under FF
you got a horizontal scrollbar, what happened in IE6 was that the
content scrolled off the *top* of the screen!!  unbelievable - and
completely impossible to fix.

2) HTML template "option-itis" resulting in thousands of lines of HTML
that becomes impossible to read, and impossible to maintain.  i think
the worst example i ever saw - and i'm sure people will find worse -
was a technique involving _four_ separate near-identical pages (each
over 3,000 lines long) - one for new entry form, one for new entry but
with error-messages interspersed, one for edit, and one for edit but
with error-messages interspersed.  cut-and-paste gone mad.

HTML templating is, for complex applications, a bd idea.  even
when you start "breaking down" the content into smaller server-side-
includes, and even when you start doing multi-layered HTML templating
(one template gets marked up and then substituted into another
template and so on), even _that_ technique gets very quickly out-of-
hand and you're left with a headache.

so now i choose pyjamas over _any_ kind of web programming, any day of
the week.

the reason is very straightforward: the amount of code being written
is small; it's in python; i can re-use classes and modules; i can even
take standard python modules such as an XMLRPC client or a JSONRPC
client and actually compile them (to javascript) for use... in a web
browser!

you can put in a < div > with an id, you can find that div using a one-
line function, and you can substitute "widgets" - your classes - into
that div.  it's a very, very powerful technique.

complex application programming should be done in a complexity-capable
programming _language_.

HTML, which is a markup language, is simply not designed - and was
never designed - to be "programmed" or to be an NP-complete
programming "language".  it's great for "static content", which can be
edited by graphical tools, and that's about it.

so, there _is_ an alternative approach, with pyjamas, to what you're
saying, diez ("Push-style ... anybody who's supposed to tinker with
the softare needs to be knowledgable in Python as well as in HTML.")

the alternative is: program the entire web site in pure python.  as if
it was a pygtk2, pyqt4 or python-wxWidgets desktop application.

l.


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


Re: False and 0 in the same dictionary

2008-11-05 Thread Marc 'BlackJack' Rintsch
On Wed, 05 Nov 2008 04:22:32 -0800, bearophileHUGS wrote:

> In Python if bools become distinct from integers you have to rewrite
> things like:
> sum(el == val for el in iterable)
> as:
> sum(1 for el in iterable if el == val)

I would expect that you can still "cast" `bool`\s to `int`\s then.  
Sometimes I write it as

sum(int(el == val) for el in iterable)

just for clarity what the intent is.

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


Re: Parse each line by character location

2008-11-05 Thread Tyler
>         So you have a classic (especially for COBOL and older FORTRAN) fixed
> field record layout, no?

Exactly, I believe COBOL. It is a daily reconciliation with an
exchange and our system's orders. One of the problems of dealing with
these old legacy systems that never seem to go away

>
>         I presume the entire file is of a single layout? That would mean
> only one splitting format is needed...

Again, correct, I only need the one format as it does not change. I
want to move it to a csv file because the application that we are
implementing reads these natively, and does not have a built in
mechanism to parse a file like this effectively. Further, this will
allow me to add some other fields for our own use. As such, the final
file will look somewhat different, but this step kinda threw me. I
started out with AWK, and didn't know whether to laugh or cry.
Thankfully, I was able to convince the "guys" to allow me to install
Python on my dev workstation (although already on production SUSE
servers).

Cheers,

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


Re: Question concerning array.array and C++

2008-11-05 Thread Hrvoje Niksic
[ Please consider posting to the capi-sig list, which is dedicated to
  answering questions like yours.
  http://mail.python.org/mailman/listinfo/capi-sig ]

Fabio <[EMAIL PROTECTED]> writes:

> Consider the object
>
> array.array('c',[40,40,40])
>
> Can I create such an object from within the C++ layer and pass it to
> the Python layer?

Yes, simply access the array type object using getattr (the "."
operator), much like you would from Python, and instantiate the type
by calling it:

// import array
PyObject *array_module = PyImport_ImportModule("array");
if (!array_module)
  goto error;

// array_type = array.array
PyObject *array_type = PyObject_GetAttrString(array_module, "array");
Py_DECREF(array_module);
if (!array_type)
  goto error;

// array = array_type('c', [40, 40, 40])
PyObject *array = PyObject_CallFunction(array_type, "c[iii]", 'c', 40, 40, 40);
if (!array)
  goto error;

// at this point you have (a new reference to) the array object
--
http://mail.python.org/mailman/listinfo/python-list


Re: Parse each line by character location

2008-11-05 Thread Lie
On Nov 5, 2:29 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
[snip]
>         So you have a classic (especially for COBOL and older FORTRAN) fixed
> field record layout, no?
>
>         I presume the entire file is of a single layout? That would mean
> only one splitting format is needed...
>
[snip]
>
>         Note that all fields are still in character format. And has been
> noted, I'm sure, if you try to turn the third field into an integer, you
> may have problems, depending upon how you do the conversion -- leading 0
> implies octal if it were a literal, though it seems int() handles it
> correctly (Python 2.5)

from help(int)
 |  ... If base is zero, the proper base is guessed based on the
 |  string content. ...

int(x) will always convert x in base 10
int(x, 0) will convert based on literal int notation, i.e. the prefix
'0x' is base 16 (hex), prefix '0' is base 8 (octal), everything else
is base 10.
int(x, n) will convert on base n, where 2 <= n <= 36

if you're still in doubt, just pass the base explicitly to the int:
int(x, 10) (superfluous though)
--
http://mail.python.org/mailman/listinfo/python-list


Raw socket when interface down.

2008-11-05 Thread Mat
Hi,

I'm trying to use raw sockets in python for a dhcp client. I write this code :

soc = socket.socket(socket.PF_PACKET, socket.SOCK_RAW)
soc.bind(("eth0",0x0800))
data = soc.recv(1024)
print len(data)

It seems to work correctly when interface is up, but when network interface is
down I get this message :
socket.error: (100, 'Network is down')

I look over a lot of C code of dhcp clients. But I didn't find something useful.
I don't how to access the network when interface is down with python. Can
someone helps ?

Thanks !

-- 
Mat

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


Re: How to build the pysqlite? Where to find the "sqlite3.h"?

2008-11-05 Thread [EMAIL PROTECTED]
On Nov 5, 12:29 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On Tue, 04 Nov 2008 21:58:17 -0500, [EMAIL PROTECTED] declaimed
> the following in comp.lang.python:

>
> > Python depends upon Sqlite... which is weird... but it is what I 
> > discovered...
>
>         Not really (weird). Python, as of 2.5, includes the PySQLite DB-API
> adapter as part of the native library/source code. BUT SQLite is NOT
> part of Python (the Windows installers typically include the SQLite
> engine as a convenience, but Linux installers expect the engine to
> already be available).


To clarify further. sqlite is supported in python by providing python
language bindings over the sqlite *native* apis. SQLite is written in
C; pysqlite uses the SQLite C api and intelligently glues it into the
python interpreter and makes python language apis available to you.
This is why Python (pysqlite2 rather) depends on the native SQLite
libraries

This is usually how any new functionality would be made available in
python - by writing python wrappers over the existing native
libraries. The other method would be to re-implement the complete
functionality in pure python (an eg of this technique would be
paramiko which implements SSH2 in pure python)

-srp
>
>         None of the other database adapters are part of the base library.
> --
>         Wulfraed        Dennis Lee Bieber               KD6MOG
>         [EMAIL PROTECTED]             [EMAIL PROTECTED]
>                 HTTP://wlfraed.home.netcom.com/
>         (Bestiaria Support Staff:               [EMAIL PROTECTED])
>                 HTTP://www.bestiaria.com/

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


Re: Can I build Python with lthread instead of pthread?

2008-11-05 Thread Aahz
In article <[EMAIL PROTECTED]>,
Akira Kitada <[EMAIL PROTECTED]> wrote:
>
>I'm running Python 2.5 on FreeBSD 4.
>pthread on FreeBSD 4 has some problems so I would like to build
>python with lthread (linuxthreads) instead of BSD's pthread.
>So I looked at configure options but couldn't find any options for it.
>Python support lthread? and how can I build python with it?

You may want to try asking on capi-sig
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

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


Re: Raw socket when interface down.

2008-11-05 Thread [EMAIL PROTECTED]
On Nov 5, 8:37 pm, Mat <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I'm trying to use raw sockets in python for a dhcp client. I write this code :
>
> soc = socket.socket(socket.PF_PACKET, socket.SOCK_RAW)
> soc.bind(("eth0",0x0800))
> data = soc.recv(1024)
> print len(data)
>
> It seems to work correctly when interface is up, but when network interface is
> down I get this message :
> socket.error: (100, 'Network is down')
>
> I look over a lot of C code of dhcp clients. But I didn't find something 
> useful.
> I don't how to access the network when interface is down with python. Can
> someone helps

mmm, if the interface is down the n/w subsystem will not send messages
out and if possible also disables reception of messages via that
interface. In your case it is likely that the interface message
reception is also disabled. You need to bring up the interface
(ifconfig eth0 up) before you can read/write any data on that
interface.

-srp

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


Re: subprocess and PPID

2008-11-05 Thread [EMAIL PROTECTED]
On Nov 5, 5:12 pm, Michele Petrazzo <[EMAIL PROTECTED]>
wrote:
> Hi all,
> I believe that this is a *nix question, but since I'm developing in
> python, I'm here.
>
> I have a code that execute into a "Popen" a command (ssh). I need that,
> if the python process die, the parent pid (PPID) of the child don't
> become 1 (like I can seen on /proc/$pid$/status ), but it has to die,
> following it's parent
> It's possible in linux and with subprocess?


AFAIK, there is no easy way to do this. If the parent python process
is doing a controlled exit, just kill the child via close() on Popen()
handle. If the parent is doing a uncontrolled exit (say via a SIGKILL
signal), you can't really do anything.

To reliably have the child exit when the parent exits, you would have
to poll for the parent from the child and do a exit when the child
detects that the parent has gone away.

-srp

>
> Thanks,
> Michele

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


Re: How to build the pysqlite? Where to find the "sqlite3.h"?

2008-11-05 Thread Shawn Milochik
This is all useful and interesting stuff, but I don't think any of it
addresses the original poster's problem, which is that he has no root
access to a Linux or Unix box, and wants to get pysqlite2 working in
his home directory. I have exactly the same problem. I have tried the
"python setup.py install --home=~" method, and I get errors from GCC
that I have no permissions (and to be honest, nor the knowledge) to
overcome.

Isn't there anyway to get a Linux binary that can just be put
somewhere in the Python path so we can use sqlite? Or are those of us
without admin/root control of our boxes screwed?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Error loading modules

2008-11-05 Thread BL
On Nov 4, 7:11 pm, John Machin <[EMAIL PROTECTED]> wrote:
> On Nov 5, 9:18 am, BL <[EMAIL PROTECTED]> wrote:
>
> > I am very new to python.  I am installing it as part of a bazzar
> > version control installation.
> > I have installed the Crypto, paramiko and cElementTree modules.  I am
> > running Solaris10x86.
> > When testing the modules I get the following results.
>
> >  python -c "import Crypto"
> > Traceback (most recent call last):
> >   File "", line 1, in 
> > ImportError: No module named Crypto
>
> What is "the Crypto module"? What is the path to the directory in
> which you installed it? Do you mean one of crypto [case matters],
> pycrypto, pyCrypto, M2Crypto, ...?

pyCrypto is the module I installed.  The directory it is installed in
is
/usr/local/lib/python2.5/site-packages  - there is one directory
called
Crytpo and two other files called  pycrytpo-2.0.1-py2.5.egg-info and
pycrytpo-2.0.1-py2.5-solaris-2.10-i86pc.egg.

The directions to check the installation of the python modules said
to
execute python -c "import Crypto"
--
http://mail.python.org/mailman/listinfo/python-list


Re: Parse each line by character location

2008-11-05 Thread Shawn Milochik
I work with tab-delimited files for a living. Because of the same need
you have, I created a Python script to do this. It has usage
information that is easy to follow (just run it without any
arguments).

I hope someone else finds this useful. I have, and use it every month.
It can be easily modified to create comma-delimited files, but that's
something I never use, so it does tabs.

http://milochik.com/shawn/fwconvert.zip



Usage:
fwconvert -r rulesFile fileName [-t|-f]
or
cat filename | fwconvert -r rulesFile" (-t|-f)

-t (to tab) or -f (to fixed-width) required when piping input to
script. Otherwise, it will be auto-determined.


Rules file format:
fieldStart:fieldLength,fieldStart:fieldLength...
Example:
1:3,4:20,24:5
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to build the pysqlite? Where to find the "sqlite3.h"?

2008-11-05 Thread [EMAIL PROTECTED]
On Nov 5, 9:22 pm, "Shawn Milochik" <[EMAIL PROTECTED]> wrote:
> This is all useful and interesting stuff, but I don't think any of it
> addresses the original poster's problem, which is that he has no root
> access to a Linux or Unix box, and wants to get pysqlite2 working in
> his home directory. I have exactly the same problem. I have tried the
> "python setup.py install --home=~" method, and I get errors from GCC
> that I have no permissions (and to be honest, nor the knowledge) to
> overcome.
>
> Isn't there anyway to get a Linux binary that can just be put
> somewhere in the Python path so we can use sqlite? Or are those of us
> without admin/root control of our boxes screwed?

1. Get sqlite3 from http://www.sqlite.org/sqlite-3.6.4.tar.gz
2. build and install sqlite3 (./configure --prefix=/any/writeable/dir
&& make install) -- you may want to supply the --disable-tcl flag if
you hit permission problems
3. get pysqlite3, edit setup.cfg libraries and include lines to point
to the lib/ and include/ dir where you installed sqlite3 in the
previous step
4. python setup.py install --home=somewhere
5. PYTHONPATH=somewhere ./python -- import pysqlite2 should work for
you
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to build the pysqlite? Where to find the "sqlite3.h"?

2008-11-05 Thread Shawn Milochik
On Wed, Nov 5, 2008 at 11:58 AM, [EMAIL PROTECTED]
<[EMAIL PROTECTED]> wrote:
> On Nov 5, 9:22 pm, "Shawn Milochik" <[EMAIL PROTECTED]> wrote:
>> This is all useful and interesting stuff, but I don't think any of it
>> addresses the original poster's problem, which is that he has no root
>> access to a Linux or Unix box, and wants to get pysqlite2 working in
>> his home directory. I have exactly the same problem. I have tried the
>> "python setup.py install --home=~" method, and I get errors from GCC
>> that I have no permissions (and to be honest, nor the knowledge) to
>> overcome.
>>
>> Isn't there anyway to get a Linux binary that can just be put
>> somewhere in the Python path so we can use sqlite? Or are those of us
>> without admin/root control of our boxes screwed?
>
> 1. Get sqlite3 from http://www.sqlite.org/sqlite-3.6.4.tar.gz
> 2. build and install sqlite3 (./configure --prefix=/any/writeable/dir
> && make install) -- you may want to supply the --disable-tcl flag if
> you hit permission problems
> 3. get pysqlite3, edit setup.cfg libraries and include lines to point
> to the lib/ and include/ dir where you installed sqlite3 in the
> previous step
> 4. python setup.py install --home=somewhere
> 5. PYTHONPATH=somewhere ./python -- import pysqlite2 should work for
> you
> --


Thanks, but either I'm missing something or you're missing something.
I can't do any of what you describe on the machine I want to use
sqlite on.

I have downloaded the binary sqlite3 file from sqlite's Web site, and
I can use it with shell scripts and via the command line with no
problem. The issue is that I don't seem to have any way available to
me to use the pysqlite2 Python module.

When I try the "python setup.py --install --home=somewhere"
installation, it blows up on GCC errors that I do not have the
permissions to even attempt to fix.  What I was asking above was
whether there was a way do download the pysqlite2 module as files that
I can just copy into a directory that Python thinks is part of its
path so I can use it without having to compile or build it in any way
on that machine.

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


Re: subprocess and PPID

2008-11-05 Thread Jorgen Grahn
On Wed, 5 Nov 2008 08:19:34 -0800 (PST), [EMAIL PROTECTED] <[EMAIL PROTECTED]> 
wrote:
> On Nov 5, 5:12 pm, Michele Petrazzo <[EMAIL PROTECTED]>
> wrote:
>> Hi all,
>> I believe that this is a *nix question, but since I'm developing in
>> python, I'm here.
>>
>> I have a code that execute into a "Popen" a command (ssh). I need that,

What's 'a "Popen"'? Is it os.popen or one of its variants?

Do you read from it or write to it?  If you do both, you should use
something like the third-party module pexpect instead.

>> if the python process die, the parent pid (PPID) of the child don't
>> become 1 (like I can seen on /proc/$pid$/status ), but it has to die,
>> following it's parent
>> It's possible in linux and with subprocess?
>
> AFAIK, there is no easy way to do this. If the parent python process
> is doing a controlled exit, just kill the child via close() on Popen()
> handle. If the parent is doing a uncontrolled exit (say via a SIGKILL
> signal), you can't really do anything.
>
> To reliably have the child exit when the parent exits, you would have
> to poll for the parent from the child and do a exit when the child
> detects that the parent has gone away.

But in the special case where he's feeding data into "ssh somewhere
somecmd" or pulling data from it, a crash of the parent should make
"somecmd" exit because it sees EOF, and thus make the ssh process end.
Sounds relatively risk-free -- but it depends on "somecmd".

/Jorgen

-- 
  // Jorgen Grahn   R'lyeh wgah'nagl fhtagn!
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to build the pysqlite? Where to find the "sqlite3.h"?

2008-11-05 Thread [EMAIL PROTECTED]
On Nov 5, 10:07 pm, "Shawn Milochik" <[EMAIL PROTECTED]> wrote:
> On Wed, Nov 5, 2008 at 11:58 AM, [EMAIL PROTECTED]
>
>
>
> <[EMAIL PROTECTED]> wrote:
> > On Nov 5, 9:22 pm, "Shawn Milochik" <[EMAIL PROTECTED]> wrote:
> >> This is all useful and interesting stuff, but I don't think any of it
> >> addresses the original poster's problem, which is that he has no root
> >> access to a Linux or Unix box, and wants to get pysqlite2 working in
> >> his home directory. I have exactly the same problem. I have tried the
> >> "python setup.py install --home=~" method, and I get errors from GCC
> >> that I have no permissions (and to be honest, nor the knowledge) to
> >> overcome.
>
> >> Isn't there anyway to get a Linux binary that can just be put
> >> somewhere in the Python path so we can use sqlite? Or are those of us
> >> without admin/root control of our boxes screwed?
>
> > 1. Get sqlite3 fromhttp://www.sqlite.org/sqlite-3.6.4.tar.gz
> > 2. build and install sqlite3 (./configure --prefix=/any/writeable/dir
> > && make install) -- you may want to supply the --disable-tcl flag if
> > you hit permission problems
> > 3. get pysqlite3, edit setup.cfg libraries and include lines to point
> > to the lib/ and include/ dir where you installed sqlite3 in the
> > previous step
> > 4. python setup.py install --home=somewhere
> > 5. PYTHONPATH=somewhere ./python -- import pysqlite2 should work for
> > you
> > --
>
> Thanks, but either I'm missing something or you're missing something.
> I can't do any of what you describe on the machine I want to use
> sqlite on.
>
> I have downloaded the binary sqlite3 file from sqlite's Web site, and

The linux binary will not work. You need the headers and the
libraries. Grab the src tar ball and build and install locally.

-srp

> I can use it with shell scripts and via the command line with no
> problem. The issue is that I don't seem to have any way available to
> me to use the pysqlite2 Python module.
>
> When I try the "python setup.py --install --home=somewhere"
> installation, it blows up on GCC errors that I do not have the
> permissions to even attempt to fix.  What I was asking above was
> whether there was a way do download the pysqlite2 module as files that
> I can just copy into a directory that Python thinks is part of its
> path so I can use it without having to compile or build it in any way
> on that machine.
>
> Thanks,
> Shawn

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


Re: Rewriting a bash script in python

2008-11-05 Thread Jorgen Grahn
On Wed, 05 Nov 2008 17:42:43 +1300, Lawrence D'Oliveiro <[EMAIL PROTECTED]> 
wrote:
> In message <[EMAIL PROTECTED]>, Chris
> Jones wrote:
>
>> I wrote this in bash and although it's worked w/o a glitch for the last
>> couple of months .. I'm not comfortable with .. "the look & feel of it".
>
> Engineering rule #1: if it works, don't fix it.

Especially if it handles your backups ;-)

-- 
  // Jorgen Grahn   R'lyeh wgah'nagl fhtagn!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Red Hat 32 bit RPM for python 2.4+

2008-11-05 Thread Michael Torrie
James Prav wrote:
> Hi ,
> 
> Could anybody please point to any available Red Hat 32 bit RPM for python
> 2.4 or greater version on Net. I searched a lot but could find for other
> flavour and not Red hat.

RPMS are distro-specific.  What distribution are you looking for?  Since
python is an integral part of any RedHat or Fedora installation, if you
want a version other than the one the OS ships with, I'd recommend you
compile it and install it in /usr/local or some other pace that won't
conflict with the system version of Python.  Trying to replace the
system version of python with a newer rpm is essentially going to break
the entire system.  Right now I find that my fedora installation has no
less than 83 packages that depend on the version of python that is
currently installed.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Rewriting a bash script in python

2008-11-05 Thread Jorgen Grahn
On Tue, 04 Nov 2008 22:11:37 -0500, Chris Jones <[EMAIL PROTECTED]> wrote:
> I wrote a trivial backup script that does the following:
>
> If tonight is the first day of the month:
>
> save last month's archive
> do a full backup of the system
>
> else:
>
> save last night's differential backup
> back up all changes relative to the current month's full backup
>
> endif
>
> I wrote this in bash and although it's worked w/o a glitch for the last
> couple of months .. I'm not comfortable with .. "the look & feel of it".

This sounds like a job for cron(8) -- it's designed for exactly these
things: doing things based on calendar events.  I assume you already
run your backups from cron rather than staying up every night to do
your stuff, so what about changing this in your crontab

   00 1 * * * full_or_incremental_backup

to this?

   00 1 1* * backup --full
   00 1 2-31 * * backup --incremental

(Or maybe two different scripts suit you better.)

That way you needn't implement your own logic for deciding when to do
a full backup. (You still need a way to find the latest full backup,
though.)

/Jorgen

-- 
  // Jorgen Grahn   R'lyeh wgah'nagl fhtagn!
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to build the pysqlite? Where to find the "sqlite3.h"?

2008-11-05 Thread Shawn Milochik
>> Thanks, but either I'm missing something or you're missing something.
>> I can't do any of what you describe on the machine I want to use
>> sqlite on.
>>
>> I have downloaded the binary sqlite3 file from sqlite's Web site, and
>
> The linux binary will not work. You need the headers and the
> libraries. Grab the src tar ball and build and install locally.
>
> -srp

That is not correct. The binary *does* work, as I said last time.

For the third time, it is not possible for me to build from source on that box.

And in any case, you keep talking about sqlite3, but I'm talking about
pysqlite2.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Rewriting a bash script in python

2008-11-05 Thread Marc 'BlackJack' Rintsch
On Wed, 05 Nov 2008 17:12:08 +, Jorgen Grahn wrote:

> On Wed, 05 Nov 2008 17:42:43 +1300, Lawrence D'Oliveiro
>
>> Engineering rule #1: if it works, don't fix it.
> 
> Especially if it handles your backups ;-)

Well, if it handles your backups it doesn't work.  It just pretends until 
you really *need* the backed up data.  ;-)

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


Python 2.3.7 Does not compile on Ubuntu 8.10 i386

2008-11-05 Thread tilley . rb
Hi guys,

Testing some older versions of Python. 2.2.3 compiled and runs just
fine on same machine. I get this error during 2.3.7 make:

case $MAKEFLAGS in \
*-s*)  CC='gcc -pthread' LDSHARED='gcc -pthread -shared' OPT='-
DNDEBUG -g -O3 -Wall -Wstrict-prototypes' ./python -E ./setup.py -q
build;; \
*)  CC='gcc -pthread' LDSHARED='gcc -pthread -shared' OPT='-DNDEBUG -
g -O3 -Wall -Wstrict-prototypes' ./python -E ./setup.py build;; \
esac
*** buffer overflow detected ***: ./python terminated
=== Backtrace: =
/lib/tls/i686/cmov/libc.so.6(__fortify_fail+0x48)[0x4016e558]
/lib/tls/i686/cmov/libc.so.6[0x4016c680]
/lib/tls/i686/cmov/libc.so.6[0x4016cde8]
./python(PySys_SetArgv+0x150)[0x80deeb0]
./python(Py_Main+0x324)[0x8056864]
./python(main+0x22)[0x8056512]
/lib/tls/i686/cmov/libc.so.6(__libc_start_main+0xe5)[0x4008a685]
./python[0x8056451]
=== Memory map: 
08048000-08119000 r-xp  08:01 41855033   /home/brad/Desktop/
Python-2.3.7/python
08119000-0811a000 r--p 000d 08:01 41855033   /home/brad/Desktop/
Python-2.3.7/python
0811a000-08138000 rw-p 000d1000 08:01 41855033   /home/brad/Desktop/
Python-2.3.7/python
08138000-0813b000 rw-p 08138000 00:00 0
0958a000-095f9000 rw-p 0958a000 00:00 0  [heap]
4000-4001a000 r-xp  08:01 37863443   /lib/ld-2.8.90.so
4001a000-4001b000 r-xp 4001a000 00:00 0  [vdso]
4001b000-4001c000 r--p 0001a000 08:01 37863443   /lib/ld-2.8.90.so
4001c000-4001d000 rw-p 0001b000 08:01 37863443   /lib/ld-2.8.90.so
4001d000-4001f000 rw-p 4001d000 00:00 0
4001f000-40026000 r--s  08:01 43081971   /usr/lib/gconv/gconv-
modules.cache
4002c000-40041000 r-xp  08:01 37881007   /lib/tls/i686/cmov/
libpthread-2.8.90.so
40041000-40042000 r--p 00014000 08:01 37881007   /lib/tls/i686/cmov/
libpthread-2.8.90.so
40042000-40043000 rw-p 00015000 08:01 37881007   /lib/tls/i686/cmov/
libpthread-2.8.90.so
40043000-40045000 rw-p 40043000 00:00 0
40045000-40047000 r-xp  08:01 37880987   /lib/tls/i686/cmov/
libdl-2.8.90.so
40047000-40048000 r--p 1000 08:01 37880987   /lib/tls/i686/cmov/
libdl-2.8.90.so
40048000-40049000 rw-p 2000 08:01 37880987   /lib/tls/i686/cmov/
libdl-2.8.90.so
40049000-4004b000 r-xp  08:01 37881015   /lib/tls/i686/cmov/
libutil-2.8.90.so
4004b000-4004c000 r--p 1000 08:01 37881015   /lib/tls/i686/cmov/
libutil-2.8.90.so
4004c000-4004d000 rw-p 2000 08:01 37881015   /lib/tls/i686/cmov/
libutil-2.8.90.so
4004d000-40071000 r-xp  08:01 37880989   /lib/tls/i686/cmov/
libm-2.8.90.so
40071000-40072000 r--p 00023000 08:01 37880989   /lib/tls/i686/cmov/
libm-2.8.90.so
40072000-40073000 rw-p 00024000 08:01 37880989   /lib/tls/i686/cmov/
libm-2.8.90.so
40073000-40074000 rw-p 40073000 00:00 0
40074000-401cc000 r-xp  08:01 37880981   /lib/tls/i686/cmov/
libc-2.8.90.so
401cc000-401ce000 r--p 00158000 08:01 37880981   /lib/tls/i686/cmov/
libc-2.8.90.so
401ce000-401cf000 rw-p 0015a000 08:01 37880981   /lib/tls/i686/cmov/
libc-2.8.90.so
401cf000-40318000 rw-p 401cf000 00:00 0
40318000-40357000 r--p  08:01 13140898   /usr/lib/locale/
en_US.utf8/LC_CTYPE
40364000-40371000 r-xp  08:01 37863486   /lib/libgcc_s.so.1
40371000-40372000 r--p c000 08:01 37863486   /lib/libgcc_s.so.1
40372000-40373000 rw-p d000 08:01 37863486   /lib/libgcc_s.so.1
bfb7e000-bfb93000 rw-p bffeb000 00:00 0  [stack]
Aborted
make: *** [sharedmods] Error 134

Any tips?

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


Re: What's your choice when handle complicated C structures.

2008-11-05 Thread Glenn Linderman
On approximately 11/4/2008 5:31 PM, came the following characters from 
the keyboard of Marc 'BlackJack' Rintsch:

On Tue, 04 Nov 2008 16:52:17 -0800, 一首诗 wrote:

  

Now I'm using the upack function of 'struct' module, but it's really
annoying to write fmt strings for complicated structures.

What will be your choice when handling binary structures?



http://construct.wikispaces.com/


Interesting.  It seems to be a bit more capable around the edges than 
unpack, and certainly has a friendlier looking syntax, but I wonder how 
the performance compares to unpack, for the cases they both handle?  
Seems like for cases they both handle, it could be beneficial to compile 
to the equivalent unpack for speed?


Containers look nice, but it seems it would be nice to allow multiple 
targets: Containers, dicts (with a special entry giving the order of the 
fields, perhaps, for reconstruction; maybe that is what a container is, 
already?), namedtuples, all seem to be reasonable alternative targets, 
with different usage tradeoffs, of course.


--
Glenn -- http://nevcal.com/
===
A protocol is complete when there is nothing left to remove.
-- Stuart Cheshire, Apple Computer, regarding Zero Configuration Networking

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


Getting function and args from generator objects

2008-11-05 Thread Rui Jorge Rei
Hi,

I have been searching for a way to fetch the originating function object
from a generator. I would also like to get all the arguments and keyword
arguments that were used when calling the function that created the
generator. I checked the inspect module, but it doesn't seem to provide that
data.
Is there any way to get this information from a generator object?
Thanks in advance.

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


Re: What's your choice when handle complicated C structures.

2008-11-05 Thread Robert Kern

一首诗 wrote:

Hi all,

Recently I am writing a small network application with python.

The protocol is binary based and defined in c header files.

Now I'm using the upack function of 'struct' module, but it's really
annoying to write fmt strings for complicated structures.

What will be your choice when handling binary structures?


I use numpy and its nested dtypes. But then, I use numpy for damn near 
everything.

  http://numpy.scipy.org/

Construct also looks appropriate.

  http://construct.wikispaces.com/

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Inheritance problem

2008-11-05 Thread Mr . SpOOn
Hi,
I have a problem with this piece of code:


class NoteSet(OrderedSet):
def has_pitch(self):
pass
def has_note(self):
pass

class Scale(NoteSet):
def __init__(self, root, type):
self.append(root)
self.type = type
ScaleType(scale=self)

OrderedSet is an external to use ordered sets. And it has an append
method to append elements to the set.

When I try to create a Scale object:

s = Scale(n, '1234567')  # n is a note

I get this error:

Traceback (most recent call last):
  File "notes.py", line 276, in 
s = Scale(n, '1234567')
  File "notes.py", line 243, in __init__
self.append(root)
  File "ordered_set.py", line 78, in append
self._insertatnode(self._end.prev, element)
AttributeError: 'Scale' object has no attribute '_end'

I can't understand where the error is.
Can you help me?

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


Reading, editing and saving a txt file

2008-11-05 Thread Artur Sousa
Hi everyone.
What I'm trying to do is a Python script that reads a txt file with the
following structure:

> AI_Tactic.dat
>  NO_AI
>  1
>
> Animation.dat
>  Intro
>  2
>
> Areas.dat
>  Start
>  8


Then asks for a user input on what line containing one of those filenames
the script should read, show the desired line, the module and it's id
number. Then ask whether to replace with a new module, by only asking the
new module's name and writing to the txt file both the new module's name and
the new module's ID number which should be the last one + 1.

The desired results should be sth like:
chklst.txt: (before)

> AI_Tactic.dat
>   NO_AI
>   1
>
> Animation.dat
>
   Intro
>   2
>
> Areas.dat
>   Start
>   8
>


> The user then runs the script:

 Which file would you want to append a new module?
> Input>Animation.dat
> This file's last entry was "Intro", ID "2". Would you like to append a new
> module?
> Input>Y
> State the new module's name.
> Input>Outro
> The module "Outro" is now appended to the list with ID "3".
>

Then, chklst.txt would be saved and end up like:

>
> AI_Tactic.dat
>   NO_AI
>   1
>
> Animation.dat
>
   Outro
>   3
>
> Areas.dat
>   Start
>   8
>

--

I've already started some programming, but I'm stuck.

file = open("chklst.txt")
for line in file:
#That's where I'm stuck...
pass
print "Which file would you want to append a new module to?
archive = (raw_input("Input>"))
#then it should find the desired module, and:
print "This file's last entry was"
print module #where module would be the module's name read by python
print "with ID number"
print idno #where idno would be the module's ID number
#I've not figured out how to print text and strings on the same line,
though.
print "Would you like to append a new module to the desired file? (Y or N)"
append = (raw_input("Input>"))
if append = "Y":
pass
if append = "N":
#it should then ask again for another file to be examined
pass
print "Please state the new module's name"
name = (raw_input("Input>"))
#then it should replace the existing module on the file the user requested
with this new one.
print "The module " + name +" was succesfully appended with ID no " idno+1
#then the program finishes.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Inheritance problem

2008-11-05 Thread Diez B. Roggisch
Mr.SpOOn wrote:

> Hi,
> I have a problem with this piece of code:
> 
> 
> class NoteSet(OrderedSet):
> def has_pitch(self):
> pass
> def has_note(self):
> pass
> 
> class Scale(NoteSet):
> def __init__(self, root, type):
> self.append(root)
> self.type = type
> ScaleType(scale=self)
> 
> OrderedSet is an external to use ordered sets. And it has an append
> method to append elements to the set.
> 
> When I try to create a Scale object:
> 
> s = Scale(n, '1234567')  # n is a note
> 
> I get this error:
> 
> Traceback (most recent call last):
>   File "notes.py", line 276, in 
> s = Scale(n, '1234567')
>   File "notes.py", line 243, in __init__
> self.append(root)
>   File "ordered_set.py", line 78, in append
> self._insertatnode(self._end.prev, element)
> AttributeError: 'Scale' object has no attribute '_end'
> 
> I can't understand where the error is.
> Can you help me?

You need to call the __init__ of NoteSet inside Scale, as otherwise the
instance isn't properly initialized.

class Scale(NoteSet):
def __init__(self, root, type):
super(Scale, self).__init__()
...

or
NoteSet.__init__(self)

if you have an old-style class.

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


Asynchat and error handling

2008-11-05 Thread Orestis Markou
Hello,

I'm trying to add some better error handling to an async_chat client.
What I want is to retry or terminate gracefully if the connection to
the server doesn't succeed. Here's what I have:

import asyncore, asynchat, socket

class http_client(asynchat.async_chat):

def __init__(self, host):
asynchat.async_chat.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
terminator = '\x00\xDE\xED\xBE\xEF\x00'
self.buffer = 'I can haz data?' + terminator
self._connected = False
self.set_terminator(terminator)
self.connect( (host, 8080) )

def handle_connect(self):
print 'connected!'

def handle_expt(self):
if not self.connected:
print 'not connected'
self.close()


def collect_incoming_data (self, data):
print data

def found_terminator (self):
print 'terminator found, Closing'
self.close()

def writable(self):
return (len(self.buffer) > 0)

def handle_write(self):
sent = self.send(self.buffer)
self.buffer = self.buffer[sent:]

if __name__ == '__main__':
c = http_client('localhost')
asyncore.loop()

If the connection fails, handle_expt is called, and I can close the
client. However, I have no information from the error, so I can't
retry the connection. I would expect the call to "connect" to raise an
exception, but apparently it's swallowed somewhere. Is there any nice
way to do this?

Thanks!

-- 
[EMAIL PROTECTED]
http://orestis.gr
--
http://mail.python.org/mailman/listinfo/python-list


Re: Finding the instance reference of an object

2008-11-05 Thread Terry Reedy

Dennis Lee Bieber wrote:


I'm sure all the programmers using FORTRAN for the last 50 years
will be very surprised to hear that it uses call-by-value!


That should be 'last 31 years'.  Fortran IV *was* call-by-value, as 
least for scalars.  I remember spending a couple of hours tracking down 
an obscure 'bug' in a once-working program when I ran it with F77. (I 
had not noticed the call-by-reference switch.) The reason was, as I 
remember, 'x = -x' in a function.  I never forgot the difference.



I've used it for 30 years


Then you apparently missed the switch ;-).

tjr


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


Re: [Python-Dev] Why don't range and xrange threat floats as floats?

2008-11-05 Thread Matthieu Brucher
2008/11/5 L V <[EMAIL PROTECTED]>:
> Why don't range and xrange threat floats as floats?
> Is there any good reason range and xrange don't threat floats as floats but
> as integers?
> When I enter float arguments in a range, the floats are treated as integers.
> (+ some warning)
>
> This is how I think it should work:
range(0, 1, 0.1)
> [0.0, 0.10001, 0.20001, 0.2,
> 0.40002, 0.5, 0.59998, 0.69996,
> 0.80004, 0.90002]
>
> I got these results by:
[x/10. for x in xrange(10)]
>
> I'm not looking for alternatives, just for the reason that it works this
> way.

Hi,

I don't think the Python developers list is th best list to post this
kind of question.

What version of Python did you use for this test?

Matthieu
-- 
Information System Engineer, Ph.D.
Website: http://matthieu-brucher.developpez.com/
Blogs: http://matt.eifelle.com and http://blog.developpez.com/?blog=92
LinkedIn: http://www.linkedin.com/in/matthieubrucher
--
http://mail.python.org/mailman/listinfo/python-list


Re: [Python-Dev] Why don't range and xrange threat floats as floats?

2008-11-05 Thread L V
python 2.5
Since it was an indirect suggestion, I thought it belonged here.
What should python-list and python-dev both be used for?
I know there is an alternative, but why not make it easier?





From: Matthieu Brucher <[EMAIL PROTECTED]>
To: L V <[EMAIL PROTECTED]>
Cc: [email protected]
Sent: Wednesday, November 5, 2008 7:38:53 PM
Subject: Re: [Python-Dev] Why don't range and xrange threat floats as floats?

2008/11/5 L V <[EMAIL PROTECTED]>:
> Why don't range and xrange threat floats as floats?
> Is there any good reason range and xrange don't threat floats as floats but
> as integers?
> When I enter float arguments in a range, the floats are treated as integers.
> (+ some warning)
>
> This is how I think it should work:
range(0, 1, 0.1)
> [0.0, 0.10001, 0.20001, 0.2,
> 0.40002, 0.5, 0.59998, 0.69996,
> 0.80004, 0.90002]
>
> I got these results by:
[x/10. for x in xrange(10)]
>
> I'm not looking for alternatives, just for the reason that it works this
> way.

Hi,

I don't think the Python developers list is th best list to post this
kind of question.

What version of Python did you use for this test?

Matthieu
-- 
Information System Engineer, Ph.D.
Website: http://matthieu-brucher.developpez.com/
Blogs: http://matt.eifelle.com and http://blog.developpez.com/?blog=92
LinkedIn: http://www.linkedin.com/in/matthieubrucher



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


Re: Getting function and args from generator objects

2008-11-05 Thread Terry Reedy

Rui Jorge Rei wrote:
I have been searching for a way to fetch the originating function object 
from a generator.


Futile, I believe.

 I would also like to get all the arguments and keyword
arguments that were used when calling the function that created the 
generator.


The arguments to a generator function are the arguments to the generator 
's next method.  The code is (in 3.0, at least) .gi_code and you can 
extract whatever you can from that.


tjr



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


Re: Inheritance problem

2008-11-05 Thread Mr . SpOOn
On Wed, Nov 5, 2008 at 6:59 PM, Diez B. Roggisch <[EMAIL PROTECTED]> wrote:
> You need to call the __init__ of NoteSet inside Scale, as otherwise the
> instance isn't properly initialized.

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


Re: How to build the pysqlite? Where to find the "sqlite3.h"?

2008-11-05 Thread Thorsten Kampe
* Shawn Milochik (Wed, 5 Nov 2008 12:28:46 -0500)
> >> Thanks, but either I'm missing something or you're missing
> >> something. I can't do any of what you describe on the machine I
> >> want to use sqlite on.
> >>
> >> I have downloaded the binary sqlite3 file from sqlite's Web site,
> >> and
> >
> > The linux binary will not work. You need the headers and the
> > libraries. Grab the src tar ball and build and install locally.
> 
> That is not correct. The binary *does* work, as I said last time.
> 
> For the third time, it is not possible for me to build from source on
> that box.

Sure you can. There are never permission problems for compiling - only 
for installing.
 
> And in any case, you keep talking about sqlite3, but I'm talking about
> pysqlite2.

You (and Kurda) keep on talking the wrong stuff. First: you don't need 
pysqlite2. SQLite support is included in the latest Python as module 
sqlite3.

If for whatever reason you need the latest SQLite module for Python 
(2.5.0), you can simply grab an rpm or build it from source and install 
it to your home directory. To build pysqlite you need the SQLite 
headers. If you can't install those to default path then simply grab the 
headers, put them somewhere into your home directory and tell the 
pysqlite build process where to find them.

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


Re: Reading, editing and saving a txt file

2008-11-05 Thread Terry Reedy

Artur Sousa wrote:

Hi everyone.
What I'm trying to do is a Python script that reads a txt file with the 
following structure:

...

I've already started some programming, but I'm stuck.


You started from the bottom up.  Now also try from the top down.  What 
should be the main structure of your program?  Ignoring details, is 
there a top-level switch or loop?  When you have that, you can cut and 
paste snippets already written into that structure.


tjr

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


Re: [Python-Dev] Why don't range and xrange threat floats as floats?

2008-11-05 Thread Steve Holden
Matthieu Brucher wrote:
> 2008/11/5 L V <[EMAIL PROTECTED]>:
>> Why don't range and xrange threat floats as floats?
>> Is there any good reason range and xrange don't threat floats as floats but
>> as integers?
>> When I enter float arguments in a range, the floats are treated as integers.
>> (+ some warning)
>>
>> This is how I think it should work:
> range(0, 1, 0.1)
>> [0.0, 0.10001, 0.20001, 0.2,
>> 0.40002, 0.5, 0.59998, 0.69996,
>> 0.80004, 0.90002]
>>
>> I got these results by:
> [x/10. for x in xrange(10)]
>> I'm not looking for alternatives, just for the reason that it works this
>> way.
>
It works this way because you can't be sure that you won't get an extra
increment. When you repeatedly add fractions together, the desired final
 result might be just less or just more than the actual integral value.
If it's just less you will get an extra increment. It just doesn't work.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


is this a good way to do imports ?

2008-11-05 Thread Stef Mientki

hello,

I can't find any good documentation or examples of packages,
so I'm not sure if this is good / correct way, although it seems to work.

root
 / dir1
   / file1.py
   / general.py

 / dir2
   / file2.py

 / general_root.py

Now I want to be able to use functions of file2 in file1,
and vice-versa.
In practice the directory structure is more complex and nested more deeply,
and basically I want all modules to be reachable by all other modules.

 file1.py 
import general
import file2
print file2.var

 file2.py 
var = 33

 general.py 
dir = '../dir'
import sys
if not ( dir in sys.path ) :
 sys.path.append ( dir )

For a more complex directory structure this is not doable.
So another approach could be

 file1.py 
import general
import file2
print file2.var

 file2.py 
var = 33

 general.py  is doesn't need to know about other branches, only 
of the root

dir = '../'
import sys
if not ( dir in sys.path ) :
 sys.path.append ( dir )
import general_root

 general_root.py  this can be fully automated
dir = '../dir2/'
import sys
if not ( dir in sys.path ) :
 sys.path.append ( dir )

And for the last thought I had:
why not use __init__.py instead of the general.py procedure ??

Maybe I should also set the current working directory to the root or to 
the python file I launch ??


please enlighten me.

thanks,
Stef Mientki

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


Re: Ordering python sets

2008-11-05 Thread Mr . SpOOn
The discussion's gone a bit off topic so I don't know if it is a good
idea to continue here. I'll try.

My first question was about a way to order a python set. Someone
suggested to try this module:

http://code.activestate.com/recipes/528878/

It seemed pretty good, but I've tried it just today and something doesn't work.
I think it doesn't work because what I have to order are objects and
not just numbers. Anyway, I'm not sure that this is the problem.

What I get when I try to append one of my object is:

  File "notes.py", line 245, in __init__
self.append(root)
  File "ordered_set.py", line 78, in append
self._insertatnode(self._end.prev, element)
  File "ordered_set.py", line 110, in _insertatnode
if element in self._map:
TypeError: unhashable instance

Don't know if it is important, but inside the class of the object that
I'm trying to append, I redefined the __eq__ and __gt__ method.
--
http://mail.python.org/mailman/listinfo/python-list


Dictionary membership check failure

2008-11-05 Thread Zac Burns
Greetings,

I have a dictionary that seems to be misbehaving on a membership
check. This test code:

1: import types
2: assert myDict.__class__ is types.DictionaryType
3: assert (key in myDict.keys()) == (key in myDict)

raises AssertionError on line three. The dictionary items are all of
type (string, function).

There are no threads.

Python version is 2.5.1, I cannot go to 2.5.2 right now because of a
module that we use that depends on 2.5.1 (maya standalone), but does
anyone know if this bug has been fixed in 2.5.2 or if I can give
anyone more information to help fix this bug?

--
Zachary Burns
Aim - Zac256FL
Production Engineer
Zindagi Games
--
http://mail.python.org/mailman/listinfo/python-list


Re: 2.6, 3.0, and truly independent intepreters

2008-11-05 Thread Andy O'Meara
On Nov 4, 10:59 am, sturlamolden <[EMAIL PROTECTED]> wrote:
> On Nov 4, 4:27 pm, "Andy O'Meara" <[EMAIL PROTECTED]> wrote:
>
> > People
> > in the scientific and academic communities have to understand that the
> > dynamics in commercial software are can be *very* different needs and
> > have to show some open-mindedness there.
>
> You are beware that BDFL's employer is a company called Google? Python
> is not just used in academic settings.

Turns out I have heard of Google (and how about you be a little more
courteous). If you've read the posts in this thread, you'll note that
the needs outlined in this thread are quite different than the needs
and interests of Google.  Note that my point was that python *could*
and *should* be used more in end-user/desktop applications, but it
can't "wag the dog" to use my earlier statement.

>
> Furthermore, I gave you a link to cilk++. This is a simple tool that
> allows you to parallelize existing C or C++ software using three small
> keywords.

Sorry if it wasn't clear, but we need the features associated with an
embedded interpreter.  I checked out clik++ when you linked it and
although it seems pretty cool, it's not a good fit for us for a number
of reasons.  Also, we like the idea of helping support a FOSS project
rather than license a proprietary product (again, to be clear, using
cilk isn't even appropriate for our situation).


> > As other posts have gone into extensive detail, multiprocessing
> > unfortunately don't handle the massive/complex data structures
> > situation (see my posts regarding real-time video processing).  
>
> That is something I don't believe. Why can't multiprocessing handle
> that?

In a few earlier posts, I went into details what's meant there:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/9d995e4a1153a1b2/09aaca3d94ee7a04?lnk=st#09aaca3d94ee7a04
http://groups.google.com/group/comp.lang.python/msg/edae2840ab432344
http://groups.google.com/group/comp.lang.python/msg/5be213c31519217b

> For Christ sake, researchers
> write global climate models using MPI. And you think a toy problem
> like 'real-time video processing' is a show stopper for using multiple
> processes.

I'm not sure why you're posting this sort of stuff when it seems like
you haven't checked out earlier posts in the this thread.  Also, you
do yourself and the people here a disservice in the way that you're
speaking to me here.  You never know who you're really talking to or
who's reading.


Andy



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


Re: is this a good way to do imports ?

2008-11-05 Thread Terrence Brannon
On Nov 5, 2:14 pm, Stef Mientki <[EMAIL PROTECTED]> wrote:

> Now I want to be able to use functions of file2 in file1,
> and vice-versa.

It sounds like __all__ in __init__.py would work:
http://www.python.org/doc/2.5.2/tut/node8.html#SECTION00840

If not, then pkgutil might of use?
http://docs.python.org/library/pkgutil.html


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


Re: Dictionary membership check failure

2008-11-05 Thread Zac Burns
Sorry everyone, I found the bug in my code shortly after posting here.

For the curious:

I was using a QString (pyqt) inadvertently in the lookup. I guess the
behavior then would be would be that QStrings hash differently than
strings which accounts for the membership check failure, but lists do
an equivalency check of some sort (I don't know the C code, this is an
educated guess) without ever hashing so it succeeded.

--
Zachary Burns
Aim - Zac256FL
Production Engineer
Zindagi Games



On Wed, Nov 5, 2008 at 11:34 AM, Zac Burns <[EMAIL PROTECTED]> wrote:
> Greetings,
>
> I have a dictionary that seems to be misbehaving on a membership
> check. This test code:
>
> 1: import types
> 2: assert myDict.__class__ is types.DictionaryType
> 3: assert (key in myDict.keys()) == (key in myDict)
>
> raises AssertionError on line three. The dictionary items are all of
> type (string, function).
>
> There are no threads.
>
> Python version is 2.5.1, I cannot go to 2.5.2 right now because of a
> module that we use that depends on 2.5.1 (maya standalone), but does
> anyone know if this bug has been fixed in 2.5.2 or if I can give
> anyone more information to help fix this bug?
>
> --
> Zachary Burns
> Aim - Zac256FL
> Production Engineer
> Zindagi Games
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to build the pysqlite? Where to find the "sqlite3.h"?

2008-11-05 Thread Shawn Milochik
On Wed, Nov 5, 2008 at 1:55 PM, Thorsten Kampe
<[EMAIL PROTECTED]> wrote:
> * Shawn Milochik (Wed, 5 Nov 2008 12:28:46 -0500)
>> >> Thanks, but either I'm missing something or you're missing
>> >> something. I can't do any of what you describe on the machine I
>> >> want to use sqlite on.
>> >>
>> >> I have downloaded the binary sqlite3 file from sqlite's Web site,
>> >> and
>> >
>> > The linux binary will not work. You need the headers and the
>> > libraries. Grab the src tar ball and build and install locally.
>>
>> That is not correct. The binary *does* work, as I said last time.
>>
>> For the third time, it is not possible for me to build from source on
>> that box.
>
> Sure you can. There are never permission problems for compiling - only
> for installing.
>
>> And in any case, you keep talking about sqlite3, but I'm talking about
>> pysqlite2.
>
> You (and Kurda) keep on talking the wrong stuff. First: you don't need
> pysqlite2. SQLite support is included in the latest Python as module
> sqlite3.
>
> If for whatever reason you need the latest SQLite module for Python
> (2.5.0), you can simply grab an rpm or build it from source and install
> it to your home directory. To build pysqlite you need the SQLite
> headers. If you can't install those to default path then simply grab the
> headers, put them somewhere into your home directory and tell the
> pysqlite build process where to find them.
>
> Thorsten


Okay, sorry if I haven't been specific enough. I don't know about the
original poster, but on the box I'm using, I don't have the latest
Python, the "make" command breaks because the system doesn't have the
proper libraries, and there is no sqlite3 module. I am not authorized
to fix any of that, and our support team isn't interested in helping
me because it's a Perl shop, not Python.

I'm not demanding that anyone solve my problem. I'm just asking if
there are files I can download and without compiling or building them
in any way, put them somewhere, point Python to that path, and be able
to use sqlite from Python. If the answer is no, it's no. I'm not
repeating myself because I enjoy it. For some reason everyone who has
answered me has ignored the basic question of whether this is possible
or not, so I have felt the need to reply and say so.

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


Using subprocess.Popen() in a Windows service

2008-11-05 Thread Mark Shewfelt
Hello,

I am attempting to use Popen() in a Windows service. I have a small
Win32 .exe that I normally run through the os.popen2() function. I've
written a class to work with the input and output parameters that are
passed and captured from this exe. When I use the class outside of a
service using either subprocess.Popen or os.popen2 work just fine.

When I use this class inside a Windows service it doesn't work. It
doesn't crash the service or anything but there are no values returned
from the Popen. Here's how I'm calling Popen:

p = subprocess.Popen( cmd, shell=True, bufsize=128,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
cwd="C:\\path_to_exe\\" )
p.wait()
(modbus_stdin, modbus_stdout)=(p.stdin,p.stdout)
lines = modbus_stdout.readlines()

While this doesn't fail there is nothing in the lines variable when it
finishes.

I am using Python 2.5 on a Windows XP Professional machine. Any help
would be greatly appreciated.

Best Regards,

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


Re: push-style templating - an xml-like way to process xhtml

2008-11-05 Thread Terrence Brannon
On Nov 5, 6:03 am, lkcl <[EMAIL PROTECTED]> wrote:

>
> * pyjamas (http://pyjs.org) - this is treating the web page and the

wow. I had never heard of it, but it is _damned_ impressive. THANK
YOU. I'm joining the club for my next webdev project!

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


Re: Extract frame from wmv

2008-11-05 Thread Martin

Tim Golden wrote:

Martin wrote:

I've looked at Pymedia but I have to admit I couldn't work it out.

Commandline might be good, but I'm really hoping someone can point me 
in the right direction, as this is not my area of expertise.



Nor mine :) Just so people can help you out, can you
be more precise in your requirement? Do you want just
the first frame (eg to act as an img placeholder for
an embedded video). Or do you want to extract one or
more arbitrary frames, eg for screen cap purposes?

This page:

 http://stream0.org/2008/02/howto-extract-images-from-a-vi.html

looks helpful from the ffmpeg pov, but I assume you're
as capable of using Google as I am. I had a very quick
go with the copy of pymedia I have installed here, but
it couldn't read a (fairly recent) .wmv file so that
might be a problem in any case.

UPDATE: Just tried:

 ffmpeg -i bacardi.wmv -r 1 -f image2 images%05d.png

from that page and it produced useful stuff. Worth a try?

TJG


Thanks again Tim,

I'm just extracting the first frame to use as a thumbnail.

I will try ffmpeg. Thanks for pointer. I didn't really know where to 
start looking.


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


Trying to set a date field in a access databse

2008-11-05 Thread [EMAIL PROTECTED]
Hi,
I cannot get the following code to work

import win32com.client
import time

engine = win32com.client.Dispatch("DAO.DBEngine.36")
db=engine.OpenDatabase(r"testdate2.mdb")
access = db.OpenRecordset("select * from test")

access.AddNew()
access.Fields("test").value=time.strptime('10:00AM', '%I:%M%p')
access.Update()

wherer test is a datetime field,
How can I do this???
-Ted

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


Re: socket.getaddrinfo: flags |= AI_ADDRCONFIG

2008-11-05 Thread Martin v. Löwis
> 1) mimic glibc default behavior, i.e. if flags is unspecified or
>None, treat it as the default value of AI_V4MAPPED |
>AI_ADDRCONFIG).

Unfortunately, that contradicts with RFC 3493, which says

#   If hints is a null pointer, the behavior
#   shall be as if it referred to a structure containing the value zero
#   for the ai_flags, ai_socktype and ai_protocol fields, and AF_UNSPEC
#   for the ai_family field.

Of course, we might chose to ignore that.

> Alternatively:
> 2) add these flags to callers of socket.getaddrinfo in various
>standard libs, e.g. httplib.

There is apparently a problem with this one, also: implementations
might define AI_ADDRCONFIG, but not implement it, but instead return
EAI_BADFLAGS. Not sure whether this is a real problem, though.

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


Re: Dictionary membership check failure

2008-11-05 Thread Steve Holden
Zac Burns wrote:
> Greetings,
> 
> I have a dictionary that seems to be misbehaving on a membership
> check. This test code:
> 
> 1: import types
> 2: assert myDict.__class__ is types.DictionaryType
[...]

For the record, it would be much simpler and more readable to say

assert type(myDict) is dict

not to mention it avoids the unnecessary import.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: Error loading modules

2008-11-05 Thread John Machin
On Nov 6, 3:21 am, BL <[EMAIL PROTECTED]> wrote:
> On Nov 4, 7:11 pm, John Machin <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Nov 5, 9:18 am, BL <[EMAIL PROTECTED]> wrote:
>
> > > I am very new to python.  I am installing it as part of a bazzar
> > > version control installation.
> > > I have installed the Crypto, paramiko and cElementTree modules.  I am
> > > running Solaris10x86.
> > > When testing the modules I get the following results.
>
> > >  python -c "import Crypto"
> > > Traceback (most recent call last):
> > >   File "", line 1, in 
> > > ImportError: No module named Crypto
>
> > What is "the Crypto module"? What is the path to the directory in
> > which you installed it? Do you mean one of crypto [case matters],
> > pycrypto, pyCrypto, M2Crypto, ...?
>
> pyCrypto is the module I installed.

or pycrypto??? What URL did you download it from?

>  The directory it is installed in
> is
> /usr/local/lib/python2.5/site-packages  - there is one directory
> called
> Crytpo and two other files called  pycrytpo-2.0.1-py2.5.egg-info and
> pycrytpo-2.0.1-py2.5-solaris-2.10-i86pc.egg.

There are *THREE* apparent typos there ("...rytpo" instead of
"...rypto"). Do please check what you type. Did you by any chance
type
   python -c "import Crytpo"
originally? Were your "following results" obtained by copy/paste or by
typing it all in yourself?

What is in the .../site-packages/Crypto directory?

>
> The directions to check the installation of the python modules said
> to
> execute python -c "import Crypto"

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


Re: Is there a better/simpler way to filter blank lines?

2008-11-05 Thread tmallen
Why do I feel like the coding style in Lutz' "Programming Python" is
very far from idiomatic Python? The content feels dated, and I find
that most answers that I get for Python questions use a different
style from the sort of code I see in this book.

Thomas

On Nov 5, 7:15 am, Jorgen Grahn <[EMAIL PROTECTED]> wrote:
> On Tue, 04 Nov 2008 15:36:23 -0600, Larry Bates <[EMAIL PROTECTED]> wrote:
> > [EMAIL PROTECTED] wrote:
> >> tmallen:
> >>> I'm parsing some text files, and I want to strip blank lines in the
> >>> process. Is there a simpler way to do this than what I have here?
> >>> lines = filter(lambda line: len(line.strip()) > 0, lines)
>
> ...
>
> > Of if you want to filter/loop at the same time, or if you don't want all the
> > lines in memory at the same time:
>
> Or if you want to support potentially infinite input streams, such as
> a pipe or socket.  There are many reasons this is my preferred way of
> going through a text file.
>
> > fp = open(filename, 'r')
> > for line in fp:
> >      if not line.strip():
> >          continue
>
> >      #
> >      # Do something with the non-blank like:
> >      #
>
> > fp.close()
>
> Often, you want to at least rstrip() all lines anyway,
> for other reasons, and then the extra cost is even less:
>
>        line = line.rstrip()
>        if not line: continue
>        # do something with the rstripped, nonblank lines
>
> /Jorgen
>
> --
>   // Jorgen Grahn  \X/     snipabacken.se>          R'lyeh wgah'nagl fhtagn!

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


Re: Ordering python sets

2008-11-05 Thread Arnaud Delobelle
Mr.SpOOn <[EMAIL PROTECTED]> writes:

> The discussion's gone a bit off topic so I don't know if it is a good
> idea to continue here. I'll try.
>
> My first question was about a way to order a python set. Someone
> suggested to try this module:
>
> http://code.activestate.com/recipes/528878/
>
> It seemed pretty good, but I've tried it just today and something
> doesn't work.  I think it doesn't work because what I have to order
> are objects and not just numbers. Anyway, I'm not sure that this is
> the problem.
>
> What I get when I try to append one of my object is:
>
>   File "notes.py", line 245, in __init__
> self.append(root)
>   File "ordered_set.py", line 78, in append
> self._insertatnode(self._end.prev, element)
>   File "ordered_set.py", line 110, in _insertatnode
> if element in self._map:
> TypeError: unhashable instance
>
> Don't know if it is important, but inside the class of the object that
> I'm trying to append, I redefined the __eq__ and __gt__ method.

Only hashable objects can go in a set.  By default a class you define is
not hashable (unless it descends from a hashable class).  To remedy this
you can define a __hash__ method in your class.  IIRC the only
requirement of a hash function is that two equal objects have the same
hash.

HTH

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


Re: Finding the instance reference of an object

2008-11-05 Thread Lie
On Nov 4, 9:33 am, Joe Strout <[EMAIL PROTECTED]> wrote:
> On Nov 3, 2008, at 5:27 PM, Marc 'BlackJack' Rintsch wrote:
>
> > Maybe this is a surprise for you, because we haven't discussed this in
> > much detail in this group lately, but it applies to Python which does
> > call-by-object or call-by-sharing.  ;-)
>
> There's no such thing.  Those are just terms made up by the Python  
> community to in place of the more standard "call-by-value" terminology  
> to make Python seem more mysterious than it really is.  I guess you  
> can call it "purple bananas" if you want, but the behavior is exactly  
> the same as what every other language calls call-by-value.
>
> But I really am trying not to continue this debate.  So that's my last  
> reply about it for tonight, I promise.  :)
>
> Cheers,
> - Joe
> 

I'm fed up with you.

In Von Neumann Architecture computers, only pass-by-value is natively
supported. Other idioms are made on top of pass-by-value.

That's why exclusively pass-by-value languages like C is most flexible
than other exclusively pass-by-.

BUT the difference is clear, if you want to do pass-by-reference in C
(I prefer to call it faux pass-by-reference), you'd have to manually
find a variable's address, pass it by-value, then dereference the
address. Compare with VB's ByRef or C++'s &, which does all that
_automatically_ for you behind the scene.

Another example: pass-by-object. I disagree with the term pass-by-
object-reference, since the notion of object reference is unnecessary
in a true pass-by-object mechanism (i.e. we should travel outside VNA
realm for a true pass-by-object mechanism). Problem is: I'm not aware
of any computer architecture that can accommodate pass-by-object
natively or whether such architecture is feasible to be made.
Solution: Emulate such architecture on a VNA computer. Limitations:
pass-by-object implementation on a VNA computer requires the notion of
object reference/pointer because VNA computers cannot pass object, it
can only pass numbers.

In pass-by-object, the whole object is passed around, not a copy of
the object like in pass-by-value or a copy of the pointer to the
object like in faux pass-by-reference. This makes pass-by-object
actually closer to pass-by-reference than to pass-by-value, since the
notion of VNA's requirement for Object Reference means passing
pointers around. But don't let it confuse you, the pass-by-object
mechanism itself does not recognize Object Reference, unlike pass-by-
reference recognition of reference/pointer.

Now that I have clearly defined the line between pass-by-object and
pass-by-value, I'm left with you thinking what's the difference
between pass-by-object and pass-by-reference. In pass-by-reference,
names are _mnemonic to location in memory_. In pass-by-object, names
are _mnemonic to objects_. In pass-by-reference, when we assign a
value to the name, we'd assign a value _to the location in memory_. In
pass-by-object, when we assign a value to the name, we assign an
object _to the name_. When passing parameters, pass-by-reference
systems passed the memory address and alias that memory address to a
local name. In pass-by-object system, since the object itself has no
idea of its own name, so it is rebound to a local name. You can say
that pass-by-reference system is memory-location-centered, while pass-
by-object system is name-centered.

To summarize, the key bit you're missing is built-in _automatic_
abstraction from pass-by-value. All pass-by- except
pass-by-value is an emulation over an architecture that can only
natively pass-by-value. pass-by-reference is emulated in C, C++, and
VB by passing memory address/pointer but C isn't a by-ref system
because C doesn't provide the automatization. What makes python's
parameter passing called as pass-by-object is because python provides
the automatization to make it seems that you can do true pass-by-
object.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a better/simpler way to filter blank lines?

2008-11-05 Thread Lie
On Nov 5, 4:56 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Wed, 05 Nov 2008 14:39:36 +1100, Ben Finney wrote:
> > Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> writes:
>
> >> On Wed, 05 Nov 2008 13:18:27 +1100, Ben Finney wrote:
>
> >> > Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> writes:
>
> >> > Your example shows only that they're important for grouping the
> >> > expression from surrounding syntax. As I said.
>
> >> > They are *not* important for making the expresison be a generator
> >> > expression in the first place. Parentheses are irrelevant for the
> >> > generator expression syntax.
>
> >> Okay, technically correct but parenthesis belong to generator
> >> expressions because they have to be there to separate them from
> >> surrounding syntax with the exception when there are already enclosing
> >> parentheses.  So parenthesis are tied to generator expression syntax.
>
> > No, I think that's factually wrong *and* confusing.
>
> >     >>> list(i + 7 for i in range(10))
> >     [7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
>
> > Does this demonstrate that parentheses are “tied to” integer literal
> > syntax? No.
>
> You can use integer literals without parenthesis, like the 7 above, but
> you can't use generator expressions without them.  They are always
> there.  In that way parenthesis are tied to generator expressions.
>
> If I see the pattern ``f(x) for x in obj if c(x)`` I look if it is
> enclosed in parenthesis or brackets to decide if it is a list
> comprehension or a generator expression.  That may not reflect the formal
> grammar, but it is IMHO the easiest and pragmatic way to look at this as
> a human programmer.
>
> Ciao,
>         Marc 'BlackJack' Rintsch

The situation is similar to tuples. What makes a tuple is the commas,
not the parens.
What makes a generator expression is " for  in
".

Parenthesis is generally required because without it, it's almost
impossible to differentiate it with the surrounding. But it is not
part of the formally required syntax.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a better/simpler way to filter blank lines?

2008-11-05 Thread Arnaud Delobelle
Lie <[EMAIL PROTECTED]> writes:
> What makes a generator expression is " for  in
> ".
>
> Parenthesis is generally required because without it, it's almost
> impossible to differentiate it with the surrounding. But it is not
> part of the formally required syntax.

... But *every* generator expression is surrounded by parentheses, isn't
it?

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


Re: Trying to set a date field in a access databse

2008-11-05 Thread Peter Otten
[EMAIL PROTECTED] wrote:

> Hi,
> I cannot get the following code to work
> 
> import win32com.client
> import time
> 
> engine = win32com.client.Dispatch("DAO.DBEngine.36")
> db=engine.OpenDatabase(r"testdate2.mdb")
> access = db.OpenRecordset("select * from test")
> 
> access.AddNew()
> access.Fields("test").value=time.strptime('10:00AM', '%I:%M%p')
> access.Update()
> 
> wherer test is a datetime field,
> How can I do this???

A first step would be to find out what the expected type of the value
attribute is. For that you can put one record into the test table using
Access with the value 10:00AM for the test field and then run 

# all code untested

import win32com.client

engine = win32com.client.Dispatch("DAO.DBEngine.36")
db = engine.OpenDatabase("testdate2.mdb")
access = db.OpenRecordset("select * from test")

access.MoveFirst()
v = access.Fields("test").value
print type(v), v

If you cannot guess what Access expects from the output of the script, post
it here (in this thread, no need to start yet another one). Don't just
say "didn't work", give tracebacks and the exact code you ran.

Judging from 
http://en.wikibooks.org/wiki/JET_Database/Data_types#Dates_and_times
you will see something like

 0.4167

If that's correct you can modify your script

def time_to_float(h, m, s):
return (h + m/60.0 + s/3600.0)/24.0 

# ...

access.AddNew()
access.Fields("test").value = time_to_float(10, 0, 0)
access.Update()

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


Re: Is there a better/simpler way to filter blank lines?

2008-11-05 Thread Steven D'Aprano
On Wed, 05 Nov 2008 21:23:57 +, Arnaud Delobelle wrote:

> Lie <[EMAIL PROTECTED]> writes:
>> What makes a generator expression is " for  in
>> ".
>>
>> Parenthesis is generally required because without it, it's almost
>> impossible to differentiate it with the surrounding. But it is not part
>> of the formally required syntax.
> 
> ... But *every* generator expression is surrounded by parentheses, isn't
> it?

Yes, but sometimes they are there in order to call a function, not to 
form the generator expression.

I'm surprised that nobody yet has RTFM:

http://docs.python.org/reference/expressions.html

[quote]
A generator expression is a compact generator notation in parentheses:

generator_expression ::=  "(" expression genexpr_for ")"
genexpr_for  ::=  "for" target_list "in" or_test [genexpr_iter]
genexpr_iter ::=  genexpr_for | genexpr_if
genexpr_if   ::=  "if" old_expression [genexpr_iter]

...
The parentheses can be omitted on calls with only one argument.
[end quote]

It seems to me that the FM says that the parentheses *are* part of the 
syntax for a generator expression, but if some other syntactic construct 
(e.g. a function call) provides the parentheses, then you don't need to 
supply a second, redundant, pair.

I believe that this is the definitive answer, short of somebody reading 
the source code and claiming the documentation is wrong.



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


Re: Is there a better/simpler way to filter blank lines?

2008-11-05 Thread Duncan Booth
Arnaud Delobelle wrote:

> Lie <[EMAIL PROTECTED]> writes:
>> What makes a generator expression is " for  in
>> ".
>>
>> Parenthesis is generally required because without it, it's almost
>> impossible to differentiate it with the surrounding. But it is not
>> part of the formally required syntax.
>
> ... But *every* generator expression is surrounded by parentheses, isn't
> it?
>
Indeed, the syntax production is:

generator_expression ::= "(" expression genexpr_for ")" 

albeit with the note: "The parentheses can be omitted on calls with only
one argument. See section 5.3.4 for the detail."  but that only means
you don't need a second set of parentheses. A generator expression is
always enclosed in parentheses, the same is NOT true of a tuple.


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


Re: 2.6, 3.0, and truly independent intepreters

2008-11-05 Thread Paul Boddie
On 5 Nov, 20:44, "Andy O'Meara" <[EMAIL PROTECTED]> wrote:
> On Nov 4, 10:59 am, sturlamolden <[EMAIL PROTECTED]> wrote:
>
> > For Christ sake, researchers
> > write global climate models using MPI. And you think a toy problem
> > like 'real-time video processing' is a show stopper for using multiple
> > processes.
>
> I'm not sure why you're posting this sort of stuff when it seems like
> you haven't checked out earlier posts in the this thread.  Also, you
> do yourself and the people here a disservice in the way that you're
> speaking to me here.  You never know who you're really talking to or
> who's reading.

I think your remarks about "people in the scientific and academic
communities" went down the wrong way, giving (or perhaps reinforcing)
the impression that such people live carefree lives and write software
unconstrained by external factors.

Anyway, to keep things constructive, I should ask (again) whether you
looked at tinypy [1] and whether that might possibly satisfy your
embedded requirements. As I noted before, the developers might share
your outlook on a number of matters. Otherwise, you might peruse the
list of Python implementations:

http://wiki.python.org/moin/implementation

Paul

[1] http://www.tinypy.org/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a better/simpler way to filter blank lines?

2008-11-05 Thread Miles
Ben Finney wrote:
> Falcolas writes:
>
>> Using the surrounding parentheses creates a generator object
>
> No. Using the generator expression syntax creates a generator object.
>
> Parentheses are irrelevant to whether the expression is a generator
> expression. The parentheses merely group the expression from
> surrounding syntax.

As others have pointed out, the parentheses are part of the generator
syntax.  If not for the parentheses, a list comprehension would be
indistinguishable from a list literal with a single element, a
generator object.  It's also worth remembering that list
comprehensions are distinct from generator expressions and don't
require the creation of a generator object.

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


Re: is this a good way to do imports ?

2008-11-05 Thread Terry Reedy

Stef Mientki wrote:

hello,

I can't find any good documentation or examples of packages,
so I'm not sure if this is good / correct way, although it seems to work.

root
 / dir1
   / file1.py
   / general.py

 / dir2
   / file2.py

 / general_root.py

Now I want to be able to use functions of file2 in file1,
and vice-versa.
In practice the directory structure is more complex and nested more deeply,
and basically I want all modules to be reachable by all other modules.


One straightforward way is plain old absolute imports.  Assume root is 
in the import path (for instance, in site packages)


 file1.py 
import general


from root.dir1 import general


import file2


from root.dir2 import file2
or even
from root.dir2.file2 import func


This will break if the tree changes.  So will new relative imports.
Pulling everything into root in its __init__.py breaks if there are 
duplicate module names.


Anyway, above is what I am doing with my current 3-level 
(pac.subpac.mod) package until I learn something really better, given 
that the interdependencies in my package should remain relatively sparse.


tjr

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


Query netgroup information through python

2008-11-05 Thread Joel Heenan
Python List,

We have a setup where we have implemented NIS Netgroups through LDAP.
I'm looking to query this information through python. We don't have a
nis domain or nis server so I don't think the nis module is
appropriate, what I think I'm looking for is python bindings for nss
(name switching services). Does such a module exist? grp, pwd, spwd I
think are all going through NSS but do not handle netgroups.

Thanks

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


Plz help..SocketServer UDP server losing lots of packets

2008-11-05 Thread id . engg
logFileName = 'log.txt'
logfile = open(logFileName, "a")
class MyUDPServer(SocketServer.UDPServer):
def server_bind(self):
self.socket.setsockopt(socket.SOL_SOCKET,
socket.SO_RCVBUF, 8388608)
self.socket.bind(self.server_address)

class LogsDumpHandler(SocketServer.DatagramRequestHandler):
def handle(self):
global logfile
# fileExists is a function which checks the existence of a file
if not fileExists(logFileName):
logfile = open(logFileName, "a")
logfile.writelines(self.rfile.readlines())

server = MyUDPServer(("",PORT), LogsDumpHandler)
server.serve_forever()
logfile.close()

The above python code is a UDP server based on SocketServer framework
and I am losing a lot of messages, I have tried almost everything,
increasing the size of the receive buffer, changing the way i read the
messages coming into server.
The above code is supposed to work as a tracing server and it does but
is losing messages.
Is there a way I can improve this code?
Any help will be highly appreciated.

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


Re: Is there a better/simpler way to filter blank lines?

2008-11-05 Thread Ben Finney
Steven D'Aprano <[EMAIL PROTECTED]> writes:

> I'm surprised that nobody yet has RTFM:
> http://docs.python.org/reference/expressions.html
> 
> generator_expression ::=  "(" expression genexpr_for ")"
> ...
> The parentheses can be omitted on calls with only one argument.

It's a fair cop. Thanks for setting me straight.

-- 
 \ “We can't depend for the long run on distinguishing one |
  `\ bitstream from another in order to figure out which rules |
_o__)   apply.” —Eben Moglen, _Anarchism Triumphant_, 1999 |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Re: Rewriting a bash script in python

2008-11-05 Thread Chris Jones
On Tue, Nov 04, 2008 at 11:11:17PM EST, Ben Finney wrote:
> Chris Jones <[EMAIL PROTECTED]> writes:
> 
> > I am thinking of rewriting it in python using OOP tactics/strategy.
> > 
> > Please advise.
> 
> I advise you not to have the object-oriented programming hammer as
> your only tool, because it's easy to then treat every problem as
> though it were a nail.

Naturally!  But then.. knowing when to use a given programming technique
is part of the problem. I have a spouse who just ruined a perfectly good
chef's knife that cost me about $80.00 because she didn't bother looking
for a screwdriver .. and thank goodness I didn't have to take her the ER
to boot.

> What you describe seems trivially a procedural sequence of branching
> steps using simple types from the standard library. 

This is for a standalone laptop.

I went to the trouble of designing, coding, and cron'ing my B/U script
for two reasons:

1. I wanted the laptop backed up regularly and -- see other posts in
   this thread.. "restorable".

2. The more I worked on this project, the more interesting it became ..
   along "what happens if" lines .. and less trivial.

Now that's over and done with.

But then I started thinking .. what if for instance I had to scale my
effort from my single system to a large "data center" with hundred of
hosts ..  with different backup policies ..  what if I had to take into
account time slots where the backups ran ..  had to consider bandwidth &
performance issues ..  media costs & their rotation and such like.

In a vague way I had this feeling that if added machines one at a time,
my current script would not scale all that well.

I hope I'm making some sense but this is why, rather than take your word
for it, which I tend to intuitively agree with anyway .. I would much
prefer trying to oop this myself and try to figure why in this instance
using object-orientation would probably only add much overhead and
complexity without any real benefits.  

IOW--we only learn by our own mistakes.

> Use functions to encapsulate the conceptually-related steps, and call
> those functions in a simple branch as you demonstrated. I see no need
> to apply object-oriented techniques for this problem.

> import datetime
> 
> def is_full_backup_required(when):
> """ Determine whether a full backup is required for datetime 'when' 
> """
> result = False
> if determine_whether_full_backup_required_for_datetime(when):
> result = True
> return result
> 
> def most_recent_incremental_backup(when):
> """ Return the most recent incremental backup before datetime 'when' 
> """
> backup = most_recent_backup(when)
> return backup
> 
> def save_previous_full_archive(when):
> """ Save the full archive previous to datetime 'when' """
> 
> def save_previous_incremental_archive(when):
> """ Save the incremental archive previous to datetime 'when' """
> 
> def perform_full_backup(system):
> """ Do a full backup of the system """
> 
> def perform_incremental_backup(system):
> """ Do an incremental backup of the system """
> 
> def get_this_system():
> """ Return the current system for backups """
> system = determine_what_this_system_is()
> return system
> 
> system = get_this_system()
> when = datetime.datetime.now()
> if is_full_backup_required(when):
> save_previous_month_archive(when)
> perform_full_backup(system)
> else:
> save_previous_incremental_archive(when)
> perform_incremental_backup(system)

Thank you very much for providing this example skeleton.

> I don't see any need for creating new classes for any of this, unless
> a "system" is more complicated than just a string for the system
> name, or a "backup" is more complicated than a tarball file.

Well .. relative to my far-fetched example of scaling above .. I thought
that maybe a "target system" -- one to backup, that is .. would be an
obvious class .. that one could find some criteria or other that would
categorize systems into subgroups .. with related backup policies, for
instance .. and each actual system would end up being an instance of
these latter "sub-classes".

Likewise a "backup" .. full or incremental .. with a system name and a
calendar date as natural attributes ..?

No harm in trying?

:-)

> Instead, the problem seems one best solved simply by abstracting the
> steps involved at each point of the *procedure*, as I've done in my
> example. 

To loosely quote someone's post on this thread .. I have AFAIK already
"solved" my problem .. So why bother? .. As indicated above this is a
case of looking at the problem from a different angle and hopefully
learn something.

> Each one of those functions could be very simple or could be
> complex enough to spawn a whole host of helper functions, possibly
> even separate modules. That seems a more useful approach than trying
> to f

Re: Plz help..SocketServer UDP server losing lots of packets

2008-11-05 Thread James Mills
On Thu, Nov 6, 2008 at 9:53 AM,  <[EMAIL PROTECTED]> wrote:
> logFileName = 'log.txt'
>logfile = open(logFileName, "a")
>class MyUDPServer(SocketServer.UDPServer):
>def server_bind(self):
>self.socket.setsockopt(socket.SOL_SOCKET,
> socket.SO_RCVBUF, 8388608)
>self.socket.bind(self.server_address)
>
>class LogsDumpHandler(SocketServer.DatagramRequestHandler):
>def handle(self):
>global logfile
> # fileExists is a function which checks the existence of a file
>if not fileExists(logFileName):
>logfile = open(logFileName, "a")
>logfile.writelines(self.rfile.readlines())
>
>server = MyUDPServer(("",PORT), LogsDumpHandler)
>server.serve_forever()
>logfile.close()

This is horrible code :/

Try these instead:
 * UDPServer ->
http://trac.softcircuit.com.au/circuits/browser/examples/udpserver.py
 * UDPClient  ->
http://trac.softcircuit.com.au/circuits/browser/examples/udpclient.py

Example usage
--

~/circuits/examples
$ ./udpserver.py
127.0.0.1, 9000:
test
127.0.0.1, 9000:
hi

~/circuits/examples
$ ./udpclient.py -b 127.0.0.1:9000 127.0.0.1:8000
test
127.0.0.1, 8000:
test
hi
127.0.0.1, 8000:
hi

You can download circuits from http://trac.softcircuit.com.au/circuits/
or get the latest development version by using Mercurial (1):
hg clone http://hg.softcircuit.com.au/projects/circuits/

cheers
James

[1] http://www.selenic.com/mercurial/wiki/

-- 
--
-- "Problems are solved by method"
--
http://mail.python.org/mailman/listinfo/python-list


Re: Rewriting a bash script in python

2008-11-05 Thread Tim Rowe
2008/11/6 Chris Jones <[EMAIL PROTECTED]>:

> Begs the question .. how do I tell what is an object-oriented vs. a
> procedural problem?

Practice, largely, so you're doing the right thing (provided you don't
trust your /real/ backup data to a tutorial program). If you find that
the program is at its neatest when it's just a couple of methods in
one class, it was a procedural problem.

Actually, from your description of the problem -- that the interest is
in all the "what if" cases -- suggests that it's a specification
problem rather than a design or implementation problem, so rather than
recoding it it might be worth looking at various approaches to
requirements capture and specification.

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


Re: Extract frame from wmv

2008-11-05 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Tim Golden
wrote:

> Alternatively, you might be able to commandline control
> mencoder or ffmpeg itself to do this. Not sure, but there
> must be *something* among those millions of command-line
> options!

FFmpeg--yes!
--
http://mail.python.org/mailman/listinfo/python-list


Re: Using subprocess.Popen() in a Windows service

2008-11-05 Thread yomgui

hi,

this is how i do it:

from subprocess import Popen, PIPE, call, check_call
if sys.platform == 'win32':
net.processWithoutGui = Popen(
['python', self.temporaryFilename,'-w'],
shell=False, cwd=lNetworkDir)
else:
net.processWithoutGui = Popen(
[self.temporaryFilename,'-w'],
shell=False, cwd=lNetworkDir)


hope it helps

yomgui



Mark Shewfelt wrote:

Hello,

I am attempting to use Popen() in a Windows service. I have a small
Win32 .exe that I normally run through the os.popen2() function. I've
written a class to work with the input and output parameters that are
passed and captured from this exe. When I use the class outside of a
service using either subprocess.Popen or os.popen2 work just fine.

When I use this class inside a Windows service it doesn't work. It
doesn't crash the service or anything but there are no values returned
from the Popen. Here's how I'm calling Popen:

p = subprocess.Popen( cmd, shell=True, bufsize=128,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
cwd="C:\\path_to_exe\\" )
p.wait()
(modbus_stdin, modbus_stdout)=(p.stdin,p.stdout)
lines = modbus_stdout.readlines()

While this doesn't fail there is nothing in the lines variable when it
finishes.

I am using Python 2.5 on a Windows XP Professional machine. Any help
would be greatly appreciated.

Best Regards,

Mark Shewfelt

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


Re: subprocess and PPID

2008-11-05 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Michele Petrazzo wrote:

> I have a code that execute into a "Popen" a command (ssh). I need that,
> if the python process die, the parent pid (PPID) of the child don't
> become 1 (like I can seen on /proc/$pid$/status ), but it has to die,
> following it's parent
> It's possible in linux and with subprocess?

There is a Linux-specific system call that says it does this (haven't
tried). See the prctl(2) man page.
--
http://mail.python.org/mailman/listinfo/python-list


How to re-import a function from a module?

2008-11-05 Thread Kurda Yon
Hi,

I have the following small problem. I run Python interactively. In the
beginning of the run I import many functions from many modules. Than I
execute some commands and notice that one of the imported functions
contains a mistake. I open another terminal in which I open the file
with the problematic function and correct the function. However, the
Python does not see my changes. It still uses the old version of the
function. In principle I could close the Python session and reopen it
again and import all functions agane. But it does not seem to be a
convenient solution. Is there a way to force Python to re-import the
function, i.e. to force it to use the new version of the function?

Thank you in advance.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to build the pysqlite? Where to find the "sqlite3.h"?

2008-11-05 Thread Kurda Yon
On Nov 5, 1:55 pm, Thorsten Kampe <[EMAIL PROTECTED]> wrote:
>
> You (and Kurda) keep on talking the wrong stuff. First: you don't need
> pysqlite2. SQLite support is included in the latest Python as module
> sqlite3.
>

By the way, I think the above statement is very helpfull. I tried to
install the "pysqlite" to be able to communicate with the "sqlite",
and then I have realized that for that I need first to install the
"sqlite"...

But I read your statement and understood that I do not need to install
neither "pysqlite" no "sqlite". In my Python session I tried to type
"from sqlite import connect" and it does not compaline. It meand that
Python see the database!!! I hope.

By the where can I find a simle tutorial about the work with the
"sqlite" from the Python?
--
http://mail.python.org/mailman/listinfo/python-list


Snippets management

2008-11-05 Thread Edwin
Hi there,

I've been looking for a snippet manager and found PySnippet but it
requires PyGTK. Do you know any other option that doesn't need much? 

I'm sort of new to python and user interfaces seem a bit far for me
right now, that's why I thought having to install PyGTK was
unnecessary.

Would you recommend installing it anyway? 

I'm on a Mac, maybe some users of Steve's Unix flavour know about a
snippets software piece? I'm looking for free/open source alternatives.

Thank you!

P.S.: I'm also new to usenet ;) and hope my english is not that bad.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to re-import a function from a module?

2008-11-05 Thread Ben Finney
Kurda Yon <[EMAIL PROTECTED]> writes:

> Is there a way to force Python to re-import the function, i.e. to
> force it to use the new version of the function?

A Python ‘import’ is conceptually two steps: execute the module, then
bind the objects that were created to names in a namespace.

The import mechanism has a short-cut: if the module has already been
imported by this Python VM, the module isn't executed again, and the
existing objects are simply re-used with new bindings as necessary.

What you want is to specifically request the module to be re-executed
to re-create the objects again, and re-bind the existing name bindings
to the objects that result.

   >>> help(reload)

-- 
 \ “I hope that after I die, people will say of me: ‘That guy sure |
  `\owed me a lot of money’.” —Jack Handey |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list


Re: Rewriting a bash script in python

2008-11-05 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Marc 'BlackJack' Rintsch
wrote:

> Well, if it handles your backups it doesn't work.  It just pretends until
> you really *need* the backed up data.  ;-)

That's why a backup system needs to be absolutely simple as possible. Avoid
complicated formats, a straightforward mirrored filesystem (e.g. updated
via rsync) is the easiest to verify that you can read your precious data.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Rewriting a bash script in python

2008-11-05 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Chris
Jones wrote:

> But then I started thinking .. what if for instance I had to scale my
> effort from my single system to a large "data center" with hundred of
> hosts ..  with different backup policies ..  what if I had to take into
> account time slots where the backups ran ..  had to consider bandwidth &
> performance issues ..  media costs & their rotation and such like.


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


Re: How to build the pysqlite? Where to find the "sqlite3.h"?

2008-11-05 Thread Shawn Milochik
On Wed, Nov 5, 2008 at 8:52 PM, Kurda Yon <[EMAIL PROTECTED]> wrote:
> By the where can I find a simle tutorial about the work with the
> "sqlite" from the Python?
> --
> http://mail.python.org/mailman/listinfo/python-list
>

Once you get the connection, you can pretty much just do whatever if
you know SQL. Here's some working code from one of my little projects:

#!/usr/bin/env python

from pysqlite2 import dbapi2 as sqlite

import time
#import sys

sqliteDatabase = "status.db"

connection = sqlite.connect(sqliteDatabase)
cursor = connection.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS auctions (auction_id
INTEGER PRIMARY KEY, numBids INTEGER, currentPrice INTEGER, timestamp
TEXT(50), itemTitle TEXT(100))')
connection.close()

local = time.localtime()
timeStamp = "%s-%02d-%02d_%02d:%02d" % (local[0], local[1], local[2],
local[3], local[4])

def recordExists(auctionID):

connection = sqlite.connect(sqliteDatabase)
cursor = connection.cursor()
cursor.execute('SELECT COUNT(auction_id) FROM auctions WHERE
auction_ID = ' + auctionID.__str__())
for row in cursor:
return row[0]

cursor.close()

connection.close()

def retrieveAuctionInfo(auctionID):
connection = sqlite.connect(sqliteDatabase)
cursor = connection.cursor()
cursor.execute('SELECT currentPrice, numBidsFROM auctions
WHERE auction_ID = ' + auctionID.__str__())
for row in cursor:
return [row[0],row[1]]

cursor.close()

def insertAuction(auctionID, currentPrice, currentBids, itemTitle):

itemTitle = itemTitle.replace('"', '""')

connection = sqlite.connect(sqliteDatabase)
cursor = connection.cursor()
insertQuery = 'INSERT INTO auctions (auction_id, currentPrice,
numBids, timestamp, itemTitle) VALUES (%s, %s, %s, "%s", "%s")' %
(auctionID, currentPrice, currentBids, timeStamp, itemTitle)
cursor.execute(insertQuery)
connection.commit()

cursor.close()

connection.close()

def updateAuction(auctionID, currentPrice, currentBids):

connection = sqlite.connect(sqliteDatabase)
cursor = connection.cursor()
updateQuery = 'UPDATE auctions SET currentPrice = %s, numBids =
%s, timestamp = "%s" WHERE auction_id = %s;' % (currentPrice,
currentBids, timeStamp,auctionID)
cursor.execute(updateQuery)
connection.commit()

cursor.close()
connection.close()

def getTotalAmount():

connection = sqlite.connect(sqliteDatabase)
cursor = connection.cursor()
selectQuery = "SELECT SUM(currentPrice) FROM  auctions WHERE numBids > 0;"
cursor.execute(selectQuery)
for row in cursor:
return float(row[0])

cursor.close()

connection.close()

def displayAuctions(sortBy="timestamp DESC"):

connection = sqlite.connect(sqliteDatabase)
cursor = connection.cursor()
selectQuery =  "SELECT auction_id, numBids, currentPrice,
timestamp, itemTitle FROM  auctions WHERE numBids > 0 ORDER BY " +
sortBy + ";"
cursor.execute(selectQuery)
for row in cursor:
auctionID, numBids, currentPrice, timestamp, itemTitle = row

print "%25s $%6.2f (%2s bids) Last update: %16s" %
(itemTitle[:25], currentPrice, numBids, timestamp)

cursor.close()

print ""

connection.close()

if __name__ == "__main__":
displayAuctions("currentPrice DESC")
displayAuctions()
#displayAuctions("numBids DESC")
print "$%3.2f" % getTotalAmount()
--
http://mail.python.org/mailman/listinfo/python-list


Re: Regexp parser and generator

2008-11-05 Thread George Sakkis
On Nov 4, 9:56 pm, Paul McGuire <[EMAIL PROTECTED]> wrote:
> On Nov 4, 1:34 pm, George Sakkis <[EMAIL PROTECTED]> wrote:
>
>
>
> > Is there any package that parses regular expressions and returns an
> > AST ? Something like:
>
> > >>> parse_rx(r'i (love|hate) h(is|er) (cat|dog)s?\s*!+')
>
> > Regex('i ', Or('love', 'hate'), ' h', Or('is', 'er'), ' ', Or('cat',
> > 'dog'), Optional('s'), ZeroOrMore(r'\s'), OneOrMore('!'))
>
> > Given such a structure, I want to create a generator that can generate
> > all strings matched by this regexp. Obviously if the regexp contains a
> > '*' or '+' the generator is infinite, and although it can be
> > artificially constrained by, say, a maxdepth parameter, for now I'm
> > interested in finite regexps only. It shouldn't be too hard to write
> > one from scratch but just in case someone has already done it, so much
> > the better.
>
> > George
>
> Check out this pyparsing regex 
> inverter:http://pyparsing.wikispaces.com/file/view/invRegex.py
>

Neat, seems like a good excuse to look into pyparsing :)

Best,
George
--
http://mail.python.org/mailman/listinfo/python-list


Malaysia python programmers

2008-11-05 Thread Marcus.CM

Hi,

I apologize if this is not the place to do this.

A python  user group for malaysia is currently being formed , so if you 
are in malaysia, feel free to join us at : www.python.my



Marcus.CM.


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


Re: damn street venders

2008-11-05 Thread Aspersieman

+1

--
Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo

On Mon, 03 Nov 2008 16:05:13 +0200, r <[EMAIL PROTECTED]> wrote:


Hey, go sell your stupid watch somewhere else.
i am tired of the message boards clogged with these stupid ads.
Nobody here cares about your cheap rolex watches or porn or anything
else.
This is python, and that is all we care about.
If we want those things we *know* how to find them.
good day!


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



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


Re: open a new terminal window from another terminal window in linux/unix system

2008-11-05 Thread David
gaurav kashyap wrote:
> What i want to do is open another terminal window from already opened
> terminal window.
>   
Why?
> Can this be achieved.If yes,please provide a tested solution
>   
How about GNU Screen
http://coding.derkeiler.com/Archive/Python/comp.lang.python/2008-09/msg01932.html


-- 
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com


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


find an object ancestor

2008-11-05 Thread Michel Perez
HI all:

imagine something like this:

class father:
pass
class son( father ):
pass

I need to know the son ancestor class how can i know this.

Thanks


---
Red Telematica de Salud - Cuba
  CNICM - Infomed
--
http://mail.python.org/mailman/listinfo/python-list


Re: damn street venders

2008-11-05 Thread Benjamin Kaplan
I'm pretty sure all of the spam is automated, so your message won't get
through to anyone.

On Mon, Nov 3, 2008 at 9:05 AM, r <[EMAIL PROTECTED]> wrote:

> Hey, go sell your stupid watch somewhere else.
> i am tired of the message boards clogged with these stupid ads.
> Nobody here cares about your cheap rolex watches or porn or anything
> else.
> This is python, and that is all we care about.
> If we want those things we *know* how to find them.
> good day!
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >