Re: neoPython : Fastest Python Implementation: Coming Soon

2021-05-05 Thread Ian Clark
I wish you best of luck, on top of everything else it looks like the
neopython namespace has already been eaten up by some crypto project

On Wed, May 5, 2021 at 11:18 AM Benjamin Schollnick <
bscholln...@schollnick.net> wrote:

> > Why? The currently extant Python implementations contribute to climate
> change as they are so inefficient;
>
> That same argument can be made for every triple-AAA video game, game
> console, etc.
>
> Python is more efficient for some problem sets, and Python is less
> efficient for other problem sets.
>
> Please feel free to come out with NeoPython.  When you are done, and it is
> backward compatible with existing Python code, I’ll be happy to benchmark
> it against Native python.  But don’t blame Python for global climate
> change.  There are plenty of bigger “causations” to Global climate change,
> then a freakin’ computer programming language.
>
> - Benjamin
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: The sum of ten numbers inserted from the user

2019-02-07 Thread Ian Clark
This is my whack at it, I can't wait to hear about it being the wrong big o
notation!

numbers=[]

while len(numbers) < 10:
try:
chip = int(input('please enter an integer: '))
except ValueError:
print('that is not a number, try again')
else:
numbers.append(chip)

print(sum(numbers))


On Thu, Feb 7, 2019 at 10:23 AM Schachner, Joseph <
joseph.schach...@teledyne.com> wrote:

> Well of course that doesn't work.  For starters, x is an int or a float
> value.  After the loop It holds the 10th value.  It might hold 432.7 ...
>  It is not a list.
> The default start for range is 0.  The stop value, as you already know, is
> not part of the range.  So I will use range(10).
>
> In the second loop, I think you thought x would be a list and you I'm sure
> you wanted to do
> for y in x:
> but instead you did
> for y in range(x)
>  and remember x might be a very large number.So the second loop would
> loop that many times, and each pass it would assign y (which has first
> value of 0 and last value of whatever x-1 is) to sum.  Even though its name
> is "sum" it is not a sum.  After the loop it would hold x-1.  You wanted to
> do  sum += y.Or sum = sum + y.   I prefer the former, but that could
> reflect my history as a C and C++ programmer.
>
> And then you printed y, but you really want to print sum  (assuming that
> sum was actually the sum).
>
> Putting all of the above together, you want to do this:
>
> vallist =[] # an empty list, so we can append to it
> for n in range(10):
> x = input("Insert a number: ")# get 1 number into x
> vallist.append(x)  # append it to our list
>
> # Now vallist holds 10 values
>
> sum = 0   # No need to start sum as a float, in Python if we add a float
> to an integer the result will be float. It doesn't matter in the program if
> sum is int or float.
> for y in vallist:
>  sum += y
>
> print( "The sum is: ", sum)
>
>
>
> -Original Message-
> From: ^Bart 
> Sent: Thursday, February 7, 2019 6:30 AM
> To: python-list@python.org
> Subject: The sum of ten numbers inserted from the user
>
> I thought something like it but doesn't work...
>
> for n in range(1, 11):
>  x = input("Insert a number: ")
>
> for y in range(x):
>  sum = y
>
>  print ("The sum is: ",y)
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: How to replace space in a string with \n

2019-01-31 Thread Ian Clark
text = "The best day of my life!"
output = ''

for i in text:
 if i == ' ':
  output +='\n'
 else:
  output += i

print(output)

throwing my hat in the ring, not only is it .replace free it is entirely
method free

On Thu, Jan 31, 2019 at 3:41 AM ^Bart  wrote:

> [Solved by myself and I'm happy!!! :)]
>
> text = "The best day of my life!"
>
> space = text[3]
>
> print (text.replace(space, "\n"))
>
> [Like what I said in another message, in the afternoon I'll ask to the
> teacher if for this exercise we're able to use .replace]
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: what considerations for changing height of replacement radiator?

2019-01-30 Thread Ian Clark
looking for a Space heater? sorry, not the Java mailing list

On Wed, Jan 30, 2019 at 3:11 PM jkn  wrote:

> Hi all
> I'm looking at changing a radiator in a bedroom shortly and wondering
> about
> my options re. sizing.
>
> The current radiator is 900mm W x 600mm H, and is single panel, no
> convector. So
> looking at some representative specs, let's say 550W output.
>
> I would be replacing this with a single panel, single convector radiator.
> From
> looking at the spec again, the same sized radiator gives around 50% greater
> output - 900W.
>
> I am wondering about fitting a 900mm W x 450mm H single panel, single
> convector,
> which would then reduce the output again to 700W or so, similar to the
> original.
>
> My reason for doing this would simply be 'neater appearance' of the smaller
> radiator, but it wouldn't be a problem if the replacement was the same
> size as
> the original. I am wondering if there is anything else (apart from power
> output)
> that I should be considering here?
>
> The radiator will be under a window and the CH is an olde school 'plan C',
> I
> think. I would probably fit a TRV in any case. There is no need to heat
> the room
> any better than currently...
>
> Thanks for any advice.
>
> Cheers
> Jon N
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python stopped installing packages

2019-01-29 Thread Ian Clark
according to https://pypi.org/project/discord.py/ Discord.py only supports
3.4 and 3.5

On Tue, Jan 29, 2019 at 4:52 PM Hamish Allen <101929...@gmail.com> wrote:

> Hi,
>
> Recently I’ve been trying to code a Discord bot in Python 3.6.2, then I
> realised that some features of discord.py were only available in Python
> 3.7+ (as seen here on the right near the top
> https://docs.python.org/3/library/asyncio.html), so I downloaded 3.7.2.
> After correctly changing the environmental variables to have Python 3.7.2
> before Python 3.6.2, I tried installing (for installing I was using cmd
> ‘pip install discord.py’, I’m not aware of any other way to install
> packages) discord.py onto Python 3.7.2, but after a few seconds there would
> be a whole page of red error text (attached), then it would say
> successfully installed. I tried importing it in code, but it would return
> errors implying it was incorrectly installed. I asked one of my friends for
> some help. He suggested uninstalling Python 3.6.2 and 3.7.2 and
> reinstalling Python 3.7.2. I thought this was a pretty good idea so I did
> it. Discord.py still refuses to be installed. I tried installing some of
> the packages I had in 3.6.2, but they had the same sort of problem. I’ve
> tried running the installer to repair the files, but that didn’t work. I
> would appreciate if you could help me. I got discord.py from here:
> https://github.com/Rapptz/discord.py I’ve tried the 3 commands in the
> Installing section and I’ve tried pip install discord.py.
>
> Thanks,
> Hamish
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Exercize to understand from three numbers which is more high

2019-01-29 Thread Ian Clark
which version of Python? I get Syntax error on 3.7.1

On Tue, Jan 29, 2019 at 12:37 PM Adrian Ordona 
wrote:

> The code actually works just the way i copy and pasted
>
> Sent from my iPhone
>
> On Jan 29, 2019, at 12:34, Ian Clark  wrote:
>
> just the pure number of letters next to parenthesis would cause the Parser
> to error out
>
> On Tue, Jan 29, 2019 at 12:32 PM Schachner, Joseph <
> joseph.schach...@teledyne.com> wrote:
>
>> Yes, that works.  Assuming it was correctly formatted when you ran it.
>> The formatting could not possibly be run in a Python interpreter, I think.
>>
>> --- Joseph S.
>>
>> From: Adrian Ordona 
>> Sent: Tuesday, January 29, 2019 2:52 PM
>> To: Schachner, Joseph 
>> Cc: Dan Sommers <2qdxy4rzwzuui...@potatochowder.com>;
>> python-list@python.org
>> Subject: Re: Exercize to understand from three numbers which is more high
>>
>> i'm also a beginner reading all the replies helps.
>> i was trying the problem myself and came up with the below code with a
>> users input.
>>
>>
>> num1 = int(input("Enter first number: "))num2 = int(input("Enter second
>> number: "))num3 = int(input("Enter third number: "))if num1 > num2 and num1
>> > num3:print(num1, " is th max number")elif num2 > num1 and num2 >
>> num3:print(num2, " is the max number")else: print(num3, "is the max
>> number")
>>
>> On Tue, Jan 29, 2019 at 1:48 PM Schachner, Joseph <
>> joseph.schach...@teledyne.com<mailto:joseph.schach...@teledyne.com>>
>> wrote:
>> Explanation: 5 > 4 so it goes into the first if.  5 is not greater than
>> 6, so it does not assign N1 to MaxNum.  The elif (because of the lack of
>> indent) applies to the first if, so nothing further is executed. Nothing
>> has been assigned to MaxNum, so that variable does not exist.  You're
>> right, it does not work.
>>
>> How about this:
>> Mylist = [ N1, N2, N3]
>> Maxnum = N1
>> for value in Mylist:
>> if value > Maxnum:
>> Maxnum = value
>> print(Maxnum)
>>
>> Or were lists and for loops excluded from this exercise?
>> --- Joe S.
>>
>> On 1/29/19 9:27 AM, Jack Dangler wrote:
>>
>> > wow. Seems like a lot going on. You have 3 ints and need to determine
>> > the max? Doesn't this work?
>> >
>> > N1, N2, N3
>> >
>> > if N1>N2
>> >if N1>N3
>> >  MaxNum = N1
>> > elif N2>N3
>> >MaxNum = N2
>> > elif N1> >MaxNum = N3
>>
>> No.  Assuing that you meant to include colons where I think you did, what
>> if (N1, N2, N3) == (5, 4, 6)?
>>
>> --
>> https://mail.python.org/mailman/listinfo/python-list
>> --
>> https://mail.python.org/mailman/listinfo/python-list
>>
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Exercize to understand from three numbers which is more high

2019-01-29 Thread Ian Clark
just the pure number of letters next to parenthesis would cause the Parser
to error out

On Tue, Jan 29, 2019 at 12:32 PM Schachner, Joseph <
joseph.schach...@teledyne.com> wrote:

> Yes, that works.  Assuming it was correctly formatted when you ran it.
> The formatting could not possibly be run in a Python interpreter, I think.
>
> --- Joseph S.
>
> From: Adrian Ordona 
> Sent: Tuesday, January 29, 2019 2:52 PM
> To: Schachner, Joseph 
> Cc: Dan Sommers <2qdxy4rzwzuui...@potatochowder.com>;
> python-list@python.org
> Subject: Re: Exercize to understand from three numbers which is more high
>
> i'm also a beginner reading all the replies helps.
> i was trying the problem myself and came up with the below code with a
> users input.
>
>
> num1 = int(input("Enter first number: "))num2 = int(input("Enter second
> number: "))num3 = int(input("Enter third number: "))if num1 > num2 and num1
> > num3:print(num1, " is th max number")elif num2 > num1 and num2 >
> num3:print(num2, " is the max number")else: print(num3, "is the max
> number")
>
> On Tue, Jan 29, 2019 at 1:48 PM Schachner, Joseph <
> joseph.schach...@teledyne.com>
> wrote:
> Explanation: 5 > 4 so it goes into the first if.  5 is not greater than 6,
> so it does not assign N1 to MaxNum.  The elif (because of the lack of
> indent) applies to the first if, so nothing further is executed. Nothing
> has been assigned to MaxNum, so that variable does not exist.  You're
> right, it does not work.
>
> How about this:
> Mylist = [ N1, N2, N3]
> Maxnum = N1
> for value in Mylist:
> if value > Maxnum:
> Maxnum = value
> print(Maxnum)
>
> Or were lists and for loops excluded from this exercise?
> --- Joe S.
>
> On 1/29/19 9:27 AM, Jack Dangler wrote:
>
> > wow. Seems like a lot going on. You have 3 ints and need to determine
> > the max? Doesn't this work?
> >
> > N1, N2, N3
> >
> > if N1>N2
> >if N1>N3
> >  MaxNum = N1
> > elif N2>N3
> >MaxNum = N2
> > elif N1 >MaxNum = N3
>
> No.  Assuing that you meant to include colons where I think you did, what
> if (N1, N2, N3) == (5, 4, 6)?
>
> --
> https://mail.python.org/mailman/listinfo/python-list
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Problem in Installing version 3.7.2(64 bit)

2019-01-29 Thread Ian Clark
back in my day we had to show our professors errors on punchcard! and we
liked it

On Sun, Jan 27, 2019 at 11:51 AM Terry Reedy  wrote:

> On 1/26/2019 6:24 AM, Vrinda Bansal wrote:
> > Dear Sir/Madam,
> >
> > After Installation of the version 3.7.2(64 bit) in Windows 8 when I run
> the
> > program it gives an error. Screenshot of the error is attached below.
>
> Nope.  This is text only mail list.  Images are tossed.  You must copy
> and paste.
>
> --
> Terry Jan Reedy
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Exercize to understand from three numbers which is more high

2019-01-29 Thread Ian Clark
threw this together, let me know what you think


num_list=[]
name_list =
['first','second','third','fourth','fifth','sixth','seventh','eighth','ninth','tenth']
name_it = name_list.pop(0)

while len(num_list) < 3:
 try:
  num_list.append( int( input(f"Insert the {name_it} number: ")))

 except ValueError:
  print('Not a number, try again!')
 else:
  name_it = name_list.pop(0)

print(f"Max number is: {sorted(num_list)[-1]}")

On Mon, Jan 28, 2019 at 1:58 AM Frank Millman  wrote:

> "^Bart"  wrote in message news:q2mghh$ah6$1...@gioia.aioe.org...
> >
> > > 1. The last two lines appear to be indented under the 'if number3 < '
> > > line. I think you want them to be unindented so that they run every
> > > time.
> >
> > I'm sorry but I didn't completely understand what you wrote about the
> last
> > two lines, please could you write how my code could be fixed?
> >
>
> The last four lines of your program look like this -
>
> if number3 < number2 and number3 < number1:
>  numbermin = number3
>
>  print("Number min is: ",numbermin)
>
>  numbermiddle = (number1+number2+number3)-(numbermax+numbermin)
>
>  print("Number middle is: ",numbermiddle)
>
> The last three lines all fall under the 'if number3 < number2' line, so
> they
> will only be executed if that line evaluates to True.
>
> I think that you want the last two lines to be executed every time. If so,
> they should be lined up underneath the 'if', not the 'print'.
>
> >
> > > if a == 1:
> > > do something
> > > elif a == 2:
> > > do something else
> >
> > Finally I understood the differences between if and elif! Lol! :D
> >
>
> It is actually short for 'else if', but I guess it is not obvious if you
> have not seen it before!
>
> Frank
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Exercize to understand from three numbers which is more high

2019-01-29 Thread Ian Clark
Like this?

num_max = 0
num_index = 0
name_list =
['first','second','third','fourth','fifth','sixth','seventh','eighth','ninth','tenth']
name_it = name_list.pop(0)


while num_index <3:
 try:
  num_list = int( input(f"Insert the {name_it} number: "))

 except ValueError:
  print('Not a number, try again!')
 else:
  num_index += 1
  if num_list > num_max:
   num_max = num_list
  name_it = name_list.pop(0)

print(f"Max number is: {num_max}")

On Tue, Jan 29, 2019 at 1:26 PM Chris Angelico  wrote:

> On Wed, Jan 30, 2019 at 8:20 AM Bob van der Poel  wrote:
> > Isn't the easiest way to do this is:
> >
> >  sorted( [n1,n2,n3] )[-1]
> >
> > to get the largest value?
>
> >>> help(max)
>
> But the point of this exercise is not to use sorted() or max().
>
> ChrisA
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Raising exception on STDIN read

2008-02-29 Thread Ian Clark
On 2008-02-28, Gabriel Genellina [EMAIL PROTECTED] wrote:
 I hope it's more clear now. Python objects are only meaningful *inside* a  
 Python program, but an *external* program can't use them directly.

Yes, sorry. This is what I was getting hung up on. My thinking was that
subprocess was orchestrating it such that any reads would be funneled
back into the Python object. Granted, that was my gut reaction to it.
Thinking (and playing) with it a bit more I now realize that that makes
no sense. Thank you for reminding me about the seperation of OS and
Python files.

Ian

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


Re: Raising exception on STDIN read

2008-02-28 Thread Ian Clark
On 2008-02-27, Gabriel Genellina [EMAIL PROTECTED] wrote:
 En Wed, 27 Feb 2008 15:06:36 -0200, Ian Clark [EMAIL PROTECTED]  
 escribi�:

 On 2008-02-27, Michael Goerz [EMAIL PROTECTED] wrote:
 Hi,

 I would like to raise an exception any time a subprocess tries to read
 from STDIN:

 latexprocess = subprocess.Popen( \
  'pdflatex' +   \
   + 'test' +  21, \
  shell=True, \
  cwd=os.getcwd(), \
  env=os.environ, \
  stdin=StdinCatcher() # any ideas here?
  )

 An exception should be raised whenever the pdflatex process
 reads from STDIN... and I have no idea how to do it. Any suggestions?

 How about with a file-like object? I haven't tested this with subprocess
 so you might want to read the manual on files if it doesn't work[1].

 Won't work for an external process, as pdflatex (and the OS) knows nothing  
 about Python objects. The arguments to subprocess.Popen must be actual  
 files having real OS file descriptors.

Taken from the subprocess documentation (emphasis mine). [1]

stdin, stdout and stderr specify the executed programs' standard
input, standard output and standard error file handles,
respectively. Valid values are PIPE, an existing file descriptor (a
positive integer), *an existing file object*, and None.

The following peice of code works fine for me with the subprocess
module. NOTE: the only difference from this and the last I posted is
that I set fileno() to _error().

import sys 
import subprocess

class ErrorFile(object):
def _error(self, *args, **kwargs):
raise AssertionError(Illegal Access)

def _noop(self, *args, **kwargs):
pass

close = flush = seek = tell = _noop
next = read = readline = readlines = xreadlines = tuncate = _error
truncate = write = writelines = fileno = _error
#   ^^

proc = subprocess.Popen(cat -, shell=True, stdin=ErrorFile())
ret = proc.wait()
print return, ret

Ian

[1] http://docs.python.org/lib/node528.html

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


Re: Raising exception on STDIN read

2008-02-28 Thread Ian Clark
On 2008-02-28, Gabriel Genellina [EMAIL PROTECTED] wrote:
 En Thu, 28 Feb 2008 14:29:04 -0200, Ian Clark [EMAIL PROTECTED]  
 escribió:

 On 2008-02-27, Gabriel Genellina [EMAIL PROTECTED] wrote:
 En Wed, 27 Feb 2008 15:06:36 -0200, Ian Clark [EMAIL PROTECTED]
 escribi�:

 On 2008-02-27, Michael Goerz [EMAIL PROTECTED] wrote:
 Hi,

 I would like to raise an exception any time a subprocess tries to read
 from STDIN:

 latexprocess = subprocess.Popen( \
  'pdflatex' +   \
   + 'test' +  21, \
  shell=True, \
  cwd=os.getcwd(), \
  env=os.environ, \
  stdin=StdinCatcher() # any ideas here?
  )

 An exception should be raised whenever the pdflatex process
 reads from STDIN... and I have no idea how to do it. Any suggestions?

 How about with a file-like object? I haven't tested this with  
 subprocess
 so you might want to read the manual on files if it doesn't work[1].

 Won't work for an external process, as pdflatex (and the OS) knows  
 nothing
 about Python objects. The arguments to subprocess.Popen must be actual
 files having real OS file descriptors.

 Taken from the subprocess documentation (emphasis mine). [1]

  stdin, stdout and stderr specify the executed programs' standard
  input, standard output and standard error file handles,
  respectively. Valid values are PIPE, an existing file descriptor (a
  positive integer), *an existing file object*, and None.

 The following peice of code works fine for me with the subprocess
 module. NOTE: the only difference from this and the last I posted is
 that I set fileno() to _error().

 import sys
 import subprocess

 class ErrorFile(object):
 def _error(self, *args, **kwargs):
 raise AssertionError(Illegal Access)

 def _noop(self, *args, **kwargs):
 pass

 close = flush = seek = tell = _noop
 next = read = readline = readlines = xreadlines = tuncate =  
 _error
 truncate = write = writelines = fileno = _error
 #   ^^

 proc = subprocess.Popen(cat -, shell=True, stdin=ErrorFile())
 ret = proc.wait()
 print return, ret

 I don't see how this could ever work. The shell knows nothing about your  
 ErrorFile objects. If subprocess.Popen doesn't reject that ErrorFile  
 instance, it's a bug. An ErrorFile instance is not an existing file  
 object.

Could you please explain why this won't work. ErrorFile exposes most all
attributes of file objects, so I don't understand why it wouldn't be
considered a file object.

Did you try running the code by any chance? It works fine for me on
2.5.1 on Linux.

Ian

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


Re: Raising exception on STDIN read

2008-02-27 Thread Ian Clark
On 2008-02-27, Michael Goerz [EMAIL PROTECTED] wrote:
 Hi,

 I would like to raise an exception any time a subprocess tries to read 
 from STDIN:

 latexprocess = subprocess.Popen( \
  'pdflatex' +   \
   + 'test' +  21, \
  shell=True, \
  cwd=os.getcwd(), \
  env=os.environ, \
  stdin=StdinCatcher() # any ideas here?
  )

 An exception should be raised whenever the pdflatex process
 reads from STDIN... and I have no idea how to do it. Any suggestions?

 Thanks,
 Michael

How about with a file-like object? I haven't tested this with subprocess
so you might want to read the manual on files if it doesn't work[1].

import sys 

class ErrorFile(object):
def _error(self, *args, **kwargs):
raise AssertionError(Illegal Access)

def _noop(self, *args, **kwargs):
pass

close = flush = seek = tell = _noop
next = read = readline = readlines = xreadlines = tuncate = 
_error
truncate = write = writelines = _error

sys.stdin = ErrorFile()
print raw_input(? )

Ian

[1] http://docs.python.org/lib/bltin-file-objects.html

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


Re: Is crawling the stack bad? Why?

2008-02-25 Thread Ian Clark
On 2008-02-25, Russell Warren [EMAIL PROTECTED] wrote:

 the threading.local class seems defined for that purpose, not that I've ever
 used it ;)

 I hadn't heard of that... it seems very useful, but in this case I
 think it just saves me the trouble of making a stash dictionary...
 unless successive calls to threading.local return the same instance?
 I'll have to try that, too.

No, successive calls to threading.local() will return different objects.
So, you call it once to get your 'data store' and then use that one
object from all your threads. It takes care of making sure each thread
gets it's own data.

Here is your example, but using threading.local instead of your own
version of it. :)

Ian

import xmlrpclib, threading, sys, thread
from SimpleXMLRPCServer import SimpleXMLRPCServer, 
SimpleXMLRPCRequestHandler

thread_data = threading.local()

class RpcContainer(object):
  def __init__(self):
self._Handlers = {} #keys = thread IDs, values=requestHandlers
  def _GetRpcClientIP(self):
#connection = self._Handlers[thread.get_ident()].connection
connection = thread_data.request.connection
ip = connection.getpeername()[0]
return ip
  def WhatIsMyIP(self):
return Your IP is: %s % self._GetRpcClientIP()

class ThreadCapableRequestHandler(SimpleXMLRPCRequestHandler):
  def do_POST(self, *args, **kwargs):
#make the handler available to the RPCs, indexed by threadID...
thread_data.request = self
SimpleXMLRPCRequestHandler.do_POST(self, *args, **kwargs)

class MyXMLRPCServer(SimpleXMLRPCServer):
  def __init__(self, RpcContainer, *args, **kwargs):
self.RpcContainer = RpcContainer
SimpleXMLRPCServer.__init__(self, *args, **kwargs)

class DaemonicServerLaunchThread(threading.Thread):
def __init__(self, RpcServer, **kwargs):
threading.Thread.__init__(self, **kwargs)
self.setDaemon(1)
self.server = RpcServer
def run(self):
self.server.serve_forever()

container = RpcContainer()
rpcServer = MyXMLRPCServer(
 RpcContainer = container,
 addr = (, 12390),
 requestHandler = ThreadCapableRequestHandler,
 logRequests = False)
rpcServer.register_function(container.WhatIsMyIP)
slt = DaemonicServerLaunchThread(rpcServer)
slt.start()

sp = xmlrpclib.ServerProxy(http://localhost:12390;)
print sp.WhatIsMyIP()

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


Re: os.fork() not working on windows (help)

2008-02-25 Thread Ian Clark
On 2008-02-25, A. Joseph [EMAIL PROTECTED] wrote:
 Please i`m trying to create a process using the os.fork() but it keep

If you're not trying to clone your current process, just make a new one,
you should look at the subprocess module.

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

Ian

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


Re: Curses and Threading

2008-01-22 Thread Ian Clark
On 2008-01-22, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 In fact you have *two* threads: the main thread, and the one you create
 explicitly.

 After you start the clock thread, the main thread continues executing,
 immediately entering the finally clause.
 If you want to wait for the other thread to finish, use the join() method.
 But I'm unsure if this is the right way to mix threads and curses.

 This is what the python documentation says:

 join([timeout])
 Wait until the thread terminates. This blocks the calling thread
 until the thread whose join() method is called terminates.

 So according to this since I need to block the main thread until the
 clock thread ends I would need the main thread to call
 cadtime().join(), correct? I'm not sure how to do this because I
 don't have a class or anything for the main thread that I know of. I
 tried putting that after cadtime().start() but that doesn't work. I
 guess what I'm trying to say is how can I tell the main thread what to
 do when it doesn't exist in my code?

 Thanks for the help
 -Brett

join() is a method on Thread objects. So you'll need a reference to the
Thread you create, then call join() on that.

thread = cadtime()
thread.start()
thread.join()

Ian

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


Re: error/warning color customization in interactive console?

2008-01-16 Thread Ian Clark
On 2008-01-16, yhvh [EMAIL PROTECTED] wrote:
 Is it possible to output error messages in a different color?
 I'm using Terminal on Gnome.

 print \033[1;31mHello\033[0m There!

Some reading:
http://en.wikipedia.org/wiki/ANSI_escape_code
http://www.ioncannon.net/ruby/101/fun-with-ansi-escape-codes/

Also, you might look at sys.excepthook to colorize an uncaught exception,
and PYTHONSTARTUP to load code automagically before an interactive
session.

Ian

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


Re: mysqldb SELECT COUNT reurns 1

2007-12-27 Thread Ian Clark
On 2007-12-27, SMALLp [EMAIL PROTECTED] wrote:
 connectionString = {host:localhost, user:root, 
 passwd:pofuck, db:fileshare}
 dataTable = files
 conn = mysql.connect(host=connectionString[host],
 user=connectionString[user], passwd=connectionString[passwd],
 db=connectionString[db])

Just to let you know, that last line can be rewritten as:

conn = mysql.connect(**connectionString)


Ian

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


Re: Debugging pipe IPC

2007-12-18 Thread Ian Clark
Jim B. Wilson wrote:
 Ian Clark wrote:
 Jim B. Wilson wrote:
 ...
 The child/client sends requests on its stdout and receives responses 
 on stdin.
 So, why can't you just run this client on the command line and let the 
 shell handle stdin/stdout for you?
 
 I'm not sure I understand the topology of your proposal?  And, it's 
 certainly possible the shell has mystical powers of which I am unaware.
 
 Are you suggesting a run client that spews the mother's messages to the 
 terminal, and I somehow cut/paste them into the client, running with 
 stdin/stdout unconnected to anything but me?  Or is there some 
 combination of tee, etal.,  I can lash together so that my commands (to 
 the client) don't get mixed up with mother's messages?
 
 Some such arrangement would surely help.  I often forget the stderr, 
 on my scratch-head debugging prints, and mother gets quite upset when 
 the incoming message doesn't fit the mold :)
 
 Jim

What I'm suggesting is to run the following from the shell: python 
internal_python_program.py. Then you type into the terminal whatever 
'mother' was sending it (Clean your room! most like) and see what it 
spits back. If the script is simply reading from stdin and writing to 
stdout there shouldn't be much of a problem. The hardest part might be 
figuring out what 'mother' actually sends it.

If it's very verbose you can type it out once to a file and redirect 
that file to the python process: python internal_python_program.py  
file_with_mother_commands.txt.

Another idea is to open a file somewhere and write your debug output to 
that. I would also suggest the logging[1] module as well. It's very 
handy for his sort of thing.

Ian

[1] http://docs.python.org/lib/module-logging.html

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


Re: Debugging pipe IPC

2007-12-18 Thread Ian Clark
Jim B. Wilson wrote:
 ...  My fondest wish is to play the role of the child at the
 good old  prompt. ...
 
 Jim

Okay, I misunderstood the direction you wanted to go. I thought that you 
wanted to play the part of the mother, giving commands to the child and 
not the other way around.

Assuming you're on a *nix make child.py as:

import os
os.system(netcat -l -p 1234 localhost)

Run it though mother and on another terminal type: netcat localhost 1234

HTH,

Ian

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


Re: Debugging pipe IPC

2007-12-17 Thread Ian Clark
Jim B. Wilson wrote:
 I have the mother (of all) application(s, written in C++) that 
 occasionally outsources certain tasks to a child Python script.  The 
 mother fork/execs (or equivalent) the child and then begins serving the 
 child's requests.
 
 The child/client sends requests on its stdout and receives responses on 
 stdin.  The interaction is facilitated by a Pyrex extension which handles 
 the lower-level aspects of the conversation and exposes a few functions 
 and classes to the script.
 
 This part works peachy keen, but debugging has so far been via 
 printstderr-and-scratch-head.
 
 On a contemplative bike ride one day, I imagined how neat it would be to 
 run interactively.  On returning, I began to experiment with rebinding 
 sys.stdin and sys.stdout to /dev/tty, using the -i command-line switch, 
 etc. to see if I could devise a child that prompted me with  and 
 allowed me to compose/test small snippets on the terminal.  So far, no 
 joy.
 
 Is this possible?  If so, can someone nudge me toward a solution or 
 better yet a recipe?
 
 Jim Wilson
 Gainesville, FL

You're looking for the cmd module. 
http://docs.python.org/lib/module-cmd.html

Ian Clark

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


Re: Debugging pipe IPC

2007-12-17 Thread Ian Clark
Jim B. Wilson wrote:
...
 The child/client sends requests on its stdout and receives responses on 
 stdin.

So, why can't you just run this client on the command line and let the 
shell handle stdin/stdout for you?

Ian Clark

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


Re: cx_Oracle + array parameter

2007-12-03 Thread Ian Clark
[EMAIL PROTECTED] wrote:
 Hello,
 
 I'm trying to pass array as an argument into PL/SQL procedure.
 According to cursor manual (http://cx-oracle.sourceforge.net/html/
 cursorobj.html) arrayvar() should be use to do it. I've created my
 array type in PL/SQL:
 
 CREATE OR REPLACE TYPE cx_array_string is table of varchar2(200);
 
 and simple procedure:
 
 CREATE OR REPLACE PROCEDURE text(ret IN cx_array_string) IS
 BEGIN
 null;
 END text;
 
 My python code:
 
 p_array = curs.arrayvar(cx_Oracle.STRING, ['1','3'])
 curs.execute('BEGIN text( :1 ); end;', [p_array] )
 
 And it gives me back an error:
 cx_Oracle.DatabaseError: ORA-06550: line 1, column 7:
 PLS-00306: wrong number or types of arguments in call to 'TEXT'
 ORA-06550: line 1, column 7:
 PL/SQL: Statement ignored
 
 It's the same when i try to use callproc() instead of execute(). I've
 searched whole internet with no luck. Could anyone please give me a
 working example python + pl/sql how to pass string array form py to
 oracle procedure, please.
 
 Thank you!

First off I've never used cxOracle or done any PL/SQL from python, but 
it looks like you're passing a list of a list to text().

  p_array = curs.arrayvar(cx_Oracle.STRING, ['1','3'])
  curs.execute('BEGIN text( :1 ); end;', [p_array] )

p_array appears to be some sort of cxOracle array, but when you pass it 
to curs.execute you wrap it in a new list: [p_array]. Try removing the 
parens and see what happens.

Ian

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


Re: Iterable Flattener with Depth.

2007-11-02 Thread Ian Clark
thebjorn wrote:
 On Nov 2, 6:32 am, praddy [EMAIL PROTECTED] wrote:
 On Nov 1, 5:03 pm, [EMAIL PROTECTED] wrote:

 Pradeep Jindal:
 Any comments?
 Something with similar functionality (plus another 20 utility
 functions/classes or so) has probably to go into the std lib... :-)
 Bye,
 bearophile
 Same Here!

 - Pradeep
 
 Yeah, everyone has to write a flatten sooner or later :-)  My version
 is at:
 
   http://blog.tkbe.org/archive/python-flatten/
 
 -- bjorn
 

And here is mine. Note that it is very similar to Michael Spencer's 
implementation[1]. The only difference is that this adds a depth counter.

def iflat(itr, depth=0):
   itr = iter(itr)
   stack = []
   cur_depth = 0

   while True:
 try:
   elem = itr.next()
   if hasattr(elem, __iter__) and cur_depth  depth:
 stack.append(itr)
 itr = iter(elem)
 cur_depth += 1
   else:
 yield elem
 except StopIteration:
   if not stack:
 raise StopIteration
   cur_depth -= 1
   itr = stack.pop()


if __name__ == __main__:
   test1 = ((0, 1, 2), ((3, 4), 5), (((6, 7), 8), 9))
   test2 = [1,[2,[3,4,5],'bash'],6,[7,[8,[9,10,['hi', 'hello', 11, 12]

   for x in (test1, test2):
 print
 print list(iflat(x))
 print
 print list(iflat(x, 1))
 print list(iflat(x, 2))
 print list(iflat(x, 3))
 print list(iflat(x, 4))
 print iflat(x, 10)

Ian

[1] http://mail.python.org/pipermail/python-list/2005-March/312022.html

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


Re: Combine two dictionary...

2007-10-01 Thread Ian Clark
Abandoned wrote:
 On 1 Ekim, 20:41, Carsten Haese [EMAIL PROTECTED] wrote:
 On Mon, 2007-10-01 at 10:24 -0700, Abandoned wrote:
 Hi..
 dict1={1: 4,  3: 5}... and 2 millions element
 dict2={3: 3,  8: 6}... and 3 millions element
 I want to combine dict1 and dict2 and i don't want to use FOR because
 i need to performance.
 You'll have to be a bit more precise here about how and where you want
 to combine. Should the result be a new dictionary or should it replace
 one of dict1 or dict2? You're also not saying how you want conflicts
 between dict1 and dict2 should be resolved. For example, both dict1 and
 dict2 say something about the key 3. One says 5, the other says 3.
 Should the combined dict say 3 or 5 or (3,5) or maybe even 4?

 Also, based on your earlier posts from today, I'm wondering if those
 dicts come from executing SQL queries. If so, you might want to consider
 combining the results in SQL (using a UNION query) instead of combining
 them in Python.

 --
 Carsten Haesehttp://informixdb.sourceforge.net
 
 I want to total score..
 For example
 dict1={1: 4,  3: 5}... and 2 millions element
 dict2={3: 3,  8: 6}... and 3 millions element
 
 result should be dict3={1:4, 3:8, 8:6}

Well not sure how this will work with 5+ million elements, but here's 
one stab at it:

  dict1={1: 4,  3: 5}
  dict2={3: 3,  8: 6}
  for key in set(dict1.keys() + dict2.keys()):
 ... x = dict1.get(key, 0)
 ... y = dict2.get(key, 0)
 ... dict3[key] = x + y
 ...
  dict3
 {8: 6, 1: 4, 3: 8}

As Carsten Haese pointed out this should really be done in SQL. You 
might try something along these lines:

SELECT
   t1.id AS id,
   NVL(t1.count, 0) + NVL(t2.count, 0) AS count
FROM DUAL
LEFT JOIN (
   SELECT
 id,
 count
   FROM table1
) AS t1 ON 1=1
LEFT JOIN (
   SELECT
 id,
 count
   FROM table2
) AS t2 ON t1.id = t2.id

NOTE: I've never actually used a UNION, but you might want to look into it.

Ian


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


Re: acronym program

2007-09-21 Thread Ian Clark
Shawn Minisall wrote:
 I'm trying to write a program that gets the first letter of every word 
 of a phrase and prints it on screen.  I'm having problems with it.  I'm 
 thinking a for loop would be good since I don't know the exact number of 
 words the user is going to enter, but after that I get confused.  How do 
 I tell python to just goto the beg of each word in the phrase and 
 include it in the acronym?  Am I on the right track?
 
 for a in string.split(phrase)
 acronym = phrase [0]
 acronym = acronym + 1
 
 thx

List comprehensions[1] to the rescue!

  phrase = 'hello there i am well how are you?'
  acronym = [word[0] for word in phrase.split()]
  acronym
 ['h', 't', 'i', 'a', 'w', 'h', 'a', 'y']

Ian

[1] http://docs.python.org/tut/node7.html#SECTION00714

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


Re: newb: Simple regex problem headache

2007-09-21 Thread Ian Clark
crybaby wrote:
 import re
 
 s1 ='nbsp;25000nbsp;'
 s2 = 'nbsp;5.5910nbsp;'
 
 mypat = re.compile('[0-9]*(\.[0-9]*|$)')
 rate= mypat.search(s1)
 print rate.group()
 
 rate=mypat.search(s2)
 print rate.group()
 rate = mypat.search(s1)
 price = float(rate.group())
 print price
 
 I get an error when it hits the whole number, that is in this format:
 s1 ='nbsp;25000nbsp;'
 For whole number s2, mypat catching empty string.  I want it to give
 me 25000.
 I am getting this error:
 
 price = float(rate.group())
 ValueError: empty string for float()
 
 Anyone knows, how I can get 25000 out of s2 = 'nbsp;5.5910nbsp;'
 using regex pattern, mypat = re.compile('[0-9]*(\.[0-9]*|$)').  mypat
 works fine for real numbers, but doesn't work for whole numbers.
 
 thanks
 

Try this:
  import re
  s1 ='nbsp;25000nbsp;'
  s2 = 'nbsp;5.5910nbsp;'
  num_pat = re.compile(r'([0-9]+(\.[0-9]+)?)')
  num_pat.search(s1).group(1)
 '25000'
  num_pat.search(s2).group(1)
 '5.5910'

Ian

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


Re: I could use some help making this Python code run faster using only Python code.

2007-09-20 Thread Ian Clark
[EMAIL PROTECTED] wrote:
 On Sep 20, 5:46 pm, Paul Hankin [EMAIL PROTECTED] wrote:
 On Sep 20, 10:59 pm, Python Maniac [EMAIL PROTECTED] wrote:

 I am new to Python however I would like some feedback from those who
 know more about Python than I do at this time.
 def scrambleLine(line):
 s = ''
 for c in line:
 s += chr(ord(c) | 0x80)
 return s
 def descrambleLine(line):
 s = ''
 for c in line:
 s += chr(ord(c)  0x7f)
 return s
 ...
 Well, scrambleLine will remove line-endings, so when you're
 descrambling
 you'll be processing the entire file at once. This is particularly bad
 because of the way your functions work, adding a character at a time
 to
 s.

 Probably your easiest bet is to iterate over the file using read(N)
 for some small N rather than doing a line at a time. Something like:

 process_bytes = (descrambleLine, scrambleLine)[action]
 while 1:
 r = f.read(16)
 if not r: break
 ff.write(process_bytes(r))

 In general, rather than building strings by starting with an empty
 string and repeatedly adding to it, you should use ''.join(...)

 For instance...
 def descrambleLine(line):
   return ''.join(chr(ord(c)  0x7f) for c in line)

 def scrambleLine(line):
   return ''.join(chr(ord(c) | 0x80) for c in line)

 It's less code, more readable and faster!
 
 I would have thought that also from what I've heard here.
 
 def scrambleLine(line):
 s = ''
 for c in line:
 s += chr(ord(c) | 0x80)
 return s
 
 def scrambleLine1(line):
 return ''.join([chr(ord(c) | 0x80) for c in line])
 
 if __name__=='__main__':
 from timeit import Timer
 t = Timer(scrambleLine('abcdefghijklmnopqrstuvwxyz'), from
 __main__ import scrambleLine)
 print t.timeit()
 
 ##  scrambleLine
 ##  13.0013366039
 ##  12.9461998318
 ##
 ##  scrambleLine1
 ##  14.4514098748
 ##  14.3594400695
 
 How come it's not? Then I noticed you don't have brackets in
 the join statement. So I tried without them and got
 
 ##  17.6010847978
 ##  17.6111472418
 
 Am I doing something wrong?
 
 --
 Paul Hankin
 
 

I got similar results as well. I believe the reason for join actually 
performing slower is because join iterates twice over the sequence. [1] 
The first time is to determine the size of the buffer to allocate and 
the second is to populate the buffer.

Ian

[1] http://mail.python.org/pipermail/python-list/2007-September/458119.html

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


Re: HTTP Protocol Client

2007-09-20 Thread Ian Clark
[EMAIL PROTECTED] wrote:
 h = httplib.HTTP('http://Google.com',80)

This should be:
h = httplib.HTTP('Google.com',80)

And I certainly agree with the others, check out urllib*.

Ian

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


Re: curses: x, y positioning

2007-09-17 Thread Ian Clark
7stud wrote:
 However, now I am having a problem trying to set the color of the text
 that is output:

import curses

def example(screen):
 if curses.has_colors():
 curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK)
 curses.init_pair(2, curses.COLOR_YELLOW, curses.COLOR_BLACK)
 curses.init_pair(3, curses.COLOR_RED, curses.COLOR_BLACK)

 screen.addstr(1, 1, 'Hello', curses.color_pair(1))
 screen.addstr(1, 7, 'World', curses.color_pair(2))
 screen.addstr(1, 12, '!!!', curses.color_pair(3) + curses.A_BOLD)
 else:
 screen.addstr(1, 1, 'You don\'t have colors enabled. :(')

 screen.addstr(3, 0, 'Press any key to continue')
 screen.refresh()
 screen.getch()

if __name__ == '__main__':
 curses.wrapper(example)

Ian

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


Re: subclass of integers

2007-09-14 Thread Ian Clark
Mark Morss wrote:
 I would like to construct a class that includes both the integers and
 None.  I desire that if x and y are elements of this class, and both
 are integers, then arithmetic operations between them, such as x+y,
 return the same result as integer addition.  However if either x or y
 is None, these operations return None.
 
 It's simple enough to construct a subclass of integers that behave in
 this way:
 
 class Nint(int):
 def __add__(self,other):
 if (other != None):
 return self+other
 else:
 return None
 def __radd__(self,other):
 if (other != None):
 return other+self
 else:
 return None
 #...and so forth
 
 However I have not been able to figure out how to make it so that
 None, as well as an integer, could be an element of my class.  My
 preliminary impression is that I have to override int.__new__; but I
 am uncertain how to do that and have been unable to find anything on
 the web explaining that.  Indeed I haven't been able to find much
 about __new__ at all.  Overriding this method of built-in classes
 seems to be quite unusual.
 
 I would very much appreciate anyone's help.

My thought would be rather than trying to cram None into a subclass of 
int, to use delegation instead...

-8--
class NoneInt(object):
 def __init__(self, value):
 self.value = value

 def __add__(self, other):
 if isinstance(other, NoneInt):
 if None in (self.value, other.value):
 return NoneInt(None)
 return NoneInt(self.value + other.value)
 elif isinstance(other, int):
 if self.value is None:
 return NoneInt(None)
 return NoneInt(self.value + other)
 else:
 raise TypeError(
 unsupported operand type(s) for +: 'NoneInt'
 and '%s' % str(other.__class__.__name__)
 )
 __radd__ = __add__

 def __str__(self):
 return 'NoneInt(%s)' % str(self.value)


def main():
 print '42? ', NoneInt(40) + NoneInt(2)
 print '41? ', NoneInt(40) + 1
 print '40? ', 25 + NoneInt(15)
 print 'None? ', NoneInt(None)
 print 'None? ', NoneInt(None) + 1
 print 'None? ', 1 + NoneInt(None)
 print 'Error? ', NoneInt(0) + 'spam'

if __name__ == '__main__':
 main()
-8--

Ian

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


Re: subclass of integers

2007-09-14 Thread Ian Clark
Ian Clark wrote:
 Mark Morss wrote:
 I would like to construct a class that includes both the integers and
 None.  I desire that if x and y are elements of this class, and both
 are integers, then arithmetic operations between them, such as x+y,
 return the same result as integer addition.  However if either x or y
 is None, these operations return None.

 (snip)

 I would very much appreciate anyone's help.
 
 My thought would be rather than trying to cram None into a subclass of 
 int, to use delegation instead...
 
 (snip)
 
 Ian

A more robust implementation that accounts for ints/longs as well as 
implementing more operations...

-8--
import operator

class NoneInt(object):
 _LEFT = 1
 _RIGHT = 2


 def __init__(self, value):
 self.value = value


 def _get_arguments(self, other, direction=_LEFT):
  Given a direction (left or right), returns the left hand
 side and right hand side values. 

 if direction == self._LEFT:
 lhs = self.value
 if isinstance(other, (int, long, type(None))):
 rhs = other
 else:
 rhs = other.value
 elif direction == self._RIGHT:
 rhs = self.value
 if isinstance(other, (int, long, type(None))):
 lhs = other
 else:
 lhs = other.value
 else:
 raise ValueError('direction must be either _LEFT or _RIGHT')
 return (lhs, rhs)


 def _operation(op, direction):
  Given a direction and an operation will return a function
 that calls the operation with the arguments in the correct
 order. 

 def func(self, other):
 if not isinstance(other, (int, long, NoneInt, type(None))):
 fmt = unsupported operand type(s) for %s: 'NoneInt' 
and '%s'
 args =  (op.__name__, other.__class__.__name__)
 raise TypeError(fmt % args)

 lhs, rhs = self._get_arguments(other, direction)

 if None in (lhs, rhs):
 return NoneInt(None)
 return NoneInt(op(lhs, rhs))
 return func


 __add__ = _operation(operator.add, _LEFT)
 __radd__ = _operation(operator.add, _RIGHT)
 __sub__ = _operation(operator.sub, _LEFT)
 __rsub__ = _operation(operator.sub, _RIGHT)
 __div__ = _operation(operator.div, _LEFT)
 __rdiv__ = _operation(operator.div, _RIGHT)
 __mul__ = _operation(operator.mul, _LEFT)
 __rmul__ = _operation(operator.mul, _RIGHT)
 # ... etc


 def __eq__(self, other):
 lhs, rhs = self._get_arguments(other)
 return lhs == rhs


 def __nonzero__(self):
 return bool(self.value)


 def __str__(self):
 return 'NoneInt(%s)' % str(self.value)

 __repr__ = __str__
-8--

Ian

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


Re: Spaces from string specifier

2007-09-14 Thread Ian Clark
Gabriel Genellina wrote:
 En Fri, 14 Sep 2007 01:57:43 -0300, Gavin Tomlins [EMAIL PROTECTED]  
 escribi�:
 
 I'm trying to work out when using a format specifier I get spaces in the
 resulting string.  Eg. Looking at the outputted string you can see that
 there are spaces after T5LAT, F4LAT etc. as I result from trying to keep  
 the
 code aligned
 
 - You should *not* build the SQL text yourself; use a parametrised query  
 instead. It's not only easier to write; it's safer, less error prone, and  
 maybe faster. See this previous post  
 http://groups.google.com/group/comp.lang.python/browse_thread/thread/b8c1ef8471f55995/
 
 - Spaces are not significant in SQL, but you may have your own reasons to  
 format the SQL text in a certain way. In addition to the ideas already  
 menctioned on that thread (avoid \, use parenthesis, and auto-concatenate  
 adjacent strings), you may use a triple-quoted string + function dedent  
  from textwrap module:
 
 py fmtSqlP300Amp = textwrap.dedent('''\
 ...   UPDATE Patient SET
 ... O2AMP = %s, O1AMP = %s, OzAMP = %s, PzAMP = %s,
 ... P4AMP = %s, CP4AMP = %s, T6AMP = %s, C4AMP = %s,
 ... TP8AMP = %s, T4AMP = %s, T5AMP = %s, P3AMP = %s
 ...   WHERE Pat_Id = %s''')
 py print fmtSqlP300Amp
 UPDATE Patient SET
O2AMP = %s, O1AMP = %s, OzAMP = %s, PzAMP = %s,
P4AMP = %s, CP4AMP = %s, T6AMP = %s, C4AMP = %s,
TP8AMP = %s, T4AMP = %s, T5AMP = %s, P3AMP = %s
 WHERE Pat_Id = %s
 
 I hope any of these ideas will fit your own needs.

Completely agree that this should not be written by hand. But if you 
absolutely *must* you might try something like this:

  fmt = 
 ... UPDATE Patient SET
 ... 02AMP = %(o2amp)s
 ... O1AMP = %(o1amp)s
 ... ...
 ... 
  args = {
 ... 'o1amp': 2.77413,
 ... 'o2amp': 2.43119
 ... }
  print fmt % args

 UPDATE Patient SET
 02AMP = 2.43119
 O1AMP = 2.77413
 ...

 

Ian

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

Re: recursion

2007-09-13 Thread Ian Clark
Neil Cerutti wrote:
 On 2007-09-13, Gigs_ [EMAIL PROTECTED] wrote:
 Can someone explain me this

 def f(l):
  if l == []:
  return []
  else:
  return f(l[1:]) + l[:1]  # = cant figure this, how is all sum 
 at the end?
 
 In plain English, the above program says:
 
 The sum of the items in list l is zero if the list is empty.
 Otherwise, the sum is the value of the first item plus the sum of
 the rest of the items in the list.

Am I missing something? What does this have to do with summing?

  def f(l):
 ... if l == []:
 ... return []
 ... else:
 ... return f(l[1:]) + l[:1]
 ...
  f([1, 2, 3, 4])
 [4, 3, 2, 1]

Ian

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


Re: sys.argv index out of range error

2007-09-13 Thread Ian Clark
Brian McCann wrote:
 init.sh
 
 #!/bin/sh
 WORKSPACE_ROOT=$1;
 
 export 
 JAVA_OPTIONS=-Djava.library.path=$WORKSPACE_ROOT/:$WORKSPACE_ROOT/:$WORKSPACE_ROOT/
 echo JAVA_OPTIONS=$JAVA_OPTIONS;
  
 set 
 PATH=$WORKSPACE_ROOT/vendor/basistech/rlp5.4/rlp/bin/ia32-glibc23-gcc32:$WORKSPACE_ROOT/vendor/basistech/rlp5.4/rlp/bin/ia32-w32-msvc71:$WORKSPACE_ROOT/lib/core:$PATH

Taken from `help set` (at the bottom of the page; emphasis mine):
   Using + rather than - causes these flags to be turned off.  The
   flags can also be used upon invocation of the shell.  The current
   set of flags may be found in $-.  *The remaining n ARGs are positional
   parameters and are assigned, in order, to $1, $2, .. $n.  If no
   ARGs are given, all shell variables are printed.*

Short answer: change set to export.

Slightly longer answer:
What this invocation of set is doing is setting the shell variable PATH 
to the value you give *and* setting the $1 variable to the same value 
and removing all other numbered variables. So if you put a print $2 
after `source init.sh $1` in bootstrap.sh you'll notice it's blank, as 
set is removing it.

The reason this happens when you source the file rather than just 
calling it is that when you source a file it runs in the current shell. 
So calling set then wipes out all the other numbered variables. When 
simply calling the script it creates a subshell where those things still 
happen, just not in the parent shell.

Ian

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


Re: Beginners Query - Simple counter problem

2007-09-06 Thread Ian Clark
Carsten Haese wrote:
 On Thu, 2007-09-06 at 11:00 -0700, Scott David Daniels wrote:
 def d6(count):
  result = 0
  for die in range(count):
  result += random.randint(1, 6)
  return result
 
 This, of course, can be further improved into:
 
 def d6(count):
 return sum(random.randint(1, 6) for die in range(count))
 

My stab at it:

  def roll(times=1, sides=6):
 ... return random.randint(times, times*sides)

Ian

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


Re: Getting original working directory

2007-09-06 Thread Ian Clark
rave247 rave247 wrote:
 ..the *original* directory location *after* os.chdir() is 
 performed.. os.getcwd() is not helping much as it returns the location 
 that was set up in os.chdir() call
 
 Thanks

Your question is akin to having a name X that is bound to some value, 
setting it to 2 and then wanting to know what the original value is. It 
just ain't gonna happen.

Simply follow the advice given by Gary and use os.getcwd() *before* the 
call to os.chdir().

Ian

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


Re: Beginners Query - Simple counter problem

2007-09-06 Thread Ian Clark
Carsten Haese wrote:
 On Thu, 2007-09-06 at 11:24 -0700, Ian Clark wrote:
 Carsten Haese wrote: 
 def d6(count):
 return sum(random.randint(1, 6) for die in range(count))

 My stab at it:

   def roll(times=1, sides=6):
  ... return random.randint(times, times*sides)
 
 That produces an entirely different probability distribution if times1.
 Consider times=2, sides=6. Your example will produce every number
 between 2 and 12 uniformly with the same probability, 1 in 11. When
 rolling two six-sided dice, the results are not evenly distributed. E.g.
 the probability of getting a 2 is only 1 in 36, but the probability of
 getting a 7 is 1 in 6.
 

Doh. I stand corrected. Probability was never a fun subject for me. :)

Ian

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


Re: Symbolic Link

2007-08-21 Thread Ian Clark
Hyuga wrote:
 On Aug 19, 4:29 pm, mosscliffe [EMAIL PROTECTED] wrote:
 The source file is in an area which python can see, but not the
 browser.  I am trying to make a link in a browser friendly area so I
 can use it to display an image file.
 
 You might want to try using an .htaccess file.  Place a file
 called .htaccess in the browser friendly area and place in it the
 line:
 
 Options +FollowSymLinks
 
 Assuming your hosting service will allow that, then it should work.
 If not, then why not just copy the image files?  Storage is cheap
 these days.
 
 Hyuga
 

My question would be why a symbolic link? Why not a hard link? Are the 
two directories on different mount points? After the script finishes 
does python need to see that image file again? Why not just move it?

Ian

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


Re: Question on SPE and pwintypes.dll

2007-08-17 Thread Ian Clark
Gerry wrote:
... but the OS wasn't migrated  ...

There's your problem right there. It's hard to run most software these 
days without an OS.

Ian

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


Re: All names in the current module

2007-08-15 Thread Ian Clark
Torsten Bronger wrote:
 Hallöchen!
 
 How can I get a list with all classes defined in the current module?
 Thank you!
 
 Tschö,
 Torsten.
 

Assuming you want to see all classes in the re module:

  import re
  help(re) #best way
 
  def isclass(cls):
... try:
... return issubclass(cls, cls)
... except TypeError:
... pass
... return False
...
  [cls for cls in dir(re) if isclass(getattr(re, cls))]
['Scanner', '_pattern_type', 'error']

Ian

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


Re: All names in the current module

2007-08-15 Thread Ian Clark
Ian Clark wrote:
 Torsten Bronger wrote:
 Hallöchen!

 How can I get a list with all classes defined in the current module?
 Thank you!

 Tschö,
 Torsten.

 
 Assuming you want to see all classes in the re module:
 
   import re
   help(re) #best way
  
   def isclass(cls):
 ... try:
 ... return issubclass(cls, cls)
 ... except TypeError:
 ... pass
 ... return False
 ...
   [cls for cls in dir(re) if isclass(getattr(re, cls))]
 ['Scanner', '_pattern_type', 'error']
 
 Ian
 

I love this list, I learn something new everyday. Didn't know about 
inspect.isclass(). Ignore this post and look at Lawrence's.

Ian

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


Re: Getting started with JPype

2007-08-13 Thread Ian Clark
Disclaimer: I have never used (or even heard of) JPype before...

porter wrote:
(snip)
 
 Package myclass.HelloWorld is not Callable
 
(snip)
 
 from jpype import *
 
 startJVM(getDefaultJVMPath(), -ea, -Djava.class.path=D:/tmp/jpype-
 reli/test/dist/test.jar'' )
 
 package = JPackage(myclass)

Shouldn't this be `package = JPackage(myclasses)` as your Java code is 
contained in the package 'myclasses' not 'myclass'?

 x = package.HelloWorld()

Change this last line to: `x = package.HelloWorld`
(class would be a better name than x IMO)

 x.do_a_message()
 
 shutdownJVM()

It looks like JPype exports Java classes as members of the object 
referred to by `package`. You then try and call it with () and python 
throws it's hands in the air as it must not be a callable.

Ian

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


Re: JPype - passing to Java main

2007-08-13 Thread Ian Clark
[EMAIL PROTECTED] wrote:
 I am trying to get JPype to pass a String into a Java class main
 function. Demonstration code below:
 
 =JAVA
 package com;
 
 public class JPypeTest {
 
public static void main(String args[]) {
  System.out.println(args[0]);
}
 
public void printArgument(String arg) {
  System.out.println(arg);
}
 }
 
 ===PYTHON===
 from jpype import *
 
 startJVM(C:/Program Files/Java/jdk1.5.0_12/jre/bin/server/jvm.dll,-
 Djava.class.path=C:/jpypetest/test/)
 
 com = JPackage(com);
 jp = com.JPypeTest();
 jp.printArgument('');
 #WANT TO CALL main(arg) HERE
 shutdownJVM()
 ===
 
 What I want is to be able to call main() with an argument from the
 python file (using JPype) and have it echo
 args[0]. I can get this to work for printArgument(), but not for
 main().
 
 Thanks,
 Sarah
 

Try this:
com.JPypeTest.main(arg)

Ian

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


Re: programmatically define a new variable on the fly

2007-08-09 Thread Ian Clark
Lee Sander wrote:
 Hi,
 
 I would like to define a new variable which is not predefined by me.
 For example,
 I want to create an array called X%s where %s is to be determined
 based on the data I am processing. So, for example, if I the file
 I'm reading has
 g 99
 on the first line, I want to create a new variable  called Xg whose
 length
 is 99.
 I tried eval(Xg=[0]*99) but that did not work.
 
 any help would be greatly appreciated
 Lee
 

  Xg
Traceback (most recent call last):
   File stdin, line 1, in module
NameError: name 'Xg' is not defined
  namespace = globals()
  var_name = 'Xg'
  var_value = [0] * 9
  namespace[var_name] = var_value
  Xg
[0, 0, 0, 0, 0, 0, 0, 0, 0]

Ian

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


Re: problems playing with dates from any month.

2007-08-02 Thread Ian Clark
krishnakant Mane wrote:
 hello,
 I have a very strange problem and I can't find any solution for that.
 I am working on an accounting package which I wish to develop in python.
 the simple problem is that I want to knoe how I can know if the given
 date is the nth day of a month.
 for example if a customer is supposed to pay his installment on every
 5th of all months,
 I want to know if today is the fifth day (jan the fifth, feb the fifth
 etc) for any given month.
 I have not found any such function.
 if I have looked (or over looked ) in the wrong places I am really sorry.
 secondly I also want to know the way in which I can convert a given
 string to a date object.
 for example if I have a string 29/09/2005, I know it is a valid date
 although it is in a string form.
 now I want to convert the above string into a real date object.
 how can I cast it this way?
 regards,
 Krishnakant.

http://docs.python.org/lib/node85.html

Then it's just:

if date_obj.day == 5:
 print 'It's the fifth day of the month'

Ian

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


Re: problems playing with dates from any month.

2007-08-02 Thread Ian Clark
krishnakant Mane wrote:
 On 02/08/07, Ian Clark [EMAIL PROTECTED] wrote:
 
 http://docs.python.org/lib/node85.html

 I looked there even before.
 but could not figure out what the code did.
 I know in that variable called s there was a string in a valid date format.
 but when datetime.strptime was used, I did not understand the place
 where a date object say d was created.
 I would expect some thing like d = and the function.  but I did not fine that.
 only reference was the datetime module and the documentation is not as good.

  import datetime
  import time
  fmt_string = '29/05/2005'
  date_tuple = time.strptime(fmt_string, '%d/%m/%Y')
  print date_tuple
(2005, 5, 29, 0, 0, 0, 6, 149, -1)
  date_tuple_minus_tz = date_tuple[0:6]
  print date_tuple_minus_tz
(2005, 5, 29, 0, 0, 0)
  date_obj = datetime.datetime(*date_tuple_minus_tz)

This last line is equivalent to the following:
  date_obj = datetime.datetime(2005, 5, 29, 0, 0, 0)
The * in front of a tuple expands it's arguments when making a function call

  print date_obj
2005-05-29 00:00:0
  print date_obj.day == 5
False

 another question I am getting is that where is the list of all
 formatting characters.  like for example Y is 4 digit year M is month
 MM is month in 2 digits etc.
 I am trying to locate a list of all these denoters.
 can you provide me the place?

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

Look for the strptime() function.

 
 
 Then it's just:

 if date_obj.day == 5:
  print 'It's the fifth day of the month'

 this was much better than the documentation, thanks,
 regards,
 Krishnakant.

Hope that helps.

Ian

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


Re: Berkely Db. How to iterate over large number of keys quickly

2007-08-02 Thread Ian Clark
lazy wrote:
 I have a berkely db and Im using the bsddb module to access it. The Db
 is quite huge (anywhere from 2-30GB). I want to iterate over the keys
 serially.
 I tried using something basic like
 
 for key in db.keys()
 
 but this takes lot of time. I guess Python is trying to get the list
 of all keys first and probbaly keep it in memory. Is there a way to
 avoid this, since I just want to access keys serially. I mean is there
 a way I can tell Python to not load all keys, but try to access it as
 the loop progresses(like in a linked list). I could find any accessor
 methonds on bsddb to this with my initial search.
 I am guessing BTree might be a good choice here, but since while the
 Dbs were written it was opened using hashopen, Im not able to use
 btopen when I want to iterate over the db.
 

db.iterkeys()

Looking at the doc for bsddb objects[1] it mentions that Once 
instantiated, hash, btree and record objects support the same methods as 
dictionaries. Then looking at the dict documentation[2] you'll find the 
dict.iterkeys() method that should do what you're asking.

Ian

[1] http://docs.python.org/lib/bsddb-objects.html
[2] http://docs.python.org/lib/typesmapping.html

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


Re: Bug in execfile?

2007-08-02 Thread Ian Clark
Fernando Perez wrote:
 Hi all,
 
 (snip)
 
 I'm really, really puzzled by this.  From reading the execfile() docs, I had
 the hunch to change the call to:
 
 execfile(fname,{})
 
 and now the problem disappears, so I can keep on working.
 
 But I'm still very bothered by the fact that changing that first call 'if 0'
 to 'if 1' has any effect on the later call to runscript().  That really
 doesn't feel right to me...

First an example:

#foo.py

from math import sin

#EOF

  dir()
['__builtins__', '__doc__', '__name__']
  execfile('foo.py')
  dir()
['__builtins__', '__doc__', '__name__', 'sin']

New session:
  dir()
['__builtins__', '__doc__', '__name__']
  execfile('foo.py', {})
  dir()
['__builtins__', '__doc__', '__name__']
  help(execfile)
Help on built-in function execfile in module __builtin__:

execfile(...)
 execfile(filename[, globals[, locals]])

 Read and execute a Python script from a file.
 The globals and locals are dictionaries, defaulting to the current
 globals and locals.  If only globals is given, locals defaults to 
  it.

By default execfile works on the *current* namespace. So exec'ing a 
script that modified it's global namespace will also modify the global 
namespace of the calling module (see my first example). If you specify a 
dictionary then execfile will use that as the global and local (maybe) 
namespace of the file that it is running (hence the global namespace of 
the calling module stays in tact per the second example). That is why 
execfile(fname, {}) works for you, it doesn't pollute your current 
namespace. It uses a different namespace when calling the file then is 
being used by the calling module.

No idea why your function failed though. *shrug*

Ian

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


Re: (no) fast boolean evaluation ?

2007-08-02 Thread Ian Clark
Stef Mientki wrote:
 hello,
 
 I discovered that boolean evaluation in Python is done fast
 (as soon as the condition is ok, the rest of the expression is ignored).
 
 Is this standard behavior or is there a compiler switch to turn it on/off ?
 
 thanks,
 Stef Mientki

It's called short circuit evaluation and as far as I know it's standard 
in most all languages. This only occurs if a conditional evaluates to 
True and the only other operators that still need to be evaluated are 
'or's or the condition evaluates to False and all the other operators 
are 'and's. The reason is those other operators will never change the 
outcome: True or'd with any number of False's will still be True and 
False and'ed to any number of Trues will still be False.

My question would be why would you *not* want this?

Ian

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


Re: Awkward format string

2007-08-01 Thread Ian Clark
beginner wrote:
 Hi,
 
 In order to print out the contents of a list, sometimes I have to use
 very awkward constructions. For example, I have to convert the
 datetime.datetime type to string first, construct a new list, and then
 send it to print. The following is an example.
 
   x=(e[0].strftime(%Y-%m-%d), e[1].strftime(%Y-%m-%d))+e[2:]
   print  f, %s\t%s\t%d\t%f\t%f\t%f\t%d % x
 
 e is a tuple. x is my new tuple.
 
 Does anyone know better ways of handling this?
 
 Thanks,
 Geoffrey
 

 import datetime
 old_tuple = (
... datetime.datetime(2007, 8, 1),
... datetime.datetime(2007, 8, 2),
... 1,
... 2.0,
... 3.0,
... 4
... )
 first_date = old_tuple[0].strftime('%Y-%m-%d')
 second_date = old_tuple[1].strftime('%Y-%m-%d')
 new_tuple = (first_date, second_date) + old_tuple[2:]
 print '\t'.join(str(i) for i in new_tuple)
2007-08-01  2007-08-02  1   2.0 3.0 4

Without more information that's the best I can think of.

Ian

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


Re: Awkward format string

2007-08-01 Thread Ian Clark
Gerard Flanagan wrote:
 (snip)

 def tostring(data):
 return tuple(strftime(x) for x in data[:2]) + data[2:]
 

Hrmm, not sure that having a function named tostring() that returns a 
tuple is the best idea. ;)

Ian

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


Re: Inverse of id()?

2007-05-20 Thread Ian Clark
On 5/20/07, Michael Hoffman [EMAIL PROTECTED] wrote:
  [snip]
 That's not what I get:

 Python 2.5 (r25:51908, Mar 13 2007, 08:13:14)
 [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin
 Type help, copyright, credits or license for more information.
   class A: pass
 ...
   class B: pass
 ...
   a = A()
   id(a)
 2146651820
   b = B()
   id(b)
 2146651948
 --
 Michael Hoffman

That's because you didn't have 'del a'.

Now I tried this in the shell and got different id's for a and b, but
when I typed it into a file and ran from there the id's where always
the same. Must have something to do with other programs allocating
space faster than I can type everything out (I do have a few processes
going). Interesting.

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


Re: need help with python

2007-05-11 Thread Ian Clark
On 11 May 2007 18:47:27 -0700, [EMAIL PROTECTED]
[EMAIL PROTECTED] wrote:
 ya so im pretty much a newb to this whole python thing... its pretty
 cool but i just started today and im already having trouble.  i
 started to use a tutorial that i found somewhere and i followed the
 instructions and couldnt get the correct results.  heres the code
 stuff...

 temperature=input(what is the temperature of the spam?)
 if temperature50:
 print the salad is properly cooked.
 else:
 print cook the salad some more.

 ya i was trying to do that but when i told it what the spams
 temperature was, it just turned off... well it wasnt working at all at
 first until i realized that i hadnt been following the instructions
 completely correctly and that i was supposed to type that code up in a
 notepad then save and open with python... so ya thats when it asked me
 what temperature the spam was and i typed a number then it just closed
 itself... im not really sure what went wrong... itd be real nice if
 someone would be like a mentor or something...


I'm making a couple of assumptions here (correct me if I'm wrong):

1. You're using windows
2. You double clicked on the .py file

What this does is open up a new terminal window and start execution of
the program. The program will execute to completion and then the
window will close automatically without waiting for you to tell it to
(lovely isn't it?). To get around this you have a couple options:

1. Run the script from the command line
2. Put this at the end of the .py file: input('Press ENTER to continue')

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


Re: e-mailing multiple values

2007-05-08 Thread Ian Clark
On 5/8/07, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:

 I have a script which has a method which returns multiple strings at once 
 using the yield. I would like to send an e-mail of these values in a single 
 e-mail instead of a mail for each string. How would I be able to do that?

 Thanks
 AJ

Are you looking for something like the following? If not, try posting
a small sampling of your code.

 def get_data():
... data = ['ham', 'eggs', 'spam']
... for item in data:
... yield item
...
 all_data = [item for item in get_data()]
 all_data
['ham', 'eggs', 'spam']

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


Re: FW: Re: e-mailing multiple values

2007-05-08 Thread Ian Clark
On 5/8/07, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 Thanks.
 That does help. When teh script sends a mail of the list item(all_data), the 
 data shows up like this:

 [('   Ham\n', '   eggs \n'),
 ('   chicken  \n', '   thighs \n')]

 So I have to figure out a way to cleanup the content

 Thanks
 Anil

Have to run, but look at strip() on string objects.

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


Re: curses mystical error output

2007-05-02 Thread Ian Clark
On 5/2/07, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 I have a fairly simple curses app which is giving me this error:

 addstr() returned ERR

 I'm trapping it and continuing.  I can see that *some* of my addstring calls
 succeed.  This one happens to be

 screen.addstr(row, 39, |)

 where row is 3.

You might be trying to write to a section that is currently off
screen. Seems to me when I was doing some curses stuff that when I
tried to write to one more row than could be fit onto my terminal that
error would come up.

Try doing the following code and make sure that you can enough space to draw it.

 (height, width) = screen.getmaxyx()

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


Re: Slicing Arrays in this way

2007-05-02 Thread Ian Clark
Yeah, having an elegant_solution() function would solve soo many of my
problems. ;)

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


Re: Removing the continous newline characters from the pythong string

2007-05-01 Thread Ian Clark
On 1 May 2007 14:30:12 -0700, mobil [EMAIL PROTECTED] wrote:
 Hi guys i m trying out newline characters and to clean them up
 a\n\n\n\n\n\n\n\n\nsss\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nvsa\n\n\n\nasf
 \n\nafs

 hello guys

 im trying to replace
 \n\n\n\n\n\n\n\n\n with \n

 thanks for help

 \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n also with \n as the browser gives
 \r carrriage returns

 thanks for any help or pointers

Is this what you were looking for?

 import re
 message = '\n\r\n\r\n\n\nhello there\n\r\n!\n'
 regex = re.compile('[\n\r]+')
 regex.sub('\n', s)
'\nhello there\n!\n'

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


Re: Read and Write the same file

2007-05-01 Thread Ian Clark
On 1 May 2007 16:03:28 -0700, JonathanB [EMAIL PROTECTED] wrote:
 Ok, so this is the scenario. I need to create a simple, no-frills XML
 editor for non-technical users. It doesn't have to do anything fancy,
 what I want is a series of text boxes with the text contents of the
 elements pre-printed. Then the users can type their changes into the
 text boxes and click submit and it will load the changes in. So here
 is the problem, this means I need to open the same file as both read
 and write. How do I do this? I'm slowly learning the DOM stuff that I
 need to know to do this, but this file thing I haven't been able to
 find anywhere.

 JonathanB

Well the most straight forward approach is to read data from the file
into memory. Let the user make any changes. Then save the data back to
the file, overwriting the oringinal copy. Now, this only really works
if you're dealing with small files.

Regardless though, you never really need to have a file open for both
reading and writing. Since they occur (so it sounds) at distinct times
during your program flow, just open it twice: the first to read, the
second to write.

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


Re: strip newline from string

2007-04-28 Thread Ian Clark
On 4/28/07, James [EMAIL PROTECTED] wrote:
[snip]
  username = getuser()
  string.strip
 (username)
  print username is %s % username
[snip]


 The autoconf.txt contains two lines, which first has an ip address and
 second a username. The problem I'm having is that the string.strip() doesn't
 appear to be stripping the newline off the username.


 Any ideas? If you need more information, just ask!


 James

string.strip() returns a copy of the string with whitespace removed,
it does not modify it in place. What you really want is:
 username = getuser().strip()

Someone correct me if I'm wrong, but I believe just about all
functions from the string module are deprecated. Use the methods from
the string class. As I'm assuming getuser() returns a string object,
just use the string functions on that directly.

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


Re: creating an object from base class

2007-04-27 Thread Ian Clark
Quote iogilvy:
 i wish to have some extended functionality added to sockets

 i can create my own socket class   class mysocket(socket.socket):

 and all should be fine. Except, the sockets are created for me by the
 accept method, listening on port. So how can i take the standard
 socket created for me and create a 'mysocket'. I need a method that
 will initialise any new properties i have added in my class, but how
 can i change the class of the socket created?


Someone correct me if I'm wrong, but I don't believe it's possible to
change the type of objects made from builtin classes. Though if it's a
custom class you can, for example:

 class Foo: pass
 class Bar: pass
 obj = Foo()
 obj.__class__ = Bar


One option is to make your custom socket a wrapper around
socket.socket and then pass through the calls you don't want to handle
to socket.socket. The downside to this is there are quite a lot of
methods that need to be accounted for. For example:

 class CustomSocket:
 def __init__(self, socket):
 self.socket = socket
 def connect(self, address):
 self.socket.connect( address + '.some.tld' )
 [etc]

 ...

 s = server_socket.accept()
 s = CustomSocket(s)


Another approach you might want to look at is populating your object
at runtime through a function. This won't give it the type you want,
but it will give it any methods and attributes it would have gotten
from your class with the added benefit of it still being of type
socket.socket. Example:

 def modify_socket( socket ):
 socket.cabbages = 'Yuk'
 socket.apples = 'Yum'

 def info():
 print 'Cabbages? %s\nApples? %s' % (socket.cabbages, socket.apples)
 obj.show_info = info

 ...

 s = server_socket.accept()
 modify_socket( s )
 s.show_info()
Cabbages? Yuk
Apples? Yum
 s.apples = 'Yummie'
 s.show_info()
Cabbages? Yuk
Apples? Yummie
 type(s)
class 'socket._socketobject'

Good luck.

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


Re: mysql rows affected

2007-04-26 Thread Ian Clark

Both cursor.execute() and cursor.executemany() return the number of rows
affected.

Here is a link to the documentation:
http://mysql-python.sourceforge.net/MySQLdb-1.2.2/public/MySQLdb.cursors.BaseCursor-class.html#execute

Ian

On 4/26/07, Carl K [EMAIL PROTECTED] wrote:


using MySQLdb, I do cursor.execute(update...)

How can I tell how many rows were affected ?

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

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