[Tutor] question re: executing exe files with arguments

2007-05-18 Thread Janani Krishnaswamy
Hi!
I am having trouble executing an exe file with 3 arguments within a
python script.  Right now I have something like this:

os.system(r'"1/2/3/program 1/2/3/argument1 1/2/3/argument2"')

I was trying it with a raw string because of the /'s within it.  I'm not
sure of any other approaches.

Any advice would be greatly appreciated!

Thanks!

Janani 

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


Re: [Tutor] Question about formating string with dictionary

2007-04-26 Thread John Fouhy
On 27/04/07, Shuai Jiang (Runiteking1) <[EMAIL PROTECTED]> wrote:
> Hello everyone,
>
> The program that I am working on right now have a template for string
> formatting.
> My question is that is it possible to use multiple dictionary to format the
> string.
>
> For example
> x = {'foo':1234, 'bar': 5678}
> y = {'spam':'hello','cheese':'good-bye'}
>
> is there any way to use his pseudo code
> template = \
> """Foo = %(foo)s
> bar = %(bar)s
> spame = %(spam)s
> cheese = %(cheese)s"""
>
> print template %x,y

My best suggestion would be to write a function to combine multiple
dictionaries into one.  eg:

def combine(*dicts):
""" Combine multiple dictionaries into one.  Rightmost
dictionaries have precedence. """
res = {}
for d in dicts:
res.update(d)
return res

Then:

x = {'foo':1234, 'bar': 5678}
y = {'spam':'hello','cheese':'good-bye'}

"""Foo = %(foo)s
bar = %(bar)s
spame = %(spam)s
cheese = %(cheese)s""" % combine(x, y)

HTH!

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


[Tutor] Question about formating string with dictionary

2007-04-26 Thread Shuai Jiang (Runiteking1)

Hello everyone,

The program that I am working on right now have a template for string
formatting.
My question is that is it possible to use multiple dictionary to format the
string.

For example
x = {'foo':1234, 'bar': 5678}
y = {'spam':'hello','cheese':'good-bye'}

is there any way to use his pseudo code
template = \
"""Foo = %(foo)s
bar = %(bar)s
spame = %(spam)s
cheese = %(cheese)s"""

print template %x,y

Thanks

Marshall
--
I like pigs. Dogs look up to us. Cats look down on us. Pigs treat us as
equals.
   Sir Winston Churchill
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question on UserDict class - copy function

2007-04-24 Thread Rikard Bosnjakovic
On 4/24/07, Ketan Joshi <[EMAIL PROTECTED]> wrote:

> If so, why isn't this function defined as:
>
> def copy(self):
> import copy
> return copy.copy(self)

The if-case in your code makes sure that the property __class__ is of
UserDict-inheritance. I believe it's there in case of multiple
classes.

class Gas:
  def __init__(self):
pass
class Oil:
  def __init__(self):
self.foo = Gas()
self.dict = UserDict()

b = Oil()

b.__class__ will be __main__.Oil, and if you pass the entire class
around and want a copy of the dict-property, the copy()-method in
UserDict will first it is a UserDict-instance before copying it. If it
isn't, it creates one out of the existing data.


-- 
- Rikard - http://bos.hack.org/cv/
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Question on UserDict class - copy function

2007-04-24 Thread Ketan Joshi
Hello All,

I am very new to Python scripting. I have just started learning about Python. 
I have a question regarding UserDict class.

UserDict class has a copy function which is defined as follows:
def copy(self):
if self.__class__ is UserDict:
return UserDict(self.data)
import copy
return copy.copy(self)

Here, as I understand, copy module is capable of making a copy of any python 
object. If so, why isn't this function defined as:

def copy(self):
import copy
return copy.copy(self)

In other words, what is the need to use the if statement first and then import 
the copy module?
if self.__class__ is UserDict:

return UserDict(self.data)

Thanks and Regards,
Ketan Joshi



__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com ___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question about cgi module

2007-04-20 Thread Andreas Kostyrka
* Mike Hansen <[EMAIL PROTECTED]> [070420 22:32]:
> Part of the web app that I'm writing will allow users to upload small
> images to be stored in a database. Is there a way to limit how big of a
> file that the user can upload? Is there some cgi setting that would
> prevent a user from upload a huge file, or stop at a certain size and
> error?

Not really. Perhaps.

You need envision the situtation:

http wise, the client assembles its request, and starts to send it to
the server. the http server is allowed to drop a http connection
anytime, and because file uploads are POSTs, the client should not
resent it without manual intervention by the user.

cgi wise, you need to check how your http server handles it.

Furthermore, you've got the little problem, that the standard cgi
module probably won't support that directly.

After having taken a view on the technical side, let's look at it from
the users perspective:

a) the error comes after the file was uploaded. Not much you can do
against that (Well, if you manage to interpret a Content-Length
header, you might abort the upload earlier, in theory).

b) aborting the request gives no sensible feedback to the user.

The typical solution for that is to use AJAX:

1.) get an unique id for the upload.
2.) post the file to an url containing the unique id.
3.) check the status of the upload via an AJAX method to give sensible
status messages, including errors.

(you need the unique id so that the AJAX calls can retrieve the status)

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


[Tutor] Question about cgi module

2007-04-20 Thread Mike Hansen
Part of the web app that I'm writing will allow users to upload small
images to be stored in a database. Is there a way to limit how big of a
file that the user can upload? Is there some cgi setting that would
prevent a user from upload a huge file, or stop at a certain size and
error? 

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


Re: [Tutor] Question about exception

2007-04-05 Thread Mike Hansen
> If the Exception is defined as a class, e will be an instance of
> that class so you can have pretty much anything available:
> 
> class MyException(Exception):
> def __init__(self, msg, mylist)
> self.msg = msg
> self.mylist = mylist
> Exception.__init__(self, msg)
> 
> try:
> check_something()
> except MyException, e:
> for entry in e.mylist: ...
> 
> Bill
> --
> INTERNET:   [EMAIL PROTECTED]  Bill Campbell; Celestial Software LLC
> URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
> FAX:(206) 232-9186  Mercer Island, WA 98040-0820; 
> (206) 236-1676
> 
> ``I don't make jokes, I just watch the Government and report 
> the facts...''
> Will Rogers

Doh! It was right in front of me, but I wasn't connecting the dots. 

Thanks,

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


Re: [Tutor] Question about exception

2007-04-05 Thread Bill Campbell
On Thu, Apr 05, 2007, Mike Hansen wrote:
>When doing a try/except block, is it possible to return a list as part
>of the exception?
>
>try:
>check_someting()
>except CheckSomethingError, e:
>for each_error in e:
>   # do something
>
>Can 'e' be a list of errors? If so, how do you construct your exception
>class?

If the Exception is defined as a class, e will be an instance of
that class so you can have pretty much anything available:

class MyException(Exception):
def __init__(self, msg, mylist)
self.msg = msg
self.mylist = mylist
Exception.__init__(self, msg)

try:
check_something()
except MyException, e:
for entry in e.mylist: ...

Bill
--
INTERNET:   [EMAIL PROTECTED]  Bill Campbell; Celestial Software LLC
URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
FAX:(206) 232-9186  Mercer Island, WA 98040-0820; (206) 236-1676

``I don't make jokes, I just watch the Government and report the facts...''
Will Rogers
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Question about exception

2007-04-05 Thread Mike Hansen
When doing a try/except block, is it possible to return a list as part
of the exception?

try:
check_someting()
except CheckSomethingError, e:
for each_error in e:
   # do something

Can 'e' be a list of errors? If so, how do you construct your exception
class?


Is it better to do it like this?

(errors) = check_something()
if errors:
   # do something 
 

Mike "head zoned out due to allergies"   
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] question about gui tool-kits

2007-04-05 Thread shawn bright
lo there all,

i have been working with pygtk2 for a while now, and, though i do like
the look and feel of a GTK2 app, i would like to do some stuff with
wx. I know, it doesn't look as cool, but , i may have need to work on
something that i can port to a windows box, and i think that wx would
be a lot easier to do. Also, i think it might prove a tad easier.

So my question is to any out there who have developed on both. What is
the comparison of how easy one is compared to another ?

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


[Tutor] question about forwarding mail with poplib

2007-02-28 Thread shawn bright
Hello there all,

i am poplib to retrieve mail from a pop server here on my local machine.
i need to be able to forward every message i get to another email address.
i looked through the poplib page on the reference online but i can't
find anything there to help me out with this. Also, the message has a
64bit encoded attachment.

anyone have a tip on how i should proceed with this ?

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


Re: [Tutor] Question about profile.run() and decorators

2007-02-27 Thread Thane.Frivold
Kent,

Thank you. 

That was just the kind of hint I needed. I will make sure to
look for objects inside imported packages in the future too; I missed
the Profile attribute when I first ran dir(profile) looking for
available functions.

In case you archive the full email threads, I have included a
copy of the working program for reference for future neophytes like
myself...

Cheers,

- Thane
  
=-=-=

import profile

def myProfileDecorator(function):
  def newFunction(obj, *args, **keywords):
p = profile.Profile()
p.runcall(function, *args, **keywords)
p.print_stats()
  return newFunction

import random

class Foo:
  @myProfileDecorator
  def results(x):
spin = [x*x for x in range(200)]
print str(x) + " Done"

x = Foo()

print x.results("Almost")

=-=-=

>-Original Message-
>From: ext Kent Johnson [mailto:[EMAIL PROTECTED] 
>Sent: Monday, February 26, 2007 7:26 PM
>To: Frivold Thane (Nokia-M/SanFrancisco)
>Cc: tutor@python.org
>Subject: Re: [Tutor] Question about profile.run() and decorators
>
>[EMAIL PROTECTED] wrote:
>
>>  Is there a way to construct a string version (suitable to pass
into 
>> profile.run()) from what is available inside a decorator function?
>> I realize that what I am trying to do could probably be done 
>> otherwise, but this arose out of questions and problems possed in a 
>> Python class I just completed, and I am still trying to find my way 
>> around the language. My 'best' attempt is shown below.
>
>Take a look at profile.Profile.runcall() (look at the source 
>for profile, it is not in the docs). This function takes an 
>actual function object as its parameter rather than a string 
>describing the function call.
>
>Kent
>
>> 
>>  Also, I have limited myself to a function with only 1 parameter,
but 
>> it seems to get even worse if you have 2 or more arguments, since
>> repr() takes only a single argument.
>> 
>>  BTW, I am using ActiveState Python 2.4.3 on Windows XP.
>> 
>>  Any and all suggestions or solutions welcomed.
>> 
>>  Thank you.
>> 
>>  Cheers,
>> 
>> - Thane
>> 
>> =-=-=
>> 
>> import profile
>> 
>> def myProfileDecorator(function):
>>   def newFunction(obj, *args):
>> # This attempt does not seem to give an object expression that
can be used
>> #expression = function.__name__ + '(' + repr(obj) + ',' +
repr(*args) + ')'
>> 
>> # This attempt generates a NameError exception
>> expression = function.__name__ + '(' + repr(*args) + ')'
>> 
>> print 'About to call: profile.run(', expression, ')'
>> profile.run(expression)
>>   return newFunction
>> 
>> import random
>> 
>> class Foo:
>>   @myProfileDecorator
>>   def results(x):
>> print str(x) + " Done"
>> 
>> x = Foo()
>> 
>> print x.results("Almost")
>> 
>> =-=-=
>> 
>> 
>> 
>>  
>> ___
>> Tutor maillist  -  Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
>> 
>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question about profile.run() and decorators

2007-02-26 Thread Kent Johnson
[EMAIL PROTECTED] wrote:

>   Is there a way to construct a string version (suitable to pass
> into profile.run()) from what is available inside a decorator function?
> I realize that what I am trying to do could probably be done otherwise,
> but this arose out of questions and problems possed in a Python class I
> just completed, and I am still trying to find my way around the
> language. My 'best' attempt is shown below.

Take a look at profile.Profile.runcall() (look at the source for 
profile, it is not in the docs). This function takes an actual function 
object as its parameter rather than a string describing the function call.

Kent

> 
>   Also, I have limited myself to a function with only 1 parameter,
> but it seems to get even worse if you have 2 or more arguments, since
> repr() takes only a single argument.
> 
>   BTW, I am using ActiveState Python 2.4.3 on Windows XP.
> 
>   Any and all suggestions or solutions welcomed.
> 
>   Thank you.
> 
>   Cheers,
> 
> - Thane
> 
> =-=-=
> 
> import profile
> 
> def myProfileDecorator(function):
>   def newFunction(obj, *args):
> # This attempt does not seem to give an object expression that can
> be used
> #expression = function.__name__ + '(' + repr(obj) + ',' +
> repr(*args) + ')'
> 
> # This attempt generates a NameError exception
> expression = function.__name__ + '(' + repr(*args) + ')'
> 
> print 'About to call: profile.run(', expression, ')'
> profile.run(expression)
>   return newFunction
> 
> import random
> 
> class Foo:
>   @myProfileDecorator
>   def results(x):
> print str(x) + " Done"
> 
> x = Foo()
> 
> print x.results("Almost")
> 
> =-=-=
> 
> 
> 
>  
> ___
> 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] Question about profile.run() and decorators

2007-02-26 Thread Thane.Frivold
To whom it may concern,

I was directed to this forum... I searched for 'decorator
profile' in the Python tutorial archives, and had no hits, so I hope
this is not a lame question.

Is there a way to construct a string version (suitable to pass
into profile.run()) from what is available inside a decorator function?
I realize that what I am trying to do could probably be done otherwise,
but this arose out of questions and problems possed in a Python class I
just completed, and I am still trying to find my way around the
language. My 'best' attempt is shown below.

Also, I have limited myself to a function with only 1 parameter,
but it seems to get even worse if you have 2 or more arguments, since
repr() takes only a single argument.

BTW, I am using ActiveState Python 2.4.3 on Windows XP.

Any and all suggestions or solutions welcomed.

Thank you.

Cheers,

- Thane

=-=-=

import profile

def myProfileDecorator(function):
  def newFunction(obj, *args):
