Creating a temporary file in Python

2007-10-31 Thread looping
Hi,

I want to create a temporary file, read it in an external command and
finally delete it (in Windows XP).

I try to use tempfile module but it doesn't work, the file couldn't be
open by my other process (error like: SP2-0310: unable to open file c:
\docume~1\looping\locals~1\temp\tmpau81-s.sql)
Is there a way to make it work or I have to manually manage
everything ?

My non working code:

f = tempfile.NamedTemporaryFile(suffix='.sql')
f.write(txt)
f.flush()
p = subprocess.Popen([SQL_PLUS, '-s', dsn, '@', SQL_PLUS_SCRIPT,
f.name],
  stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
p.wait()
f.close()

Thanks for your help.

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


Re: Creating a temporary file in Python

2007-10-31 Thread looping
On Oct 31, 2:16 pm, Diez B. Roggisch [EMAIL PROTECTED] wrote:

 I'm not an expert, but I think you need to close the file first - you under
 windows here, which can be picky about such stuff AFAIK. Or maybe there is
 some other mode-specifier.

 Diez

Actually closing the file delete it without any chance to use it...

Well I changed my code this way:

filename = tempfile.mktemp(suffix='.sql')
f = open(filename, 'wb')
try:
f.write(txt.encode('cp1252'))
f.close()
p = Popen([SQL_PLUS, '-s', dsn,
'@', SQL_PLUS_SCRIPT, f.name],
stdout=PIPE, stderr=STDOUT)
p.wait()
finally:
os.remove(filename)

I understand the security issues of temporary file (as explained in
Python doc) but maybe standard lib need a NamedTemporaryFile that
could be used by another process.

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


Re: Creating a temporary file in Python

2007-10-31 Thread looping
On Oct 31, 2:16 pm, Sion Arrowsmith [EMAIL PROTECTED]
wrote:
  [ ... ] Whether the name can be used to open the file a second time,
 while the named temporary file is still open, varies across platforms
 (it can be so used on Unix; it cannot on Windows NT or later).

I didn't notice this limitation when reading the doc, thanks to point
me to it.

So for the future newbie that look something like this, here is my
final code:

fd, filename = tempfile.mkstemp(suffix='.sql')
f = os.fdopen(fd, 'wb')
try:
f.write(txt.encode('cp1252'))
f.close()
p = Popen([SQL_PLUS, '-s', dsn,
'@', SQL_PLUS_SCRIPT, filename],
stdout=PIPE, stderr=STDOUT)
p.wait()
finally:
os.remove(filename)


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


Regular Expression question

2007-10-25 Thread looping
Hi,
It's not really a Python question but I'm sure someone could help me.

When I use RE, I always have trouble with this kind of search:

Ex.

I've a text file:

create or replace package XXX
...

create or replace package body XXX
...

now I want to search the position (line) of this two string.

for the body I use:
s = re.search(r'create\s+or\s+replace\s+package\s+body\s+', txt,
re.IGNORECASE)

but how to search for the other line ?
I want the same RE but explicitly without body.

Thanks for your help.

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


Re: Regular Expression question

2007-10-25 Thread looping
On Oct 25, 8:49 am, Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote:

 needle = re.compile(r'create\s+or\s+replace\s+package(\s+body)?\s+',
 re.IGNORECASE)

What I want here is a RE that return ONLY the line without the body
keyword.
Your RE return both.
I know I could use it but I want to learn how to search something that
is NOT in the string using RE.



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


Re: Regular Expression question

2007-10-25 Thread looping
On Oct 25, 9:25 am, Peter Otten [EMAIL PROTECTED] wrote:

 You want a negative lookahead assertion then:


Now I feel dumb...
I've seen the (?!...) dozen times in the doc but never figure out that
it is what I'm looking for.

So this one is the winner:
s = re.search(r'create\s+or\s+replace\s+package\s+(?!body\s+)', txt,
re.IGNORECASE)

Thanks Peter and Marc.

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


Twisted (or for loops ?) madness

2007-10-15 Thread looping
Hi,
Probably not the best group to post my question but I'm sure there is
some people here that use Twisted.
First here is the beginning of my source code:

from twisted.internet import reactor, defer, threads
import time

class CompilerThread(object):
def __init__(self, task, delay):
self.task = task
self.delay = delay

def _processing(self, delay):
print 'Start :', self.task
# Simulate delayed result, to fire immediately use
self.d.callback(self.task)
time.sleep(delay)
return self.task

def compile(self):
print 'Compile :', self.task
print self
# Create Deferred in another thread and add callback
self.d = threads.deferToThread(self._processing,
self.delay).addCallback(self.print_result)
# Return the deferred, this way you could add callback later
return self.d

def print_result(self, result):
# Print result
print 'Compiler result :', result, self.task
# MUST return result otherwise next callback receive None
return result

# Create Compiler objects
ct1 = CompilerThread('*OBJECT 1*', 2)
ct2 = CompilerThread('*OBJECT 2*', 3)
ct3 = CompilerThread('*OBJECT 3*', 5)

# Use succeed to create a deferred already fired
d = defer.succeed(None)

Now my problem:
With this code everything work fine:

d.addCallback(lambda result: ct1.compile())
d.addCallback(lambda result: ct2.compile())
d.addCallback(lambda result: ct3.compile())

reactor.callLater(20, reactor.stop)
reactor.run()

Output:

Compile : *OBJECT 1*
__main__.CompilerThread object at 0x00BAD070
Start : *OBJECT 1*
Compiler result : *OBJECT 1* *OBJECT 1*
Compile : *OBJECT 2*
__main__.CompilerThread object at 0x00BAD050
Start : *OBJECT 2*
Compiler result : *OBJECT 2* *OBJECT 2*
Compile : *OBJECT 3*
__main__.CompilerThread object at 0x00CDA4B0
Start : *OBJECT 3*
Compiler result : *OBJECT 3* *OBJECT 3*


But when I try to replace this code with a for loops, something goes
wrong:

l = [ct1, ct2, ct3]
for c in l:
d.addCallback(lambda result: c.compile())

reactor.callLater(20, reactor.stop)
reactor.run()

Output:

Compile : *OBJECT 1*
__main__.CompilerThread object at 0x00BAD030
Start : *OBJECT 1*
Compiler result : *OBJECT 1* *OBJECT 1*
Compile : *OBJECT 3*
__main__.CompilerThread object at 0x00CD9470
Start : *OBJECT 3*
Compiler result : *OBJECT 3* *OBJECT 3*
Compile : *OBJECT 3*
__main__.CompilerThread object at 0x00CD9470
Start : *OBJECT 3*
Compiler result : *OBJECT 3* *OBJECT 3*

OBJECT 3 run 2 times and OBJECT 2 never ?!?

Any idea ? Maybe something related to Threads ?
Thanks for your help.

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


Re: Twisted (or for loops ?) madness

2007-10-15 Thread looping
On Oct 15, 9:46 am, looping [EMAIL PROTECTED] wrote:
 l = [ct1, ct2, ct3]
 for c in l:
 d.addCallback(lambda result: c.compile())

 reactor.callLater(20, reactor.stop)
 reactor.run()

 Output:

 Compile : *OBJECT 1*
 __main__.CompilerThread object at 0x00BAD030
 Start : *OBJECT 1*
 Compiler result : *OBJECT 1* *OBJECT 1*
 Compile : *OBJECT 3*
 __main__.CompilerThread object at 0x00CD9470
 Start : *OBJECT 3*
 Compiler result : *OBJECT 3* *OBJECT 3*
 Compile : *OBJECT 3*
 __main__.CompilerThread object at 0x00CD9470
 Start : *OBJECT 3*
 Compiler result : *OBJECT 3* *OBJECT 3*

 OBJECT 3 run 2 times and OBJECT 2 never ?!?

 Any idea ? Maybe something related to Threads ?
 Thanks for your help.

After further tests, it look like it is the lambda that cause the
problem:
-Adding a parameter result to compile(self, result)
-Changing d.addCallback(lambda result: c.compile()) for
d.addCallback(c.compile)

And everything run fine.

Why lambda doesn't work ? (variable scope problem ?)

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


Re: Twisted (or for loops ?) madness

2007-10-15 Thread looping
On Oct 15, 12:33 pm, Michele Simionato [EMAIL PROTECTED]
wrote:
 is a design decision, in the sense that Python always do late binding.
 If you

 you will get funclist[0]() == funclist[1]() == funclist[2]() == 3 (you
 get the latest
 binding of i). As you see, it has nothing to do with lambdas.


Thanks Diez, replacing my addCallback with d.addCallback(lambda
result, comp=c: comp.compile()) do the trick.

So if I understand what Michele wrote (thanks too), when a function is
defined (with def), no scope is saved and every variable value not
passed in parameter is lost ?  It means that variable value come from
the outer scope when the function is called ?


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


Re: Twisted (or for loops ?) madness

2007-10-15 Thread looping
On Oct 15, 1:51 pm, Michele Simionato [EMAIL PROTECTED]
wrote:
 On Oct 15, 1:01 pm, looping [EMAIL PROTECTED] wrote:

  So if I understand what Michele wrote (thanks too), when a function is
  defined (with def), no scope is saved and every variable value not
  passed in parameter is lost ?  It means that variable value come from
  the outer scope when the function is called ?

 Yes, in my example you get the value of i at the function *calling*
 time,
 not at the function definition time. If you want to store the value at
 the
 definition time, you must use the default argument trick:

 funclist = []
 for i in 1,2,3:
   def f(i=i):
  print i
   funclist.append(f)

Michele Simionato

Thanks Michele, now I understand how it works and I learned something
new. Not a bad day...

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


operator overloading

2007-04-04 Thread looping
Hi,
for the fun I try operator overloading experiences and I didn't
exactly understand how it works.

Here is my try:
 class myint(int):
def __pow__(self, value):
return self.__add__(value)

 a = myint(3)
 a ** 3
6

OK, it works. Now I try different way to achieve the same result but
without much luck:

 class myint(int):
pass
 myint.__pow__ = myint.__add__

or:
 class myint(int):
__pow__ = int.__add__

or:
 class myint(int):
pass
 a.__pow__ = a.__add__

but for every try the result was the same:
 a = myint(3)
 a ** 3
27

Why it doesn't works ?

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


cx_Oracle and unicode data

2007-03-15 Thread looping
Hi,

I need to get data from an Oracle DB that contains unicode data
(chinese text).
But the chinese data that I receive is wrong (only ¿).
After a look at the Oracle documentation I've found an environment
variable called NLS_LANG that you could set to define what charset the
DB client use and it work fine.

But it's not what I call a 'clean' solution and I suppose that it must
exist another way to force the client DB to use UTF8, or another
solution to get my data.
Could someone help me ?
Thanks.

Example:

# -*- coding: latin1 -*-
import os
import cx_Oracle

os.environ[NLS_LANG] = .UTF8

con = cx_Oracle.connect(demo/[EMAIL PROTECTED])
cur = con.cursor()
cur.execute(select DESCRIPTION from DEC_DESCRIPTION where
DEC_DESCRIPTION_ID = 1792528)
val1 = cur.fetchone()[6]
val2 = cur.fetchone()[6]
print con.encoding, con.nencoding, con.maxBytesPerCharacter
cur.close()
print val1.decode(con.encoding)
print val2.decode(con.encoding)

del os.environ[NLS_LANG]



UTF-8 UTF-8 3
珀マザーボードのテスト作業 颇マザーボードのテスト作業マザーボードのテスト作業,

without NLS_LANG setting I get:

WINDOWS-1252 WINDOWS-1252 1
¿ ¿,
-- 
http://mail.python.org/mailman/listinfo/python-list

pytz2007c error

2007-03-06 Thread looping
Hi,
Why this error ?

 from pytz import timezone
 eastern = timezone('US/Eastern')
Traceback (most recent call last):
  File interactive input, line 1, in module
  File C:\Python25\lib\site-packages\pytz-2007c-py2.5.egg\pytz
\__init__.py, line 93, in timezone
  File C:\Python25\lib\site-packages\pytz-2007c-py2.5.egg\pytz
\tzfile.py, line 33, in build_tzinfo
for trans in data[:timecnt]]
  File C:\Python25\lib\site-packages\pytz-2007c-py2.5.egg\pytz
