[Tutor] not invoking the shell from python

2005-06-21 Thread Shuying Wang
Hi tutors,

I've got an external program that I'm calling from python with
os.popen. The problem is that I need to pass this program an arbitrary
body of text. I've tried escaping characters before passing it as
input but the shell still expands out certain characters. I noticed
with python2.4. How do I bypass the shell and hand arguments directly
to the program?

The problematic line in question looks like this:
os.popen('''rt create -t ticket set requestor='%s' owner='%s'
queue='%s' subject="%s" text="%s" status='%s' ''' %
  (data['requestor'],data['owner'],data['queue'],
re.sub(r'\"',r'\\"',data['subject']), re.sub(r'\"',r'\\"',
data['body']), data['status'])

thanks in advance,
Shuying
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Importing from directories below yourself...

2005-06-21 Thread lawrence wang
Say I have a directory tree like this:

foo
- bar
 -- quux.py
- baz
 -- glonk.py

>From within glonk.py, how do I import quux.py? I've tried going to
foo, running baz/glonk.py, and using "from bar import quux", but this
doesn't seem to work.

Thanks in advance!
Lawrence
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Importing from directories below yourself...

2005-06-21 Thread Kent Johnson
lawrence wang wrote:
> Say I have a directory tree like this:
> 
> foo
> - bar
>  -- quux.py
> - baz
>  -- glonk.py
> 
>>From within glonk.py, how do I import quux.py? I've tried going to
> foo, running baz/glonk.py, and using "from bar import quux", but this
> doesn't seem to work.

You need a file named __init__.py in bar/. The file can be empty; it is a 
marker that tells Python to treat bar/ as a package.

You will also need __init__.py in baz/ if you want to be able to import glonk 
from another module.

See http://docs.python.org/tut/node8.html#SECTION00840

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] not invoking the shell from python

2005-06-21 Thread Alan G
> input but the shell still expands out certain characters. I noticed
> with python2.4. How do I bypass the shell and hand arguments
directly
> to the program?

The first thing I'd do is create the command string before passing
it to popen - that way we can debug easier by seeing exactly what
is being passed through!

> The problematic line in question looks like this:

cmd = '''rt create -t ticket set requestor='%s' owner='%s'
queue='%s' subject="%s" text="%s" status='%s' ''' %
(data['requestor'],
data['owner'],
data['queue'],
re.sub(r'\"',r'\\"',data['subject']),
re.sub(r'\"',r'\\"',data['body']),
data['status'])
# your code was missing the closing parens above but I assume
# that was just a posting error?

print cmd   # for debug only
os.popen(cmd)

See if the line you are producing is what you think it should be.
Try typing it in at the shell and see if you get the same effect?

Without knowing the details of your data its hard to say much more.

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] who called the class method?

2005-06-21 Thread David Driver
Is there a way to test if a class method was called from an instance? 

What I am trying to do is if a method is called from the class return
a commanding proxy with an mock or stub type object as the proxied
object. If it is called from the instance I want to return a proxy for
the instance.

Does what I am trying to do make sense?

Thanks!
-- 

***
See there, that wasn't so bad.
***
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] MySQL Connection Function

2005-06-21 Thread Don Parris
As a newbie developer, the easiest way for me to connect to MySQL is to
just copy & paste the connection commands into each funtion I write. 
However, I know that's far from ideal, and consumes more time than its
worth.  I would like to create a MySQL connection function that I can just
call up whenever I need it from within an other function.

### The Connection Definition ###
# def mysql_Conn():
# Create a connection object and create a cursor.
# Con = MySQLdb.Connect(host="127.0.0.1", port=3306, user="user",
  passwd="password", db="chaddb_test")   # email text wrap here
# Cursor = Con.cursor()

### The function that Calls the Connection ###
def mbr_Roster():
mysql_Conn()

# Make SQL string and execute it.
sql = "SELECT fst_name, lst_name FROM person\
where env_num is not null\
order by lst_name"
Cursor.execute(sql)

# Fetch all results from the cursor into a sequence and close the
# connection.
Results = Cursor.fetchall()
Con.close()