# This attempt does not seem to give an object expression that can
be used
#expression = function.__name__ + '(' + repr(obj) + ',' +
repr(*args) + ')'

# This attempt generates a NameError exception
expression = function.__name__ + '(' + repr(*args) + ')'

print 'About to call: profile.run(', expression, ')'
profile.run(expression)
  return newFunction

import random

class Foo:
  @myProfileDecorator
  def results(x):
print str(x) + " Done"

x = Foo()

print x.results("Almost")

=-=-=



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


Re: [Tutor] Question about local scopes (namespaces)

2007-02-21 Thread Kent Johnson
Adam Pridgen wrote:
> Sorry for the long email, and thanks in advance.
> 
> In the below example, is the list foo supposed to retain the value
> after the function, Bar(), returns?

Yes

> Is the list foo supposed to reinitialized on each call to Bar(),
> meaning len(foo) == 0, and when Bar() returns len(foo) (when Bar() is
> called w/out parameters)?

No. See
http://www.effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm

Kent

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


[Tutor] Question about local scopes (namespaces)

2007-02-21 Thread Adam Pridgen

Sorry for the long email, and thanks in advance.

In the below example, is the list foo supposed to retain the value
after the function, Bar(), returns?

Is the list foo supposed to reinitialized on each call to Bar(),
meaning len(foo) == 0, and when Bar() returns len(foo) (when Bar() is
called w/out parameters)?

In the example, Bar() is called multiple times, and for the first
three times, I expect foo to initialized as an empty list.  When I
call Bar() and make the assignment however, it turns out that foo is
not reinitialized and it acts like a statically type variable in C or
Java (e.g. retaining its value from each call and subsequent
execution).  I would have expected only one instance of the string in
f after it is assigned the name of foo, however there are four.

My understanding of the code below is as follows:
--If Bar is called without any parameters, then foo is initialized as
an empty list, always.
--If Bar is called with a list parameter, then the name foo is aliased
to that object.
--In the last two cases, if Bar() returns a value to an assignment,
the list will be aliased to that variable name as well
--When Bar() returns, if there is nothing aliased to the list foo,
then the list is destroyed

Is the my understanding correct?  Thank you again for taking the time
to review my question.

--Adam


def Bar(foo=[]):
  foo.append("newb got a keyboard\n")
  return foo

if __name__ == "__main__":
  Bar()
  Bar()
  Bar()
  f = Bar()
  print f