\tzinfo.py, line 27, in memorized_datetime
dt = datetime.utcfromtimestamp(seconds)
ValueError: timestamp out of range for platform localtime()/gmtime()
function

I'm running python 2.5 on WinXP French with the egg from CheeseShop.

Same error with all timezone (like timezone('Europe/Zurich'),
timezone('Europe/Amsterdam'), ...) except a few one:
 print timezone('UTC')
UTC

Is this a pytz problem or something I didn't understand ?

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


Re: pytz2007c error

2007-03-06 Thread looping
On Mar 6, 9:51 am, looping [EMAIL PROTECTED] wrote:
 Hi,
 Why this error ?

  from pytz import timezone
  eastern = timezone('US/Eastern')

 Traceback (most recent call last):
   File interactive input, line 1, in module
   File C:\Python25\lib\site-packages\pytz-2007c-py2.5.egg\pytz
 \__init__.py, line 93, in timezone
   File C:\Python25\lib\site-packages\pytz-2007c-py2.5.egg\pytz
 \tzfile.py, line 33, in build_tzinfo
 for trans in data[:timecnt]]
   File C:\Python25\lib\site-packages\pytz-2007c-py2.5.egg\pytz
 \tzinfo.py, line 27, in memorized_datetime
 dt = datetime.utcfromtimestamp(seconds)
 ValueError: timestamp out of range for platform localtime()/gmtime()
 function

 I'm running python 2.5 on WinXP French with the egg from CheeseShop.

 Same error with all timezone (like timezone('Europe/Zurich'),
 timezone('Europe/Amsterdam'), ...) except a few one: print timezone('UTC')

 UTC

 Is this a pytz problem or something I didn't understand ?

