Re: Convert string to command..

2007-10-18 Thread Abandoned
On Oct 18, 8:53 pm, Hrvoje Niksic <[EMAIL PROTECTED]> wrote:
> Abandoned <[EMAIL PROTECTED]> writes:
> > > When you load it, convert the string to dict with cPickle.loads
> > > instead of with eval.
>
> > Yes i understand and this very very good ;)
>
> Good!  :-)
>
> > psycopg2.ProgrammingError: invalid byte sequence for encoding "UTF8":
> > 0x80
> > HINT:  This error can also happen if the byte sequence does not match
> > the encoding expected by the server, which is controlled by
> > "client_encoding".
>
> Use a different column type for cache2's column, one more appropriate
> for storing binary characters (perhaps BYTEA for Postgres).  Don't
> forget to also use a bind variable, something like:
>
> cursor.execute("INSERT INTO cache2 VALUES (?)", a)
>
> Using "INSERT ... ('%s')" % (a) won't work, since the huge binary
> string in a can contain arbitrary characters, including the single
> quote.

I tryed:
cursor.execute("INSERT INTO cache2 VALUES (?)", a)
and
cursor.execute("INSERT INTO cache2 VALUES (%s)", (a,) )
but the result is same..

> psycopg2.ProgrammingError: invalid byte sequence for encoding "UTF8":
> 0x80
> HINT:  This error can also happen if the byte sequence does not match
> the encoding expected by the server, which is controlled by
> "client_encoding".

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


Re: ANN: Pyrex 0.9.6.3

2007-10-18 Thread David Tremouilles
Hello,

 Was about to report the same problem with setup.py.

Regards,

David

2007/10/18, [EMAIL PROTECTED] <[EMAIL PROTECTED]>:
> On Oct 17, 4:12 am, Greg Ewing <[EMAIL PROTECTED]> wrote:
> > Pyrex 0.9.6.3 is now available:
> >
> >http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/
> >
> > Main features of this release:
> >
> >* The C API now uses just one name in the module namespace,
> >  instead of a name per C function.
> >
> >* The 'cdef' keyword and following extern/public/api qualifiers
> >  can be factored out of a group of declarations and made into
> >  a block header, e.g.
> >
> >cdef public:
> >  int spam
> >  float ftang
> >  void tomato()
> >
> >* A 3-argument form of the builtin getattr function has been
> >  added, called getattr3().
> >
> > What is Pyrex?
> > --
> >
> > Pyrex is a language for writing Python extension modules.
> > It lets you freely mix operations on Python and C data, with
> > all Python reference counting and error checking handled
> > automatically.
>
> Did anyone else notice that the setup.py file is screwed up? Or that
> the link on this guy's website for the Test Suite/Framework is broken?
>
> Mike
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Noob questions about Python

2007-10-18 Thread Michele Simionato
On Oct 18, 7:44 pm, MRAB <[EMAIL PROTECTED]> wrote:
> It returns '' when number == 0, so you need to test for that case:
>
> > def baseN(number, N=2):
> > """
> > >>> baseN(9, 2)
> > '1001'
> > """
> > assert 2 <= N <= 10
> > assert isinstance(number, int) and number >= 0
>
> if number == 0:
> return "0"
>
> > b = []
> > while number:
> > b.append(str(number % N))
> > number /= N
> > return ''.join(reversed(b))

Right, or you can just change the last line:

return ''.join(reversed(b)) or '0'


 Michele Simionato

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


Re: why doesn't have this list a "reply-to" ?

2007-10-18 Thread [david]
Robert Kern wrote:
> [david] wrote:
>> Steve Lamb wrote:
>>> On 2007-10-17, Byung-Hee HWANG <[EMAIL PROTECTED]> wrote:
 Just click "Ctrl-L", then you can reply to lists directly if you use
 good mailer like mutt or thunderbird or evolution ;; 
>>> Thunderbird only if it has the list-reply patch, has either enigmail or
>>> mhengy installed and has the reply-to-list addon installed.  Otherwise, no,
>>> Thunderbird still, years later, lacks that feature.  Part of the reason why 
>>> I
>>> am test driving gmane in slrn right now.  :)
>> I'm using Thunderbird 2.0.0.0: I use the right-click menu.
> 
> And click what? I have Thunderbird 2.0.0.6 on OS X and only see "Reply to 
> Sender
> Only" and "Reply to All".
> 

Sorry, I was only responding to the technical content.

What I meant was, one platform (check the user-agent field) has 
implemented the default build differently, and has done so for a long time.

[david]
-- 
http://mail.python.org/mailman/listinfo/python-list


problem with eric

2007-10-18 Thread Pradnyesh Sawant
Hello,
I have the following single line in my .py file:

from PyQt4 import QtCore, QtGui

if i run it from eric, i get the following error:

unhandled RuntimeError
"the PyQt4.QtCore and qt modules both wrap the QObject class"

i think that eric is probably trying to load both Qt3 and Qt4, but i don't 
understand why (i'm explicitly mentioning PyQt4). How do i tell eric to use 
just Qt4, and not Qt3?

ps: i have made both Qt and Qt4 Directory to contain /usr/share/qt4, in 
preferences->qt. but that too does not help.
-- 
warm regards,
Pradnyesh Sawant
--
Computers are to make people happy, not people to make computers happy.
--Gerald Jay Sussman, MIT
-- 
http://mail.python.org/mailman/listinfo/python-list


I can't get minimock and nosetests to play nice

2007-10-18 Thread Matthew Wilson


I'm curious if anyone has ever tried using nosetests along with
minimock.

I'm trying to get the two to play nice and not making progress.  I
also wonder if I'm using minimock incorrectly.

Here's the code I want to test, saved in a file dtfun.py.

class Chicken(object):
   "I am a chicken."
   def x(self): return 1
   def z(self): return 1

def g():

   """
   Verify that we call method x on an instance of the Chicken class.

   # First set up the mockery.
   >>> from minimock import Mock
   >>> Chicken = Mock('Chicken')
   >>> Chicken.mock_returns = Mock('instance_of_chicken')

   Now this stuff is the real test.
   >>> g()
   Called Chicken()
   Called instance_of_chicken.x()
   """

   # This is what the function does.
   c = Chicken()
   c.x()

if __name__ == "__main__":

   # First set up the mockery.
   from minimock import Mock
   Chicken = Mock('Chicken')
   Chicken.mock_returns = Mock('instance_of_chicken')

   # Now run the tests.
   import doctest
   doctest.testmod()

Here's the results when I run the code using doctest.testmod (which
passes) and nosetests --with-doctest (KABOOM):

$ python dtfun.py # Nothing is a good thing here.

$ nosetests --with-doctest dtfun.py
F
==
FAIL: Doctest: dtfun.g
--
Traceback (most recent call last):
 File "doctest.py", line 2112, in runTest
   raise self.failureException(self.format_failure(new.getvalue()))
AssertionError: Failed doctest test for dtfun.g
 File "/home/matt/svn-checkouts/scratch/python/dtfun/dtfun.py", line 13,
in g

--
File "/home/matt/svn-checkouts/scratch/python/dtfun/dtfun.py", line
22, in dtfun.g
Failed example:
   g()
Expected:
   Called Chicken()
   Called instance_of_chicken.x()
Got nothing


--
Ran 1 test in 0.015s

FAILED (failures=1)

It seems like nose isn't building the mock objects.

Any ideas?

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


Re: Noob: Loops and the 'else' construct

2007-10-18 Thread Gabriel Genellina
En Thu, 18 Oct 2007 23:44:27 -0300, Ixiaus <[EMAIL PROTECTED]>  
escribió:

> I have just come across a site that discusses Python's 'for' and
> 'while' loops as having an (optional) 'else' structure.
>
> At first glance I interpreted it as being a bit like the 'default'
> structure in PHP's switch block... But the switch block isn't a loop,
> so, I am now confused as to the reason for using 'else' with the for
> and while loops...
>
> A few quick tests basically show that statements in the else structure
> are executed at the fulfillment of the loop's expression (ie, no
> break).

A `while` loop tests a condition: if it evaluates to true, keep cycling;  
if it is false, stop. The `else` clause is executed when the condition is  
false, as in any `if` statement. If you exit the loop by using `break`,  
the `else` part is not executed (because you didn't get out of the loop by  
determining the condition falseness)

You can think of a `for` loop as meaning `while there are remaining  
elements to be iterated, keep cycling` and the `else` clause applies when  
there are no more elements. A `break` statement does not trigger the else  
clause because the iteration was not exhausted.

Once you get the idea, it's very simple.

-- 
Gabriel Genellina

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


Re: vote for Python - PLEASE

2007-10-18 Thread [EMAIL PROTECTED]
On Oct 18, 6:12 pm, Monty Taylor <[EMAIL PROTECTED]> wrote:
> Hey everybody,
>
> MySQL has put up a poll onhttp://dev.mysql.comasking what your primary
> programming language is.

But it doesn't ask that, it asks what your
primary programming language is FOR DEVELOPING
MYSQL APPLICATIONS.

In my case, there is no such language (even though
I primarily use Python) BECAUSE I DON'T USE MYSQL.


> Even if you don't use MySQL - please go stick
> in a vote for Python. I'm constantly telling folks that Python needs
> more love, but PHP and Java are kicking our butts...
>
> (I know the world would be a better place if the poll were honest,

There is dishonestly and there's outright lying

> but
> I'd rather that people got the message that they should do more python
> development work!)

Maybe the Python community doesn't need your help.

>
> Thanks!
> Monty


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


Noob: Loops and the 'else' construct

2007-10-18 Thread Ixiaus
I have just come across a site that discusses Python's 'for' and
'while' loops as having an (optional) 'else' structure.

At first glance I interpreted it as being a bit like the 'default'
structure in PHP's switch block... But the switch block isn't a loop,
so, I am now confused as to the reason for using 'else' with the for
and while loops...

A few quick tests basically show that statements in the else structure
are executed at the fulfillment of the loop's expression (ie, no
break).

Example:

for i in range(10):
 print i
else:
 print 'the end!'

0
1
2
3
4
5
6
7
8
9
10
the end!

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


Noob: Loops and the 'else' construct

2007-10-18 Thread Ixiaus
I have just come across a site that discusses Python's 'for' and
'while' loops as having an (optional) 'else' structure.

At first glance I interpreted it as being a bit like the 'default'
structure in PHP's switch block... But the switch block isn't a loop,
so, I am now confused as to the reason for using 'else' with the for
and while loops...

A few quick tests basically show that statements in the else structure
are executed at the fulfillment of the loop's expression (ie, no
break).

Example:

for i in range(10):
 print i
else:
 print 'the end!'

0
1
2
3
4
5
6
7
8
9
10
the end!

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


Re: What Data is Available With a Pickled Object Over a Socket?

2007-10-18 Thread Gabriel Genellina
En Thu, 18 Oct 2007 19:21:15 -0300, milan_sanremo  
<[EMAIL PROTECTED]> escribió:

> I've read the library entry for pickle a couple of times, and I'm
> still not
> sure what data is maintained when an item is pickled and sent over a
> socket.

For most "normal" objects, all their instance attributes are stored.

> pickledMailbag = cPickle.dump(mb, HIGHEST_PROTOCOL)

Please copy&paste actual code when posting, don't retype it...
The above line should read cPickle.dumps, I presume.

> while 1:
> pickledData = conn.recv(1024)
> if not pickledData break

Instead of reinventing the wheel again, I'd try to use the existing server  
classes in the standard library, like SimpleHTTPServer by example. Among  
other things, you are not accumulating pickledData.

> mb = cPickle.load(pickledData)
>
> At this point, does mb contain a dictionary with the two envelopes
> with
> their data?

Asuming you managed to get pickledData right, and you use cPickle.loads:  
yes, mb should contain the same things as the original.

-- 
Gabriel Genellina

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


Re: Noob questions about Python

2007-10-18 Thread Ixiaus
That was a very helpful answer Steven, thank you for taking the time
to write it!

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


Re: ConfigParser preserving file ordering

2007-10-18 Thread Joshua J. Kugler
On Thursday 18 October 2007 15:23, Frank Aune wrote:

> Hello,
> 
> I use ConfigParser and actually quite like it, EXCEPT that it doesnt
> preserve the section order of the original config file when writing a new.
> This behaviour is hopeless IMO, and I've been looking for alternatives.
> 
> I've been reading the interesting discussion on python-dev about
> improvements to ConfigParser:
> 
> http://mail.python.org/pipermail/python-dev/2006-January/060138.html
> 
> I know there are patches to archieve what I want, but tbh I need
> functionality present in the standard library or as a last option
> sub-class ConfigParser to archieve ordering preservation.
> 
> Since the thread above is nearly two years old, I'm wondering if something
> has happended in this department?

Have you taken a look at ConfigObj?

http://www.voidspace.org.uk/python/configobj.html

j

-- 
Joshua Kugler
Lead System Admin -- Senior Programmer
http://www.eeinternet.com
PGP Key: http://pgp.mit.edu/  ID 0xDB26D7CE

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

Re: Static variable vs Class variable

2007-10-18 Thread bambam


"Steven D'Aprano" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> On Wed, 17 Oct 2007 13:41:06 +0200, Hrvoje Niksic wrote:
>
>> The current implementation of += uses __add__ for addition and __iadd__
>> for addition that may or may not be in-place.  I'd like to know the
>> rationale for that design.
>
> Everything you need is in the PEP:
>
> http://www.python.org/dev/peps/pep-0203/
>
>
>
> -- 
> Steven.

Which illustrates that the proposal, while simplified for implementation,
is not exactly what was desired*

""" is both more readable and less error prone, because it is
instantly obvious to the reader that it is  that is being
changed, and not  that is being replaced
"""

As we see from this thread, it is not instantly obvious to the reader;
the meaning of "changed, not replaced" is ambiguous.

[david]

* That is, unless ambiguity was the desideratum 


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


Re: Is there a way to tell if a script has been run by Pythonw.exe instead of Python.exe?

2007-10-18 Thread michaelvmata
On Oct 18, 2:56 pm, Metalone <[EMAIL PROTECTED]> wrote:
> In particular I want to know how to tell if reading and writing to the
> console can occur.
> Something like
> sys.isConsolePresent()

Look at sys.executable to find the name of the binary for the Python
interpreter.

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


Re: Need scrip to reed rss feeds

2007-10-18 Thread Andreas Kraemer
On Oct 18, 4:39 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> Hi,
> Does any one know whare I can find some code to phrase a rss feeds?
> Thank you,
> Ted

Try http://feedparser.org/

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


vote for Python - PLEASE

2007-10-18 Thread Monty Taylor
Hey everybody,

MySQL has put up a poll on http://dev.mysql.com asking what your primary 
programming language is. Even if you don't use MySQL - please go stick 
in a vote for Python. I'm constantly telling folks that Python needs 
more love, but PHP and Java are kicking our butts...

(I know the world would be a better place if the poll were honest, but 
I'd rather that people got the message that they should do more python 
development work!)

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


Re: Noob questions about Python

2007-10-18 Thread MRAB
On Oct 18, 7:05 am, Michele Simionato <[EMAIL PROTECTED]>
wrote:
> On Oct 17, 5:58 pm, Ixiaus <[EMAIL PROTECTED]> wrote:
>
> > def bin2dec(val):
> > li = list(val)
> > li.reverse()
> > res = [int(li[x])*2**x for x in range(len(li))]
> > print sum(res)
>
> > It basically does the same thing int(string, 2) does.
>
> > Thank you for the responses!
>
> BTW, here is the reverse function dec2bin, so that you can
> bang your head on it for a while ;)
>
It returns '' when number == 0, so you need to test for that case:

> def baseN(number, N=2):
> """
> >>> baseN(9, 2)
> '1001'
> """
> assert 2 <= N <= 10
> assert isinstance(number, int) and number >= 0
if number == 0:
return "0"
> b = []
> while number:
> b.append(str(number % N))
> number /= N
> return ''.join(reversed(b))
>
>Michele Simionato


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


Re: Embedded Boost.Python Enum

2007-10-18 Thread Cory
Ok, I finally got it figured out. The secret which no one told me what
that if you're doing embedding, you have to initialize your modules!

BOOST_PYTHON_MODULE(Enums){ ... } defines the function initEnums()
which must be called before you can import the module. Finally figured
it out by looking here: 
http://members.gamedev.net/sicrane/articles/EmbeddingPythonPart1.html

It's odd to me that little tidbit got left out of the boost.python
tutorial page on embedding... I must have looked at it 100 times.


On Oct 18, 12:59 am, Cory <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I have a hopefully quick question about how to use Boost.Python to
> export an Enum.
> I am embedding python in C++ and am currently exporting my classes in
> the following way:
>
> nameSpace["OBJECT"] = class_("OBJECT")
> .def("getType", &OBJECT::getType)
> .def("setSprite", &OBJECT::setSprite);
>
> So following this, I assumed that when exporting an enum the following
> should work:
>
> nameSpace["OBJECT_TYPE"] = enum_("OBJECT_TYPE")
> .value("GENERIC_OBJECT",GENERIC_OBJECT)
> .value("MAP_OBJECT",MAP_OBJECT)
> .value("TOTAL_OBJECT_TYPES",TOTAL_OBJECT_TYPES)
> .export_values();
>
> while the above compiles, it causes the following run time exception:
>
> AttributeError: 'NoneType' object has no attribute 'OBJECT_TYPE'
>
> I took a look at the documentation and the only explanation I found
> for enum appeared to be for extending python with modules. using the
> following form:
>
> BOOST_PYTHON_MODULE(enums)
> {
> enum_("color")
> .value("red", red)
> .value("green", green)
> .export_values()
> .value("blue", blue)
> ;
>
> }
>
> I COULD do the above, I would prefer the first method if possible. I
> however do not know how to import the module if it is statically
> linked because doing a simple import does not work and I am not
> familiar enough with the boost.python library, Python C API, or Python
> itself to know how to set it up. So My question is this:
>
> How can I either make the first method of adding an enum work and not
> throw the exception, OR once I create the BOOST_PYTHON_MODULE in an
> embedded python c++ program how to I then import that module into my
> embedded python?
>
> Thanks in advance for any help
>
> -Cory


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


Need scrip to reed rss feeds

2007-10-18 Thread [EMAIL PROTECTED]
Hi,
Does any one know whare I can find some code to phrase a rss feeds?
Thank you,
Ted

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


ConfigParser preserving file ordering

2007-10-18 Thread Frank Aune
Hello,

I use ConfigParser and actually quite like it, EXCEPT that it doesnt preserve 
the section order of the original config file when writing a new. This 
behaviour is hopeless IMO, and I've been looking for alternatives.

I've been reading the interesting discussion on python-dev about improvements 
to ConfigParser:

http://mail.python.org/pipermail/python-dev/2006-January/060138.html

I know there are patches to archieve what I want, but tbh I need functionality 
present in the standard library or as a last option sub-class ConfigParser to 
archieve ordering preservation.

Since the thread above is nearly two years old, I'm wondering if something has 
happended in this department?

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


Re: Is there a way to tell if a script has been run by Pythonw.exe instead of Python.exe?

2007-10-18 Thread Graham Dumpleton
On Oct 19, 7:56 am, Metalone <[EMAIL PROTECTED]> wrote:
> In particular I want to know how to tell if reading and writing to the
> console can occur.
> Something like
> sys.isConsolePresent()

Have you tried:

  sys.stdin.isatty()
  sys.stdout.isatty()

Graham

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


Re: Noob questions about Python

2007-10-18 Thread Steven D'Aprano
On Wed, 17 Oct 2007 23:06:24 -0700, Ixiaus wrote:

> I know '<<' is shifting x over by n bits; but could you point me to some
> literature that would explain why it is the same as "x*2**n"? (Googling
> only returns bit shift, but doesn't necessarily explain the manner in
> which you are using it)

In decimal, multiplying by ten shifts the digits to the left by one place:

31 * 10 => 310
310 * 10 => 3100
3100 * 10 => 31000

In binary, multiplying by two shifts the bits to the left by one place:

101 * 10 => 1010
1010 * 10 => 10100
10100 * 10 => 101000

Because the underlying numbers are the same regardless of what base we 
use to write it in, bit-shifts to the left are equivalent to repeated 
multiplication by two regardless of the display base. Hence:

>>> 7 << 1
14
>>> 14 << 1
28
>>> 28 << 1
56

or to do it another way:

>>> 7 << 3  # multiplication by 2**3
56



Similarly, a bit-shift to the right is equivalent to dividing by two and 
dropping any remainder.



> I will have to read up more on Generators, but maybe you can give me a
> lowdown on why
> sum([1 << k for k, i in enumerate(reversed(val)) if int(i)]) is less
> efficient than using a Generator (is the generator a 'temporary' list?)
> sum(1 << k for k, i in enumerate(reversed(val)) if int(i))

The list comprehension:

[1 << k for k, i in enumerate(reversed(val)) if int(i)]

creates the entire list first. That potentially can require a lot of 
memory, leading to all sorts of complicated memory shuffles as the list 
is resized, paging, etc. 

Using a generator expression means that you avoid creating the entire 
list all in one go. That saves you memory, which may mean that you save 
time.

However, for small sets of input, it is likely that the overhead of 
creating the generator in the first place outweighs the saving of not 
creating the whole list.

The definition of "small" depends on what you are trying to do. In my 
tests, I have found that sum(list comprehension) is marginally faster 
than sum(generator expression) even for 10,000 items.


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


Re: Getting error message/trace over the C API

2007-10-18 Thread Sami Vaisanen
On Tue, 16 Oct 2007 18:55:22 +, Duncan Booth wrote:

> Sami Vaisanen <[EMAIL PROTECTED]> wrote:
> 
>> Hello group,
>>  
>> I'm writing a C++ based application that embeds the python engine. Now I
>> have a problem regarding exception/error information. Is there a way to
>> get the exception message and possibly the traceback into a string for
>> example? I've been eyeballing the PyErr_ module and it seems fairly
>> limited. In other words PyErr_Print() calls the right functions for
>> getting the exception information but unfortunately it is hardwired to
>> print this data directly into sys.stderr, and for an embedded application
>> this is completely inappropriate. 
>>  
>>  
>> Please advice how to do this.
>> 
> All you have to do is call whatever functions you would call from Python. 
> e.g. from C you need to import traceback, then call getattr to get the 
> appropriate function (e.g. format_exc or format_exception), then just call 
> it.



void get_python_exception(string& message, string& traceback)
{
GIL g;
 
PyObject* type  = NULL;
PyObject* value = NULL;
PyObject* trace = NULL;
 
PyErr_Fetch(&type, &value, &trace);
 
py_ref ref_type(type);
py_ref ref_value(value);
py_ref ref_trace(trace);
 
py_ref name(PyString_FromString("traceback"));
py_ref module(PyImport_Import(name.get()));
if (module)
{
py_ref fun(PyObject_GetAttrString(module.get(), "format_exc"));
if (fun)
{
PyErr_Restore(type, value, trace);
ref_type.release();
ref_value.release();
ref_trace.release();
 
py_ref ret(PyObject_CallObject(fun.get(), NULL));
if (ret && PyString_Check(ret.get()))
{
char* str = PyString_AsString(ret.get());
message = str;
traceback = "traceback not available";
return;
}
}
}
message   = "message not available";
traceback = "traceback not available";
}

str evaluates to "None", any ideas what gives here? I've also tried to
call the traceback with a different function, such as
PyObject_CallFunctionObjArgs but the result is still same.

Thanks





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


Re: Extending Python with C API

2007-10-18 Thread Sami Vaisanen
On Thu, 13 Sep 2007 21:26:33 -0400, Carsten Haese wrote:

> On Thu, 2007-09-13 at 18:05 -0700, Thierry Masson wrote:
>> Hello,
>> 
>> I'm trying to use the C API to extend Python. I've looked at various
>> books and web sites (including the docs at python.org) and I can't get
>> any of the samples to work. Below is a very minimalist example that
>> I'm trying to get working and I was wondering if someone could tell me
>> where I'm going wrong. It's probably something very obvious to those
>> familiar with this technique. 
>>[snip...]
>> The setup script builds the library OK, and I've verified that
>> gtestmodule.so is getting created. But when I try to run a test script
>> ( test.py, above) that uses the library, I get this error:
>> 
>> Traceback (most recent call last):
>>   File "test.py", line 2, in ?
>> import gtestmodule
>> ImportError: ./gtestmodule.so: undefined symbol: PyBuildValue 
> 
> Your module C code uses an unknown function by the name of PyBuildValue.
> The actual name of the function you mean is Py_BuildValue.
> 
> HTH,