Results:
C:\workspace\ProvingGrounds\src\Bill>python Bug.py
['newb got a keyboard\n', 'newb got a keyboard\n', 'newb got a
keyboard\n', 'newb got a keyboard\n']
def Bar(foo=[]):
   foo.append("newb got a keyboard\n")
   return foo

if __name__ == "__main__":
   Bar()
   Bar()
   Bar()
   f = Bar()
   print f

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


Re: [Tutor] question

2007-02-14 Thread William Allison
Caicedo, Richard IT2 NSWC wrote:
>
> I am trying to get the $ python promt I can't seem to get it.  I can 
> get the python shell but when I press enter I don't get the $ python?
>
> 
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>   
The $ is probably referring to the BASH prompt at which you would type 
the command
python to bring up the interactive interpreter.
Will
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question

2007-02-14 Thread Luke Paireepinart
Caicedo, Richard IT2 NSWC wrote:
>
> I am trying to get the $ python promt I can't seem to get it.  I can 
> get the python shell but when I press enter I don't get the $ python?
>
I don't understand what you're asking.
What is the $ prompt?
If you have a python shell you mean you have a python interpreter you 
can type statements into, right?
the default prompt for the interpreter is >>>.
HTH,
-Luke
>
> 
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>   

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


Re: [Tutor] question

2007-02-14 Thread Luke Paireepinart
Alan Gauld wrote:
> "Doug Potter" <[EMAIL PROTECTED]> wrote
>   
>> I don't get  the output I would expect from the following.
>> 
>
>   
> a = open('arp.txt')
> file = a.read()
> file = file.split('\n')
>   
>
> Easier to do
>
> file = open('arp.txt').readlines()
>
> But file is a bad name since its an alias for open...
>
>   
> b = open('arplist.txt','w')
>   
>
> Not sure why you do this
>
>   
> clean1 = []
>
>   
>
> clean is an empty list
>
>   
> for i in file:
>   
>> ... clean1 = i[26:40]
>> 
>
> clean is now overwritten by a string until you reach the 
> end of the file upon which clean1 will be an empty string
>
>   
> clean1
>   
>> ''
>> 
>
> Which it is...
>
> I think you may have meant to use the append method
>
> for i in file:
> clean1.append(i[26:40])
>
> And since you can iterate over a file the whole thing shrinks to:
>
> clean1 = []
> for i in open('arp.txt'):
> clean1.append(i[26:40])
> print clean1
>
> Or even more succinctly:
>
> clean1 = [i[26:40] for i in open('arp.txt')]
>   
Would this file stay open until the scope changes or is it immediately 
garbage collected, or does something else happen?
Is it unnecessary to use the close methods of files if there are no 
references to the object anymore?
If you had a variable assigned to an open file, and then assigned it to 
something else,
the file would be automatically closed?
Are there any caveats here or is this as safe as closing the file in a 
separate statement?
I've always assumed that you had to explicitly close files.

If you did
file('something.out', 'w').writelines(['testitem1\n','testitem2\n'])
the file would be closed immediately after this was done executing, right?
is there a special func like __init__ that is called when files need to 
be deleted? perhaps __del__?

Feel free to refer me to a tutorial/reference that explains python 
garbage collecting or something.
I would google it myself but I have a huge gigantic test tomorrow.
If no one feels like answering I'll look into it this weekend.
Thanks.

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


[Tutor] question

2007-02-14 Thread Caicedo, Richard IT2 NSWC
I am trying to get the $ python promt I can't seem to get it.  I can get
the python shell but when I press enter I don't get the $ python? 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question about importing threads

2007-02-11 Thread Luke Paireepinart
shawn bright wrote:
> great, saves me 15 lines.
> thanks
You have 15 lines of imports?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question about importing threads

2007-02-11 Thread shawn bright

great, saves me 15 lines.
thanks

sk

On 2/11/07, Kent Johnson <[EMAIL PROTECTED]> wrote:


shawn bright wrote:
> one last queston. if i have a class that i import as a module, say a
> script that emails me when something goes wrong.
> so i have a file called my_own_email.py and in it a class called
> MyOwnEmail. Now MyOwnEmail needs the smtplib module. Do i need to import
> it just for the my_own_email.py or do i need to import it in both that
> module and my program that calls it. ?

You only have to import a module in the module that uses it.

Kent


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


Re: [Tutor] question about importing threads

2007-02-11 Thread Kent Johnson
shawn bright wrote:
> one last queston. if i have a class that i import as a module, say a 
> script that emails me when something goes wrong.
> so i have a file called my_own_email.py and in it a class called 
> MyOwnEmail. Now MyOwnEmail needs the smtplib module. Do i need to import 
> it just for the my_own_email.py or do i need to import it in both that 
> module and my program that calls it. ?

You only have to import a module in the module that uses it.

Kent

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


Re: [Tutor] question about importing threads

2007-02-11 Thread shawn bright

Yes, Mr Gauld, this is a help. Even though i am still newbie enough to take
some time digesting it.

one last queston. if i have a class that i import as a module, say a script
that emails me when something goes wrong.
so i have a file called my_own_email.py and in it a class called MyOwnEmail.
Now MyOwnEmail needs the smtplib module. Do i need to import it just for the
my_own_email.py or do i need to import it in both that module and my program
that calls it. ?

thanks


On 2/9/07, ALAN GAULD <[EMAIL PROTECTED]> wrote:


> i have two classes in my program that use a global object
> that is a socket connection.
> ... code snipped
> is there something tricky about passing this as a global object to
> different modules that would need to use it?

Whiler its possible to use a global in this way its usually better to
avoid global objects in a reusable component since otherwise it
might clash with another global that the reuser already has. Its much
better to use a parameter which can be provided by the user of the
classes. In this case the socklet becomesc a parameter.

A good place to put this parameter would be the init method of both
your classes, where they would store a reference to it as an internal
attribute. (remember that in Python all attributes are references so if
you pass the same socket to both constructors both classes will point
at the same socket).

This approach also allows the user of your classes to suvbstitute
any socketlike object that they mauy have, even their own bespoke
version if needed. That greatly increases the flexibility of your code.

> Or does this go along with what you wrote a while back about
> having classes that depend on each other ?

If you really must use a shared global then I would strongly consider
putting both classes, the global variable and an initialisation function
all in a single module. If however tyou can parameterise things as
described then you need to consider whether anyone would be
able to (and want to) use either of the classes without the other.
If you always need them as a pair they still should go in one module,
otherwise put them in separate modules.

> One runs as a thread, the other responds to gui input.

Does it respond to GUI input or just input? If it can be independant
of the GUI (and you should really try hard to make it so) then its
independant and best in its own module. The fact that the other runs
in a thred is fairly irrelevant to this discussion, the real issue is
whether it has hard coded dependencies on the other class. For
example does it instantiate a copy within its methods? (in which
case you must import the other module/class into this module) And
more especially does it take an instance as a parameter of a method?
(in which case the *re-user* must import the other module.) In the second
case I'd say definitely put them in a single module, in the first case
consider it, but it's not essential.

I hope that makes sense,

Alan G.


On 12/31/06, Alan Gauld <[EMAIL PROTECTED]> wrote:
>
> "shawn bright" <[EMAIL PROTECTED]> wrote
>
> > Yes, the thing is getting to be a pain to deal with at this size, i
> > am
> > in-process of splitting out the classes into their own files.
>
> One thing to watch is that while its easy and tempting to create
> one file per class it's often better to keep dependant classes
> together.
> In other words if class A can only be used together with class B
> then it is often better to keep A and B in the same module.
> Anyone who needs B can import the module and anyone who
> needs A needs B too so it saves them having to import two
> modules.
>
> As in all things in programming a little bit of thought is often
> better than the first "obvious" strategy. Grady Booch described
> the above strategy by saying that "the unit of reuse is the category"
> (which in his OO notation was a set of related classes) and in
> Python that means the module.
>
> Regards,
>
> Alan G.
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>



--
New Yahoo! Mail is the ultimate force in competitive emailing. Find out
more at the Yahoo! Mail 
Championships.
Plus: play games and win prizes.

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


Re: [Tutor] question about importing threads

2007-02-09 Thread ALAN GAULD
> i have two classes in my program that use a global object 
> that is a socket connection.
> ... code snipped
> is there something tricky about passing this as a global object to 
> different modules that would need to use it?


Whiler its possible to use a global in this way its usually better to 
avoid global objects in a reusable component since otherwise it 
might clash with another global that the reuser already has. Its much 
better to use a parameter which can be provided by the user of the 
classes. In this case the socklet becomesc a parameter.

A good place to put this parameter would be the init method of both 
your classes, where they would store a reference to it as an internal 
attribute. (remember that in Python all attributes are references so if 
you pass the same socket to both constructors both classes will point 
at the same socket).

This approach also allows the user of your classes to suvbstitute 
any socketlike object that they mauy have, even their own bespoke 
version if needed. That greatly increases the flexibility of your code.

> Or does this go along with what you wrote a while back about 
> having classes that depend on each other ?

If you really must use a shared global then I would strongly consider 
putting both classes, the global variable and an initialisation function 
all in a single module. If however tyou can parameterise things as 
described then you need to consider whether anyone would be 
able to (and want to) use either of the classes without the other. 
If you always need them as a pair they still should go in one module, 
otherwise put them in separate modules.

> One runs as a thread, the other responds to gui input.

Does it respond to GUI input or just input? If it can be independant 
of the GUI (and you should really try hard to make it so) then its 
independant and best in its own module. The fact that the other runs 
in a thred is fairly irrelevant to this discussion, the real issue is 
whether it has hard coded dependencies on the other class. For 
example does it instantiate a copy within its methods? (in which 
case you must import the other module/class into this module) And 
more especially does it take an instance as a parameter of a method?
(in which case the *re-user* must import the other module.) In the second 
case I'd say definitely put them in a single module, in the first case 
consider it, but it's not essential.

I hope that makes sense,

Alan G.


On 12/31/06, Alan Gauld <[EMAIL PROTECTED]> wrote:
"shawn bright" <[EMAIL PROTECTED]> wrote

> Yes, the thing is getting to be a pain to deal with at this size, i
> am
> in-process of splitting out the classes into their own files.


One thing to watch is that while its easy and tempting to create
one file per class it's often better to keep dependant classes
together.
In other words if class A can only be used together with class B

then it is often better to keep A and B in the same module.
Anyone who needs B can import the module and anyone who
needs A needs B too so it saves them having to import two
modules.

As in all things in programming a little bit of thought is often

better than the first "obvious" strategy. Grady Booch described
the above strategy by saying that "the unit of reuse is the category"
(which in his OO notation was a set of related classes) and in

Python that means the module.

Regards,

Alan G.


___
Tutor maillist  -  Tutor@python.org

http://mail.python.org/mailman/listinfo/tutor












___ 
New Yahoo! Mail is the ultimate force in competitive emailing. Find out more at 
the Yahoo! Mail Championships. Plus: play games and win prizes. 
http://uk.rd.yahoo.com/evt=44106/*http://mail.yahoo.net/uk ___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question about importing threads

2007-02-09 Thread shawn bright

ok, i have started doing this with my 4000 + line file. So far its been
working out.
i have another question about it.

i have two classes in my program that use a global object that is a socket
connection.

example:
global  my_sockobj
serverhost = 'mehost.com'
serverport = 9100
my_sockobj = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
my_sockobj.connect((serverhost,serverport))

then i use my_socket.recv to get stuff from the socket in one class
and my_socket.send to send stuff from another class.

is there something tricky about passing this as a global object to different
modules that would need to use it?
Or does this go along with what you wrote a while back about having classes
that depend on each other ?

One runs as a thread, the other responds to gui input.

thanks for any tips.

shawn

On 12/31/06, Alan Gauld <[EMAIL PROTECTED]> wrote:


"shawn bright" <[EMAIL PROTECTED]> wrote

> Yes, the thing is getting to be a pain to deal with at this size, i
> am
> in-process of splitting out the classes into their own files.

One thing to watch is that while its easy and tempting to create
one file per class it's often better to keep dependant classes
together.
In other words if class A can only be used together with class B
then it is often better to keep A and B in the same module.
Anyone who needs B can import the module and anyone who
needs A needs B too so it saves them having to import two
modules.

As in all things in programming a little bit of thought is often
better than the first "obvious" strategy. Grady Booch described
the above strategy by saying that "the unit of reuse is the category"
(which in his OO notation was a set of related classes) and in
Python that means the module.

Regards,

Alan G.


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

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


Re: [Tutor] question about a list of lists

2007-01-29 Thread Kent Johnson
shawn bright wrote:
> Thanks Kent,
>i am going with option A, the helper set, because i also need to 
> count the occurances and this seems to be the easiest solution.

If you need the number of unique items that is just the length of the 
final list. If you need the number of occurrences of each initial item 
then a dict mapping initial item to count (or maybe a list of lists) 
would be the way to go.

Kent

> 
> thanks for your help.
> 
> shawn
> 
> On 1/28/07, *Kent Johnson* <[EMAIL PROTECTED] > 
> wrote:
> 
> shawn bright wrote:
>  > lo there all.
>  >
>  > i have a list of lists that i want to build, only if an item is
> not in
>  > the list already.
>  >
>  > kinda like this
>  > new_list = []
>  > for item in lists: # item will look something like [var1, var2,
> var3]
>  > if item[0] in new_list ( only the first element of each list
> ) like
>  > new_list[0][0]
>  >
>  > basicly, i want to know if item[0]   is one of the items[0] in my
> new_list
>  >
>  > whats a good pythonic way to do this? i mean, i have a couple of
> way to
>  > do this, but they are ugly.
> 
> One way to do this is to keep a helper set that contains the first
> elements of each list. Something like
> new_list = []
> firsts = set()
> for item in lists:
>if item[0] not in firsts:
>  new_list.append(item)
>  firsts.add(item[0]
> 
> If you don't care about the order of the result, and if two lists have
> duplicate first items you are happy to use the first, then you could use
> a dict mapping first item to list:
> 
> new_list = dict((item[0], item) for item in lists).values()
> 
> Kent
> 
> 


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


Re: [Tutor] question about a list of lists

2007-01-29 Thread shawn bright

Thanks Kent,
  i am going with option A, the helper set, because i also need to count
the occurances and this seems to be the easiest solution.

thanks for your help.

shawn

On 1/28/07, Kent Johnson <[EMAIL PROTECTED]> wrote:


shawn bright wrote:
> lo there all.
>
> i have a list of lists that i want to build, only if an item is not in
> the list already.
>
> kinda like this
> new_list = []
> for item in lists: # item will look something like [var1, var2, var3]
> if item[0] in new_list ( only the first element of each list ) like
> new_list[0][0]
>
> basicly, i want to know if item[0]   is one of the items[0] in my
new_list
>
> whats a good pythonic way to do this? i mean, i have a couple of way to
> do this, but they are ugly.

One way to do this is to keep a helper set that contains the first
elements of each list. Something like
new_list = []
firsts = set()
for item in lists:
   if item[0] not in firsts:
 new_list.append(item)
 firsts.add(item[0]

If you don't care about the order of the result, and if two lists have
duplicate first items you are happy to use the first, then you could use
a dict mapping first item to list:

new_list = dict((item[0], item) for item in lists).values()

Kent


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


Re: [Tutor] question about a list of lists

2007-01-28 Thread Kent Johnson
shawn bright wrote:
> lo there all.
> 
> i have a list of lists that i want to build, only if an item is not in 
> the list already.
> 
> kinda like this
> new_list = []
> for item in lists: # item will look something like [var1, var2, var3]
> if item[0] in new_list ( only the first element of each list ) like 
> new_list[0][0]
> 
> basicly, i want to know if item[0]   is one of the items[0] in my new_list
> 
> whats a good pythonic way to do this? i mean, i have a couple of way to 
> do this, but they are ugly.

One way to do this is to keep a helper set that contains the first 
elements of each list. Something like
new_list = []
firsts = set()
for item in lists:
   if item[0] not in firsts:
 new_list.append(item)
 firsts.add(item[0]

If you don't care about the order of the result, and if two lists have 
duplicate first items you are happy to use the first, then you could use 
a dict mapping first item to list:

new_list = dict((item[0], item) for item in lists).values()

Kent

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


Re: [Tutor] question about a list of lists

2007-01-28 Thread Alan Gauld

"shawn bright" <[EMAIL PROTECTED]> wrote

> new_list = []
> for item in lists: # item will look something like [var1, var2, 
> var3]
>if item[0] in new_list

> basicly, i want to know if item[0]   is one of the items[0] in my 
> new_list

Your pseudo code is pretty much exactly right.
What more are you looking for?

Alan G. 


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


[Tutor] question about a list of lists

2007-01-28 Thread shawn bright

lo there all.

i have a list of lists that i want to build, only if an item is not in the
list already.

kinda like this
new_list = []
for item in lists: # item will look something like [var1, var2, var3]
   if item[0] in new_list ( only the first element of each list ) like
new_list[0][0]

basicly, i want to know if item[0]   is one of the items[0] in my new_list

whats a good pythonic way to do this? i mean, i have a couple of way to do
this, but they are ugly.

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


Re: [Tutor] question about *args and functions

2007-01-26 Thread shawn bright

Great, gents, thanks.

tried it out and is working fine, this will clean up a lot of stuff for me.
thanks for your help !

shawn

On 1/26/07, Wesley Brooks <[EMAIL PROTECTED]> wrote:


Greetings,

You could default it to None and check in your script to see if it has
changed.
def some_function(req_var, req_var2, un_req_var=None):
   if un_req_var != None:
   dosomething
   else:
   dosomethingelse

Wesley Brooks.

On 26/01/07, shawn bright <[EMAIL PROTECTED]> wrote:
> lo there all,
>
> if i have a function that sometimes needs a value passed to it and
sometimes
> not, is this where i use *args ?
>
> like this
>
> def some_function(req_var, req_var2, un_req_var):
> do some stuff
> return value
>
> how would i use this if sometimes i need to process un_req_var and
sometimes
> not ?
>
> thanks
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>

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


Re: [Tutor] question about *args and functions

2007-01-26 Thread Wesley Brooks
Greetings,

You could default it to None and check in your script to see if it has changed.
def some_function(req_var, req_var2, un_req_var=None):
   if un_req_var != None:
   dosomething
   else:
   dosomethingelse

Wesley Brooks.

On 26/01/07, shawn bright <[EMAIL PROTECTED]> wrote:
> lo there all,
>
> if i have a function that sometimes needs a value passed to it and sometimes
> not, is this where i use *args ?
>
> like this
>
> def some_function(req_var, req_var2, un_req_var):
> do some stuff
> return value
>
> how would i use this if sometimes i need to process un_req_var and sometimes
> not ?
>
> thanks
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question about *args and functions

2007-01-26 Thread Kent Johnson
shawn bright wrote:
> lo there all,
> 
> if i have a function that sometimes needs a value passed to it and 
> sometimes not, is this where i use *args ?

No, use an optional argument.

> 
> like this
> 
> def some_function(req_var, req_var2, un_req_var):
> do some stuff
> return value
> 
> how would i use this if sometimes i need to process un_req_var and 
> sometimes not ?

def some_function(req_var, req_var2, un_req_var=None):
 do some stuff
 return value

Now the caller can write some_function(1, 2) or some_function(1, 2, 3). 
You can distinguish the two by checking for 'un_req_var is None'.

If None is a legitimate value for un_req_var then you need to pick some 
other sentinal value. If there is no built-in value that works, create 
your own:

missing = object()
def some_function(req_var, req_var2, un_req_var=missing):

Kent

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


Re: [Tutor] question about *args and functions

2007-01-26 Thread Andre Engels

2007/1/26, shawn bright <[EMAIL PROTECTED]>:


lo there all,

if i have a function that sometimes needs a value passed to it and
sometimes not, is this where i use *args ?



No. *args is used if there are arguments that could occur more than once.

like this


def some_function(req_var, req_var2, un_req_var):
do some stuff
return value

how would i use this if sometimes i need to process un_req_var and
sometimes not ?



Use:
def some_function(req_var, req_var2, un_req_var = None):
   do some stuff
   return value

Now, the function can be called both with and without un_req_var, and if it
is called without un_req_var, within the function body un_req_var is
considered to be None.


--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] question about *args and functions

2007-01-26 Thread shawn bright

lo there all,

if i have a function that sometimes needs a value passed to it and sometimes
not, is this where i use *args ?

like this

def some_function(req_var, req_var2, un_req_var):
   do some stuff
   return value

how would i use this if sometimes i need to process un_req_var and sometimes
not ?

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


[Tutor] Question about structuring my pygtk program

2007-01-23 Thread Tino Dai

Hi Everybody,

  I have a question about structuring first pygtk program now that I
have the basics working, I am moving to the next step of organizing my
program so it doesn't turn into spaghetti code. Right now, what I'm doing is
if a component of the GUI is used in more than one spot, I make that into a
separate little function returning a GUI fragment that I can call several
times throughout the program. I have been doing this type of "non-redundant
code" in a non-GUI environment for many years, and it's worked well. Also, I
read about this technique from the Pragmatic Programmer - having one section
of code that does a specific task - instead of having it in multiple
locations. Does this translate to the GUI environment? If so, is there an
easy of accessing the different input boxes easily? If you need a code
exxample, just ask.

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


Re: [Tutor] question about object oriented programming and inheritance using datetime module

2007-01-16 Thread Kent Johnson
Terry Carroll wrote:
> An example is if you wanted to create a "birthdate" class, which was just 
> like a regular date, but also included the birthstone that corresponded to 
> the date.  We could create a "birthdate" module that included a 
> "Birthdate" class:
> 
> ###
> 
> import datetime
> 
> class Birthdate(datetime.date):
> 
> def __init__(self, year, month, day):
> stones = ["Garnet", "Amethyst", "Aquamarine",
>   "Diamond", "Emerald", "Perl",
>   "Ruby", "Python", "Sapphire",
>   "Opal", "Topaz", "Turquoise"]
> self.birthstone = stones[month-1]

I think you are missing the line
   datetime.date.__init__(self, year, month, day)

somewhere in here.

I am very surprised that this works, my understanding was that 
datetime.date was immutable and required overriding __new__() rather 
than __init__(). But it does work...

Kent

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


Re: [Tutor] question about object oriented programming and inheritance using datetime module

2007-01-16 Thread Terry Carroll
On Mon, 15 Jan 2007, Kent Johnson wrote:

> [EMAIL PROTECTED] wrote:
> 
> > My class inherits from the date class, but I 
> > have to type 'from datetime import date' before I can initialize the 
> > class definition.  Is there some way to avoid this ? 
> 
> No, and really there is no reason to want to avoid this. You have to 
> import any external module that you want to use directly. Imports are 
> very common in Python code and there is no reason not to use them.

I had a similar issue when I started Python, so I think I know what tpc
may be after.

My thought was that I did not want to do the import if the class was not 
actually going to be used.

I was really thinking about it the wrong way, though.  Really, I would not 
want to do the import unless the class was going to be *defined* for use.  
The right approach here is to put the class into a module, and the import 
statement into the new module as well.

Then, a program that needs to use the class imports the module; and that 
module, only if it is imported, imports the classes on which it depends.

In this case, tpc's class might be defined in a MyDateStuff.py module,
which contains:




import datetime

class age_calculator(datetime.date):
   etc.



Then, when he imports MyDateStuff, it imports datetime and defines 
age_calculator.

I second Kent's concerns over this, though.  It sounds like age_calculator
is really a method that uses datetime.date; not a subclass of
datetime.date.

The question you should ask is: will an age_calculator object actually 
also be a date object?  If so, subclassing makes sense.  Otherwise, think 
of using a method.

Put another way, you should think of a statement like 

   class age_calculator(datetime.date):

as meaning "define a new class named age_calculator; an age_calculator
object is a type of date object."

An example is if you wanted to create a "birthdate" class, which was just 
like a regular date, but also included the birthstone that corresponded to 
the date.  We could create a "birthdate" module that included a 
"Birthdate" class:

###

import datetime

class Birthdate(datetime.date):

def __init__(self, year, month, day):
stones = ["Garnet", "Amethyst", "Aquamarine",
  "Diamond", "Emerald", "Perl",
  "Ruby", "Python", "Sapphire",
  "Opal", "Topaz", "Turquoise"]
self.birthstone = stones[month-1]

###

We could create a Birthdate object like this:

>>> import birthdate
>>> z = birthdate.Birthdate(1971, 7, 12)

Note, it has the birthstone for July:

>>> z.birthstone
'Ruby'

It also has inherited the other attributes and methods of the standard
datetime.date class on which it was based:

>>> z.isoformat()
'1971-07-12'

Because a birthdate is after all, just a particular kind of date; and the 
Birthdate class is just a particular kind of date class.

But in your case, with a name like "age_calculator", it doesn't sound like 
an "age_calculator" is a kind of date.  It sounds like a thing that 
calculates ages.

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


Re: [Tutor] question about object oriented programming and inheritance using datetime module

2007-01-15 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
> hey guys, I've been experimenting with Python's datetime module, and I 
> created a function that, given a person's birthdate, calculates how old 
> that person is.  Now I want to create a class called age_calculator that 
> does much the same thing.  

Why? You have a perfectly good function that does what you want, there 
is no need to turn it into a class. One of the strengths of Python is 
that not everything needs to be a class.

> My class inherits from the date class, but I 
> have to type 'from datetime import date' before I can initialize the 
> class definition.  Is there some way to avoid this ? 

No, and really there is no reason to want to avoid this. You have to 
import any external module that you want to use directly. Imports are 
very common in Python code and there is no reason not to use them.

Inheriting from date isn't a very good idea. You should inherit from 
date if your class will be a specialized kind of date. I guess you could 
think of your class as adding an age() method to date, but you are 
thinking of it as a calculator. Also date objects are immutable which 
makes it harder to create a subclass of date. (You have to override 
__new__() rather than __init__(), but explaining that will probably just 
confuse you at this point.)

There are a few things in your code that are a bit confused - you need 
to call the base class __init__() in your __init__() method, and 
__init__() does not return a value. You should probably read up a bit 
more on classes in Python, either a book or one of the on-line tutorials.

> 
> Also, once I type the import statement and initialize my class 
> definition, I can create an instance of age_calculator.  The instance of 
> age_calculator stores the given birthdate, and gives me a infinite loop 
> traceback when I call self.today().  If I don't inherit from date, I 
> would need to put the import statement somewhere inside a method, and I 
> don't recall ever seeing that done.

It is OK to put an import inside a function or method, but why do you 
think you need to do this?

>  Part of me feels like that's not as 
> elegant as defining an age_calculator class that inherits from 
> datetime.date, but I'm not sure how to do this.  For what it's worth, 
> here's my pseudocode (that inherits from date module) and working code 
> (that does not inherit from date module):
> 
> from datetime import date
> 
> class age_calculator(date):
> def __init__(self, year, month, day):
> time_delta = self.today() - self
> number_of_years = time_delta.days / 365
> return number_of_years

I'm not sure why this gives an infinite loop (not even sure what an 
"infinite loop traceback" is), but you have not initialized the base 
class so the year, month, day parameters are not used at all.