OK, the error come from datetime.utcfromtimestamp that doesn't support
negative value.
pytz try to pass -1633280400 to this function.

Is this a problem from Windows ?

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


Return type of operator on inherited class

2007-03-05 Thread looping
Hi,
my question is on this example:

class MyStr(str):
def hello(self):
print 'Hello !'

s1 = MyStr('My string')
s2 = MyStr('My second string')

s1.hello()
s2.hello()

s = s1 + s2

s.hello()


Hello !
Hello !
Traceback (most recent call last):
  File string, line 204, in run_nodebug
  File module1, line 13, in module
AttributeError: 'str' object has no attribute 'hello'

How could I get a type MyStr from the 'plus' (__add__) operation
without overriding it in my class ?
I need to override *every* operator I like to use ?

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


Using ctypes with Windows API to get FileVersion of a file

2006-11-14 Thread looping
Hi,
I need to get the FileVersion of some files on Windows. The best way
look like to use function GetFileVersionInfo from the Windows API. I
first try with pywin32 and it work well, but with ctypes now included
in Python 2.5, use it look like a good idea.
So I write the code below that work fine, but I'm not sure it's the
best way to do what I want.
My main concern is about the codepages extraction: could I use a struct
to make the job ?
Codepages is actually an array of struct, how could I use ctypes to
extract it ?