void get_python_exception(string& message, string& traceback)
{
GIL g;
 
PyObject* type  = NULL;
PyObject* value = NULL;
PyObject* trace = NULL;
 
PyErr_Fetch(&type, &value, &trace);
 
py_ref ref_type(type);
py_ref ref_value(value);
py_ref ref_trace(trace);
 
py_ref name(PyString_FromString("traceback"));
py_ref module(PyImport_Import(name.get()));
if (module)
{
py_ref fun(PyObject_GetAttrString(module.get(), "format_exc"));
if (fun)
{
PyErr_Restore(type, value, trace);
ref_type.release();
ref_value.release();
ref_trace.release();
 
py_ref ret(PyObject_CallObject(fun.get(), NULL));
if (ret && PyString_Check(ret.get()))
{
char* str = PyString_AsString(ret.get());
message = str;
traceback = "traceback not available";
return;
}
}
}
message   = "message not available";
traceback = "traceback not available";
}

str evaluates to "None", any ideas what gives here? I've also tried to
call the traceback with a different function, such as
PyObject_CallFunctionObjArgs but the result is still same.

Thanks



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


Re: python logging module and custom handler specified in config file

2007-10-18 Thread Frank Aune
On Thursday 18 October 2007 19:26:59 Vinay Sajip wrote:
> The same technique applies to the arguments passed to the constructor.
>
> Hope this helps,
>

Thank you! This seems like exactly what I was looking for. 

Very impressive logging framework btw - I use it whenever I can =)

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


Re: Convert string to command..

2007-10-18 Thread Steven D'Aprano
On Thu, 18 Oct 2007 14:05:34 -0300, Sebastian Bassi wrote:

> On 10/18/07, Adam Atlas <[EMAIL PROTECTED]> wrote:
>>
>> Use the builtin function "eval".
> 
> What is the difference with os.system()?

Everything.

eval() evaluates Python expressions like "x.append(2+3)".

os.system() calls your operating system's shell with a command.


-- 
Steven.

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


What Data is Available With a Pickled Object Over a Socket?

2007-10-18 Thread milan_sanremo
I've read the library entry for pickle a couple of times, and I'm
still not
sure what data is maintained when an item is pickled and sent over a
socket.

Two importable modules:

class envelope():
def __init__(self, rec, d):
self.recipient = rec
self.listData = d

class mailbag():
def __init__(self):
self.dicEnvelope = []

def addEnvelope(self, uuid, envelope):
self.dicEnvelope[uuid] = envelope


Client
-
import envelope, mailbag, cPickle, socket