> 
> class age_calculator:
> def __init__(self, year, month, day):
> self.year = year
> self.month = month
> self.day = day
> 
> def calculate_age(self):
> from datetime import date
> birth_date = date( self.year, self.month, self.day)
> date_today = date.today()
> time_delta = date_today - birth_date
> number_of_years = time_delta.days / 365
> return number_of_years

This is better, but compare it to your functional version and you should 
see why the function is preferred.

Kent

> 
> age_calculator(1964, 9, 27).calculate_age()
> 42
> 
> 
> 
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


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


Re: [Tutor] question about object oriented programming and inheritance using datetime module

2007-01-15 Thread Luke Paireepinart
[EMAIL PROTECTED] wrote:
> hey guys, I've been experimenting with Python's datetime module, and I 
> created a function that, given a person's birthdate, calculates how 
> old that person is.  Now I want to create a class called 
> age_calculator that does much the same thing.  My class inherits from 
> the date class, but I have to type 'from datetime import date' before 
> I can initialize the class definition.  Is there some way to avoid 
> this ? 
No.
In order to use class inheritance syntax,
class some_class(some_object):

some_object must be defined.
Otherwise you'll get a variable not defined error.
You could make your own class called 'date' and inherit from that,
but what would be the point of that?
>
> Also, once I type the import statement and initialize my class 
> definition, I can create an instance of age_calculator.  The instance 
> of age_calculator stores the given birthdate, and gives me a infinite 
> loop traceback when I call self.today().  If I don't inherit from 
> date, I would need to put the import statement somewhere inside a 
> method, and I don't recall ever seeing that done.
What makes you think you'd have to import within a method?
Import datetime.date into the global namespace.
That's perfectly alright.
Especially since your class depends on it being available.
>   Part of me feels like that's not as elegant as defining an 
> age_calculator class that inherits from datetime.date, but I'm not 
> sure how to do this.  For what it's worth, here's my pseudocode (that 
> inherits from date module) and working code (that does not inherit 
> from date module):
The way you'd go about doing this is to make an extra function that is 
unique to your inherited class (for example, calculate_age).
>
> from datetime import date
>
> class age_calculator(date):
> def __init__(self, year, month, day):
> time_delta = self.today() - self
> number_of_years = time_delta.days / 365
> return number_of_years
This init method is overriding the init of the inherited date class.
The reason today() doesn't work is probably because of this.
>
> class age_calculator:
> def __init__(self, year, month, day):
> self.year = year
> self.month = month
> self.day = day
>
> def calculate_age(self):
> from datetime import date
> birth_date = date( self.year, self.month, self.day)
> date_today = date.today()
> time_delta = date_today - birth_date
> number_of_years = time_delta.days / 365
> return number_of_years
>
Just move the import outside of the class.
from datetime import date
class age_calculator:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day

def calculate_age(self):
birth_date = date( self.year, self.month, self.day)
date_today = date.today()
time_delta = date_today - birth_date
number_of_years = time_delta.days / 365
return number_of_years

I don't think you really want to inherit from date.
HTH,
-Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] question about object oriented programming and inheritance using datetime module

2007-01-15 Thread tpc

hey guys, I've been experimenting with Python's datetime module, and I
created a function that, given a person's birthdate, calculates how old that
person is.  Now I want to create a class called age_calculator that does
much the same thing.  My class inherits from the date class, but I have to
type 'from datetime import date' before I can initialize the class
definition.  Is there some way to avoid this ?

Also, once I type the import statement and initialize my class definition, I
can create an instance of age_calculator.  The instance of age_calculator
stores the given birthdate, and gives me a infinite loop traceback when I
call self.today().  If I don't inherit from date, I would need to put the
import statement somewhere inside a method, and I don't recall ever seeing
that done.  Part of me feels like that's not as elegant as defining an
age_calculator class that inherits from datetime.date, but I'm not sure how
to do this.  For what it's worth, here's my pseudocode (that inherits from
date module) and working code (that does not inherit from date module):

from datetime import date

class age_calculator(date):
   def __init__(self, year, month, day):
   time_delta = self.today() - self
   number_of_years = time_delta.days / 365
   return number_of_years

class age_calculator:
   def __init__(self, year, month, day):
   self.year = year
   self.month = month
   self.day = day

   def calculate_age(self):
   from datetime import date
   birth_date = date(self.year, self.month, self.day)
   date_today = date.today()
   time_delta = date_today - birth_date
   number_of_years = time_delta.days / 365
   return number_of_years

age_calculator(1964, 9, 27).calculate_age()
42
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question on joining out of order dictionary elements

2007-01-11 Thread Luke Paireepinart
raghu raghu wrote:
>
> [snip original message]
>
>
> To print or to retain individual values from a list,it has to be 
> written in the form of
> config={'test1':'elem1','test2':'elem2','test3':'elem3'}
> config['test4'] = 'elem4'
> print config.values()
> print config['test1']- To get individual values from a list
> If we want to retrieve all the values or say 2 from 4 its not possible 
> to put in a while loop and get that as a list only takes one argument 
> at a time better way is to extract individually and respective keys 
> could not be obtained if corresponding values are given.
Hello, raghu -
Please don't reply like this.
It breaks threading.
You should have a Re: in the title bar,
and the quoted text should have > before it.
If you reply like you did, it creates a new thread in Thunderbird.
I believe the 'reply all' button has some kind of magic that tells mail 
clients it's a reply to another message.

In addition, please don't use bolding.
If you reply normally, it will be clear what text is yours and what is 
from the original author.
Bolding text just makes it harder to read.
Thanks,
-Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question on joining out of order dictionary elements

2007-01-11 Thread Andrew Robert
I like this solution.

Thanks everyone for all of the suggestions.

On 1/11/07, Andre Engels <[EMAIL PROTECTED]> wrote:
> 2007/1/11, raghu raghu <[EMAIL PROTECTED]>:
>
> > >>> print "\\".join((config["val2"]
> > ,config["val1"],config["val3"]))
> > elem2\elem1\elem3
> >
> > or
> >
> > >>> print "%s\\%s\\%s" %
> (config["val2"],config["val1"],config["val3"])
> > elem2\elem1\elem3
> >
> > but this seems somehow uneligent.
> >
> > Are there a more efficient/compact ways of doing this kind of
> > operation or is this it?
> >
>
> Maybe you like:
> print "\\".join([config[val] for val in ["val2","val1","val3"]])
>
> --
> Andre Engels, [EMAIL PROTECTED]
> ICQ: 6260644  --  Skype: a_engels
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>


-- 
Thank you,
Andrew Robert

Senior MQ Engineer
Information Technologies
Massachusetts Financial Services
Phone: 617-954-5882
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question on joining out of order dictionary elements

2007-01-11 Thread Andre Engels

2007/1/11, raghu raghu <[EMAIL PROTECTED]>:


>>> print "\\".join((config["val2"],config["val1"],config["val3"]))
elem2\elem1\elem3

or

>>> print "%s\\%s\\%s" % (config["val2"],config["val1"],config["val3"])
elem2\elem1\elem3

but this seems somehow uneligent.

Are there a more efficient/compact ways of doing this kind of
operation or is this it?



Maybe you like:
print "\\".join([config[val] for val in ["val2","val1","val3"]])

--
Andre Engels, [EMAIL PROTECTED]
ICQ: 6260644  --  Skype: a_engels
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Question on joining out of order dictionary elements

2007-01-11 Thread raghu raghu

Hi everyone,

I have a quick quick question joining out of order dictionary values.

For example:

I created an empty


config={}


Added some key/value pairs


config["test1"]="elem1"
config["test2"]="elem2"
config["test3"]="elem3"


etc




Dumped the values and joined them at the same time.


print "\\".join(config.values())

elem1\elem3\elem2

This is fine but it doesn't entirely solve the issue.

Only some of the key/value pairs in the dictionary are needed so a
dump of all values does not work.

Also, the order in which the values are joined is important so walking
through and joining all values does not work either.


The simplest way would be to do something like:


print "\\".join((config["val2"],config["val1"],config["val3"]))

elem2\elem1\elem3

or


print "%s\\%s\\%s" % (config["val2"],config["val1"],config["val3"])

elem2\elem1\elem3

but this seems somehow uneligent.

Are there a more efficient/compact ways of doing this kind of
operation or is this it?

The key/value pairs in these examples are contrived for purposes of
this discussion but the end goal is to piece together server and
directory path information for use with pysvn.

I have a Perl programmer who is learning Python and he is griping that
this kind of operation is far simpler in Perl.

To print or to retain individual values from a list,it has to be written in
the form of
config={'test1':'elem1','test2':'elem2','test3':'elem3'}
config['test4'] = 'elem4'
print config.values()
print config['test1']- To get individual values from a list
If we want to retrieve all the values or say 2 from 4 its not possible to
put in a while loop and get that as a list only takes one argument at a time
better way is to extract individually and respective keys could not be
obtained if corresponding values are given.



--

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


Re: [Tutor] Question on joining out of order dictionary elements

2007-01-10 Thread John Fouhy
On 11/01/07, Andrew Robert <[EMAIL PROTECTED]> wrote:
> Only some of the key/value pairs in the dictionary are needed so a
> dump of all values does not work.
>
> Also, the order in which the values are joined is important so walking
> through and joining all values does not work either.

Well, a dictionary is by definition unordered, so you will need to
tell python which elements you want, and in which order.

I would do something like this:


config = {}
# insert code here to set the values of config

keysToDump = ['test1', 'test2', 'test3']
output = '\\'.join(config[k] for k in keysToDump)


(note that, if you are using python2.3 or earlier, you will need to
write that last line as:

output = '\\'.join([config[k] for k in keysToDump])

)

HTH!

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


[Tutor] Question on joining out of order dictionary elements

2007-01-10 Thread Andrew Robert
Hi everyone,

I have a quick quick question joining out of order dictionary values.

For example:

I created an empty

>>> config={}

Added some key/value pairs

>>> config["test1"]="elem1"
>>> config["test2"]="elem2"
>>> config["test3"]="elem3"

  etc
>>>

Dumped the values and joined them at the same time.

>>> print "\\".join(config.values())
elem1\elem3\elem2

This is fine but it doesn't entirely solve the issue.

Only some of the key/value pairs in the dictionary are needed so a
dump of all values does not work.

Also, the order in which the values are joined is important so walking
through and joining all values does not work either.


The simplest way would be to do something like:

>>> print "\\".join((config["val2"],config["val1"],config["val3"]))
elem2\elem1\elem3

or

>>> print "%s\\%s\\%s" % (config["val2"],config["val1"],config["val3"])
elem2\elem1\elem3

but this seems somehow uneligent.

Are there a more efficient/compact ways of doing this kind of
operation or is this it?

The key/value pairs in these examples are contrived for purposes of
this discussion but the end goal is to piece together server and
directory path information for use with pysvn.

I have a Perl programmer who is learning Python and he is griping that
this kind of operation is far simpler in Perl.

-- 
Thank you,
Andrew Robert

Senior MQ Engineer
Information Technologies
Massachusetts Financial Services
Phone: 617-954-5882
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question about __name__ global variable (Was: Tutor Digest, Vol 35, Issue 27)

2007-01-09 Thread wesley chun
> The global variable __name__ is equal to '__main__' when the python
> script is run.
> If the script is imported, __name__ is something other than '__main__'
> (not sure what.)


it will be the name of your module.  so for foo.py, if you execute it
(as a script), __name__ == '__main__', but if you 'import foo',
__name__ == 'foo'.

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] question about pydev

2007-01-09 Thread shawn bright

hey there gents, i was wondering if anyone uses pydev ?
its a plugin for eclipse. Has lots of cool stuffs, but i don't like the way
it does code snippets,
when i paste one that is kinda long, it messes up the indentation.
anyone know a way around this ? i have posted this question on the pydev
sourceforge list ( about 2 weeks ago )
and have not heard anything, so thought i would ask the folk most likely to
be using it.

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


Re: [Tutor] Question about __name__ global variable (Was: Tutor Digest, Vol 35, Issue 27)

2007-01-09 Thread Luke Paireepinart
raghu raghu wrote:
> i have a clarification regarding built in function,in some scripts it 
> is being used and it is give n: if _name_ == '_main_'
> why this is being used in the scripts?
The global variable __name__ is equal to '__main__' when the python 
script is run.
If the script is imported, __name__ is something other than '__main__' 
(not sure what.)
So by checking if __name__ == '__main__' we can ensure that our code can 
work both as a standalone script
and as a module.
For example:

#test-script.py
import random

def someFunction(a):
return a * random.randrange(100)