Thanks for your comments and advices.

import array
from ctypes import *

def get_file_info(filename, info):

Extract information from a file.

# Get size needed for buffer (0 if no info)
size = windll.version.GetFileVersionInfoSizeA(filename, None)
# If no info in file - empty string
if not size:
return ''
# Create buffer
res = create_string_buffer(size)
# Load file informations into buffer res
windll.version.GetFileVersionInfoA(filename, None, size, res)
r = c_uint()
l = c_uint()
# Look for codepages
windll.version.VerQueryValueA(res, '\\VarFileInfo\\Translation',
  byref(r), byref(l))
# If no codepage - empty string
if not l.value:
return ''
# Take the first codepage (what else ?)
codepages = array.array('H', string_at(r.value, l.value))
codepage = tuple(codepages[:2].tolist())
# Extract information
windll.version.VerQueryValueA(res, ('\\StringFileInfo\\%04x%04x\\'
+ info) % codepage,
byref(r), byref(l))
return string_at(r.value, l.value)

print get_file_info(r'C:\WINDOWS\system32\calc.exe', 'FileVersion')

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


Big speed boost in os.walk in Python 2.5

2006-10-13 Thread looping
Hi,
I noticed a big speed improvement in some of my script that use os.walk
and I write a small script to check it:
import os
for path, dirs, files in os.walk('D:\\FILES\\'):
pass