How do I get mbr_Roster() to recognize the 'Cursor' from mysql_Conn()?  Do I
need to declare the cursor as a global variable?

>From the Traceback:
global name 'Cursor' is not defined


Don
-- 
evangelinuxGNU Evangelist
http://matheteuo.org/   http://chaddb.sourceforge.net/
"Free software is like God's love - you can share it with anyone anytime
anywhere."
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] MySQL Connection Function

2005-06-21 Thread Pujo Aji
This a very simple connection using mysql.

1. connect to mysql:
db = mySQLdb.connect(user='root',passwd='something')

2. To execute and get the result:
c = db.cursor()
c.execute(sql comment)
result = c.fetchall()

you can wrap it in a class object.

pujo

On 6/21/05, Don Parris <[EMAIL PROTECTED]> wrote:
> As a newbie developer, the easiest way for me to connect to MySQL is to
> just copy & paste the connection commands into each funtion I write.
> However, I know that's far from ideal, and consumes more time than its
> worth.  I would like to create a MySQL connection function that I can just
> call up whenever I need it from within an other function.
> 
> ### The Connection Definition ###
> # def mysql_Conn():
> # Create a connection object and create a cursor.
> # Con = MySQLdb.Connect(host="127.0.0.1", port=3306, user="user",
>   passwd="password", db="chaddb_test")   # email text wrap here
> # Cursor = Con.cursor()
> 
> ### The function that Calls the Connection ###
> def mbr_Roster():
> mysql_Conn()
> 
> # Make SQL string and execute it.
> sql = "SELECT fst_name, lst_name FROM person\
> where env_num is not null\
> order by lst_name"
> Cursor.execute(sql)
> 
> # Fetch all results from the cursor into a sequence and close the
> # connection.
> Results = Cursor.fetchall()
> Con.close()
> 
> How do I get mbr_Roster() to recognize the 'Cursor' from mysql_Conn()?  Do I
> need to declare the cursor as a global variable?
> 
> >From the Traceback:
> global name 'Cursor' is not defined
> 
> 
> Don
> --
> evangelinuxGNU Evangelist
> http://matheteuo.org/   http://chaddb.sourceforge.net/
> "Free software is like God's love - you can share it with anyone anytime
> anywhere."
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Built-in modules

2005-06-21 Thread Alberto Troiano
Hey tutors

I have some classes I want to make available as built-in modules in Python 
2.3.4 over Windows
To make myself clear in case you don't understand I have the file List.py (a 
nested list C# like) and I want to be able to call the class List (which is 
inside the List.py) without having to copy it in every folder where I have a 
script that needs this module

Can I do that?

You see I googled about it but it seems I'm not using the right words.

Best Regards

Alberto


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] who called the class method?

2005-06-21 Thread Kent Johnson


David Driver wrote:
> Is there a way to test if a class method was called from an instance? 
> 
> What I am trying to do is if a method is called from the class return
> a commanding proxy with an mock or stub type object as the proxied
> object. If it is called from the instance I want to return a proxy for
> the instance.

Hmm. Why not just differentiate them at the point of call? If you want to do
class T(object):
  @classmethod
  def foo(cls):
pass

instead of t.foo() and T.foo() use t.foo_from_instance() and 
T.foo_from_class()??

If you must, I can think of two ways to do this. The __get__() method of a 
property has an instance parameter which is the instance or None, you could use 
that. Or you can use __new__() to create an instance method that shadows the 
classmethod. 


class Test2(object):
class _foo(object):
''' A descriptor for Test2.foo '''
def __get__(self, instance, owner):
# Test2.foo returns a function
def _fooImpl():
Test2.fooImpl(instance)
return _fooImpl

foo = _foo()
del _foo

@classmethod
def fooImpl(cls, instance):
print 'fooImpl called with instance =', instance

t = Test2()
t.foo()
Test2.foo()


import new

class Test(object):
def __new__(cls):
def foo(self):
print 'foo() called from an instance'
instance = object.__new__(cls)
instance.foo = new.instancemethod(foo, instance, Test)
return instance

@classmethod
def foo(cls):
print 'foo() called as a classmethod'