if __name__ == "__main__":
print "The number 42 passed to someFunction is: " + someFunction(42)

#-

If we want to use the function someFunction from test-script.py in a 
different file,
the 'main' part won't be run.
#
import test-script

print "The number 3 passed to someFunction is: " + someFunction(3)
#-

if the 'if __name__ == '__main__' ' test weren't in the original 
test-script.py,
the 42 version of the print statement would be run whenever someone 
imported it.

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


Re: [Tutor] Question about ConfigParser

2007-01-07 Thread Jan Erik Moström
Reply to Dave Kuhlman <[EMAIL PROTECTED]> 07-01-06 15:26:

>It's sort of hidden, but note the restriction to string values in
>the docs on the set method:
>
>set(section, option, value)
>If the given section exists, set the given option to the specified
>value; otherwise raise NoSectionError. While it is possible to use
>RawConfigParser (or ConfigParser with raw parameters set to true)
>for internal storage of non-string values, full functionality
>(including interpolation and output to files) can only be achieved
>using string values. New in version 1.6.

A ... I was spending all my time reading the docs for 
'items' ;-)

Thanks

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


Re: [Tutor] Question about ConfigParser

2007-01-06 Thread Dave Kuhlman
On Sat, Jan 06, 2007 at 10:40:27PM +0100, Jan Erik Mostr??m wrote:
> I'm trying to use ConfigParser for the first time and I'm 
> missing something. I have this code
> 
> import ConfigParser
> import datetime
> 
> conf = ConfigParser.ConfigParser()
> 
> conf.add_section('general')
> conf.set( 'general', 'revision', 0 )
> conf.set( 'general', 'date', 
> datetime.datetime.now().strftime("%Y-%m-%d") )
> conf.set( 'general', 'currentsetname', '' )
> conf.set( 'general', 'incrementalcount', 0 )
> conf.add_section( "Hello world" )
> conf.set( "Hello world", 'apa', 3298 )
> 
> print conf.sections()
> print conf.items('general')
> 
> #for debug_repos in conf.sections():
> #   print debug_repos #, conf.items( debug_repos )
> 
> 
> When I run this I get the following result
> 
> ['Hello world', 'general']
> Traceback (most recent call last):
>File "backup.py", line 15, in 
>  print conf.items('general')
>File 
> "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ConfigParser.py",
>  
> line 557, in items
>  for option in options]
>File 
> "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ConfigParser.py",
>  
> line 565, in _interpolate
>  if "%(" in value:
> TypeError: argument of type 'int' is not iterable
> 
> What am I missing with the items call?

Here is a clue -- If you write out your configuration to a file
with something like:

conf.write(sys.stdout)

and store it in a file.  Then, if you read it in, all seems to work
well.  For example, the following function:

def test2():
conf = ConfigParser.ConfigParser()
conf.read('test1.conf')
print 'options -- general:', conf.options('general')
opt1 = conf.get('general', 'date')
print 'opt1:', opt1
print conf.items('general')

executes without error.  Can you guess why?

Note that in your original code, the default values for some of
your options have type int.  If you change those to strings, then
the error goes away.  For example, change:

conf.set( 'general', 'revision', 0 )

to:

conf.set( 'general', 'revision', "0" )

Writing it to a file does this conversion and hides the error.

It's sort of hidden, but note the restriction to string values in
the docs on the set method:

set(section, option, value)
  If the given section exists, set the given option to the specified
  value; otherwise raise NoSectionError. While it is possible to use
  RawConfigParser (or ConfigParser with raw parameters set to true)
  for internal storage of non-string values, full functionality
  (including interpolation and output to files) can only be achieved
  using string values. New in version 1.6.

Dave


-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Question about ConfigParser

2007-01-06 Thread Jan Erik Moström
I'm trying to use ConfigParser for the first time and I'm 
missing something. I have this code

import ConfigParser
import datetime

conf = ConfigParser.ConfigParser()

conf.add_section('general')
conf.set( 'general', 'revision', 0 )
conf.set( 'general', 'date', 
datetime.datetime.now().strftime("%Y-%m-%d") )
conf.set( 'general', 'currentsetname', '' )
conf.set( 'general', 'incrementalcount', 0 )
conf.add_section( "Hello world" )
conf.set( "Hello world", 'apa', 3298 )

print conf.sections()
print conf.items('general')

#for debug_repos in conf.sections():
#   print debug_repos #, conf.items( debug_repos )


When I run this I get the following result

['Hello world', 'general']
Traceback (most recent call last):
   File "backup.py", line 15, in 
 print conf.items('general')
   File 
"/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ConfigParser.py",
 
line 557, in items
 for option in options]
   File 
"/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/ConfigParser.py",
 
line 565, in _interpolate
 if "%(" in value:
TypeError: argument of type 'int' is not iterable

What am I missing with the items call?

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


Re: [Tutor] Question regarding parsing HTML with BeautifulSoup

2007-01-04 Thread Shuai Jiang (Runiteking1)

Hi,

Wow, thats much more elegant than the idea I thought of.

Thank you very much Kent!

Marshall

On 1/3/07, Kent Johnson <[EMAIL PROTECTED]> wrote:


Shuai Jiang (Runiteking1) wrote:
> Hello,
>
> I'm working on a program that need to parse a financial document on the
> internet
> using BeautifulSoup. Because of the nature of the information, it is all
> grouped
> as a table. I needed to get 3 types of info and have succeeded quite
> well using
> BeautifulSoup, but encountered problems on the third one.
>
> My question is that is there any easy way to parse an HTML tables column
> easily using BeautifulSoup. I copied the table here and I need to
> extract the EPS. The numbers are
> every sixth one from the   tag ex 2.27, 1.86, 1.61...

Here is one way, found with a little experimenting at the command prompt:

In [1]: data = '''

...: '''
In [3]: from BeautifulSoup import BeautifulSoup as BS

In [4]: soup=BS(data)

In [11]: for tr in soup.table.findAll('tr'):
: print tr.contents[11].string
:
:
EPS
2.27
  1.86
1.61
  1.27
1.18
  0.84
0.73
  0.46
0.2
  0.0

Kent






--
I like pigs. Dogs look up to us. Cats look down on us. Pigs treat us as
equals.
   Sir Winston Churchill
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question regarding parsing HTML with BeautifulSoup

2007-01-03 Thread Kent Johnson
Shuai Jiang (Runiteking1) wrote:
> Hello,
> 
> I'm working on a program that need to parse a financial document on the 
> internet
> using BeautifulSoup. Because of the nature of the information, it is all 
> grouped
> as a table. I needed to get 3 types of info and have succeeded quite 
> well using
> BeautifulSoup, but encountered problems on the third one.
> 
> My question is that is there any easy way to parse an HTML tables column
> easily using BeautifulSoup. I copied the table here and I need to 
> extract the EPS. The numbers are
> every sixth one from the   tag ex 2.27, 1.86, 1.61...

Here is one way, found with a little experimenting at the command prompt:

In [1]: data = '''

...: '''
In [3]: from BeautifulSoup import BeautifulSoup as BS

In [4]: soup=BS(data)

In [11]: for tr in soup.table.findAll('tr'):
: print tr.contents[11].string
:
:
EPS
2.27
  1.86
1.61
  1.27
1.18
  0.84
0.73
  0.46
0.2
  0.0

Kent


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


[Tutor] Question regarding parsing HTML with BeautifulSoup

2007-01-03 Thread Shuai Jiang (Runiteking1)

Hello,

I'm working on a program that need to parse a financial document on the
internet
using BeautifulSoup. Because of the nature of the information, it is all
grouped
as a table. I needed to get 3 types of info and have succeeded quite well
using
BeautifulSoup, but encountered problems on the third one.

My question is that is there any easy way to parse an HTML tables column
easily using BeautifulSoup. I copied the table here and I need to extract
the EPS. The numbers are
every sixth one from the   tag ex 2.27, 1.86, 1.61...

Thanks!

Marshall

   
    
   Sales
   EBIT
   Depreciation
   Total Net
Income
   EPS
   Tax Rate
(%)
   

   
   02/06
   30,848.0

   1,721.0

   456.0
   1,140.0


   2.27
   33.76
   
   
   02/05
   27,433.0

   1,443.0


   459.0
   934.0
   1.86
   35.27
   
   
   02/04

   24,548.0

   1,296.0

   385.0
   800.0
   1.61
   38.27

   
   
   03/03
   20,943.0

   1,014.0

   310.0
   622.0

   1.27
   38.66
   
   
   03/02
   17,711.0

   926.0

   245.0
   570.0
   1.18
   38.44
   
   
   03/01

   15,189.0

   649.0
   165.0
   401.0
   0.84
   38.21

   
   
   02/00
   12,494.02

   562.57

   109.54

   347.07


   0.73
   38.31
   
   
   02/99
   10,064.65

   351.68


   73.63
   216.28

   0.46
   38.5
   
   
   02/98

   8,337.76

   133.4
   71.58
   81.94
   0.2
   38.58

   
   
   03/97
   7,770.68

   2.87
   66.84
   1.75

   0.0
   39.05
   


--
I like pigs. Dogs look up to us. Cats look down on us. Pigs treat us as
equals.
   Sir Winston Churchill
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question about importing threads

2006-12-31 Thread Alan Gauld
"shawn bright" <[EMAIL PROTECTED]> wrote

> Yes, the thing is getting to be a pain to deal with at this size, i 
> am
> in-process of splitting out the classes into their own files.

One thing to watch is that while its easy and tempting to create
one file per class it's often better to keep dependant classes 
together.
In other words if class A can only be used together with class B
then it is often better to keep A and B in the same module.
Anyone who needs B can import the module and anyone who
needs A needs B too so it saves them having to import two
modules.

As in all things in programming a little bit of thought is often
better than the first "obvious" strategy. Grady Booch described
the above strategy by saying that "the unit of reuse is the category"
(which in his OO notation was a set of related classes) and in
Python that means the module.

Regards,

Alan G. 


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


Re: [Tutor] question about importing threads

2006-12-31 Thread shawn bright

Thanks, Alan.
Yes, the thing is getting to be a pain to deal with at this size, i am
in-process of splitting out the classes into their own files.
Thanks for your help.

shawn

On 12/30/06, Alan Gauld <[EMAIL PROTECTED]> wrote:



"shawn bright" <[EMAIL PROTECTED]> wrote i

> testing this right away. This long a .py script is becomming a
> headache and
> i think it will be easier by far if it is pulled apart somewhat.

As a general rule of thumb, any Python script (or any programming
language file for that matter!) that gets longer than 4 or 5 hundred
lines should be looked at closely in terms of splitting it into
modules.

There are a few (very few) times where I've seen a thousand line
file that was justified, but nearly any time you get beyond 500
lines you should be splitting things up - especially in high level
languages like Python where the methods/functions tend to be
short anyway.

FWIW

A quick check of the Python standard library shows the
average file size there to be: 459 lines(*) And that's pretty
high IMHO!

There are 19 files over a thousand lines and the biggest file
is over 3000 lines... which seems way too big to me!
But that's out of 188 files...

(*)
Cygwin; Python 2.4
In case you want to repeat for your version I used:
>>> libs = [len(open(f).readlines()) for f in glob('*.py')]
>>> print sum(libs)/len(libs)
>>> print max(libs)
>>> print len([s for s in libs if s>1000])

Alan G


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

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


Re: [Tutor] question about importing threads

2006-12-30 Thread Alan Gauld

"shawn bright" <[EMAIL PROTECTED]> wrote i

> testing this right away. This long a .py script is becomming a 
> headache and
> i think it will be easier by far if it is pulled apart somewhat.

As a general rule of thumb, any Python script (or any programming
language file for that matter!) that gets longer than 4 or 5 hundred
lines should be looked at closely in terms of splitting it into 
modules.

There are a few (very few) times where I've seen a thousand line
file that was justified, but nearly any time you get beyond 500
lines you should be splitting things up - especially in high level
languages like Python where the methods/functions tend to be
short anyway.

FWIW

A quick check of the Python standard library shows the
average file size there to be: 459 lines(*) And that's pretty
high IMHO!

There are 19 files over a thousand lines and the biggest file
is over 3000 lines... which seems way too big to me!
But that's out of 188 files...

(*)
Cygwin; Python 2.4
In case you want to repeat for your version I used:
>>> libs = [len(open(f).readlines()) for f in glob('*.py')]
>>> print sum(libs)/len(libs)
>>> print max(libs)
>>> print len([s for s in libs if s>1000])

Alan G


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


Re: [Tutor] question about importing threads

2006-12-30 Thread shawn bright

great help, and great link, thanks again.
shawn

On 12/30/06, Kent Johnson <[EMAIL PROTECTED]> wrote:


shawn bright wrote:
> Kent, Thanks.
> this is great. Yes, when i start the thread, i also pass the gtk object
> to it.
> kinda like this.
>
> serial_1 = Serial1(self.serial_1_buffer, self.serial_1_view)
> serial_1.start()
>
> so i am wanting to change that, but i do not exactly know how to stop a
> thread once i have it running, so that i could start another one.

The usual way to stop a thread is to set a flag that the thread checks.
Here is an example using a threading.Event as a flag:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65448

> anyway, thanks for the link and the info, i am going to get started on
> testing this right away. This long a .py script is becomming a headache
> and i think it will be easier by far if it is pulled apart somewhat.

Yes, 4000 lines is pretty long for one file IMO.

Kent



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


Re: [Tutor] question about importing threads

2006-12-30 Thread Kent Johnson
shawn bright wrote:
> Kent, Thanks.
> this is great. Yes, when i start the thread, i also pass the gtk object 
> to it.
> kinda like this.
> 
> serial_1 = Serial1(self.serial_1_buffer, self.serial_1_view)
> serial_1.start()
> 
> so i am wanting to change that, but i do not exactly know how to stop a 
> thread once i have it running, so that i could start another one.

The usual way to stop a thread is to set a flag that the thread checks. 
Here is an example using a threading.Event as a flag:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65448

> anyway, thanks for the link and the info, i am going to get started on 
> testing this right away. This long a .py script is becomming a headache 
> and i think it will be easier by far if it is pulled apart somewhat.