Results on Windows XP after some run to fill the disk cache (with
~59000 files and ~3500 folders):
Python 2.4.3 : 45s
Python 2.5 : 10s

Very nice, but somewhat strange...
Is Python 2.4.3 os.walk buggy ???
Is this results only valid in Windows or *nix system show the same
difference ?
The profiler show that most of time is spend in ntpath.isdir and this
function is *a lot* faster in Python 2.5.
Maybe this improvement could be backported in Python 2.4 branch for the
next release ?


Python 2.4.3
 604295 function calls (587634 primitive calls) in 48.629 CPU
seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
625540.2640.0000.2640.000 :0(append)
10.0010.001   48.593   48.593 :0(execfile)
660740.1970.0000.1970.000 :0(len)
 35215.2190.0015.2190.001 :0(listdir)
10.0360.0360.0360.036 :0(setprofile)
62554   38.8120.001   38.8120.001 :0(stat)
10.0000.000   48.593   48.593 string:1(?)
660740.2180.0000.2180.000 ntpath.py:116(splitdrive)
 35200.0090.0000.0090.000 ntpath.py:246(islink)
625540.7670.000   40.1370.001 ntpath.py:268(isdir)
660740.4330.0000.6500.000 ntpath.py:51(isabs)
660740.8800.0001.7260.000 ntpath.py:59(join)
20183/35221.2170.000   48.5730.014 os.py:211(walk)
10.0000.000   48.629   48.629
profile:0(execfile('test.py'))
00.000 0.000  profile:0(profiler)
625540.1740.0000.1740.000 stat.py:29(S_IFMT)
625540.3850.0000.5590.000 stat.py:45(S_ISDIR)
10.0190.019   48.592   48.592 test.py:1(?)


Python 2.5:
 604295 function calls (587634 primitive calls) in 17.386 CPU
seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
625540.2470.0000.2470.000 :0(append)
10.0010.001   17.315   17.315 :0(execfile)
660740.1680.0000.1680.000 :0(len)
 35215.2870.0025.2870.002 :0(listdir)
10.0710.0710.0710.071 :0(setprofile)
625547.8120.0007.8120.000 :0(stat)
10.0000.000   17.315   17.315 string:1(module)
660740.1860.0000.1860.000 ntpath.py:116(splitdrive)
 35200.0090.0000.0090.000 ntpath.py:245(islink)
625540.7120.0009.0130.000 ntpath.py:267(isdir)
660740.3940.0000.5810.000 ntpath.py:51(isabs)
660740.8150.0001.5640.000 ntpath.py:59(join)
20183/35221.1760.000   17.2960.005 os.py:218(walk)
10.0000.000   17.386   17.386
profile:0(execfile('test.py'))
00.000 0.000  profile:0(profiler)
625540.1590.0000.1590.000 stat.py:29(S_IFMT)
625540.3310.0000.4890.000 stat.py:45(S_ISDIR)
10.0180.018   17.314   17.314 test.py:1(module)

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


Re: Big speed boost in os.walk in Python 2.5

2006-10-13 Thread looping
Fredrik Lundh wrote:
 looping wrote:

 
  Very nice, but somewhat strange...
  Is Python 2.4.3 os.walk buggy ???


 Why are you asking if something's buggy when you've already figured out
 what's been improved?

You're right, buggy isn't the right word...

Anyway thanks for your detailed informations and I'm very pleased with
the performance improvement even if it's only a side effect and only on
Windows.

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


Re: Add NTLM proxy authentication to urllib2

2006-09-08 Thread looping
Thanks for the answers.

I've done some tests with urllib2 and pywin32 and managed to partialy
implement the NTLM authentication, but it look like you need a
persistent connection (http 1.1 or 'Keep-Alive') to complete the
authentication.
Unfortunatly, urllib2 use a new connection for each request and
changing this behavior look difficult.
So I will probably write my own library.

Maybe there is something to do with the urlgrabber module ?

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


Add NTLM proxy authentication to urllib2