t = Test()
t.foo()
Test.foo()


If you ask on comp.lang.python you will probably get more clever answers but 
really, why do you need to do this?

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Built-in modules

2005-06-21 Thread Kent Johnson
Alberto Troiano wrote:
> Hey tutors
> 
> I have some classes I want to make available as built-in modules in Python 
> 2.3.4 over Windows
> To make myself clear in case you don't understand I have the file List.py (a 
> nested list C# like) and I want to be able to call the class List (which is 
> inside the List.py) without having to copy it in every folder where I have a 
> script that needs this module

In your Python23\Lib folder make a folder called site-packages. (If you already 
have one that's OK too.) Put List.py in site-packages. It will be available to 
any Python program.

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Class vs. Static Methods

2005-06-21 Thread Chuck Allison
Sorry for the elementary question: I was wondering if someone could
explain the difference to me between class and static methods. Coming
from other languages, I'm used to static methods, but not "class
methods". Thanks.

-- 
Best regards,
 Chuck

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] loading an image into a Postgre database

2005-06-21 Thread Mike Hansen
I'm having trouble loading an image into a Postgre database. The code is below 
as well as the traceback in the apache log. Is something up with my 
sqlStatement? Do I need to use something other than %s? How can I avoid that 
type error?

Thanks,

Mike


#! /usr/bin/env python

import cgi
from pyPgSQL import PgSQL
# from pyPgSQL.PgSQL import PgBytea

def main():
 form = cgi.FieldStorage()
 if form.has_key("filename"):
 item = form["filename"]
 imageName = form["imagename"]
 if item.file:
 data = item.file.read()
 data_obj = PgSQL.PgBytea(data)
 connectdb =PgSQL.connect('server:port:database:username:password')
 cur = connectdb.cursor()
 sqlStatement = """INSERT INTO images (image)
   VALUES (%s);
""" % (data_obj)
 cur.execute(sqlStatement)
 cur.close()
 connectdb.commit()
 print "Content-type: text/html\n\n"
 print "image loaded"


if __name__ == '__main__':
 main()


Traceback (most recent call last):
   File "/var/www/htdocs/mtest/imagetest.py", line 28, in ?
 main()
   File "/var/www/htdocs/mtest/imagetest.py", line 20, in main
 cur.execute(sqlStatement)
   File "/usr/lib/python2.3/site-packages/pyPgSQL/PgSQL.py", line 3038, in 
execute
 self.res = self.conn.conn.query(_qstr)
TypeError: query() argument 1 must be string without null bytes, not str
[Tue Jun 21 14:34:46 2005] [error] [client 10.95.100.11] Premature end of 
script 
headers: /var/www/htdocs/mtest/imagetest.py10.95.100.11] Premature end of script
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Class vs. Static Methods

2005-06-21 Thread Chinook
On Tue, 21 Jun 2005 16:52:09 -0400, Chuck Allison wrote
(in article <[EMAIL PROTECTED]>):

> Sorry for the elementary question: I was wondering if someone could
> explain the difference to me between class and static methods. Coming
> from other languages, I'm used to static methods, but not "class
> methods". Thanks.
> 
> 

Does this help (from the QR)?

Static methods : Use staticmethod(f) to make method f(x) static (unbound).
Class methods: like a static but takes the Class as 1st argument => Use f = 
classmethod(f) to make method f(theClass, x) a class method.

The decorators @staticmethod and @classmethod replace more elegantly the 
equivalent declarations f = staticmethod(f) and f = classmethod(f).

Lee C


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] loading an image into a Postgre database

2005-06-21 Thread Danny Yoo


On Tue, 21 Jun 2005, Mike Hansen wrote:

> I'm having trouble loading an image into a Postgre database. The code is
> below as well as the traceback in the apache log. Is something up with
> my sqlStatement? Do I need to use something other than %s? How can I
> avoid that type error?


Hi Mike,

At the moment, you're trying to do the direct value interpolation like
this:

>  sqlStatement = """INSERT INTO images (image)
>VALUES (%s);
> """ % (data_obj)
>  cur.execute(sqlStatement)