remoteHost = "999.666.888.777
mb = mailbag()
env1 = envelope('John', ('a', 'b', 'c'))
env2 = envelope('Mary', ('d', 'e', f'))

mb.addEnvelope(1, env1)
mb.addEvenlop(2, env2)

pickledMailbag = cPickle.dump(mb, HIGHEST_PROTOCOL)

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(remoteHost)
sock.send(pickledMailbag)

Server
-
import envelope, mailbag, cPickle, socket

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(host, port)
sock.listen(5)
conn, addr = sock.accept()
while 1:
pickledData = conn.recv(1024)
if not pickledData break

mb = cPickle.load(pickledData)

At this point, does mb contain a dictionary with the two envelopes
with
their data?

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


Re: Strange behaviour with reversed()

2007-10-18 Thread Dustan
On Oct 18, 3:52 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Thu, 18 Oct 2007 15:24:27 +1000, Ben Finney wrote:
> > Steven D'Aprano <[EMAIL PROTECTED]> writes:
>
> >> and help(reversed) but neither gives any insight to what happens when
> >> you use reversed() on a sequence, then modify the sequence.
>
> > I would think the answer is the same for any question about modifying
> > sequences while iterating: "undefined, therefore don't do that".
>
> That's not correct. You can modify sequences while iterating, and the
> results are often perfectly predictable (but watch out for off-by-one
> errors):

Perhaps a better word to use here would have been "undocumented", and
therefore unsafe to use, as it might differ in different versions, or
in different data-types. Dictionaries cannot continue iteration once
they have changed size.

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


Is there a way to tell if a script has been run by Pythonw.exe instead of Python.exe?

2007-10-18 Thread Metalone
In particular I want to know how to tell if reading and writing to the
console can occur.
Something like
sys.isConsolePresent()

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


Re: ANN: Pyrex 0.9.6.3

2007-10-18 Thread kyosohma
On Oct 17, 4:12 am, Greg Ewing <[EMAIL PROTECTED]> wrote:
> Pyrex 0.9.6.3 is now available:
>
>http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/
>
> Main features of this release:
>
>* The C API now uses just one name in the module namespace,
>  instead of a name per C function.
>
>* The 'cdef' keyword and following extern/public/api qualifiers
>  can be factored out of a group of declarations and made into
>  a block header, e.g.
>
>cdef public:
>  int spam
>  float ftang
>  void tomato()
>
>* A 3-argument form of the builtin getattr function has been
>  added, called getattr3().
>
> What is Pyrex?
> --
>
> Pyrex is a language for writing Python extension modules.
> It lets you freely mix operations on Python and C data, with
> all Python reference counting and error checking handled
> automatically.

Did anyone else notice that the setup.py file is screwed up? Or that
the link on this guy's website for the Test Suite/Framework is broken?

Mike

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


Re: Running another python interpreter

2007-10-18 Thread Gabriel Genellina
On 18 oct, 16:55, Sushant <[EMAIL PROTECTED]> wrote:

> Does gateway.py has the python interpreter in the top (i.e.,
> #!/usr/local/bin/python)

The OP said he's on Windows so that doesn't matter.

> On Thursday 18 October 2007 2:13 pm, Simon Pickles wrote:
>
> > os.spawnv(os.P_NOWAIT, "gateway.py", ())

Try with:

os.spawnl(os.P_NOWAIT, sys.executable, sys.executable, "gateway.py")

or use the subprocess module.

--
Gabriel Genellina

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


Re: CGI and external JavaScript nightmare

2007-10-18 Thread IamIan
> > The OP's problem is that he suffers from the delusion that people want
> > to steal the source code for hisCGIscript.

Why is assuming someone may try to get my source CGI delusional?

I'm on a shared server (Dreamhost). The CGI itself has 755 permissions
to execute, but what about folder permissions, etc? If you could
expand on "access to the server, and so on" that would be great.

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


Re: image resize question

2007-10-18 Thread Matimus
On Oct 18, 11:56 am, "Tim Arnold" <[EMAIL PROTECTED]> wrote:
> Hi, I'm using the Image module to resize PNG images from 300 to 100dpi for
> use in HTML pages, but I'm losing some vertical and horizontal lines in the
> images (usually images of x-y plots).
>
> Here's what I do:
> import Image
> def imgResize(self,filename):
> img = Image.open(filename)
> dpi = img.info.get('dpi')
> if dpi and 295 < int(dpi[0]) < 305:
> wd = img.size[0]/3.0 #convert from 300dpi to 100dpi
> ht = img.size[1]/3.0
> newimg= img.resize((int(wd),int(ht)))
> newimg.save(filename)
>
> imgResize('myimage.png')
>
> Can someone point me to a better way so I don't lose the reference lines in
> the images?
> thanks,
> --Tim Arnold

Resize accepts a second parameter that is used to determine what kind
of downsampling filter to use (http://www.pythonware.com/library/pil/
handbook/image.htm). The default is Image.NEAREST, which just samples
the nearest pixel and results in the type of data loss you are seeing.
If you want something better try one of the following and see which
works best for you: Image.BILINEAR, Image.BICUBIC or Image.ANTIALIAS.

example:
...
newimg = img.resize((int(wd),int(ht)),Image.ANTIALIAS)
...

Matt

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


Re: strptime and microseconds

2007-10-18 Thread Gabriel Genellina
On 18 oct, 13:46, mathieu <[EMAIL PROTECTED]> wrote:
> On Oct 18, 6:36 pm, mathieu <[EMAIL PROTECTED]> wrote:
> > >   I am trying to use strptime to parse my microseconds but I was not
> > > able the documentation for it. The only list I found was:
> Ok final version is simply:
>
> s1 = "20070619"
> s2 = "115344.51"
> s3 = "115446.123456"
>
> ms2 = eval(s2) % 1
> mms2 = int(ms2 * 100 + 0.5)
> ms3 = eval(s3) % 1
> mms3 = int(ms3 * 100 + 0.5)
>
> s = s1 + s2
> d1 = datetime(*strptime(s[:14], "%Y%m%d%H%M%S")[0:6])
> d1 = d1.replace(microsecond = mms2)

What about this:

py> import datetime
py> s1 = "20070619 115344.025"
py> p1, p2 = s1.split(".", 1)
py> d1 = datetime.datetime.strptime(p1, "%Y%m%d %H%M%S")
py> ms = int(p2.ljust(6,'0')[:6])
py> d1.replace(microsecond=ms)
datetime.datetime(2007, 6, 19, 11, 53, 44, 25000)

--
Gabriel Genellina

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


AttributeError - FM Receiver - Intermediate freq.

2007-10-18 Thread noroi

Hi, 

   I got problems while running Eric Blossom's FM receiver's example codes
from the GNURadio tutorial page; the RF front end reads the signal input
from daughter board, and when the compiler tried to call mothods to set
values for IF and gain, such as set_AGC(), get_output_freq(), etc... it
seems not able to find those methods/ functions... Could someone be kind
enough to give me some pointers for solving such errors? 


Traceback (most recent call last): 
  
  File "./nuradio.py", line 91, in __init__ 
IF_freq = rf_front_end.get_output_freq ()  
  File "/usr/local/lib/python2.4/site-packages/gnuradio/usrp.py", line 181,
in __getattr__ 
return getattr(self._u, name) 
AttributeError: 'usrp1_source_c_sptr' object has no attribute
'get_output_freq' 

ps. link for the full script is as below: 
http://www.gnu.org/software/gnuradio/doc/exploring-gnuradio.html#fm-receiver 

Best, 
  
  eric
-- 
View this message in context: 
http://www.nabble.com/AttributeError---FM-Receiver---Intermediate-freq.-tf4649640.html#a13283346
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Problem with format string / MySQL cursor

2007-10-18 Thread Florian Lindner
On 18 Okt., 22:08, Paul McNett <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > On Oct 19, 7:32 am, Florian Lindner <[EMAIL PROTECTED]> wrote:
> >> Hello,
> >> I have a string:
>
> >> INSERT INTO mailboxes (`name`, `login`, `home`, `maildir`, `uid`,
> >> `gid`, `password`) VALUES (%s, %s, %s, %s, %i, %i, %s)
>
> >> that is passed to a MySQL cursor from MySQLdb:
>
> >> ret = cursor.execute(sql, paras)
>
> >> paras is:
>
> >> ('flindner', '[EMAIL PROTECTED]', '/home/flindner/', '/home/
> >> flindner/Mail/test', 1001, 1001, '123')
>
> >> But that gives me an error:
>
> >> Traceback (most recent call last):
> >>   File "account.py", line 188, in ?
> >> main()
> >>   File "account.py", line 33, in main
> >> execute(action, account_type, options)
> >>   File "account.py", line 129, in execute
> >> executeSQL(sql, options.username, options.login, options.home,
> >> options.directory, options.uid, options.gid, options.password)
> >>   File "/home/flindner/common.py", line 29, in executeSQL
> >> ret = cursor.execute(sql, paras)
> >>   File "/usr/lib/python2.4/site-packages/MySQLdb/cursors.py", line
> >> 148, in execute
> >> query = query % db.literal(args)
> >> TypeError: int argument required
>
> >> I don't see errors in the format string or some other problem
>
> >> What's wrong?
> > You should be using '?' for parameter bindings in your sql string not
> > python format specifiers (you are after all writing sql here not
> > python).
>
> > INSERT INTO mailboxes (`name`, `login`, `home`, `maildir`, `uid`,
> > `gid`, `password`) VALUES (?, ?, ?, ?, ?, ?, ?)
>
> Sorry Tim, but that isn't correct:
>
> >>> import MySQLdb
> >>> MySQLdb.paramstyle
>
> 'format'
>
> Florian, what happens when you replace your %i with %s?

That works! Thanks! But a weird error message for this solution...

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


Re: Elisp Tutorial: HTML Syntax Coloring Code Block

2007-10-18 Thread j.oke
On 18 Ott, 06:15, Xah Lee <[EMAIL PROTECTED]> wrote:
> [...]

Half lost on my firmness gains to more glad heart,
Or violent and from forage drives
A glimmering of all sun new begun
Both harp thy discourse they march'd,
Forth my early, is not without delay;
For their soft with whirlwind; and balm.
Undoubtedly he scornful turn'd round ninefold,
Though doubled now what redounds,
And chains these a lower world devote, yet inflicted?
Till body or rare, and best things else enjoy'd in heav'n
To stand divided light at ev'n and poise their eyes,
Or nourish, lik'ning spiritual, I have thou appear.

-Henley

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


Re: Convert string to command..

2007-10-18 Thread [EMAIL PROTECTED]
On Oct 18, 1:38 pm, Bruno Desthuilliers  wrote:
> Abandoned a écrit :
> (snip)
>
> > I'm very confused :(
> > I try to explain main problem...
> > I have a table like this:
> > id-1 | id-2 | value
> > 23 24   34
> > 56 68   66
> > 56 98   32455
> > 55 62   655
> > 56 28   123
> >  ( 3 millions elements)
>
> > I select where id=56 and 100.000 rows are selecting but this took 2
> > second. (very big for my project)
>
> Not to bad in the absolute.
>
> > I try cache to speed up this select operation..
> > And create a cache table:
> > id-1 | all
> > 56{68:66, 98:32455, 62:655}
>
> I really doubt this is the right way to go.
>
> > When i select where id 56 i select 1 row and its took 0.09 second but
> > i must convert text to dictionary..
>
> > Have you got any idea what can i do this conver operation ?
>
> Other alread answered
>
> > Have you got any idea what can i do cache for this table ?
>
> Depends on your RDBMS. And as far as I'm concerned, I'd start by trying
> to find out how to optimize this query within the RDBMS - good ones are
> usually highly optimized softwares with provision for quite a lot of
> performance tuning.

Just the overhead of the query is a killer compared to a dictionary
lookup in Python, even if all you're doing is selecting an integer
from a 1-row, 1-column table.

Usually you can get around that by making a single query to return all
of your results (or a handful of queries), but occasionally it just
doesn't matter how fast the DB can get to the data--the simple act of
asking it is slow enough on its own.

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

Re: Problem with format string / MySQL cursor

2007-10-18 Thread Paul McNett
[EMAIL PROTECTED] wrote:

> On Oct 19, 7:32 am, Florian Lindner <[EMAIL PROTECTED]> wrote:
>> Hello,
>> I have a string:
>>
>> INSERT INTO mailboxes (`name`, `login`, `home`, `maildir`, `uid`,
>> `gid`, `password`) VALUES (%s, %s, %s, %s, %i, %i, %s)
>>
>> that is passed to a MySQL cursor from MySQLdb:
>>
>> ret = cursor.execute(sql, paras)
>>
>> paras is:
>>
>> ('flindner', '[EMAIL PROTECTED]', '/home/flindner/', '/home/
>> flindner/Mail/test', 1001, 1001, '123')
>>
>> But that gives me an error:
>>
>> Traceback (most recent call last):
>>   File "account.py", line 188, in ?
>> main()
>>   File "account.py", line 33, in main
>> execute(action, account_type, options)
>>   File "account.py", line 129, in execute
>> executeSQL(sql, options.username, options.login, options.home,
>> options.directory, options.uid, options.gid, options.password)
>>   File "/home/flindner/common.py", line 29, in executeSQL
>> ret = cursor.execute(sql, paras)
>>   File "/usr/lib/python2.4/site-packages/MySQLdb/cursors.py", line
>> 148, in execute
>> query = query % db.literal(args)
>> TypeError: int argument required
>>
>> I don't see errors in the format string or some other problem
>>
>> What's wrong?


> You should be using '?' for parameter bindings in your sql string not
> python format specifiers (you are after all writing sql here not
> python).
> 
> INSERT INTO mailboxes (`name`, `login`, `home`, `maildir`, `uid`,
> `gid`, `password`) VALUES (?, ?, ?, ?, ?, ?, ?)



Sorry Tim, but that isn't correct:

>>> import MySQLdb
>>> MySQLdb.paramstyle


'format'

Florian, what happens when you replace your %i with %s?


-- 
pkm ~ http://paulmcnett.com

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


Re: Can you escape a % in string that will used for substitution

2007-10-18 Thread Tim Chase
> Is there a way to do:
> 
> s = "I like python %i%s of the time."
> print s % (99, "%")
> 
> without having to pass in "%"?

You mean like

  s = "I like python %i%% of the time."
  print s % 99

http://docs.python.org/lib/typesseq-strings.html

-tkc




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


Re: Running another python interpreter

2007-10-18 Thread Sushant
Does gateway.py has the python interpreter in the top (i.e., 
#!/usr/local/bin/python)

-Sushant.
On Thursday 18 October 2007 2:13 pm, Simon Pickles wrote:
> Well, I tried:
>
> os.spawnv(os.P_NOWAIT, "gateway.py", ())
>
> and got:
>
> OSError: [Errno 8] Exec format
>
> Simon Pickles wrote:
> > Hello,
> >
> > I have several servers which link to each other (and of course, to
> > clients).
> >
> > At present, I am starting them in turn manually. Is there a way with
> > python to say, "open gateway.py in a new interpreter window"?
> >
> > I looked at execv, etc, but they seem to replace the current process.
> > Ah, maybe I need spawnv().
> >
> > I am on windows i386, python 2.5
> >
> > Thanks
> >
> > si
-- 
http://mail.python.org/mailman/listinfo/python-list


Can you escape a % in string that will used for substitution

2007-10-18 Thread Gerard Brunick
Is there a way to do:

s = "I like python %i%s of the time."
print s % (99, "%")

without having to pass in "%"?

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


Re: problem with Python class creating

2007-10-18 Thread Bruno Desthuilliers
dmitrey a écrit :
> Hi all,
> I have the code like this one:
> 
> from myMisc import ooIter
> class MyClass:

Unless you have a need for compatibility with aged Python versions, 
you'd be better using new-style classes:

class MyClass(object):

> def __init__(self): pass

This is the default behaviour, so you may as well get rid of this line.

> iterfcn = lambda *args: ooIter(self) # i.e pass the class instance
> to other func named ooIter

cf below about this...

> field2 = val2
> field3 = val3 # etc

You're aware that these two attributes are *class* attributes (that is, 
shared by all instances) ?

> So it yields "global name 'self' is not defined", that is true.

Indeed.

> How
> could I handle the situation?


 iterfcn = lambda self: ooIter(self)

which could as well be written:

 def iterfcn(self):
 ooIter(self)


Remember that Python's methods are - at least at this stage - plain 
functions, so the 'self' parameter is *not* optional - else how could 
the function access the current instance ?

And FWIW, you don't need the *args if you don't use any other than 'self'.

> Currently I do (and it works, but give me some troubles - I should
> call MyClass.__init__ for each children class,

Not unless these classes define their own initializers. But that's 
another problem

> and there are lots of
> those ones)
> 
> class MyClass:
> def __init__(self):
> iterfcn = lambda *args: ooIter(self) 

The real problem is that you create one anonymous function *per instance*.

> I suspect it has better solution, is it?

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


Re: problem with Python class creating

2007-10-18 Thread timaranz
On Oct 19, 8:22 am, dmitrey <[EMAIL PROTECTED]> wrote:
> Hi all,
> I have the code like this one:
>
> from myMisc import ooIter
> class MyClass:
> def __init__(self): pass
> iterfcn = lambda *args: ooIter(self) # i.e pass the class instance
> to other func named ooIter
> field2 = val2
> field3 = val3 # etc
>
> So it yields "global name 'self' is not defined", that is true. How
> could I handle the situation?
>
> Currently I do (and it works, but give me some troubles - I should
> call MyClass.__init__ for each children class, and there are lots of
> those ones)
>
> class MyClass:
> def __init__(self):
> iterfcn = lambda *args: ooIter(self) # i.e pass the class
> instance to other func named ooIter
> field2 = val2
> field3 = val3 # etc
>
> I suspect it has better solution, is it?
> Thank you in advance, Dmitrey

without having tested - I think this should work for you:

from myMisc import ooIter

class MyClass:
 def __init__(self): pass
 iterfcn = lambda self: ooIter(self)

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


Re: Problem with format string / MySQL cursor

2007-10-18 Thread timaranz
On Oct 19, 7:32 am, Florian Lindner <[EMAIL PROTECTED]> wrote:
> Hello,
> I have a string:
>
> INSERT INTO mailboxes (`name`, `login`, `home`, `maildir`, `uid`,
> `gid`, `password`) VALUES (%s, %s, %s, %s, %i, %i, %s)
>
> that is passed to a MySQL cursor from MySQLdb:
>
> ret = cursor.execute(sql, paras)
>
> paras is:
>
> ('flindner', '[EMAIL PROTECTED]', '/home/flindner/', '/home/
> flindner/Mail/test', 1001, 1001, '123')
>
> But that gives me an error:
>
> Traceback (most recent call last):
>   File "account.py", line 188, in ?
> main()
>   File "account.py", line 33, in main
> execute(action, account_type, options)
>   File "account.py", line 129, in execute
> executeSQL(sql, options.username, options.login, options.home,
> options.directory, options.uid, options.gid, options.password)
>   File "/home/flindner/common.py", line 29, in executeSQL
> ret = cursor.execute(sql, paras)
>   File "/usr/lib/python2.4/site-packages/MySQLdb/cursors.py", line
> 148, in execute
> query = query % db.literal(args)
> TypeError: int argument required
>
> I don't see errors in the format string or some other problem
>
> What's wrong?
>
> Thanks,
>
> Florian

You should be using '?' for parameter bindings in your sql string not
python format specifiers (you are after all writing sql here not
python).

INSERT INTO mailboxes (`name`, `login`, `home`, `maildir`, `uid`,
`gid`, `password`) VALUES (?, ?, ?, ?, ?, ?, ?)

Cheers
Tim


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


problem with Python class creating

2007-10-18 Thread dmitrey
Hi all,
I have the code like this one:

from myMisc import ooIter
class MyClass:
def __init__(self): pass
iterfcn = lambda *args: ooIter(self) # i.e pass the class instance
to other func named ooIter
field2 = val2
field3 = val3 # etc

So it yields "global name 'self' is not defined", that is true. How
could I handle the situation?

Currently I do (and it works, but give me some troubles - I should
call MyClass.__init__ for each children class, and there are lots of
those ones)

class MyClass:
def __init__(self):
iterfcn = lambda *args: ooIter(self) # i.e pass the class
instance to other func named ooIter
field2 = val2
field3 = val3 # etc

I suspect it has better solution, is it?
Thank you in advance, Dmitrey

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


Re: Strange behaviour with reversed()

2007-10-18 Thread Terry Reedy

"Steven D'Aprano" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
|I don't understand how reversed() is operating. I've read the description
| in the docs:
|
| reversed(seq)
| Return a reverse iterator. seq must be an object which supports the
| sequence protocol (the __len__() method and the __getitem__() method with
| integer arguments starting at 0). New in version 2.4.

The input specification strongly suggests that rev.next() successively 
yields seq[len(seq)-1], ..., seq[0]

The main question is when len(seq) is called -- on creation as it is, or 
immediately before the first yield as you appear to expect, and as it would 
be in this generator (which does NOT match the actual implementation):

def rev(seq):
n = len(seq)
while n:
 n =-1
 yield seq[n]

If len(seq) were called repeatedly (after the yield, for instance), then 
termination would no longer guaranteed (see below).

I suppose the doc could be augmented with "The iterator is intialized once 
with len(sequence) when it is created, rather than when first used or 
anytime thereafter."  But I wonder whether that would confuse those not 
thinking about corner case nuances.

| and help(reversed) but neither gives any insight to what happens when you
| use reversed() on a sequence, then modify the sequence.

The sequence can potentially be modified between all calls to RL.next, and 
not just before the first as in your examples.

abcs = list('abc')
for a in reversed(abcs):
print a
abcs.append(a)

The 'reverse' of a changing sequence, especially one changing in length, is 
a poorly defined concept.

| >>> L = list("abc")
| >>> RL = reversed(L)
| >>> del L
| >>> list(RL)
| ['c', 'b', 'a']
|
| This suggests that reversed() makes a copy of the list:

Nope.  'del L' merely removes the association between 'L' and the list, 
leaving the internal association between RL and the list and hence the list 
itself.  So the above is consistent with storing a reference (and an index 
initialized to len-1).

| >>> L = list("abc")
| >>> RL = reversed(L)
| >>> L.append("d")
| >>> list(RL)
| ['c', 'b', 'a']
|
| This suggests that reversed() uses a reference to the original list:

It suggests that it uses a reference and an index initialized to len-1 when 
reversed is called (rather than when RL.next is first called).

| >>> RL = reversed(L)
| >>> L[0] = 'e'
| >>> list(RL)
| ['d', 'c', 'b', 'e']
|
| And these examples suggests that reversed() is confused, or at least
| confusing:

This is completely consist with iterating down via reference and index.

| >>> RL = reversed(L)
| >>> del L[2]
| >>> list(RL)
| []

In the internal loop of list, RL first tries to return L[2].  But that 
raises an exception, so RL quits

Terry Jan Reedy



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


image resize question

2007-10-18 Thread Tim Arnold
Hi, I'm using the Image module to resize PNG images from 300 to 100dpi for 
use in HTML pages, but I'm losing some vertical and horizontal lines in the 
images (usually images of x-y plots).

Here's what I do:
import Image
def imgResize(self,filename):
img = Image.open(filename)
dpi = img.info.get('dpi')
if dpi and 295 < int(dpi[0]) < 305:
wd = img.size[0]/3.0 #convert from 300dpi to 100dpi
ht = img.size[1]/3.0
newimg= img.resize((int(wd),int(ht)))
newimg.save(filename)

imgResize('myimage.png')

Can someone point me to a better way so I don't lose the reference lines in 
the images?
thanks,
--Tim Arnold


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


Re: Embedded Boost.Python Enum

2007-10-18 Thread Roman Yakovenko
On 10/18/07, Cory <[EMAIL PROTECTED]> wrote:
>
> Hi,
>
> I have a hopefully quick question about how to use Boost.Python to
> export an Enum.
> I am embedding python in C++ and am currently exporting my classes in
> the following way:
>
> nameSpace["OBJECT"] = class_("OBJECT")
> .def("getType", &OBJECT::getType)
> .def("setSprite", &OBJECT::setSprite);
>
> So following this, I assumed that when exporting an enum the following
> should work:
>
> nameSpace["OBJECT_TYPE"] = enum_("OBJECT_TYPE")
> .value("GENERIC_OBJECT",GENERIC_OBJECT)
> .value("MAP_OBJECT",MAP_OBJECT)
> .value("TOTAL_OBJECT_TYPES",TOTAL_OBJECT_TYPES)
> .export_values();
>
> while the above compiles, it causes the following run time exception:
>
> AttributeError: 'NoneType' object has no attribute 'OBJECT_TYPE'
>
> I took a look at the documentation and the only explanation I found
> for enum appeared to be for extending python with modules. using the
> following form:
>
> BOOST_PYTHON_MODULE(enums)
> {
> enum_("color")
> .value("red", red)
> .value("green", green)
> .export_values()
> .value("blue", blue)
> ;
>
> }


I think you should read next documentation:

http://boost.org/libs/python/doc/v2/scope.html

I COULD do the above, I would prefer the first method if possible. I
> however do not know how to import the module if it is statically
> linked because doing a simple import does not work and I am not
> familiar enough with the boost.python library, Python C API, or Python
> itself to know how to set it up. So My question is this:
>
> How can I either make the first method of adding an enum work and not
> throw the exception, OR once I create the BOOST_PYTHON_MODULE in an
> embedded python c++ program how to I then import that module into my
> embedded python?


http://boost.org/libs/python/doc/tutorial/doc/html/python/embedding.html
Embedding example:
http://svn.boost.org/trac/boost/browser/trunk/libs/python/test/import_.cpp

HTH

-- 
Roman Yakovenko
C++ Python language binding
http://www.language-binding.net/
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Strange behaviour with reversed()

2007-10-18 Thread Andreas Kraemer
On Oct 18, 2:25 am, Duncan Booth <[EMAIL PROTECTED]> wrote:
> Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> >> Note that the starting index is determined at creation time, not when
> >> the iteration begins. So, if you create a reversed object over a list
> >> containing 3 elements, the first returned element will be seq[2],
> then
> >> seq[1], then seq[0]. It doesn't matter if you modify the list after
> >> creating the reversed object but before starting the iteration: it
> will
> >> start at seq[2] even if it's not the last item, and will silently
> stop
> >> if seq[2] is not a valid index anymore.
>
> > You know, that's probably the *least* intuitive behaviour possible.
>
> > For reversed() to iterate over the input as it was at creation time is
> a
> > reasonable design choice; for it to iterate over the input as it is at
> > call time is also a reasonable design choice; but for it to iterate
> over
> > some unholy mutant melding of the sequence as-it-was and as-it-is is
> > simply bizarre. I hope it just fell out of the implementation and
> wasn't
> > a deliberate design choice.
>
> You mean that you don't find it intuitive that it iterates through the
> indices that existed at creation time and returns the values as they are
> now? I'd have said that was the *most* intuitive behaviour.
>
> The only other behaviours I would regard as intuitive for iteration over
> a mutating sequence would be to throw an exception either for mutating
> the sequence while the iterator exists or for using the iterator after a
> mutation.

Maybe it would have been slightly more intuitive if reversed() had
been implemented like this,

def Reversed(seq):
  for i in xrange(len(seq)-1,-1,-1):
yield seq[i]

so that the length of the sequence is determined when the iteration
starts, not when the iterator is created?

The unfortunate naming may also have added to the confusion since its
similarity to "sorted" suggests that a copy of the list is returned.
However,

>>> type(reversed([]))


and for comparison

>>> type(iter([]))


reveals what it really is.

-Andreas

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


Re: Appending a list's elements to another list using a list comprehension

2007-10-18 Thread Debajit Adhikary
On Oct 18, 9:47 am, [EMAIL PROTECTED] (Alex Martelli) wrote:
> Debajit Adhikary <[EMAIL PROTECTED]> wrote:
>
> > How does "a.extend(b)" compare with "a += b" when it comes to
> > performance? Does a + b create a completely new list that it assigns
> > back to a? If so, a.extend(b) would seem to be faster. How could I
> > verify things like these?
>
> That's what the timeit module is for, but make sure that the snippet
> you're timing has no side effects (since it's repeatedly executed).
> E.g.:
>
> brain:~ alex$ python -mtimeit -s'z=[1,2,3];b=[4,5,6]'
> 'a=z[:];a.extend(b)'
> 100 loops, best of 3: 0.769 usec per loop
> brain:~ alex$ python -mtimeit -s'z=[1,2,3];b=[4,5,6]' 'a=z[:];a+=b'
> 100 loops, best of 3: 0.664 usec per loop
> brain:~ alex$ python -mtimeit -s'z=[1,2,3];b=[4,5,6]'
> 'a=z[:];a.extend(b)'
> 100 loops, best of 3: 0.769 usec per loop
> brain:~ alex$ python -mtimeit -s'z=[1,2,3];b=[4,5,6]' 'a=z[:];a+=b'
> 100 loops, best of 3: 0.665 usec per loop
> brain:~ alex$
>
> The repetition of the measurements show them very steady, so now you
> know that += is about 100 nanoseconds faster (on my laptop) than extend
> (the reason is: it saves the tiny cost of looking up 'extend' on a; to
> verify this, use much longer lists and you'll notice that while overall
> times for both approaches increase, the difference between the two
> approaches remains about the same for lists of any length).

> You can find more details on commandline use of timeit at
>  (see adjacent nodes in Python
> docs for examples and details on the more advanced use of timeit inside
> your own code) but I hope these indications may be of help anyway.

Thanks for the wonderful explanation on timeit.
Thats one more tool now in my arsenal :P

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


Problem with format string / MySQL cursor

2007-10-18 Thread Florian Lindner
Hello,
I have a string:

INSERT INTO mailboxes (`name`, `login`, `home`, `maildir`, `uid`,
`gid`, `password`) VALUES (%s, %s, %s, %s, %i, %i, %s)

that is passed to a MySQL cursor from MySQLdb:

ret = cursor.execute(sql, paras)

paras is:

('flindner', '[EMAIL PROTECTED]', '/home/flindner/', '/home/
flindner/Mail/test', 1001, 1001, '123')

But that gives me an error:

Traceback (most recent call last):
  File "account.py", line 188, in ?
main()
  File "account.py", line 33, in main
execute(action, account_type, options)
  File "account.py", line 129, in execute
executeSQL(sql, options.username, options.login, options.home,
options.directory, options.uid, options.gid, options.password)
  File "/home/flindner/common.py", line 29, in executeSQL
ret = cursor.execute(sql, paras)
  File "/usr/lib/python2.4/site-packages/MySQLdb/cursors.py", line
148, in execute
query = query % db.literal(args)
TypeError: int argument required


I don't see errors in the format string or some other problem

What's wrong?

Thanks,

Florian

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


1 year free

2007-10-18 Thread nayloon
www.nayloon.com business2business website.Full dynamic and 2 language
10 pages.You post your products you can find customer from all over
world.Try it.You will see the different.

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


Re: Convert string to command..

2007-10-18 Thread Carsten Haese
On Thu, 2007-10-18 at 19:53 +0200, Hrvoje Niksic wrote:
> Don't
> forget to also use a bind variable, something like:
> 
> cursor.execute("INSERT INTO cache2 VALUES (?)", a)

I second the advice, but that code won't work. The bind parameters must
be a sequence, and psycopg2 (unfortunately) uses %s for parameter
markers, instead of the SQL standard question mark. So the actual code
would be

cursor.execute("INSERT INTO cache2 VALUES (%s)", (a,) )

HTH,

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: Running another python interpreter

2007-10-18 Thread Simon Pickles
Well, I tried:
   
os.spawnv(os.P_NOWAIT, "gateway.py", ())

and got:

OSError: [Errno 8] Exec format



Simon Pickles wrote:
> Hello,
>
> I have several servers which link to each other (and of course, to clients).
>
> At present, I am starting them in turn manually. Is there a way with 
> python to say, "open gateway.py in a new interpreter window"?
>
> I looked at execv, etc, but they seem to replace the current process. 
> Ah, maybe I need spawnv().
>
> I am on windows i386, python 2.5
>
> Thanks
>
> si
>   
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert string to command..

2007-10-18 Thread Hrvoje Niksic
Abandoned <[EMAIL PROTECTED]> writes:

> > When you load it, convert the string to dict with cPickle.loads
> > instead of with eval.
> 
> Yes i understand and this very very good ;)

Good!  :-)

> psycopg2.ProgrammingError: invalid byte sequence for encoding "UTF8":
> 0x80
> HINT:  This error can also happen if the byte sequence does not match
> the encoding expected by the server, which is controlled by
> "client_encoding".

Use a different column type for cache2's column, one more appropriate
for storing binary characters (perhaps BYTEA for Postgres).  Don't
forget to also use a bind variable, something like:

cursor.execute("INSERT INTO cache2 VALUES (?)", a)

Using "INSERT ... ('%s')" % (a) won't work, since the huge binary
string in a can contain arbitrary characters, including the single
quote.
-- 
http://mail.python.org/mailman/listinfo/python-list


Running another python interpreter

2007-10-18 Thread Simon Pickles
Hello,

I have several servers which link to each other (and of course, to clients).

At present, I am starting them in turn manually. Is there a way with 
python to say, "open gateway.py in a new interpreter window"?

I looked at execv, etc, but they seem to replace the current process. 
Ah, maybe I need spawnv().

I am on windows i386, python 2.5

Thanks

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


Re: Noob questions about Python

2007-10-18 Thread Arnaud Delobelle
On Oct 18, 7:06 am, Ixiaus <[EMAIL PROTECTED]> wrote:
[...]
> I know '<<' is shifting x over by n bits; but could you point me to
> some literature that would explain why it is the same as "x*2**n"?

I haven't got literature but I've got a (hopefully straightforward)
explanation:

In binary 2 is 10.  When you multiply by 10, you shift all your digits
left by 1 place.
When you multiply by 10**n (which is 1 followed by n zeroes), you
shift all your digits left by n places.

HTH

--
Arnaud


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


Re: Best way to generate alternate toggling values in a loop?

2007-10-18 Thread Luis Zarrabeitia
On Thursday 18 October 2007 09:09, Grant Edwards wrote:
> I like the solution somebody sent me via PM:
>
> def toggle():
> while 1:
> yield "Even"
> yield "Odd"
>

That was me.
Sorry, list, I meant to send it to everyone but I my webmail didn't respect 
the list* headers :(.

Thanks, Grant!

-- 
Luis Zarrabeitia (aka Kyrie)
Fac. de Matemática y Computación, UH.
http://profesores.matcom.uh.cu/~kyrie
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert string to command..

2007-10-18 Thread Bruno Desthuilliers
Abandoned a écrit :
(snip)
> I'm very confused :(
> I try to explain main problem...
> I have a table like this:
> id-1 | id-2 | value
> 23 24   34
> 56 68   66
> 56 98   32455
> 55 62   655
> 56 28   123
>  ( 3 millions elements)
> 
> I select where id=56 and 100.000 rows are selecting but this took 2
> second. (very big for my project)

Not to bad in the absolute.

> I try cache to speed up this select operation..
> And create a cache table:
> id-1 | all
> 56{68:66, 98:32455, 62:655}

I really doubt this is the right way to go.

> When i select where id 56 i select 1 row and its took 0.09 second but
> i must convert text to dictionary..
> 
> Have you got any idea what can i do this conver operation ?

Other alread answered

> Have you got any idea what can i do cache for this table ?

Depends on your RDBMS. And as far as I'm concerned, I'd start by trying 
to find out how to optimize this query within the RDBMS - good ones are 
usually highly optimized softwares with provision for quite a lot of 
performance tuning.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert string to command..

2007-10-18 Thread Bruno Desthuilliers
Richard Brodie a écrit :
> "Matimus" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
> 
>> I think several people have given you the correct answer, but for some
>> reason you aren't getting it. Instead of saving the string
>> representation of a dictionary to the database...
> 
> Mind you, if this were Jeopardy, "Store a binary pickle
> of a denormalized table back in the database" would
> be a tough one. 
> 
> 
Indeed.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert string to command..

2007-10-18 Thread Bruno Desthuilliers
Abandoned a écrit :
(snip)
> import cPickle as pickle
> a="{2:3,4:6,2:7}"
> s=pickle.dumps(a, -1)
> g=pickle.loads(s);
> print g
> '{2:3,4:6,2:7}'
> 
> Thank you very much for your answer but result is a string ??
> 
Of course it's a string. That's what you pickled. What did you hope ? If 
you want a dict back, then pickle a dict.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert string to command..

2007-10-18 Thread Bruno Desthuilliers
Abandoned a écrit :
> On Oct 18, 6:51 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
>> On Thu, 18 Oct 2007 08:41:30 -0700, Abandoned wrote:
>>> import cPickle as pickle
>>> a="{2:3,4:6,2:7}"
>>> s=pickle.dumps(a, -1)
>>> g=pickle.loads(s);
>>> print g
>>> '{2:3,4:6,2:7}'
>>> Thank you very much for your answer but result is a string ??
>> In Python terms yes, strings in Python can contain any byte value.  If you
>> want to put this into a database you need a BLOB column or encode it as
>> base64 or something similar more ASCII safe.
>>
>> Ciao,
>> Marc 'BlackJack' Rintsch
> 
> '{2:3,4:6,2:7}' already in database, i select this and convert to real
> dictionary..

MVHO is that whoever uses a RDBMS to store language-specific serialized 
collections should be shot down without sommation.

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


Re: python logging module and custom handler specified in config file

2007-10-18 Thread Vinay Sajip
On 15 Oct, 15:15, Frank Aune <[EMAIL PROTECTED]> wrote:
> What I'm wondering, is if its possible to specify the database handler in a
> config file like:
>
> [handler_database]
> class=DBHandler
> level=DEBUG
> formatter=database
> args=('localhost', uid='root')
>
> I've seen the log_test14.py example bundled withloggingmodule, which
> describes the DBHandler class and I can get it working if I attach this
> handler to the root logger inside my application, but I would really like to
> do it through a config file like above. But since thelogging.handlers module
> does not know about the DBHandler class, obviously this does not work.
>
> I was thinking perhaps specifying module and classname in the class= option
> above, like class=dbhandler.DBHandler, but it will just complain that
> name 'dbhandler' is not defined.
>
> Is this possible to archieve somehow?
>

The values in the config file are interpreted in the context of the
logging module's namespace. Hence, one way of achieving what you want
is putting any custom handlers in
a module of your own, and providing a binding in the logging module's
namespace. For example: assuming your DBHandler is defined in a module
customhandlers, you could do this somewhere in your code, before
loading the configuration:

import logging
import customhandlers # Use your own module name here

logging.custhandlers = customhandlers # Bind your module to
"custhandlers" in logging

and then your logging configuration can refer to
"custhandlers.DBHandler". Of course I merely used "custhandlers" and
"customhandlers" to show how you can bind to an arbitrary name.

The same technique applies to the arguments passed to the constructor.

Hope this helps,

Vinay Sajip


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


Re: Convert string to command..

2007-10-18 Thread Richard Brodie

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

> I think several people have given you the correct answer, but for some
> reason you aren't getting it. Instead of saving the string
> representation of a dictionary to the database...

Mind you, if this were Jeopardy, "Store a binary pickle
of a denormalized table back in the database" would
be a tough one. 


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


Re: CGI and external JavaScript nightmare

2007-10-18 Thread Paul Boddie
On 18 Okt, 17:24, Steve Holden <[EMAIL PROTECTED]> wrote:
> allen.fowler wrote:

[Quoting IamIan...]

> >> One CGI question - since all of my CGIs are spitting out HTML is their
> >> source code safe? wget and linking to the source deliver the output
> >> HTML. Are there any other methods of trying to steal the source CGI I
> >> need to protect against?

[...]

> > Not sure I fully understand the question.
>
> > Can you post the CGI code here?
>
> That's funny.

Yes, there's no point in employing sophisticated technical mechanisms
for security when they are all undermined by some good old-fashioned
social engineering. ;-)

> The OP's problem is that he suffers from the delusion that people want
> to steal the source code for his CGI script.

The solution being that of ensuring that the Web server settings tell
the server to always run CGI scripts and never serve up the scripts
themselves as content. Additional security, such as file permissions,
access to the server, and so on, are beyond the scope of casual Usenet
advice with the level of detail provided by the inquirer.

Paul

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


Re: Convert string to command..

2007-10-18 Thread Sebastian Bassi
On 10/18/07, Adam Atlas <[EMAIL PROTECTED]> wrote:
>
> Use the builtin function "eval".

What is the difference with os.system()?

-- 
Sebastián Bassi (セバスティアン). Diplomado en Ciencia y Tecnología.
Curso Biologia molecular para programadores: http://tinyurl.com/2vv8w6
GPG Fingerprint: 9470 0980 620D ABFC BE63 A4A4 A3DE C97D 8422 D43D
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Convert string to command..

2007-10-18 Thread Abandoned
On Oct 18, 7:40 pm, Hrvoje Niksic <[EMAIL PROTECTED]> wrote:
> Abandoned <[EMAIL PROTECTED]> writes:
> > Sorry i can't understand :(
> > Yes my database already has data in the "{..}" format and i select
> > this and i want to use it for dictionary..
>
> But, do you use Python to create that data?  If so, simply convert it
> to pickle binary format instead of "{...}".  As explained in my other
> post:
>
> > id-1 | all
> > 56{68:66, 98:32455, 62:655}
>
> If you use Python to create this cache table, then simply don't dump
> it as a dictionary, but as a pickle:
>
> id-1 | all
> 56 
>
> When you load it, convert the string to dict with cPickle.loads
> instead of with eval.

Yes i understand and this very very good ;)
But i have a problem..
a=eval(a)
a=pickle.dumps(a, -1)
cursor.execute("INSERT INTO cache2 VALUES ('%s')" % (a))
conn.commit()

and give me error:

psycopg2.ProgrammingError: invalid byte sequence for encoding "UTF8":
0x80
HINT:  This error can also happen if the byte sequence does not match
the encoding expected by the server, which is controlled by
"client_encoding".



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


Fwd: Pyinotify : which user ?

2007-10-18 Thread Roc Zhou
-- Forwarded message --
From: Roc Zhou <[EMAIL PROTECTED]>
Date: Oct 19, 2007 12:48 AM
Subject: Re: Pyinotify : which user ?
To: Sébastien Weber <[EMAIL PROTECTED]>

The command lsof or fuser can report who is using the file, maybe you can
have a look at their source code, but they must be C code.

But since inotify is not absolute realtime, once the file is modified,
lsof or fuser can not return the right result.

I think it's better to use a good authentication method if you want to
use inotify this way, then you know when a user logged in and what
actions or commands he/she invoked, and record the inotify events with
timestamps. And a more careful permission strategy may be more sensible.

Or you can make use of SVN?

I'm also doing a project that makes use of pyinotify, one function of it
can be a "REPORT" as an IDS(Intrusion Detection System), and I reaches
several limitations of pyinotify, which you may be interested in.

The project is at:
http://sourceforge.net/projects/crablfs

And the document is at:
http://crablfs.sourceforge.net/#ru_data_man

Thanks.

On 18 Oct 2007 16:00:24 GMT, Sébastien Weber <[EMAIL PROTECTED]> wrote:
>
> Hello,
>
> I'm actually writing an application with pyinotify which watchs a
> directory.
> Pyinotify lets me know the events (access, modify, suppression, etc.) on
> and in the directory, but not the users who are responsable of them.
> Does someone know a library which could give me that information (who's
> using a file) ?
>
> Thank's in advance,
>
> SW.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Convert string to command..

2007-10-18 Thread Hrvoje Niksic
Abandoned <[EMAIL PROTECTED]> writes:

> Sorry i can't understand :(
> Yes my database already has data in the "{..}" format and i select
> this and i want to use it for dictionary..

But, do you use Python to create that data?  If so, simply convert it
to pickle binary format instead of "{...}".  As explained in my other
post:

> id-1 | all
> 56{68:66, 98:32455, 62:655}

If you use Python to create this cache table, then simply don't dump
it as a dictionary, but as a pickle:

id-1 | all
56 

When you load it, convert the string to dict with cPickle.loads
instead of with eval.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: some questions about Python and tkinter

2007-10-18 Thread fabdeb
On Oct 16, 9:17 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Tue, 16 Oct 2007 11:52:22 -0700, fabdeb wrote:
> > the first: what is the differences between a function and a classe?
>
> A class bundles data and functions into one object.
>
> > In which case i should use a function ?
> > In which case i should use a class ?
>
> If you have several functions that operate on the same data it might make
> sense to put all into a class to treat them as one "unit".
>
> > The second: there is some pincipals gui toolkit: tkinter , Python Mega-
> > Widgets, PyGTK, PyQt, FxPy, WxPy
>
> > what are the advantages of each one, and in which case i use each of
> > them?
>
> `Tkinter` is part of the standard library.  If you use that or one of the
> others is a matter of taste to some degree.  In a GNOME environment PyGTK
> may look more natural, under KDE a PyQt or PyKDE based GUI may feel more
> "native".  Another factor for a decision might be the license of the GUI
> toolkit.
>
> Ciao,
> Marc 'BlackJack' Rintsch

Thanks for all your links and responses .
I have a better comprehension of what i have to do for my program.

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


Re: strptime and microseconds

2007-10-18 Thread mathieu
On Oct 18, 6:36 pm, mathieu <[EMAIL PROTECTED]> wrote:
> On Oct 18, 6:00 pm, mathieu <[EMAIL PROTECTED]> wrote:
>
>
>
> > Hi there,
>
> >   I am trying to use strptime to parse my microseconds but I was not
> > able the documentation for it. The only list I found was:
>
> >  http://docs.python.org/lib/module-time.html
>
> >  So I can get seconds with %S, but nowhere is there a microsecond
> > symbol...
>
> > Thanks for pointer to doc,
> > -Mathieu
>
> > s1 = "20070619"
> > s2 = "150348.62"
> > s = s1+s2
> > d = datetime(*strptime(s, "%Y%m%d%H%M%S.%?"))
>
> Getting closer...
>
> s1 = "20070619"
> s2 = "115344.51"
> s3 = "115445.123456"
>
> ms2 = eval(s2) % 1
> mms2 = int(ms2 * 100 + 0.5)
> ms3 = eval(s3) % 1
> mms3 = int(ms3 * 100 + 0.5)
>
> s = s1 + s2
> d1 = datetime(*strptime(s[:12], "%Y%m%d%H%M%S")[0:6])
> d1.replace(microsecond = mms2)
> #print d1.microsecond
>
> s = s1 + s3
> d2 = datetime(*strptime(s[:12], "%Y%m%d%H%M%S")[0:6])
> d2.replace(microsecond = mms3)
> #print d2.microsecond
>
> d = d2 - d1
> print d.seconds
> print d.microseconds
>
> why would d.microseconds be 0 ??
>
> Thanks,
> -Mathieu


D'oh !

Ok final version is simply:

s1 = "20070619"
s2 = "115344.51"
s3 = "115446.123456"

ms2 = eval(s2) % 1
mms2 = int(ms2 * 100 + 0.5)
ms3 = eval(s3) % 1
mms3 = int(ms3 * 100 + 0.5)

s = s1 + s2
d1 = datetime(*strptime(s[:14], "%Y%m%d%H%M%S")[0:6])
d1 = d1.replace(microsecond = mms2)
#
s = s1 + s3
d2 = datetime(*strptime(s[:14], "%Y%m%d%H%M%S")[0:6])
d2 = d2.replace(microsecond = mms3)
#
d = d2 - d1
print d.seconds
print d.microseconds

sorry for the noise :))
-Mathieu




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


Re: Convert string to command..

2007-10-18 Thread Matimus
On Oct 18, 9:09 am, Abandoned <[EMAIL PROTECTED]> wrote:
> On Oct 18, 6:57 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
>
>
>
> > Abandoned wrote:
> > > On Oct 18, 6:35 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> > >> Abandoned wrote:
> > >> > On Oct 18, 6:14 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> > >> >> Abandoned wrote:
> > >> >> > Thanks you all answer..
> > >> >> > But "eval" is very slow at very big dictionary {2:3,4:5,6:19}
> > >> >> > (100.000 elements)
> > >> >> > Is there any easy alternative ?
>
> > >> >> How big? How slow? For me, a 1-element list takes  0.04 seconds to
> > >> >> be parsed. Which I find fast.
>
> > >> >> Diez
>
> > >> > 173.000 dict elements and it tooks 2.2 seconds this very big time for
> > >> > my project
>
> > >> Where does the data come from?
>
> > >> Diez
>
> > > Data come from database..
> > > I want to cache to speed up my system and i save the dictionary to
> > > database for speed up but eval is very slow for do this.
> > > Not: 2.2 second only eval operation.
>
> > Does the dictionary change often?
>
> > And you should store a pickle to the database then. Besides, making a
> > database-query of that size (after all, we're talking a few megs here) will
> > take a while as well - so are you SURE the 2.2 seconds are a problem? Or is
> > it just that you think they are?
>
> > Diez- Hide quoted text -
>
> > - Show quoted text -
>
> I'm very confused :(
> I try to explain main problem...
> I have a table like this:
> id-1 | id-2 | value
> 23 24   34
> 56 68   66
> 56 98   32455
> 55 62   655
> 56 28   123
>  ( 3 millions elements)
>
> I select where id=56 and 100.000 rows are selecting but this took 2
> second. (very big for my project)
> I try cache to speed up this select operation..
> And create a cache table:
> id-1 | all
> 56{68:66, 98:32455, 62:655}
>
> When i select where id 56 i select 1 row and its took 0.09 second but
> i must convert text to dictionary..
>
> Have you got any idea what can i do this conver operation ?
> or
> Have you got any idea what can i do cache for this table ?

I think several people have given you the correct answer, but for some
reason you aren't getting it. Instead of saving the string
representation of a dictionary to the database, pickle the dictionary
(not the string representation, but the actual dictionary) and save
the pickled object as a BLOB to the database. using pickle to re-
create the dictionary should be much faster than evaluating a string
representation of it.

Matt


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


Re: strptime and microseconds

2007-10-18 Thread mathieu
On Oct 18, 6:00 pm, mathieu <[EMAIL PROTECTED]> wrote:
> Hi there,
>
>   I am trying to use strptime to parse my microseconds but I was not
> able the documentation for it. The only list I found was:
>
>  http://docs.python.org/lib/module-time.html
>
>  So I can get seconds with %S, but nowhere is there a microsecond
> symbol...
>
> Thanks for pointer to doc,
> -Mathieu
>
> s1 = "20070619"
> s2 = "150348.62"
> s = s1+s2
> d = datetime(*strptime(s, "%Y%m%d%H%M%S.%?"))


Getting closer...

s1 = "20070619"
s2 = "115344.51"
s3 = "115445.123456"

ms2 = eval(s2) % 1
mms2 = int(ms2 * 100 + 0.5)
ms3 = eval(s3) % 1
mms3 = int(ms3 * 100 + 0.5)

s = s1 + s2
d1 = datetime(*strptime(s[:12], "%Y%m%d%H%M%S")[0:6])
d1.replace(microsecond = mms2)
#print d1.microsecond

s = s1 + s3
d2 = datetime(*strptime(s[:12], "%Y%m%d%H%M%S")[0:6])
d2.replace(microsecond = mms3)
#print d2.microsecond

d = d2 - d1
print d.seconds
print d.microseconds

why would d.microseconds be 0 ??

Thanks,
-Mathieu

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


Re: Convert string to command..

2007-10-18 Thread Hrvoje Niksic
Abandoned <[EMAIL PROTECTED]> writes:

> I select where id=56 and 100.000 rows are selecting but this took 2
> second. (very big for my project)
> I try cache to speed up this select operation..
> And create a cache table:
> id-1 | all
> 56{68:66, 98:32455, 62:655}

If you use Python to create this cache table, then simply don't dump
it as a dictionary, but as a pickle:

id-1 | all
56 

When you load it, convert the string to dict with cPickle.loads
instead of with eval.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert string to command..

2007-10-18 Thread Abandoned
On Oct 18, 7:02 pm, Hrvoje Niksic <[EMAIL PROTECTED]> wrote:
> Abandoned <[EMAIL PROTECTED]> writes:
> > import cPickle as pickle
> > a="{2:3,4:6,2:7}"
> > s=pickle.dumps(a, -1)
> > g=pickle.loads(s);
> > print g
> > '{2:3,4:6,2:7}'
>
> > Thank you very much for your answer but result is a string ??
>
> Because you gave it a string.  If you give it a dict, you'll get a
> dict:
>
> >>> import cPickle as pickle
> >>> a = {1:2, 3:4}
> >>> s = pickle.dumps(a, -1)
> >>> g = pickle.loads(s)
> >>> g
>
> {1: 2, 3: 4}
>
> If your existing database already has data in the "{...}" format, then
> eval it only the first time.  Then you'll get the dict which you can
> cache thruogh the use of dumps/loads.

Sorry i can't understand :(
Yes my database already has data in the "{..}" format and i select
this and i want to use it for dictionary..
in your example:
first data is a string
finally data is already string

I want to command like eval. (eval is not good because it is slow for
my project)

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


Re: Convert string to command..

2007-10-18 Thread Hrvoje Niksic
Abandoned <[EMAIL PROTECTED]> writes:

> import cPickle as pickle
> a="{2:3,4:6,2:7}"
> s=pickle.dumps(a, -1)
> g=pickle.loads(s);
> print g
> '{2:3,4:6,2:7}'
>
> Thank you very much for your answer but result is a string ??

Because you gave it a string.  If you give it a dict, you'll get a
dict:

>>> import cPickle as pickle
>>> a = {1:2, 3:4}
>>> s = pickle.dumps(a, -1)
>>> g = pickle.loads(s)
>>> g
{1: 2, 3: 4}

If your existing database already has data in the "{...}" format, then
eval it only the first time.  Then you'll get the dict which you can
cache thruogh the use of dumps/loads.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert string to command..

2007-10-18 Thread Abandoned
On Oct 18, 6:57 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> Abandoned wrote:
> > On Oct 18, 6:35 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> >> Abandoned wrote:
> >> > On Oct 18, 6:14 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> >> >> Abandoned wrote:
> >> >> > Thanks you all answer..
> >> >> > But "eval" is very slow at very big dictionary {2:3,4:5,6:19}
> >> >> > (100.000 elements)
> >> >> > Is there any easy alternative ?
>
> >> >> How big? How slow? For me, a 1-element list takes  0.04 seconds to
> >> >> be parsed. Which I find fast.
>
> >> >> Diez
>
> >> > 173.000 dict elements and it tooks 2.2 seconds this very big time for
> >> > my project
>
> >> Where does the data come from?
>
> >> Diez
>
> > Data come from database..
> > I want to cache to speed up my system and i save the dictionary to
> > database for speed up but eval is very slow for do this.
> > Not: 2.2 second only eval operation.
>
> Does the dictionary change often?
>
> And you should store a pickle to the database then. Besides, making a
> database-query of that size (after all, we're talking a few megs here) will
> take a while as well - so are you SURE the 2.2 seconds are a problem? Or is
> it just that you think they are?
>
> Diez- Hide quoted text -
>
> - Show quoted text -

I'm very confused :(
I try to explain main problem...
I have a table like this:
id-1 | id-2 | value
23 24   34
56 68   66
56 98   32455
55 62   655
56 28   123
 ( 3 millions elements)

I select where id=56 and 100.000 rows are selecting but this took 2
second. (very big for my project)
I try cache to speed up this select operation..
And create a cache table:
id-1 | all
56{68:66, 98:32455, 62:655}

When i select where id 56 i select 1 row and its took 0.09 second but
i must convert text to dictionary..

Have you got any idea what can i do this conver operation ?
or
Have you got any idea what can i do cache for this table ?

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


strptime and microseconds

2007-10-18 Thread mathieu
Hi there,

  I am trying to use strptime to parse my microseconds but I was not
able the documentation for it. The only list I found was:

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

 So I can get seconds with %S, but nowhere is there a microsecond
symbol...

Thanks for pointer to doc,
-Mathieu


s1 = "20070619"
s2 = "150348.62"
s = s1+s2
d = datetime(*strptime(s, "%Y%m%d%H%M%S.%?"))

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


Pyinotify : which user ?

2007-10-18 Thread Sébastien Weber
Hello,

I'm actually writing an application with pyinotify which watchs a 
directory.
Pyinotify lets me know the events (access, modify, suppression, etc.) on 
and in the directory, but not the users who are responsable of them.
Does someone know a library which could give me that information (who's 
using a file) ?

Thank's in advance,

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


Re: Convert string to command..

2007-10-18 Thread Diez B. Roggisch
Abandoned wrote:

> On Oct 18, 6:35 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
>> Abandoned wrote:
>> > On Oct 18, 6:14 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
>> >> Abandoned wrote:
>> >> > Thanks you all answer..
>> >> > But "eval" is very slow at very big dictionary {2:3,4:5,6:19}
>> >> > (100.000 elements)
>> >> > Is there any easy alternative ?
>>
>> >> How big? How slow? For me, a 1-element list takes  0.04 seconds to
>> >> be parsed. Which I find fast.
>>
>> >> Diez
>>
>> > 173.000 dict elements and it tooks 2.2 seconds this very big time for
>> > my project
>>
>> Where does the data come from?
>>
>> Diez
> 
> Data come from database..
> I want to cache to speed up my system and i save the dictionary to
> database for speed up but eval is very slow for do this.
> Not: 2.2 second only eval operation.

Does the dictionary change often?

And you should store a pickle to the database then. Besides, making a
database-query of that size (after all, we're talking a few megs here) will
take a while as well - so are you SURE the 2.2 seconds are a problem? Or is
it just that you think they are?

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


version 1.4 of scalar class released

2007-10-18 Thread [EMAIL PROTECTED]
Version 1.4 of my scalar class is available at

http://RussP.us/scalar.htm

No major changes. I have corrected the "repr" function to make it more
useful, and I have added a "unit_type" function that returns the type
of a unit (e.g., time, length, force). The unit_type function is
intended mainly for interactive, "calculator-style" use.

If you do scientific or engineering calculations or programming,
please check out my scalar class. I think you'll like it.

It will relieve you of the burden of keeping track of units ("darn, I
can't remember if that angle is in radians or degrees?"). And the
really nifty thing about it is that, when you want high execution
speed for production runs, you can easily switch off the units with a
simple change of the import line. All the unit objects will then be
replaced with bulit-in types (typically floats), and your output will
be unchanged, but you will notice a dramatic speedup.

A complete user guide is available in both pdf and html formats. Give
it a try and let me know what you think!

--Russ P.

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


Re: Convert string to command..

2007-10-18 Thread Abandoned
On Oct 18, 6:51 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Thu, 18 Oct 2007 08:41:30 -0700, Abandoned wrote:
> > import cPickle as pickle
> > a="{2:3,4:6,2:7}"
> > s=pickle.dumps(a, -1)
> > g=pickle.loads(s);
> > print g
> > '{2:3,4:6,2:7}'
>
> > Thank you very much for your answer but result is a string ??
>
> In Python terms yes, strings in Python can contain any byte value.  If you
> want to put this into a database you need a BLOB column or encode it as
> base64 or something similar more ASCII safe.
>
> Ciao,
> Marc 'BlackJack' Rintsch

'{2:3,4:6,2:7}' already in database, i select this and convert to real
dictionary..

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


Re: Convert string to command..

2007-10-18 Thread Marc 'BlackJack' Rintsch
On Thu, 18 Oct 2007 08:41:30 -0700, Abandoned wrote:

> import cPickle as pickle
> a="{2:3,4:6,2:7}"
> s=pickle.dumps(a, -1)
> g=pickle.loads(s);
> print g
> '{2:3,4:6,2:7}'
> 
> Thank you very much for your answer but result is a string ??

In Python terms yes, strings in Python can contain any byte value.  If you
want to put this into a database you need a BLOB column or encode it as
base64 or something similar more ASCII safe.

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


Re: Convert string to command..

2007-10-18 Thread Abandoned
On Oct 18, 6:35 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> Abandoned wrote:
> > On Oct 18, 6:14 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> >> Abandoned wrote:
> >> > Thanks you all answer..
> >> > But "eval" is very slow at very big dictionary {2:3,4:5,6:19}
> >> > (100.000 elements)
> >> > Is there any easy alternative ?
>
> >> How big? How slow? For me, a 1-element list takes  0.04 seconds to be
> >> parsed. Which I find fast.
>
> >> Diez
>
> > 173.000 dict elements and it tooks 2.2 seconds this very big time for
> > my project
>
> Where does the data come from?
>
> Diez

Data come from database..
I want to cache to speed up my system and i save the dictionary to
database for speed up but eval is very slow for do this.
Not: 2.2 second only eval operation.

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


Re: Convert string to command..

2007-10-18 Thread Abandoned
On Oct 18, 6:26 pm, Hrvoje Niksic <[EMAIL PROTECTED]> wrote:
> Abandoned <[EMAIL PROTECTED]> writes:
> > 173.000 dict elements and it tooks 2.2 seconds this very big time
> > for my project
>
> If you're generating the string from Python, use cPickle instead.
> Much faster:
>
> >>> import time
> >>> d = dict((i, i+1) for i in xrange(17))
> >>> len(d)
> 17
> >>> s=repr(d)
> >>> t0 = time.time(); d2 = eval(s); t1 = time.time()
> >>> t1-t0
> 1.5457899570465088
> >>> import cPickle as pickle
> >>> s = pickle.dumps(d, -1)
> >>> len(s)
> 1437693
> >>> t0 = time.time(); d2 = pickle.loads(s); t1 = time.time()
> >>> t1-t0
>
> 0.060307979583740234>>> len(d2)
>
> 17
>
> That is 25x speedup.  Note that cPickle's format is binary.  Using the
> textual format makes for more readable pickles, but reduces the
> speedup to "only" 9.5x on my machine.
>
> P.S.
> Before someone says that using pickle is unsafe, remember that he is
> considering *eval* as the alternative.  :-)


import cPickle as pickle
a="{2:3,4:6,2:7}"
s=pickle.dumps(a, -1)
g=pickle.loads(s);
print g
'{2:3,4:6,2:7}'

Thank you very much for your answer but result is a string ??

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


Re: Convert string to command..

2007-10-18 Thread Diez B. Roggisch
Abandoned wrote:

> On Oct 18, 6:14 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
>> Abandoned wrote:
>> > Thanks you all answer..
>> > But "eval" is very slow at very big dictionary {2:3,4:5,6:19}
>> > (100.000 elements)
>> > Is there any easy alternative ?
>>
>> How big? How slow? For me, a 1-element list takes  0.04 seconds to be
>> parsed. Which I find fast.
>>
>> Diez
> 
> 173.000 dict elements and it tooks 2.2 seconds this very big time for
> my project

Where does the data come from?

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


Re: Convert string to command..

2007-10-18 Thread Hrvoje Niksic
Abandoned <[EMAIL PROTECTED]> writes:

> 173.000 dict elements and it tooks 2.2 seconds this very big time
> for my project

If you're generating the string from Python, use cPickle instead.
Much faster:

>>> import time
>>> d = dict((i, i+1) for i in xrange(17))
>>> len(d)
17
>>> s=repr(d)
>>> t0 = time.time(); d2 = eval(s); t1 = time.time()
>>> t1-t0
1.5457899570465088
>>> import cPickle as pickle
>>> s = pickle.dumps(d, -1)
>>> len(s)
1437693
>>> t0 = time.time(); d2 = pickle.loads(s); t1 = time.time()
>>> t1-t0
0.060307979583740234
>>> len(d2)
17

That is 25x speedup.  Note that cPickle's format is binary.  Using the
textual format makes for more readable pickles, but reduces the
speedup to "only" 9.5x on my machine.


P.S.
Before someone says that using pickle is unsafe, remember that he is
considering *eval* as the alternative.  :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: CGI and external JavaScript nightmare

2007-10-18 Thread Steve Holden
allen.fowler wrote:
>> One CGI question - since all of my CGIs are spitting out HTML is their
>> source code safe? wget and linking to the source deliver the output
>> HTML. Are there any other methods of trying to steal the source CGI I
>> need to protect against?
>>
>> Thank you.
> 
> Not sure I fully understand the question.
> 
> Can you post the CGI code here?
> 
That's funny.

The OP's problem is that he suffers from the delusion that people want 
to steal the source code for his CGI script.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden

Sorry, the dog ate my .sigline so I couldn't cat it

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


Re: open remote terminal

2007-10-18 Thread Steve Holden
Fabian Braennstroem wrote:
> Hi,
> 
> I would like to use python to start an terminal, e.g. xterm, and login on a
> remote machine using rsh or ssh. This could be done using 'xterm -e ssh
> machine', but after the login I would like to jump to a given directory.
> Does anyone have an idea how to do this with python?
> 
> Regards!
> Fabian
> 
pexpect would be the usual solution, I believe, if you could get it to 
interact correctly with your virtual terminal.

   http://pexpect.sourceforge.net/

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden

Sorry, the dog ate my .sigline so I couldn't cat it

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


Re: Convert string to command..

2007-10-18 Thread Abandoned
On Oct 18, 6:14 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> Abandoned wrote:
> > Thanks you all answer..
> > But "eval" is very slow at very big dictionary {2:3,4:5,6:19}
> > (100.000 elements)
> > Is there any easy alternative ?
>
> How big? How slow? For me, a 1-element list takes  0.04 seconds to be
> parsed. Which I find fast.
>
> Diez

173.000 dict elements and it tooks 2.2 seconds this very big time for
my project

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


Re: Convert string to command..

2007-10-18 Thread Diez B. Roggisch
Abandoned wrote:

> Thanks you all answer..
> But "eval" is very slow at very big dictionary {2:3,4:5,6:19}
> (100.000 elements)
> Is there any easy alternative ?

How big? How slow? For me, a 1-element list takes  0.04 seconds to be
parsed. Which I find fast.

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


Re: Convert string to command..

2007-10-18 Thread Abandoned
Thanks you all answer..
But "eval" is very slow at very big dictionary {2:3,4:5,6:19}
(100.000 elements)
Is there any easy alternative ?

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


Re: pymssql - insert NULL to int

2007-10-18 Thread Diez B. Roggisch
rc wrote:

> On Oct 17, 11:07 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
>> rc wrote:
>> > How to insert NULL values in to int field using params.
>>
>> > I'm trying to use pymssql.execute, passing the operation and list of
>> > params.  One of the values in the params is a NULL value going to int
>> > field.  The pymssql._quote() puts ' around the NULL which causes an
>> > exception to be thrown, is there a way to use the params for this or
>> > do I need to build the insert string myself?
>>
>> > pymssql.DatabaseError: internal error: SQL Server message 245,
>> > severity 16, state 1, line 1:
>> > Conversion failed when converting the varchar value 'NULL' to data
>> > type int.
>> > DB-Lib error message 10007, severity 5:
>> > General SQL Server error: Check messages from the SQL Server.
>>
>> Can you show us the actual code you use? I doubt that such a basic thing
>> isn't working.
>>
>> You are aware that you have to pass None, not "NULL"?
>>
>> Diez
> 
> I had tried None and was getting the same error as 'NULL', however, I
> tried again after your post and its working now.  Not sure what I
> changed but thanks for getting me to tried it again.

I'm pretty sure you tried "None" instead of None

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


Re: Pull Last 3 Months

2007-10-18 Thread Hyuga
On Oct 18, 12:25 am, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> I prefer the calendar module in that case:
>
> py> import locale
> py> locale.setlocale(locale.LC_ALL, '')
> 'Spanish_Argentina.1252'
> py>
> py> import calendar
> py> calendar.month_abbr[12]
> 'Dic'
> py> def prev_months(since, howmany):
> ...   return [calendar.month_abbr[(since.month-i-2) % 12 + 1] for i in
> range(how
> many)]
> ...
> py> import datetime
> py> prev_months(datetime.datetime(2005,2,10), 4)
> ['Ene', 'Dic', 'Nov', 'Oct']
> py> prev_months(datetime.datetime(2005,10,17), 3)
> ['Sep', 'Ago', 'Jul']

Ah, you beat me to it.  I was going to point out that if you're going
to be using month strings, you should use calendar, since it can also
use the correct locale.  Plus, it offers a ridiculously simple
solution to this problem compared to all the others.

Hyuga

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


Re: Convert string to command..

2007-10-18 Thread Diez B. Roggisch
Abandoned wrote:

> I want to convert a string to command..
> For example i have a string:
> a="['1']"
> I want to do this list..
> How can i do ?

The correct wording here would be expression. To evaluate expressions, there
is the function eval:

a = eval("['1']")

But beware: if the expression contains some potentially harmful code, it
will be executed. So it is generally considered bad style to use eval.

An example that fails would be 

a = eval("10**2000**2000")

or such thing.

Another alternative is to use parsers like simplejson to extract the
information. This of course only works, if your expressions are valid json.

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


Re: Convert string to command..

2007-10-18 Thread Adam Atlas
On Oct 18, 10:23 am, Abandoned <[EMAIL PROTECTED]> wrote:
> I want to convert a string to command..
> For example i have a string:
> a="['1']"
> I want to do this list..
> How can i do ?

Use the builtin function "eval".

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


Convert string to command..

2007-10-18 Thread Abandoned
I want to convert a string to command..
For example i have a string:
a="['1']"
I want to do this list..
How can i do ?

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


Re: Best way to generate alternate toggling values in a loop?

2007-10-18 Thread cokofreedom
On Oct 18, 3:48 pm, Iain King <[EMAIL PROTECTED]> wrote:
> On Oct 18, 2:29 am, Grant Edwards <[EMAIL PROTECTED]> wrote:
>
>
>
> > On 2007-10-17, Debajit Adhikary <[EMAIL PROTECTED]> wrote:
>
> > > # Start of Code
>
> > > def evenOdd():
> > > values = ["Even", "Odd"]
> > > state = 0
> > > while True:
> > > yield values[state]
> > > state = (state + 1) % 2
>
> > I'd replace the last line with
>
> >   state ^= 1
>
> > to save a couple instructions, but I spend too much time
> > working with micoroprocessors running on clocks measured in the
> > KHz.
>
> > There are probably other more Pythonic ways...
>
> I always use:
>
>state = 1 - state
>
> for toggles.  I doubt it's much more pythonic though :)
>
> Iain

why not do
state = not state
?

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


  1   2   >