2006-09-05 Thread looping
Hi,
I have to make internet connections through an ISA proxy server that
use NTLM or Kerberos authorization method.
I've found a program in python called ntlmaps that act like a proxy and
could make the NTLM authentication, but you have to run it and make all
your connection through it, not an optimal solution.
So what I really need is an enhanced urllib2 that support NTLM or
Kerberos.
I've found that pywin32 could manage NTLM encryption with the sspi
module but I've no idea how to implement it in urllib2, NTLM
authentication use a 'Token dance' between client and server.

Anyone has an experience, a demo or an idea to share ?

Thanks.

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


Re: Dispatch with multiple inheritance

2006-07-19 Thread looping
Michael J. Fromberger wrote:

 Is there a better (i.e., more elegant) way to handle the case marked
 (**) above?


You have to call super in each method __init__, if you don't, the call
chain break before the end:

class A (object):
def __init__(self):
super(A, self).__init__()
print cons A

class B (object):
def __init__(self):
super(B, self).__init__()
print cons B

class C (A):
def __init__(self):
super(C, self).__init__()
print cons C

class D (B):
def __init__(self):
super(D, self).__init__()
print cons D

class E (C, D):
def __init__(self):
super(E, self).__init__()  # calls C constructor
print cons E

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


Re: Dispatch with multiple inheritance

2006-07-19 Thread looping

looping wrote:
 Michael J. Fromberger wrote:
 
  Is there a better (i.e., more elegant) way to handle the case marked
  (**) above?
 

 You have to call super in each method __init__, if you don't, the call
 chain break before the end:

 class A (object):
 def __init__(self):
 super(A, self).__init__()
 print cons A

 class B (object):
 def __init__(self):
 super(B, self).__init__()
 print cons B

 class C (A):
 def __init__(self):
 super(C, self).__init__()
 print cons C

 class D (B):
 def __init__(self):
 super(D, self).__init__()
 print cons D

 class E (C, D):
 def __init__(self):
 super(E, self).__init__()  # calls C constructor
 print cons E

After a second tought, it's probably better to call __init__ method
explicitly in class E:

class A (object):
def __init__(self):
print cons A

class B (object):
def __init__(self):
print cons B

class C (A):
def __init__(self):
super(C, self).__init__()
print cons C

class D (B):
def __init__(self):
super(D, self).__init__()
print cons D

class E (C, D):
def __init__(self):
D.__init__(self)
C.__init__(self)
print cons E

this way you have to choose which __init__ from class D or class C is
calling, and which is calling first.
Any Python Guru to give is opinion ?

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


Re: Way for see if dict has a key

2006-06-30 Thread looping

Michele Petrazzo wrote:
 Bruno Desthuilliers wrote:
  but what the better
 
  Depends on the context.
 

 If know only one context: see if the key are into the dict... What other
 context do you know?

 Michele

Why do you want to do that ?

if key in dict:
  value = dict[key]
else:
  value = None

could be write:

try:
  value = dict[key]
except KeyError:
  value = None

so depends of the context...

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


Re: Includeing Python in text files

2006-05-22 Thread looping

Paolo Pantaleo wrote:
 I am working on this:

 I have  a text file, containig certain section in the form
 ?py
   python code here
 py?

 I parse the text file and substitute the python code with its result
 [redirecting sys.stdin to a StringIO]. It something like php or
 embedded perl.

 So my little toy works not bad, but I was wondering if such a feature
 already existed, if yes, can you point me out some links?

 Thnx
 PAolo

 --
 if you have a minute to spend please visit my photogrphy site:
 http://mypic.co.nr

Like Diez had said, use a template system or you could look at COG:
http://www.nedbatchelder.com/code/cog/

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


Re: Question about exausted iterators

2006-05-18 Thread looping

Christophe wrote:
 Ok, call me stupid if you want but I know perfectly well the solution
 to that problem ! Come on, I was showing example code of an horrible
 gotcha on using iterators.


OK, your are stupid ;-)
Why asking questions when you don't want to listen answers ?




 Instead of saying that all works as intended could you be a little
 helpful and tell me why it was intended in such an obviously broken way
 instead ?

Why an exausted iterator must return an Exception (other than
StopIteration of course) ?
Well an exausted iterator could be seen like an empty string or an
empty list (or tons of others things), so you expect the code
for car in :
  print car
to return an Exception because it's empty ???
It's your job to check the iterator when it need to be.

Regards.
Dom

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


Re: can anyone advise me