The issue is that this style of direct SQL interpolation won't work very
well on non-SQLish data.  Python has no clue what the context of your
interpolation is: when you ask it to do:

##
sqlStatement = """INSERT INTO images (image)
   VALUES (%s); """ % data_obj
##

it has no idea that you're constructing an SQL statement, and it's
oblivious to the special SQL quoting rules you need to use to pass binary
data to the database.


Another instance of this problem comes up even with normal string data:
something like:

cursor.execute("insert into people(name) values ('%s')" % name)

will break as soon as someone with the name "O'Reilly" meets the
application.



Thankfully, you don't have to change much to fix the formatting bug.  The
only thing you'll need to do is let the SQL cursor do the value formatting
for you:

##
sqlStatement = """INSERT INTO images (image)
  VALUES (%s);
cur.execute(sqlStatement, (data_obj))
##

Cursors know how to do the proper value interpolation that's specific to
SQL: just pass the extra values to the execute() function, and the SQL
driver will do the hard work.


Hope this helps!

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] loading an image into a Postgre database

2005-06-21 Thread Danny Yoo
> Thankfully, you don't have to change much to fix the formatting bug.  The
> only thing you'll need to do is let the SQL cursor do the value formatting
> for you:
>
> ##
> sqlStatement = """INSERT INTO images (image)
>   VALUES (%s);
> cur.execute(sqlStatement, (data_obj))
> ##


Hi Mike,


Gaaa.  I was a little sloppy there, wasn't I?  Let me fix that:

##
sqlStatement = """INSERT INTO images (image)
  VALUES (%s);"""
cur.execute(sqlStatement, (data_obj,))
##


My apologies!

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Class vs. Static Methods

2005-06-21 Thread Chuck Allison
Hello Chinook,

So is the main motivation for class methods so that you can have the
class object available? It seems you can have that anyway in a static
method by just asking. I'm sure there's a good reason for this, but I
haven't yet gotten to the point of mastery where I can see a need for
class methods (even after reading Martelli's Nutshell). I understand
the syntax issues - I just don't see the need yet.

Tuesday, June 21, 2005, 3:28:48 PM, you wrote:

C> On Tue, 21 Jun 2005 16:52:09 -0400, Chuck Allison wrote
C> (in article <[EMAIL PROTECTED]>):

>> Sorry for the elementary question: I was wondering if someone could
>> explain the difference to me between class and static methods. Coming
>> from other languages, I'm used to static methods, but not "class
>> methods". Thanks.
>> 
>> 

C> Does this help (from the QR)?

C> Static methods : Use staticmethod(f) to make method f(x) static (unbound).
C> Class methods: like a static but takes the Class as 1st argument => Use f = 
C> classmethod(f) to make method f(theClass, x) a class method.

C> The decorators @staticmethod and @classmethod replace more elegantly the 
C> equivalent declarations f = staticmethod(f) and f = classmethod(f).

C> Lee C


C> ___
C> Tutor maillist  -  Tutor@python.org
C> http://mail.python.org/mailman/listinfo/tutor



-- 
Best regards,
 Chuck

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Numbers & Characters As Dictionary Keys

2005-06-21 Thread Alan G
> >print "%s\t%s" % (m,menu[m][0])
> > 
> I am curious what the "%" by itself is doing.

Its a standard string formatting operation in Python.
The % operator basically says substitute the values 
in the folowing tuple for the marked fields in the 
foregoing string.

The print statement above therefore is roughly equivalent 
to:

print m + '\t' + menu[m][0]

But the formatting markers allow you to add formatting 
data like the minimum number of characters, right/left 
justification, number of digits after a decimal point, 
hex or decimal display of numbers etc etc.

Take a look in the Python docs for string formatting.

Alan G.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] how do i pause a script ?

2005-06-21 Thread nephish
Hey all,
how do i pause a script. like
print 'something'
pause a half second
print 'something else'

any takers?

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] who called the class method?

2005-06-21 Thread David Driver
Ketn

You are correct.

What I will do is an instance method that calls the class method with
an optional parameter.