Yes, 4000 lines is pretty long for one file IMO.

Kent


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


Re: [Tutor] question about importing threads

2006-12-30 Thread shawn bright

Kent, Thanks.
this is great. Yes, when i start the thread, i also pass the gtk object to
it.
kinda like this.

serial_1 = Serial1(self.serial_1_buffer, self.serial_1_view)
serial_1.start()

so i am wanting to change that, but i do not exactly know how to stop a
thread once i have it running, so that i could start another one.

anyway, thanks for the link and the info, i am going to get started on
testing this right away. This long a .py script is becomming a headache and
i think it will be easier by far if it is pulled apart somewhat.

thanks again
shawn

On 12/30/06, Kent Johnson <[EMAIL PROTECTED]> wrote:


shawn bright wrote:
> Hello there all.
> i have an app that has grown to about 4000 lines. It uses 6 threads and
> a GTK2 GUI.
> i was wondering if i could split it into seperate files that i could
> import. Each thread is a class.

That should be fine.

> i did not think that this would be a problem, but some of the threads
> pass information to views and buffers.

How do the threads find out about the views and buffers? If they are
global objects then you will have a problem. If they are passed to the
threads as parameters then it should be fine.

> If i had a thread outside of the main file, could i pass a gtk object to
> it so that it could write to it when it needed too?

Yes.

> and one last thing. If i did this, would i be able to only import the
> class when i started the thread, and then re-import it if i started the
> thread later . If so, this would allow me to work on a thread without
> having to restart the main program, and i could let the other threads
> keep running. As i find bugs, i could squash them without loosing any
> functionality of the other threads. Then if i wanted to stop or restart
> a thread by clicking a button, i could just re-import the class.
>
> is this ok ?

You can use reload() to update a module that has been changed. You will
also have to recreate any objects that were created from classes in the
module so they become instances of the modified module. You might be
interested in this recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164

Kent

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



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


Re: [Tutor] question about importing threads

2006-12-30 Thread Kent Johnson
shawn bright wrote:
> Hello there all.
> i have an app that has grown to about 4000 lines. It uses 6 threads and 
> a GTK2 GUI.
> i was wondering if i could split it into seperate files that i could 
> import. Each thread is a class.

That should be fine.

> i did not think that this would be a problem, but some of the threads 
> pass information to views and buffers.

How do the threads find out about the views and buffers? If they are 
global objects then you will have a problem. If they are passed to the 
threads as parameters then it should be fine.

> If i had a thread outside of the main file, could i pass a gtk object to 
> it so that it could write to it when it needed too?

Yes.

> and one last thing. If i did this, would i be able to only import the 
> class when i started the thread, and then re-import it if i started the 
> thread later . If so, this would allow me to work on a thread without 
> having to restart the main program, and i could let the other threads 
> keep running. As i find bugs, i could squash them without loosing any 
> functionality of the other threads. Then if i wanted to stop or restart 
> a thread by clicking a button, i could just re-import the class.
> 
> is this ok ?

You can use reload() to update a module that has been changed. You will 
also have to recreate any objects that were created from classes in the 
module so they become instances of the modified module. You might be 
interested in this recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164

Kent

> 
> thanks
> shawn
> 
> 
> 
> 
> ___
> 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] question about importing threads

2006-12-30 Thread shawn bright

Hello there all.
i have an app that has grown to about 4000 lines. It uses 6 threads and a
GTK2 GUI.
i was wondering if i could split it into seperate files that i could import.
Each thread is a class.
i did not think that this would be a problem, but some of the threads pass
information to views and buffers.
If i had a thread outside of the main file, could i pass a gtk object to it
so that it could write to it when it needed too?
and one last thing. If i did this, would i be able to only import the class
when i started the thread, and then re-import it if i started the thread
later . If so, this would allow me to work on a thread without having to
restart the main program, and i could let the other threads keep running. As
i find bugs, i could squash them without loosing any functionality of the
other threads. Then if i wanted to stop or restart a thread by clicking a
button, i could just re-import the class.

is this ok ?

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


Re: [Tutor] Question about exception handling

2006-12-17 Thread Adam Bark

On 17/12/06, Asrarahmed Kadri <[EMAIL PROTECTED]> wrote:



Hi Folks,

Is it possible to catch exception raised in module A to be caught in
module B.

If yes, then please let me know how to do it.



You can easily test this yourself. First right a quick module, something
like this will do:

def exception_test():
   raise Exception

then start an interpreter and do the following


import your_module
try:

... your_module.exception_test()
... except:
... print "Caught it!"
...

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


[Tutor] Question about exception handling

2006-12-17 Thread Asrarahmed Kadri

Hi Folks,

Is it possible to catch exception raised in module A to be caught in module
B.

If yes, then please let me know how to do it.

TIA.

Regards,
Asrarahmed Kadri



--
To HIM you shall return.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question about HORIZONTAL BAR CHART.....

2006-11-26 Thread Luke Paireepinart
Asrarahmed Kadri wrote:
> As far as I understand, I need to design an algorithm which computes 
> the padding between each bar (space between each bar) and the length 
> of each bar ( remember that this is a HORIZONTAL BAR CHART).
I think what you want to design is an algorithm that computes the HEIGHT 
of each bar (as it's a HORIZONTAL bar chart)
because the vertical padding, (The space between each bar) is a fixed 
number, like 20 pixels.  At least that's what i would do.
This height is dependent upon the number of data sets you have.

For the width of the bars (remember this is a horizontal bar chart, so 
the heights of the bars will all be the same, but the widths will be 
different)
you will want to set it up so that the largest data value is set to the 
widest bar, and the rest are percentages of this width.
I hope that helps.
-Luke

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


Re: [Tutor] Question about HORIZONTAL BAR CHART.....

2006-11-25 Thread Asrarahmed Kadri

As far as I understand, I need to design an algorithm which computes the
padding between each bar (space between each bar) and the length of each bar
( remember that this is a HORIZONTAL BAR CHART).

I am trying to understand your email. ( Please bear with my slow
comprehension )

Regards,
Asrarahmed Kadri


On 11/24/06, Luke Paireepinart <[EMAIL PROTECTED]> wrote:


Asrarahmed Kadri wrote:
>
>
> Hi Folks,
>
> I am constructing a bar-chart using Tkinter. The function takes a list
> 'data' and draws horizontal bar for each value.
> Now what I want is  the the canvas widget should be able to handle
> variable number of data-items. I cannot figure out how to do that,
> because I have hard coded the lengths of X and Y axes. I want to make
> the entire function a lot more flexible so that it determines the
> length of both the axes on the basis of data supplied to it.
#disclaimer
Note: I didn't realize you said horizontal bar charts.
This does vertical bar charts.
It should be trivial to change this.
Sorry for not reading your post more carefully to begin with.


#for width
>>> data = [1,5,6,7,8,3,2,9]
>>>target_width = 600
>>>padding = 10
>>>num_of_data_items = len(data)
>>>individual_width =(
target_width-(padding*(num_of_data_items-1)))/num_of_data_items
>>>individual_width
66
>>>individual_width*num_of_data_items
528
>>>padding* (len(data)-1)
70
>>>528 + 70
598

#for height
>>>target_height = 600
>>> maxval = max(yvals)
>>> for item in yvals:
   print int((float(item)/maxval) * target_height)

66
333
400
466
533
200
133
600

Did you honestly try to think this through before posting?
It's a very simple concept.
Not trying to be mean, just frank.
I think you could've done this on your own if you had tried.
Good luck with your bar charts. :)

When you ask a question such as this
"I cannot figure out how to do that, because I have hard coded the
lengths of X and Y axes. I want to make the entire function a lot more
flexible so that it determines the length of both the axes on the basis
of data supplied to it."
The way you should be reasoning is this:
I have hardcoded the lengths of the x and y axes.
I need to change this for my function to operate how I want it to.
How do I change it?
1) I have the data set already, so how do i figure out the width? (or
height, if you're doing horizontal bar graphs)
Well, I can make the following distinctions:
- I have a target width (the width of the canvas) that they must all fit
within.
- all bars will be the same width
- there should be some distance between each bar.
- this distance should be the same no matter how many data elements
there are, IE fixed.
- so if I have a fixed width between variable amounts of data, how would
I design an algorithm to perform this for me on any arbitrary data set?

2) How do I figure out the height of the data sets? (or width, if you're
doing horizontal bar graphs)
The following distinctions can be made:
- I have a target height that they all must fit within (the height of
the canvas)
- Only the maximum value should be the full height of the canvas.
- the others should be less than this height, depending NOT on their
ratio to the height of the maximum bar, but on their ratio to the data
that generated this.
-- what do we use for ratios? Fractions!

HTH,
-Luke





--
To HIM you shall return.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question about __init__ in a class

2006-11-13 Thread Andreas Kostyrka
* shawn bright <[EMAIL PROTECTED]> [061113 23:51]:
> hey thanks, did not think about the possible consequences of the use of a
> built in as a variable name.

Well, the consequences are minimal:

a) pylint complains by default about that.
b) if you paste code into your function, you might get problems, as it
might use the "standard" id.

Please note, that self.id is safe from that, but you probably want to
name the attribute of the instance the same as the constructor
arguments.

Andreas

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


Re: [Tutor] question about __init__ in a class

2006-11-13 Thread shawn bright
hey thanks, did not think about the possible consequences of the use of a built in as a variable name.-skOn 11/13/06, Andreas Kostyrka <
[EMAIL PROTECTED]> wrote:* shawn bright <
[EMAIL PROTECTED]> [061113 19:46]:> Hello there all.> i have a class that i need to load some class variables depending on what is> passed to the class, it would either be set up using one variable or
> another. The values for the class variables would be loaded from a database.> But how it is looked up depends on how its called. Like this:>> class Sensor_Object(object):>def __init__(self, id, monitor):
>if id:>   self.id = id>   load values from the database>   value1 = somevalue>   value2 = someOthervalue>else:
>   self.monitor = monitor>   get some values from database>   value1 = somevalue>   value2 = someothervalue>> now i could call it like this:>
> new_monitor = sensor.Sensor('', 'XJ191')> or> new_monitor = sensor.Sensor('3433', '')> to load based on the other variable.>> i think that this would work, but i was thinking that there must be a
> cleaner way to do it.Well, the code is basically ok, but I'd propose the following (it willhelp using the instances):class Sensor_Object(object):sensid = Nonemonitor = None
...Basically, provide class variables shadowing your "main" instanceattributes. I've also renamed id to sensid as id is an builtinfunction. (it's legal and ok to use id, but some tools like pylint
like to complain about that style of shadowing.)The benefit is easy, in other methods, you can use code like this:if self.sensid is not None: instead of the more clumsyif hasattr(self, "sensid"):
Andreas> any suggestions ?>> sk> ___> Tutor maillist  -  Tutor@python.org> 
http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question about __init__ in a class

2006-11-13 Thread Andreas Kostyrka
* shawn bright <[EMAIL PROTECTED]> [061113 19:46]:
> Hello there all.
> i have a class that i need to load some class variables depending on what is
> passed to the class, it would either be set up using one variable or
> another. The values for the class variables would be loaded from a database.
> But how it is looked up depends on how its called. Like this:
> 
> class Sensor_Object(object):
>def __init__(self, id, monitor):
>if id:
>   self.id = id
>   load values from the database
>   value1 = somevalue
>   value2 = someOthervalue
>else:
>   self.monitor = monitor
>   get some values from database
>   value1 = somevalue
>   value2 = someothervalue
> 
> now i could call it like this:
> 
> new_monitor = sensor.Sensor('', 'XJ191')
> or
> new_monitor = sensor.Sensor('3433', '')
> to load based on the other variable.
> 
> i think that this would work, but i was thinking that there must be a
> cleaner way to do it.

Well, the code is basically ok, but I'd propose the following (it will
help using the instances):

class Sensor_Object(object):
sensid = None
monitor = None

...

Basically, provide class variables shadowing your "main" instance
attributes. I've also renamed id to sensid as id is an builtin
function. (it's legal and ok to use id, but some tools like pylint
like to complain about that style of shadowing.)

The benefit is easy, in other methods, you can use code like this:
if self.sensid is not None:
 instead of the more clumsy
if hasattr(self, "sensid"):
 
Andreas

> any suggestions ?
> 
> sk

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

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


Re: [Tutor] question about __init__ in a class