2006-04-27 Thread looping
try something like this:

x = 0
while x  10:
z = 0
print '-' + str(x) + '-'
x = x + 1
while z  x:
print '.' + str(z) + '.',
z = z + 1

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


Why new Python 2.5 feature class C() return old-style class ?

2006-04-11 Thread looping
For Python developers around.

From Python 2.5 doc:
The list of base classes in a class definition can now be empty. As an
example, this is now legal:
  class C():
  pass

nice but why this syntax return old-style class, same as class C:,
and not the new style class C(object): ?
Old-style class are somewhat deprecated and could be almost always be
replaced by new-style class, so this syntax could be a nice shortcut to
create them.

Am I wrong or is there something that I've missed ?

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


Re: Why new Python 2.5 feature class C() return old-style class ?

2006-04-11 Thread looping
Peter Hansen wrote:
 Georg Brandl wrote:
  class C():
 
  is meant to be synonymous with
 
  class C:
 
  and therefore cannot create a new-style class.

 I think looping understands that, but is basically asking why anyone
 is bothering with a change that involves a part of the language that is
 effectively deprecated.  In other words, class(): never used to be
 valid, so why make it valid now?

 -Peter

Exact.
But I think that if we make class C(): a synonym of class
C(object):, it will save lot of keystrokes ;-)
So I think the idea is great but the result is not actually very
usefull.

Delphi (Pascal?) use almost the same concept:
TTest = class

is a synonym of

TTest = class(TObject)

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


XMLRPCServer issues

2006-03-27 Thread looping
Hi,

I had some issues with XMLRPCServer and I try to validate my
workaround.

My first try was this (somewhat self explaining code):

from DocXMLRPCServer import DocXMLRPCServer
from cx_Oracle import connect

def get_task_list(user):
sql = 
select   ISS.ISS_ISSUE_NUMBER
   , ISS.ISS_DESCRIPTION
   , ISS.C_PC_ISS_STATUS
   , ISS.ISS_IN_WORK
   , ISS.PC_ISSUES_ID
   , DES.GCDTEXT1
from ...
   where ...

con = connect('DEVELOP/[EMAIL PROTECTED]')
cur = con.cursor()
cur.execute(sql, USE_NAME = user.upper())
result = cur.fetchall()
cur.close()
con.close()
return result

server = DocXMLRPCServer((localhost, 8000))
server.register_function(get_task_list)
server.serve_forever()


But I had 2 errors with this code:
-PC_ISSUES_ID column could be an integer of 12 digits but the XML
generator only allow 2L**31-1 long integer, so I had an
Overflowexception: long int exceeds XML-RPC.
-Text columns (like ISS_DESCRIPTION) could contains non ascii char.
(éàç) but the server doesn't allow to specify the encoding to use
for the XML, so parser error on non-ascii char. on the client side
(ExpatError: not well-formed (invalid token)).

My working code with workarounds for these issues is:

from DocXMLRPCServer import DocXMLRPCServer
from cx_Oracle import connect

#increase MAXINT constant to allow 12 digits integer for PC_ISSUES_ID
#(long int exceeds XML-RPC exception)
import xmlrpclib
xmlrpclib.MAXINT = 

def get_task_list(user):
sql = 
select   ISS.ISS_ISSUE_NUMBER
   , ISS.ISS_DESCRIPTION
   , ISS.C_PC_ISS_STATUS
   , ISS.ISS_IN_WORK
   , ISS.PC_ISSUES_ID
   , DES.GCDTEXT1
from ...
   where ...

con = connect('DEVELOP/[EMAIL PROTECTED]')
cur = con.cursor()
cur.execute(sql, USE_NAME = user.upper())
result = cur.fetchall()
cur.close()
con.close()
#convert string column to unicode (XML generator does not use
# encoding so string must be UTF8 or unicode)
result = [list(row) for row in result]
for row in result:
for count, x in enumerate(row):
if isinstance(x, str):
row[count] = x.decode('cp1252')
return result

server = DocXMLRPCServer((localhost, 8000))
server.register_function(get_task_list)
server.serve_forever()


But it seems to me not very clean, especially the MAXINT hack.
Has anyone a better solution ?

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


Re: XMLRPCServer issues