I don't know what I was thinking, I was just messing around with
nested classes for the first time and kind of forgot how to program.


On 6/21/05, David Driver <[EMAIL PROTECTED]> wrote:
> Is there a way to test if a class method was called from an instance?
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how do i pause a script ?

2005-06-21 Thread Brian van den Broek
nephish said unto the world upon 21/06/2005 20:17:
> Hey all,
> how do i pause a script. like
> print 'something'
> pause a half second
> print 'something else'
> 
> any takers?
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 

Hi,

import time

for i in range(5):
 time.sleep(i)
 print time.asctime()

when run produces:

 >>> Tue Jun 21 18:23:00 2005
Tue Jun 21 18:23:01 2005
Tue Jun 21 18:23:03 2005
Tue Jun 21 18:23:06 2005
Tue Jun 21 18:23:10 2005


6.11 time -- Time access and conversions
"sleep(secs)
 Suspend execution for the given number of seconds. The argument 
may be a floating point number to indicate a more precise sleep time. 
The actual suspension time may be less than that requested because any 
caught signal will terminate the sleep() following execution of that 
signal's catching routine. Also, the suspension time may be longer 
than requested by an arbitrary amount because of the scheduling of 
other activity in the system."
http://docs.python.org/lib/module-time.html

Best,

Brian vdB

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] MySQL Connection Function

2005-06-21 Thread Alan G
> worth.  I would like to create a MySQL connection function that I
can just
> call up whenever I need it from within an other function.

Good idea!

> ### The Connection Definition ###
> # def mysql_Conn():
> # Create a connection object and create a cursor.
> # Con = MySQLdb.Connect(host="127.0.0.1", port=3306,
user="user",
>   passwd="password", db="chaddb_test")   # email text wrap here
> # Cursor = Con.cursor()

return Con.cursor()

> How do I get mbr_Roster() to recognize the 'Cursor' from
mysql_Conn()?
> Do I need to declare the cursor as a global variable?

No you need to return it from your function.
See the topic on modules and functions for more about
returning values from functions.

You might find you need to clear the cursor before using it too.

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] who called the class method?

2005-06-21 Thread Alan G

> Is there a way to test if a class method was called from an
instance?

I think you'll need to override the __getattr__ method.
It will pick up the call and you can test whether its a
class mrethod being called. I think...

> What I am trying to do is if a method is called from the
> class return a commanding proxy with an mock or stub type
> object as the proxied object. If it is called from the
> instance I want to return a proxy for the instance.

I'm not quite sure I understand because you are mixing object
oriented terminology with procedural programming terminology.

I think you mean you want to have a class with various methods.
You may or may not have instances of the class.
You want to know when a method is invoked whether this was via
a direct call of the class's method or via a message being
sent to an instance?

OR do you mean you will have an actual class method
(ie static in C++/Java speak) and want to know if the
activating message was sent to the class object or to
an instance of the class?

Or do you want to know if the class method was invoked
from within another method of the same class or invoked
by a message sent from an instance of another class?

Those are all different scenarios which could be described
by your paragraph above, which do you mean?
Or is it something different again?

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Built-in modules

2005-06-21 Thread Alan G
> nested list C# like) and I want to be able to call the class List
(which is
> inside the List.py) without having to copy it in every folder where
I have a
> script that needs this module
>
> Can I do that?

Yes.

See Kent's reply to a similar post about creating a package.

You can also just copy the module file List.py into a folder
that's in your search path. That works too. But calling it List
is probably bad since Python already has Lists. Maybe you could
rename it something like NestedList? (Whatever that is!)

HTH,

Alan G.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Class vs. Static Methods

2005-06-21 Thread Chinook
On Tue, 21 Jun 2005 17:58:09 -0400, Chuck Allison wrote
(in article <[EMAIL PROTECTED]>):