2006-11-13 Thread Kent Johnson
Mike Hansen wrote:
>  
> 
>> -Original Message-
>> From: [EMAIL PROTECTED] 
>> [mailto:[EMAIL PROTECTED] On Behalf Of shawn bright
>> Sent: Monday, November 13, 2006 11:45 AM
>> To: tutor-python
>> Subject: [Tutor] question about __init__ in a class
>>
>> Hello there all.
>> i have a class that i need to load some class variables 
>> depending on what is passed to the class, it would either be 
>> set up using one variable or another.

> I don't know if it's cleaner, but it might be easier to read if you use
> default named arguments.
> def __init__(self, id = None, monitor = None):
> 
> Calling it
> new_monitor = sensor.Sensor(monitor = 'XJ191')
> new_monitor = sensor.Sensor(id = '3433')
> 
> Check to make sure one or the other arguments is supplied. Otherwise
> throw an exception.
> 
> Maybe there'll be some better ideas from other posters.

That is a good solution. Another way is to make new functions that wrap 
the constructor. In sensor.py add:

def fromId(id):
   return Sensor(id, None)

def fromMonitor(monitor):
   return Sensor(None, monitor)

Then client code is
new_monitor = sensor.fromMonitor('XJ191')
new_monitor = sensor.fromId('3433')

Kent

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


Re: [Tutor] question about __init__ in a class

2006-11-13 Thread shawn bright
Thats a lot better, thanks, will use it like that.-shawnOn 11/13/06, Mike Hansen <[EMAIL PROTECTED]
> wrote:> -Original Message-> From: 
[EMAIL PROTECTED]> [mailto:[EMAIL PROTECTED]] On Behalf Of shawn bright> Sent: Monday, November 13, 2006 11:45 AM> To: tutor-python> Subject: [Tutor] question about __init__ in a class
>> Hello there all.> i have a class that i need to load some class variables> depending on what is passed to the class, it would either be> set up using one variable or another. The values for the
> class variables would be loaded from a database. But how it> is looked up depends on how its called. Like this:>> class Sensor_Object(object):> def __init__(self, id, monitor):
> if id:>self.id = id>load values from the database>value1 = somevalue>value2 = someOthervalue> else:
>self.monitor = monitor>get some values from database>value1 = somevalue>value2 = someothervalue>> now i could call it like this:
>> new_monitor = sensor.Sensor('', 'XJ191')> or> new_monitor = sensor.Sensor('3433', '')> to load based on the other variable.>> i think that this would work, but i was thinking that there
> must be a cleaner way to do it.> any suggestions ?>> skI don't know if it's cleaner, but it might be easier to read if you usedefault named arguments.def __init__(self, id = None, monitor = None):
Calling itnew_monitor = sensor.Sensor(monitor = 'XJ191')new_monitor = sensor.Sensor(id = '3433')Check to make sure one or the other arguments is supplied. Otherwisethrow an exception.Maybe there'll be some better ideas from other posters.
Mike-  NOTICE:  This e-mail transmission and any documents or files attached to  it contain information for the sole use of the above-identified individual or entity.
  Its contents may be privileged, confidential, and exempt from disclosure under the law.  Any dissemination, distribution, or copying of this communication is strictly prohibited.  Please notify the sender immediately if you are not the intended recipient.
FGNS___Tutor maillist  -  Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor

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


Re: [Tutor] question about __init__ in a class

2006-11-13 Thread Mike Hansen
 

> -Original Message-
> From: [EMAIL PROTECTED] 
> [mailto:[EMAIL PROTECTED] On Behalf Of shawn bright
> Sent: Monday, November 13, 2006 11:45 AM
> To: tutor-python
> Subject: [Tutor] question about __init__ in a class
> 
> Hello there all.
> i have a class that i need to load some class variables 
> depending on what is passed to the class, it would either be 
> set up using one variable or another. The values for the 
> class variables would be loaded from a database. But how it 
> is looked up depends on how its called. Like this: 
> 
> class Sensor_Object(object):
> def __init__(self, id, monitor):
> if id:
>self.id = id
>load values from the database
>value1 = somevalue 
>value2 = someOthervalue
> else:
>self.monitor = monitor
>get some values from database
>value1 = somevalue
>value2 = someothervalue
> 
> now i could call it like this: 
> 
> new_monitor = sensor.Sensor('', 'XJ191')
> or
> new_monitor = sensor.Sensor('3433', '')
> to load based on the other variable.
> 
> i think that this would work, but i was thinking that there 
> must be a cleaner way to do it. 
> any suggestions ?
> 
> sk

I don't know if it's cleaner, but it might be easier to read if you use
default named arguments.
def __init__(self, id = None, monitor = None):

Calling it
new_monitor = sensor.Sensor(monitor = 'XJ191')
new_monitor = sensor.Sensor(id = '3433')

Check to make sure one or the other arguments is supplied. Otherwise
throw an exception.

Maybe there'll be some better ideas from other posters.

Mike



-

  NOTICE:  This e-mail transmission and any documents or files attached to
  it contain information for the sole use of the above-identified individual or 
entity.

  Its contents may be privileged, confidential, and exempt from disclosure 
under the law.
  Any dissemination, distribution, or copying of this communication is strictly 
prohibited.

  Please notify the sender immediately if you are not the intended recipient.

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


[Tutor] question about __init__ in a class

2006-11-13 Thread shawn bright
Hello there all.i have a class that i need to load some class variables depending on what is passed to the class, it would either be set up using one variable or another. The values for the class variables would be loaded from a database. But how it is looked up depends on how its called. Like this:
class Sensor_Object(object):    def __init__(self, id, monitor):    if id:   self.id = id   load values from the database   value1 = somevalue
   value2 = someOthervalue    else:   self.monitor = monitor   get some values from database   value1 = somevalue   value2 = someothervaluenow i could call it like this:
new_monitor = sensor.Sensor('', 'XJ191')ornew_monitor = sensor.Sensor('3433', '')to load based on the other variable.i think that this would work, but i was thinking that there must be a cleaner way to do it.
any suggestions ?sk   
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] question

2006-11-03 Thread Jonathon Sisson
Hi Doug,

I'm not a Python guru, but shouldn't you be putting the output of 
file.split('\n') into a list, and not back into a string (for clarity's 
sake?).

Also, if you have two trailing newlines on the file, your final string 
will be '', so you should be doing clean1.append(i[26:40]) in your for 
loop, right?

Let me know if that helps...

Jonathon


Doug Potter wrote:
> I don't get  the output I would expect from the following.
> The variable clean1 gives me an empty string.  But if i change the for 
> loop to print i[26:40] I get all the info.
> what do I need to do to capture all the data to clean1? 
> 
> Thanks.
> 
>  >>> a = open('arp.txt')
>  >>> file = a.read()
>  >>> file = file.split('\n')
>  >>> a.close()
>  >>> b = open('arplist.txt','w')
>  >>> clean1 = []
>  >>>
>  >>> for i in file:
> ... clean1 = i[26:40]
> ...
>  >>> clean1
> ''
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question

2006-11-03 Thread Alan Gauld
"Doug Potter" <[EMAIL PROTECTED]> wrote
>I don't get  the output I would expect from the following.

> >>> a = open('arp.txt')
> >>> file = a.read()
> >>> file = file.split('\n')

Easier to do

file = open('arp.txt').readlines()

But file is a bad name since its an alias for open...

> >>> b = open('arplist.txt','w')

Not sure why you do this

> >>> clean1 = []
> >>>

clean is an empty list

> >>> for i in file:
> ... clean1 = i[26:40]

clean is now overwritten by a string until you reach the 
end of the file upon which clean1 will be an empty string

> >>> clean1
> ''

Which it is...

I think you may have meant to use the append method

for i in file:
clean1.append(i[26:40])

And since you can iterate over a file the whole thing shrinks to:

clean1 = []
for i in open('arp.txt'):
clean1.append(i[26:40])
print clean1

Or even more succinctly:

clean1 = [i[26:40] for i in open('arp.txt')]
print clean1

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld

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


Re: [Tutor] question about classes and atributes

2006-11-03 Thread Alan Gauld
"Kent Johnson" <[EMAIL PROTECTED]> wrote 
> Alan Gauld wrote:
>> I'm not sure about adding methods at run time, I've never 
> Sure it works:
> 
> In [1]: class foo(object): pass
>...:
> In [4]: def show(self): print "Hi, I'm a foo"
> 
> In [5]: foo.show=show
> 
> In [6]: f.show()
> Hi, I'm a foo

Cool! 
I'm constantly amazed at the power and simplicity of Python.

> More advanced explanation:

Yes, it makes sense when its explained. 
But I'd never have intuitively thought of that!

Thanks for the info Kent.

Alan G.


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


[Tutor] question

2006-11-03 Thread Doug Potter
I don't get  the output I would expect from the following.
The variable clean1 gives me an empty string.  But if i change the for 
loop to print i[26:40] I get all the info.
what do I need to do to capture all the data to clean1? 

Thanks.

 >>> a = open('arp.txt')
 >>> file = a.read()
 >>> file = file.split('\n')
 >>> a.close()
 >>> b = open('arplist.txt','w')
 >>> clean1 = []
 >>>
 >>> for i in file:
... clean1 = i[26:40]
...
 >>> clean1
''

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


Re: [Tutor] question about classes and atributes

2006-11-03 Thread euoar
Thank you folks, for your excellent answers. This is really a fantastic 
place to learn python :-)


__ 
LLama Gratis a cualquier PC del Mundo. 
Llamadas a fijos y móviles desde 1 céntimo por minuto. 
http://es.voice.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question about classes and atributes

2006-11-03 Thread Kent Johnson
Alan Gauld wrote:
> "euoar" <[EMAIL PROTECTED]> wrote in 
>> So, in python, you can add methods at run time to an 
>> object, and even you can add them to a class at run time?
> 
> I'm not sure about adding methods at run time, I've never 
> tried it but I think the magic around the self parameter 
> might not work. But you can definitely add attributes.

Sure it works:

In [1]: class foo(object): pass
...:

In [2]: f=foo()

In [3]: f.show()
---
Traceback (most recent call last)

D:\Projects\e3po\ in ()

: 'foo' object has no attribute 'show'

In [4]: def show(self): print "Hi, I'm a foo"
...:

In [5]: foo.show=show

In [6]: f.show()
Hi, I'm a foo


More advanced explanation:
The magic around the self parameter is actually built-in to every 
function object (or its class, anyway). Functions have __get__() methods 
which means they can be used as descriptors. When Python evaluates 
f.show(), quite a few steps happen:

- find the value of the show attribute in the class definition. This 
finds the show function object.
- the function object has a __get__() method, so call show.__get__(obj) 
where obj is the original object being accessed.
- the __get__() method wraps obj and the original function into a new 
callable object and returns that.
- finally the temporary callable is actually called (by calling its 
__call__() method) and the wrapper adds the self parameter to the 
argument list and dispatches to the wrapped (original) function.


The descriptor mechanism is only used for class attributes, not instance 
attributes, so if you want to add a method to an individual instance you 
have to do a little more work using new.instancemethod:

In [12]: def show2(self): print "I'm still a foo"
:

The naive approach won't work:
In [14]: f.show2 = show2

In [15]: f.show2()
: show2() takes exactly 1 argument (0 given)

In [17]: import new

In [21]: f.show2 = new.instancemethod(show2, f)

In [22]: f.show2()
I'm still a foo

I hope that makes sense to someone; I had to see it about 10 times 
myself before a light bulb went on. (This is number 10 :-)

More info here and in the references:
http://www.python.org/doc/2.2.3/whatsnew/sect-rellinks.html#SECTION00032

Kent

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


Re: [Tutor] question about classes and atributes

2006-11-03 Thread Alan Gauld