2006-03-27 Thread looping

Brian Quinlan wrote:
 1. Is there on option to get cx_Oracle to return string data as unicode
 rather than strings objects? XML-RPC aside, dealing with unicode objects
 might be better than dealing with encoded strings.

I don't think cx_Oracle can return unicode string, so my code to
convert string is not so bad.

 2. You might want to transmit integers as strings rather than use the
 XML-RPC integer type (which is limited to numbers between -2147483648
 and 2147483647).

Is it a limit of XML-RPC RFC or a limit (probably with a good reason)
of the python xmlrpclib ?

Thanks for your answer.

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


Re: XMLRPCServer issues

2006-03-27 Thread looping

Fredrik Lundh wrote:
 looping wrote:

   2. You might want to transmit integers as strings rather than use the
   XML-RPC integer type (which is limited to numbers between -2147483648
   and 2147483647).
 
  Is it a limit of XML-RPC RFC or a limit (probably with a good reason)
  of the python xmlrpclib ?

 the specification defines an integer field as a four-byte signed integer.

 /F

OK, I will remove my MAXINT hack and convert value to string.

Thanks everybody for your fast answers, nice group with nice (and
brillant) people.
See you later for my next question.

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


How to create a Visual SourceSafe plugin in Python

2006-03-14 Thread looping
Hi,
I try to create a COM object with win32com to track events in Visual
SourceSafe.
I tried to modify ExcelAddin.py demo but with no luck.
I've now a Delphi DLL that make that job so I know it's possible.

If someone have an exemple, please help me.

Best regards.
Kadeko

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


Re: pysqlite problem

2006-03-01 Thread looping
Is it the complete code ?

If so then you have to create the table each time you connect to the
DB.

You use an in-memory DB (:memory:) so all the data of the DB is lost
when you close the connection, including the schema of the DB.

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


Re: pysqlite problem

2006-03-01 Thread looping
OK, it's better.

You use relative path to your file 'ex1', are you really sure that you
open the right file and not creating another DB in another path ?

Try to use absolute path (r'c:\temp\ex1').

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


Re: TypeError when subclassing 'list'

2006-02-27 Thread looping
Gerard Flanagan wrote:
 Hello all

 Could anyone shed any light on the following Exception? The code which
 caused it is below.  Uncommenting the 'super' call in 'XmlNode' gives
 the same error. If I make XmlNode a subclass of 'object' rather than
 'list' then the code will run.

 Thanks in advance.

 Exception:

 Traceback (most recent call last):
   File C:\Program
 Files\Python\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py,
 line 310, in RunScript
 exec codeObject in __main__.__dict__
   File C:\Documents and Settings\Gerard\My
 Documents\Scripts\Python\XmlNode\XmlNode.py, line 5, in ?
 class XmlNode(list):
 TypeError: Error when calling the metaclass bases
 __init__() takes at most 2 arguments (4 given)

 Code:

 from elementtree.SimpleXMLWriter import XMLWriter

 class XmlNode(list):
 tag = None
 attrib = None
 value = None
 def __init__(self, tag, **attrib):
 #super(list, self).__init__()
 self.tag = tag
 self.attrib = attrib

 def __repr__(self):
 return XmlNode %s at %x % (self.tag, id(self))

 def write(self, writer):
 writer.start(self.tag, self.attrib)
 if self.value is not None:
 writer.data(self.value)
 ##for node in self:
 ##node.write(writer)
 writer.end()

 class HtmlElement(XmlNode):
 def __init__(self, tag, value='', **attrib):
 super(HtmlElement, self).__init__(tag=tag, **attrib)
 self.value = value

 class li(HtmlElement):
 def __init__(self, value=None, **attrib):
 super(li, self).__init__(tag='li', **attrib)

 class ul(HtmlElement):
 def __init__(self, **attrib):
 super(ul, self).__init__(tag='ul', **attrib)

 if __name__ == '__main__':
 from StringIO import StringIO

 item = li('item')
 items = ul()
 #items.apppend(item)
 out = StringIO()
 writer = XMLWriter(out)
 items.write(writer)
 print
 print out.getvalue()
 out.close()

 #super(list, self).__init__()
I think this line must be:
  super(XmlNode, self).__init__()

But just a guess...

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