> Hello Chinook,
> 
> So is the main motivation for class methods so that you can have the
> class object available? It seems you can have that anyway in a static
> method by just asking. I'm sure there's a good reason for this, but I
> haven't yet gotten to the point of mastery where I can see a need for
> class methods (even after reading Martelli's Nutshell). I understand
> the syntax issues - I just don't see the need yet.
> 
> Tuesday, June 21, 2005, 3:28:48 PM, you wrote:
> 
> C> On Tue, 21 Jun 2005 16:52:09 -0400, Chuck Allison wrote
> C> (in article <[EMAIL PROTECTED]>):
> 
>>> Sorry for the elementary question: I was wondering if someone could
>>> explain the difference to me between class and static methods. Coming
>>> from other languages, I'm used to static methods, but not "class
>>> methods". Thanks.
>>> 
>>> 
> 
> C> Does this help (from the QR)?
> 
> C> Static methods : Use staticmethod(f) to make method f(x) static (unbound).
> C> Class methods: like a static but takes the Class as 1st argument => Use f 

> = 
> C> classmethod(f) to make method f(theClass, x) a class method.
> 
> C> The decorators @staticmethod and @classmethod replace more elegantly the 
> C> equivalent declarations f = staticmethod(f) and f = classmethod(f).
> 
> C> Lee C
> 
> 
> C> ___
> C> Tutor maillist  -  Tutor@python.org
> C> http://mail.python.org/mailman/listinfo/tutor
> 
> 
> 
> 

Chuck,

Being fairly new to Python myself, I know how to create them and how to 
reference them.  I also know to use a static method in a factory pattern 
because it's name is then local to the scope it is defined in and it is 
called without an instance argument.  Mostly they work like simple functions 
that happen to be coded inside a class.  Static methods are usually used with 
class attributes to manage information that spans all instances generated 
from a class (a book's example is keeping track of the number of instances 
generated from a class).  Class methods are similar, but Python automatically 
passes the class (not an instance) into the method's leftmost argument.  

I have also read that such was introduced to clear up a gotcha before Python 
2.3

Yea, yea, your saying, but you never answered my question :~)  All I can 
relate to at this point in my learning cycle is that it's all a name space 
issue (re: instance, static and class).  Maybe one of the gurus can enlighten 
both of us further.  

Lee C


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Numbers & Characters As Dictionary Keys

2005-06-21 Thread [EMAIL PROTECTED]
-- Original Message -
Subject: Re: [Tutor] Numbers & Characters As Dictionary Keys
Date: Tue, 21 Jun 2005 17:47:41 +0100
From: "Alan G" <[EMAIL PROTECTED]>
To: "Don Parris" <[EMAIL PROTECTED]>,
"Python Tutor List" 


> >print "%s\t%s" % (m,menu[m][0])
> > 
> I am curious what the "%" by itself is doing.

Its a standard string formatting operation in Python.
The % operator basically says substitute the values 
in the folowing tuple for the marked fields in the 
foregoing string.

The print statement above therefore is roughly equivalent 
to:

print m + '\t' + menu[m][0]

But the formatting markers allow you to add formatting 
data like the minimum number of characters, right/left 
justification, number of digits after a decimal point, 
hex or decimal display of numbers etc etc.

Take a look in the Python docs for string formatting.

I was able to understand the '\t' and the '%s'.  It was that lone % sign that 
made it look weird to me.  I will be digging into the string formatting stuff, 
for sure.  I'm hoping to produce an output format that will be acceptable for 
certain organizations.  When I cannot focus on the MySQL portion of this app, 
I'll be focusing on the other aspects.  I seem to be able to build simple 
functions.  It's when I want to reduce the amount of code I have to write that 
I start running into issues. :)

Don

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Class vs. Static Methods

2005-06-21 Thread Alan G

> Sorry for the elementary question: I was wondering if someone could
> explain the difference to me between class and static methods.
Coming
> from other languages, I'm used to static methods, but not "class
> methods". Thanks.

There probably is a deep and subtle difference in Python but to
all intents and purposes they are the same thing.

class method is the original and logically correct name and has
been around in Smalltalk, Objective C, Lisp and most early OOP
languages for a long time. It means a method of the class itself
rather than of an instance and is typically used to perform
an operation on the entire class - ie all the existing instances.