"euoar" <[EMAIL PROTECTED]> wrote in 
> Thank you for your answer and the examples. 
> So without self it is an instance variable (like "static" 
> in java/c#). 

Without self it is a class attribute like static etc in C++/Java.
An instance variable is one that is unique to an instance!

Although I think it may be more powerful since I seem to 
recall that static members are not accessible via inheritance
whereas Python class variables are. Also i'm not sure if 
statics can be reached via an instance whereas Python class 
variables can.

But my Java/C# is very rusty on statics...

Note also that you can go even further by specifying 
class methods too but they need special syntax. 

If you are only familiar with Java style statics you might 
find the concept of class variables and methods a little 
different in Python, which follows the traditional OOP 
style of Lisp and SmallTalk rather than the hybrid OOP 
style of Java etc. That is, a class variable/method is 
usually treated as one that applies to the class itself, 
or one that is shared by all instances. Java tend to use 
static methods as a replacement for traditional functions, 
ie. things you can do without creating an instance. You can 
do both things in any of the languages but conceptually 
they tend to be treated differently, especially since 
Python supports stand-alone functions.

> Are you creating new atributes and methods at run time? 
> Is that what has happened? In fact I have tried also this:

Yes, Python classes are a special type of container (really 
a special type of dictionary) , so just as you can add new 
keys to a dictionary you an add new attributes to a class
or object at run time.

> So, in python, you can add methods at run time to an 
> object, and even you can add them to a class at run time?

I'm not sure about adding methods at run time, I've never 
tried it but I think the magic around the self parameter 
might not work. But you can definitely add attributes.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld

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


Re: [Tutor] question about classes and atributes

2006-11-03 Thread Luke Paireepinart

>>> I think I don't understand the OOP in python, could anyone explain why 
>>> this code works?
>>>
>>> class example:
>>> atribute = "hello world"
>>>
>>> print example.atribute
>>>
>>> Why you don't have to make an object of the class to access to the 
>>> atribute?
>>>   
because that attribute is part of the Class object that's created when 
you declare a class.

As you can see by the following code:
 >>> class example:
attribute = 'hello, world!'
 >>> example


there is actually a type of object called 'class.'
when you make an instance of a class,
 >>> a = example()
 >>> a
<__main__.example instance at 0x00B40440>

it is now a example object instance.
> Thank you for your answer and the examples. So without self it is an 
> instance variable (like "static" in java/c#). But then, I don't 
> understand how is it possible this in your example:
>
> c1.ca = 140 
>   
Because c1 is an instance of the class 'C', it has the attribute .ca 
already in it.
This is a reference to the class attribute 'ca' which is equal to 123.
However, when you change c1.ca, because the class attribute 'ca' is 
immutable (since it's an integer)
a local copy of ca is created with the value 140 in it.
C.ca is still 123.
If you now do C.ca = 234,
c1.ca is still 140, because it now has a local (instance) attribute 
called 'ca' that hides the class attribute.
However, if you do something like this...
class C:
ca = 123
c1 = C()
C.ca = 567
print c1.ca

you will get an output of '567'.
because c1 never got the local instance attribute to replace the 
reference to the class-wide attribute,
so changing the C.ca will also affect c1.ca.

> or down:
>
> print C.method
>
> Are you creating new atributes and methods at run time? Is that what has 
> happened? In fact I have tried also this:
>
> class example:
>   atribute = "green"
>
> obj = example()
> obj.a_new_atribute = "white"
>
> And even this seems to be correct:
>
> class example:
>   atribute = "green"
>
> example._other_atribute = "yellow"
>
>
> So, in python, you can add methods at run time to an object, and even you can 
> add them to a class at run time?
>   
No, you're confusing Python with a compiled language.
You're not adding methods to an object at run-time because there's not a 
distinction between runtime and compile-time in Python,
because compile-time doesn't exist.
You can add attributes to classes any time you want inside your program.
Just like I can add an element to a list any time I want.
a = [1,2,3]
a.append(4)
Classes are just objects, as lists are, and integers are, and  
everything else is as well.
And when I execute the code, Python knows how to do all of these things.

You see, an interpreted session is not the same as you think of 'at run 
time' being.
For the most part, an interpreted session is exactly the same as if I 
were to type the code into a text document,
save it, and execute it.
So yeah, anywhere in your program you can add methods to classes,
but really saying 'at run-time' is confusing terminology.
It implies that if I were running someone else's program I could just
add methods in on the fly whenever I wanted to.
This is not true, unless they've enabled this functionality.


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


Re: [Tutor] question about classes and atributes

2006-11-03 Thread euoar
Andreas Kostyrka escribió:
> Because your atribute is a class attribute:
>
> class C:
> ca = 123
>
> print C.ca # 123
> c1 = C()
> print c1.ca# 123
> c1.ca = 140 
> print c1.ca# 140
> print C.ca # 123
> c2 = C()
> print c2.ca# 123
> C.ca = 141
> print C.ca # 141
> print c1.ca# 140
> print c2.ca# 141
>
> Basically, when an instance does not have an attribute, it looks them up
> in the class, which might recurse into base classes.
>
> Furthermore, objects & classes 101 material:
>
> class C:
> def method(self):
> print self
>
> c = C()
> print c.method  # bound method to c
> print C.method  # unbound method, checks that first argument is a C
> print C.__dict__["method"]
> # function, does NOT check first argument.
>
> So basically, the whole self argument handling is magic that happpens
> during attribute lookup.
>
> Andreas
>
> Am Freitag, den 03.11.2006, 14:27 +0100 schrieb euoar:
>   
>> I think I don't understand the OOP in python, could anyone explain why 
>> this code works?
>>
>> class example:
>> atribute = "hello world"
>>
>> print example.atribute
>>
>> Why you don't have to make an object of the class to access to the 
>> atribute?
>>
>> ( class example:
>>atribute = "hello world"
>>   
>>   obj = example()
>>   print obj.atribute
>>
>>
>> Thanks in advance.
>>
>>  
>> __ 
>> LLama Gratis a cualquier PC del Mundo. 
>> Llamadas a fijos y móviles desde 1 céntimo por minuto. 
>> http://es.voice.yahoo.com
>> ___
>> Tutor maillist  -  Tutor@python.org
>> http://mail.python.org/mailman/listinfo/tutor
>> 
Thank you for your answer and the examples. So without self it is an 
instance variable (like "static" in java/c#). But then, I don't 
understand how is it possible this in your example:

c1.ca = 140 

or down:

print C.method

Are you creating new atributes and methods at run time? Is that what has 
happened? In fact I have tried also this:

class example:
atribute = "green"

obj = example()
obj.a_new_atribute = "white"

And even this seems to be correct:

class example:
atribute = "green"

example._other_atribute = "yellow"


So, in python, you can add methods at run time to an object, and even you can 
add them to a class at run time?



__ 
LLama Gratis a cualquier PC del Mundo. 
Llamadas a fijos y móviles desde 1 céntimo por minuto. 
http://es.voice.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question about classes and atributes

2006-11-03 Thread Andreas Kostyrka
Because your atribute is a class attribute:

class C:
ca = 123

print C.ca # 123
c1 = C()
print c1.ca# 123
c1.ca = 140 
print c1.ca# 140
print C.ca # 123
c2 = C()
print c2.ca# 123
C.ca = 141
print C.ca # 141
print c1.ca# 140
print c2.ca# 141

Basically, when an instance does not have an attribute, it looks them up
in the class, which might recurse into base classes.

Furthermore, objects & classes 101 material:

class C:
def method(self):
print self

c = C()
print c.method  # bound method to c
print C.method  # unbound method, checks that first argument is a C
print C.__dict__["method"]
# function, does NOT check first argument.

So basically, the whole self argument handling is magic that happpens
during attribute lookup.

Andreas

Am Freitag, den 03.11.2006, 14:27 +0100 schrieb euoar:
> I think I don't understand the OOP in python, could anyone explain why 
> this code works?
> 
> class example:
> atribute = "hello world"
>
> print example.atribute
> 
> Why you don't have to make an object of the class to access to the 
> atribute?
> 
> ( class example:
>atribute = "hello world"
>   
>   obj = example()
>   print obj.atribute
> 
> 
> Thanks in advance.
> 
>   
> __ 
> LLama Gratis a cualquier PC del Mundo. 
> Llamadas a fijos y móviles desde 1 céntimo por minuto. 
> http://es.voice.yahoo.com
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor


signature.asc
Description: Dies ist ein digital signierter Nachrichtenteil
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] question about classes and atributes

2006-11-03 Thread euoar
I think I don't understand the OOP in python, could anyone explain why 
this code works?

class example:
atribute = "hello world"
   
print example.atribute

Why you don't have to make an object of the class to access to the 
atribute?

( class example:
   atribute = "hello world"
  
  obj = example()
  print obj.atribute


Thanks in advance.


__ 
LLama Gratis a cualquier PC del Mundo. 
Llamadas a fijos y móviles desde 1 céntimo por minuto. 
http://es.voice.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question about pylab

2006-10-31 Thread shawn bright
ok, looks like the date2num() function on a datetime.datetime object is working. So cool.i am very new at this, so i may be back ( read probably be back ). Thanks much for the tips.i appreciate it a lot.sk
On 10/31/06, Kent Johnson <[EMAIL PROTECTED]> wrote:
shawn bright wrote:> hey there,> i am trying to use a graph and chart app called matplotlib, but i cannot> figgure out how to have it plot a simple chart over time.> the docs say to use the function plot_date() but i cannot seem to get
> the values to agree.> I am sending datetimes to the charting app for x, and the y is a list of> values that the our equipment reports.> sometimes there are lots of reports in a row, and i would like the chart
> to show it like that instead of plotting out every time as an evenly> spaced tick on the x scale. Does this make any sense, what i am after> here? Anyway, if any of you have much experience with this sort of
> thing, or may suggest a package (pylab is my first attempt) please send> me some advice.I have used pylab to create a scatterplot of date vs value. The datevalues were created by calling pylab.date2num
() on a datetime.datetimevalue. The axes were set up with this code:# Set up the xaxisax = axes([0.05, 0.05, 0.9, 0.9])ax.xaxis.set_major_locator(MinuteLocator(interval=10))ax.xaxis.set_minor_locator
(MinuteLocator())ax.xaxis.set_major_formatter(DateFormatter("%H:%M"))I called pylab.scatter() to create the plot.HTH,Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question about pylab

2006-10-31 Thread Kent Johnson
shawn bright wrote:
> hey there,
> i am trying to use a graph and chart app called matplotlib, but i cannot 
> figgure out how to have it plot a simple chart over time.
> the docs say to use the function plot_date() but i cannot seem to get 
> the values to agree.
> I am sending datetimes to the charting app for x, and the y is a list of 
> values that the our equipment reports.
> sometimes there are lots of reports in a row, and i would like the chart 
> to show it like that instead of plotting out every time as an evenly 
> spaced tick on the x scale. Does this make any sense, what i am after 
> here? Anyway, if any of you have much experience with this sort of 
> thing, or may suggest a package (pylab is my first attempt) please send 
> me some advice.

I have used pylab to create a scatterplot of date vs value. The date 
values were created by calling pylab.date2num() on a datetime.datetime 
value. The axes were set up with this code:

# Set up the xaxis
ax = axes([0.05, 0.05, 0.9, 0.9])

ax.xaxis.set_major_locator(MinuteLocator(interval=10))
ax.xaxis.set_minor_locator(MinuteLocator())
ax.xaxis.set_major_formatter(DateFormatter("%H:%M"))


I called pylab.scatter() to create the plot.

HTH,
Kent

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


Re: [Tutor] question about pylab

2006-10-31 Thread Markus Rosenstihl

Am 31.10.2006 um 08:35 schrieb shawn bright:

> hey there,
> i am trying to use a graph and chart app called matplotlib, but i 
> cannot figgure out how to have it plot a simple chart over time.
> the docs say to use the function plot_date() but i cannot seem to get 
> the values to agree.
> I am sending datetimes to the charting app for x, and the y is a list 
> of values that the our equipment reports.
> sometimes there are lots of reports in a row, and i would like the 
> chart to show it like that instead of plotting out every time as an 
> evenly spaced tick on the x scale. Does this make any sense, what i am 
> after here? Anyway, if any of you have much experience with this sort 
> of thing, or may suggest a package (pylab is my first attempt) please 
> send me some advice.
>
> thanks for your time,
> sk

I am not sure if I get it right, could you give us some sample data   
and some code what you have tried?
I never used plot_date, but I could give it a try.

Regards,
Markus

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


[Tutor] question about pylab

2006-10-30 Thread shawn bright
hey there,i am trying to use a graph and chart app called matplotlib, but i cannot figgure out how to have it plot a simple chart over time.the docs say to use the function plot_date() but i cannot seem to get the values to agree. 
I am sending datetimes to the charting app for x, and the y is a list of values that the our equipment reports. sometimes there are lots of reports in a row, and i would like the chart to show it like that instead of plotting out every time as an evenly spaced tick on the x scale. Does this make any sense, what i am after here? Anyway, if any of you have much experience with this sort of thing, or may suggest a package (pylab is my first attempt) please send me some advice.
thanks for your time,sk
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question abt numpy and Numeric...........

2006-10-24 Thread Asrarahmed Kadri
I got it, both are same, numpy is the latest.
Numeric being the oldest, numarray in the middle and the latest is numpy.
 
Got it ..
Thanks Kent..
 
On 10/24/06, Kent Johnson <[EMAIL PROTECTED]> wrote:
Asrarahmed Kadri wrote:>> Folks,>> Is numpy different from Numeric; or are both one and the same >??
>> Kindly explain the difference ..Seehttp://numpy.scipy.org/#older_array___Tutor maillist  -  
Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutor-- To HIM you shall return. 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Question abt numpy and Numeric...........

2006-10-24 Thread Kent Johnson
Asrarahmed Kadri wrote:
> 
> Folks,
>  
> Is numpy different from Numeric; or are both one and the same >??
>  
> Kindly explain the difference ..

See
http://numpy.scipy.org/#older_array

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


[Tutor] Question abt numpy and Numeric...........

2006-10-24 Thread Asrarahmed Kadri
Folks,
 
Is numpy different from Numeric; or are both one and the same >??
 
Kindly explain the difference ..
 
Regards,
Asrarahmed-- To HIM you shall return. 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question about number of threads

2006-10-12 Thread Kent Johnson
shawn bright wrote:
> Hey there,
> i have an app that runs several processes as threads.
> using the threading.Thread()
> 
> now, i have another app that does the same thing. Now, pretty soon, we 
> will be combining all the features of the two packages together into one 
> app.
> 
> My question is, is there a limit on how many threads one GUI application 
> can have running in the background ?
> Most of them are sleeping most of the time. They wake up and do 
> something every 10 seconds, 20 minutes, etc...

IIRC the number of threads is limited by memory - each thread requires 
some heap space for its stack, etc. I don't think you will have trouble 
until you have hundreds or thousands of threads.

For example on my computer this program prints 1031 before it exits with 
thread.error: can't start new thread:

import time
from threading import Thread, activeCount

def run():
 while 1:
 time.sleep(1)

while 1:
 print activeCount()
 t=Thread(target=run)
 t.setDaemon(1)
 t.start()

(The setDaemon() call lets the application exit normally when it gets an 
exception; otherwise it hangs with all the threads running.)

Kent

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


[Tutor] question about number of threads

2006-10-12 Thread shawn bright
Hey there,
i have an app that runs several processes as threads.
using the threading.Thread()

now, i have another app that does the same thing. Now, pretty soon, we
will be combining all the features of the two packages together into
one app. 

My question is, is there a limit on how many threads one GUI application can have running in the background ?
Most of them are sleeping most of the time. They wake up and do something every 10 seconds, 20 minutes, etc...

Any pitfalls out there i shoud know about ?

thanks

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


Re: [Tutor] question about looping.

2006-10-08 Thread Hugo González Monteverde
Doug Potter wrote:

> for i in routers:
> os.system('/bin/touch' %s) % i
> 
> of course this dosn't work.
> 
> Is there a simple way to get this done?

Yep, someone already answered that you can create the file in write mode 
and then close it, but I wanted to add a little more in why your 
solution doesn't work.

You're not interpolating the filename INTO the os.system string


The following would work

  for i in routers:
  os.system('/bin/touch %s'%1)

Granted, you should also provide a filename with a full path for simplicity.

HTH

Hugo

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


Re: [Tutor] question about looping.

2006-10-06 Thread Carlos Hanson
Doug Potter wrote:
> Hi,
> 
> I at trying to create a bunch of text files in a single directory on a 
> Linux system,
> something like this.
> 
> import os
> 
> routers = ['adnc-6321', 'adnp-2341', 'adnw-2632']
> 
> for i in routers:
> os.system('/bin/touch' %s) % i
> 
> of course this dosn't work.

try using the following:

for i in routers:
os.system('/bin/touch %s' % i)

> Is there a simple way to get this done?

You can also use the builtin file object:

for i in routers:
f = file(i, 'w')
f.close()

> Thanks for your time.
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Carlos Hanson
Web Specialist
Tigard-Tualatin School District
503.431.4053
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] question about looping.

2006-10-06 Thread Kent Johnson
Doug Potter wrote:
> Hi,
> 
> I at trying to create a bunch of text files in a single directory on a 
> Linux system,
> something like this.
> 
> import os
> 
> routers = ['adnc-6321', 'adnp-2341', 'adnw-2632']
> 
> for i in routers:
> os.system('/bin/touch' %s) % i

I think you're close, just a little out of order. Think about it this way:
- first you need to create a string containing the command, using the 
string formatting operations.
'/bin/touch %s' % i
will do that. Note the %s is part of the string, and the % i is part of 
the formatting expression.

- next you pass the formatted string to os.system(). So the whole 
formatting expression has to go inside the parentheses - the value of 
the expression is passed to os.system():
os.system('/bin/touch %s' % i)

You could also do this without calling out to the system - just open a 
file for writing and close it again:
open(i, 'w').close()

Kent

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


<    3   4   5   6   7   8   9   10   >