The term 'static' comes from C++ where it refers to the fact
that the code for static methods lives on the heap rather
than the stack and so is persistent and the variables
effectively shared - this echos C's use of 'static' variables.
Java and Object Pascal copied the name from C++ and now Python
seems to have adopted both names just to accomodate all tastes!

Alan G.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Class vs. Static Methods

2005-06-21 Thread Kent Johnson
Chuck Allison wrote:
> Hello Chinook,
> 
> So is the main motivation for class methods so that you can have the
> class object available? It seems you can have that anyway in a static
> method by just asking.

No, a classmethod is passed the class that it is called on. If you have an 
inheritance tree you don't know this with a staticmethod.

 >>> class Test(object):
 ...   @staticmethod
 ...   def static(): # no args
 ... print 'I have no clue how I was called'
 ...   @classmethod
 ...   def cls(cls):
 ... print 'I was called on class', cls
 ...
 >>> t=Test()
 >>> t.static()
I have no clue how I was called
 >>> t.cls()
I was called on class 
 >>>
 >>> class T2(Test):
 ...   pass
 ...
 >>> t2=T2()
 >>> t2.static()
I have no clue how I was called
 >>> t2.cls()
I was called on class 
 >>> T2.cls()
I was called on class 

I can't think of a good use case for this at the moment...maybe some factory 
functions might care...

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] MySQL Connection Function

2005-06-21 Thread Python
As a newbie developer, the easiest way for me to connect to MySQL is to
> just copy & paste the connection commands into each funtion I write. 
> However, I know that's far from ideal, and consumes more time than its
> worth.  I would like to create a MySQL connection function that I can just
> call up whenever I need it from within an other function.

I like to use the following style of code.  Since there will be
passwords, the connection strings should be somewhat protected.  Put
them in a separate file that can be controlled.  Here's my sample code.
>>>
#! /usr/bin/python
# sqlconnect.py
import MySQLdb as SQLdb

db_parms = {
'regular': {
'host': 'localhost',
'user':'regular_user',
'passwd':'password',
'db':'some_database',
},
'premium': {
'host':'localhost',
'user':'premium_user',
'passwd':'password',
'db': 'SGSG02',
},
"super": {
'host': 'localhost',
'unix_socket': '/var/lib/superdb/mysql.sock',
'user':'super_user',
'passwd':'password',
'db':'some_database',
},
}

def connect( parm_name):
parms = db_parms[parm_name]
return SQLdb.connect( **parms)


Use a dictionary to save the connect parameters.  Different users and
circumstances can require different parameters.  To use this code

import sqlconnect as sql
conn = sql.connect('regular')

# then get a cursor so that you can do something to the database
curs = conn.Cursor()
curs.execute(Some_SQL_Command)
results = curs.fetchall()
curs.close()

Your example code seems to view getting a connection and a cursor as
closely related.  Typically, a connection is kept for the life of the
application process and cursors are created, used, and closed as needed.


-- 
Lloyd Kvam
Venix Corp

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] who called the class method?

2005-06-21 Thread David Driver
You are right to be confused because I was as well. I was shooting for:

> OR do you mean you will have an actual class method
> (ie static in C++/Java speak) and want to know if the
> activating message was sent to the class object or to
> an instance of the class?

The easiest solution was to do a class method 'GetDefaultProxy' that
creates the default object (a stub with initial values) and creates
the proxy with it and an instance method 'GetInstanceProxy' that
creates the proxy for the already instanced object.

I am working on integrating sqlobject with formencode's validators and
a commanding proxy. Partly as an academic exercise. It is the biggest
OO project that I have ever tried in any language and it has turned
out to be pretty neat. There are a few details to work out but in the
end I think that I will have something special.

On 6/21/05, Alan G <[EMAIL PROTECTED]> wrote:
> 
> > Is there a way to test if a class method was called from an
> instance?
> 
> I think you'll need to override the __getattr__ method.
> It will pick up the call and you can test whether its a
> class mrethod being called. I think...
> 
> > What I am trying to do is if a method is called from the
> > class return a commanding proxy with an mock or stub type
> > object as the proxied object. If it is called from the
> > instance I want to return a proxy for the instance.
> 
> I'm not quite sure I understand because you are mixing object
> oriented terminology with procedural programming terminology.
> 
> I think you mean you want to have a class with various methods.
> You may or may not have instances of the class.
> You want to know when a method is invoked whether this was via
> a direct call of the class's method or via a message being
> sent to an instance?
> 
> OR do you mean you will have an actual class method
> (ie static in C++/Java speak) and want to know if the
> activating message was sent to the class object or to
> an instance of the class?
> 
> Or do you want to know if the class method was invoked
> from within another method of the same class or invoked
> by a message sent from an instance of another class?
> 
> Those are all different scenarios which could be described
> by your paragraph above, which do you mean?
> Or is it something different again?
> 
> Alan G
> Author of the Learn to Program web tutor
> http://www.freenetpages.co.uk/hp/alan.gauld
> 
> 


-- 

***
See there, that wasn't so bad.
***
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] MySQL Connection Function

2005-06-21 Thread Don Parris
On Tue, 21 Jun 2005 19:13:43 -0400
Python <[EMAIL PROTECTED]> wrote:

 
> I like to use the following style of code.  Since there will be
> passwords, the connection strings should be somewhat protected.  Put
> them in a separate file that can be controlled.  Here's my sample code.
> >>>
>

> 
> Your example code seems to view getting a connection and a cursor as
> closely related.  Typically, a connection is kept for the life of the
> application process and cursors are created, used, and closed as needed.
> 
> 
I'll be tinkering with your suggestion tonight.  You're absolutely correct,
though - my view of the connection & cursor is as you say.  Thanks for
correcting my understanding.  I've gotten that impression based on the
rather brief examples used in the tutorials.  They merely give an example of
connecting to the database and closing the connection, without describing
the reality of the process.

Don
-- 
evangelinuxGNU Evangelist
http://matheteuo.org/   http://chaddb.sourceforge.net/
"Free software is like God's love - you can share it with anyone anytime
anywhere."
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] List of regular expressions

2005-06-21 Thread Shidan
Hi I have a list of regular expression patterns like such:

thelist = 
['^594694.*','^689.*','^241.*','^241(0[3-9]|1[0145]|2[0-9]|3[0-9]|41|5[1-37]|6[138]|75|8[014579]).*']


Now I want to iterate thru each of these like:

for pattern in thelist:
regex=re.compile(pattern)
if regex.match('24110'):
the_pattern = pattern
.
.
sys.exit(0)

but in this case it will pick thelist[2] and not the list[3] as I wanted to,
how can I have it pick the pattern that describes it better from the list.

Thanks for your help and advice in advance,
Shidan
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] not invoking the shell from python

2005-06-21 Thread Hugo González Monteverde
Hi Wang,

You need to do what the shell does, all up the program directly, like this:

fork parent,
in the parent, reap the child
in the child, call exec() with the subprogram as the argument

Here's an example:

import os

program_executable = "/bin/ls"
parameters = ["/home/me/file1.txt", "/home/me/file2.txt"]

pid = os.fork()

if pid==0: #I'm the child
os.execv(program_executable, program_executable + parameters)
else: #I'm the parent
os.waitpid(-1) #wait and reap a child process

--
I have not been able to test it since I'm in Windows but this should do. 
This is basically just an implementation of what system() does... the 
waitpid() step is necessary in order not to leave a zombie process lying 
around.

Hope it helps,

Hugo


Shuying Wang wrote:
> Hi tutors,
> 
> I've got an external program that I'm calling from python with
> os.popen. The problem is that I need to pass this program an arbitrary
> body of text. I've tried escaping characters before passing it as
> input but the shell still expands out certain characters. I noticed
> with python2.4. How do I bypass the shell and hand arguments directly
> to the program?
> 
> The problematic line in question looks like this:
> os.popen('''rt create -t ticket set requestor='%s' owner='%s'
> queue='%s' subject="%s" text="%s" status='%s' ''' %
> (data['requestor'],data['owner'],data['queue'],
> re.sub(r'\"',r'\\"',data['subject']), re.sub(r'\"',r'\\"',
> data['body']), data['status'])
> 
> thanks in advance,
> Shuying
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor