[Tutor] Links for programming using MySQL

2006-01-19 Thread John Joseph

Hi 
I  wanted  to try out python with MySQL databases
, I would like to get info about the link to sites ,
which gives you examples on how to do  python
programming  by using MySQL database
 Please guide 
   Thanks 
  Joseph John 



___ 
To help you stay safe and secure online, we've developed the all new Yahoo! 
Security Centre. http://uk.security.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Open file error

2006-01-19 Thread Kent Johnson
andy senoaji wrote:
> Thanks Danny & Alan,
> 
> your print repr(os.listdir("C:/")) has embarrased myself :(. I found out 
> the file name is Test.txt.txt in my c: drive. I guess I learn something 
> here.

If you tell Windows not to hide file extensions you won't make that 
mistake again. On my computer (Win2k) it is under Tools / Folder Options 
/ View / Hide file extensions for known file types.

Kent

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


Re: [Tutor] Links for programming using MySQL

2006-01-19 Thread Wolfram Kraus
John Joseph wrote:
> Hi I  wanted  to try out python with MySQL databases , I would like
> to get info about the link to sites , which gives you examples on how
> to do  python programming  by using MySQL database Please guide 
> Thanks Joseph John
> 
> 
Try this one:
http://sourceforge.net/docman/?group_id=22307

HTH,
Wolfram

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


Re: [Tutor] a class knowing its self

2006-01-19 Thread Ewald Ertl
Hi!


Ben Vinger wrote:
> Hello
> 
> I've been reading about how a class has access to its
> own 'self', so I tried the following, but it is not
> working as I would expect:
> 
> class Skill:
>def __init__(self):
>   self.history = []  
> 
>def setName(self, skill):
>   self.name = skill
> 
>def getName(self):
>   return self.name
> 
> # Assigning data to my class:  
> 
> SkillNames = [r'python', r'apache', r'mysql']
> 
> #a.)
> python = Skill()
> python.setName('python')
> print python.getName()
> 
> #b.)
> for s in SkillNames:
>   s = Skill()
>   s.setName(s)
>   print s.getName()
> 
Have a more precisely look at your code.
s.getName() does just return, what you have put into
the class with setName(). ( Reassignment of a variable to
something different what you intended ).

HTH Ewald


> Why does a work and b not?   
> 
> b returns:
> <__main__.Skill instance at 0x401e260c>
> <__main__.Skill instance at 0x401e230c>
> <__main__.Skill instance at 0x401e23ec>
> 
> why does b not return the names of the 3 instances of
> Skill?
> 
> Thanks
> Ben
> 
> 
>   
> ___ 
> To help you stay safe and secure online, we've developed the all new Yahoo! 
> Security Centre. http://uk.security.yahoo.com
> ___
> 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] Python + MySQL , my first simple program does not gives results

2006-01-19 Thread John Joseph
Hi  
   I  tried out my first Pyhton program with MySQL 
 I was trying to get the  some result , eg
 describe table, select * from table
   but my program does not give the expected results ,
 nor it gives any error 
 I am adding  my code in this mail 
 Please guide me , why I am not
getting  any results displayed 
 Thanks 
   Joseph John 
***8


"""  For learning for
 To connect to a database "learnpython" , with
mysql user name "john" password "asdlkj"
 To describe a table "contact"
 To get result of  SQL statement

"""


import MySQLdb
class learnpython_db:
def __init__(self):
db =
MySQLdb.connect(host="localhost",user =
"john",password = "asdlkj", db = learnpython)
cursor = db.cursor()
cursor.execute(" describe contact" )
cursor.execute(" SELECT * from
contact" )








___ 
Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail 
http://uk.messenger.yahoo.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python + MySQL , my first simple program does not gives results

2006-01-19 Thread Pujo Aji
You should fetch the results.   try: 

   result
= cursor.fetchall()   print result

Cheers,pujo import MySQLdbclass learnpython_db:def __init__(self):
db =MySQLdb.connect(host="localhost",user ="john",password = "asdlkj", db = learnpython)cursor = db.cursor()cursor.execute
(" describe contact" )
cursor.execute(" SELECT * fromcontact" )___Yahoo! Messenger - NEW crystal clear PC to PC calling worldwide with voicemail 
http://uk.messenger.yahoo.com___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] Indexing in a series for a newbie

2006-01-19 Thread Jon Moore
HelloI need some help for a program I am writing as a newbie to Python.I have created a series:WORDS = ("python", "program", "code", "xylophone")
and then assigned one of them randomly to the variable 'word':word = random.choice(WORDS)I know that if I do:
print wordThe randomly chosen word will be displayed. I also know that if I type:print WORDS[x]I will get the corresponding word back. But how do I find 'programaticaly' the index number for the string that 
random.choice has chosen?The reason I ask is that I an writing a simple word jumble game and need to link the randomly chosen word to a hint should the user need one.-- Best Regards
Jon Moore
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Indexing in a series for a newbie

2006-01-19 Thread Pujo Aji
Hello Jon,Why don't use randint so you can record the index and the value Example:    WORDS = ("python", "program", "code", "xylophone")    Indword = random.randint
(0,len(WORDS)-1)    word = WORDS[Indword]    print Indword    print wordCheers,pujoOn 1/19/06, Jon Moore <
[EMAIL PROTECTED]> wrote:HelloI need some help for a program I am writing as a newbie to Python.
I have created a series:WORDS = ("python", "program", "code", "xylophone")
and then assigned one of them randomly to the variable 'word':word = random.choice(WORDS)I know that if I do:

print wordThe randomly chosen word will be displayed. I also know that if I type:print WORDS[x]I will get the corresponding word back. But how do I find 'programaticaly' the index number for the string that 
random.choice has chosen?The reason I ask is that I an writing a simple word jumble game and need to link the randomly chosen word to a hint should the user need one.-- Best Regards

Jon Moore

___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] Indexing in a series for a newbie

2006-01-19 Thread Wolfram Kraus
Jon Moore wrote:
> Hello
> 
> I need some help for a program I am writing as a newbie to Python.
> 
> I have created a series:
> 
> WORDS = ("python", "program", "code", "xylophone")
> 
> and then assigned one of them randomly to the variable 'word':
> 
> word = random.choice(WORDS)
> 
> I know that if I do:
> 
> print word
> 
> The randomly chosen word will be displayed. I also know that if I type:
> 
> print WORDS[x]
> 
> I will get the corresponding word back. But how do I find 
> 'programaticaly' the index number for the string that random.choice has 
> chosen?
> 
> The reason I ask is that I an writing a simple word jumble game and need 
> to link the randomly chosen word to a hint should the user need one.
> 
> -- 
> Best Regards
> 
> Jon Moore
You can convert your WORDS-tuple to a list and use the index() method:

idx = list(WORDS).index(word)

HTH,
Wolfram

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


Re: [Tutor] Indexing in a series for a newbie

2006-01-19 Thread Todd Maynard
Another approach would be to change your data structure to include the words 
and hints together as tuples in the same tuple.

ie...

WORDS=( ("python","The python hint"),("program","The program hint"),
("code","The code hint") )

then you can do...

word, hint = random.choice(WORDS)


>>> WORDS=( ("python","The python hint"),("program","The program hint"),
("code","The code hint") )
>>> word, hint = random.choice(WORDS)
>>> word
'code'
>>> hint
'The code hint'
>>>


Happy coding,

-- Todd Maynard


On Thursday 19 January 2006 10:36, Jon Moore wrote:
> Hello
>
> I need some help for a program I am writing as a newbie to Python.
>
> I have created a series:
>
> WORDS = ("python", "program", "code", "xylophone")
>
> and then assigned one of them randomly to the variable 'word':
>
> word = random.choice(WORDS)
>
> I know that if I do:
>
> print word
>
> The randomly chosen word will be displayed. I also know that if I type:
>
> print WORDS[x]
>
> I will get the corresponding word back. But how do I find 'programaticaly'
> the index number for the string that random.choice has chosen?
>
> The reason I ask is that I an writing a simple word jumble game and need to
> link the randomly chosen word to a hint should the user need one.
>
> --
> Best Regards
>
> Jon Moore

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


[Tutor] how to do multiple searching against many lists

2006-01-19 Thread Srinivas Iyyer
Hi Group, 

my Problem:

I have soms list for variety of animals, birds,
bacteria


I have another list:
search_list =
['cat','python','parrot','donkey','e.coli']

animals = ['cat','tiger','donkey','zebra','lemur']
birs = ['parrot','mina','oriole','blue jay']
bacteria =
['e.coli','bacillus','staphy','acetobacter']

my output should look like this:

cat '\t' animal
python '\t' animal
parrot '\t' bird
donkey '\t'animal
e.coli '\t' bacteria

Can I do this using dictionaries , so that to make it
faster?

Thanks
Srini

__
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] how to do multiple searching against many lists

2006-01-19 Thread Pujo Aji
Yes you can.you can make:    search_list =['cat','python','parrot','donkey','e.coli']    animals = ['python','cat','tiger','donkey','zebra','lemur']    birds = ['parrot','mina','oriole','blue jay']    bacteria = ['
e.coli','bacillus','staphy','acetobacter']    mydic = {}    for animal in animals :     mydic[animal] = 'animal'        for bird in birds:    mydic[bird] = 'bird'        for bacteri in bacteria:
    mydic[bacteri] = 'bacteria'            for x in search_list:    print x, mydic[x]Don't forget to include 'python' in animals group.Cheers,pujo
On 1/19/06, Srinivas Iyyer <[EMAIL PROTECTED]> wrote:
Hi Group,my Problem:I have soms list for variety of animals, birds,bacteriaI have another list:search_list =['cat','python','parrot','donkey','e.coli']animals = ['cat','tiger','donkey','zebra','lemur']
birs = ['parrot','mina','oriole','blue jay']bacteria =['e.coli','bacillus','staphy','acetobacter']my output should look like this:cat '\t' animalpython '\t' animalparrot '\t' birddonkey '\t'animal
e.coli '\t' bacteriaCan I do this using dictionaries , so that to make itfaster?ThanksSrini__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
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] how to do multiple searching against many lists

2006-01-19 Thread Kent Johnson
Srinivas Iyyer wrote:
> Hi Group, 
> 
> my Problem:
> 
> I have soms list for variety of animals, birds,
> bacteria
> 
> 
> I have another list:
> search_list =
> ['cat','python','parrot','donkey','e.coli']
> 
> animals = ['cat','tiger','donkey','zebra','lemur']
> birs = ['parrot','mina','oriole','blue jay']
> bacteria =
> ['e.coli','bacillus','staphy','acetobacter']
> 
> my output should look like this:
> 
> cat '\t' animal
> python '\t' animal
> parrot '\t' bird
> donkey '\t'animal
> e.coli '\t' bacteria
> 
> Can I do this using dictionaries , so that to make it
> faster?

I would make animals, birds and bacteria into sets rather than dicts 
since the values don't map to anything. You could store the sets in a 
single dict to give you the name -> set mapping. For example:

  >>> animals = set(['cat','tiger','donkey','zebra','lemur'])
  >>> birds = set(['parrot','mina','oriole','blue jay'])
  >>> bacteria = set(['e.coli','bacillus','staphy','acetobacter'])
  >>> fauna = { 'animals' : animals, 'birds' : birds, 'bacteria' : 
bacteria }
  >>> for item in ['cat','python','parrot','donkey','e.coli']:
  ...   for setName, setValue in fauna.iteritems():
  ... if item in setValue:
  ...   print '%s\t%s' % (item, setName)
  ...
cat animals
parrot  birds
donkey  animals
e.coli  bacteria

Or, if each critter can be in only one set, you could make one dict that 
maps the critter name to the set it is in, and just do one lookup:

  >>> fauna2 = {}
  >>> for animal in animals: fauna2[animal] = 'animal'
  ...
  >>> for bird in birds: fauna2[bird] = 'bird'
  ...
  >>> for bacterium in bacteria: fauna2[bacterium] = 'bacteria'
  ...
  >>> for item in ['cat','python','parrot','donkey','e.coli']:
  ...   print '%s\t%s' % (item, fauna2.get(item, 'None'))
  ...
cat animal
python  None
parrot  bird
donkey  animal
e.coli  bacteria

Kent

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


Re: [Tutor] Indexing in a series for a newbie

2006-01-19 Thread Danny Yoo


On Thu, 19 Jan 2006, Jon Moore wrote:

> I need some help for a program I am writing as a newbie to Python.
>
> I have created a series:
>
> WORDS = ("python", "program", "code", "xylophone")
>
> and then assigned one of them randomly to the variable 'word':
>
> word = random.choice(WORDS)
>
> I will get the corresponding word back. But how do I find 'programaticaly'
> the index number for the string that random.choice has chosen?

Hi Jon,

If you need the index as well as the sequence element, then it may be more
practical to select a random index rather than a random element.  The
reason is because it's easy to get a sequence element from its index, but
not necessarily visa-versa.

The random.randrange() function may be useful here.

Good luck!

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


Re: [Tutor] Python + MySQL , my first simple program does not gives results

2006-01-19 Thread Danny Yoo


On Thu, 19 Jan 2006, John Joseph wrote:

> Hi
>I  tried out my first Pyhton program with MySQL
>  I was trying to get the  some result , eg
>  describe table, select * from table


Hi John,

Unlike Java, Python doesn't force you to put everything in a class.  You
can try the simpler:

##
import MySQLdb
db = MySQLdb.connect(host="localhost",user =
 "john",password = "asdlkj", db = learnpython)
cursor = db.cursor()
cursor.execute(" describe contact" )
cursor.execute(" SELECT * from contact" )
##

from toplevel.



>  but my program does not give the expected results ,

What do you expect to see, and from where?

A call to cursor.execute()  sets the cursor up so that subsequent calls to
cursor.fetchone() will give us result rows.  See:

http://www.amk.ca/python/writing/DB-API.html

You need to add some code to print out the result set.  The link above is
a tutorial to the database interface that should help you get started.


Good luck!

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


Re: [Tutor] [Re] Fwd: Strings backwards

2006-01-19 Thread Victor Bouffier
This was just posted by John Fouhy (snipped part of it):

Basically, the syntax is [start:stop:step].

If step is negative, you work backwards.  eg:
>>> string.lowercase[20:10:-2]   # letters 20, 18, 16, 14, 12
'usqom'

And if you omit the start or stop parameters, and step is
negative,
then start defaults to the end of the list and stop to the
beginning.

So string.lowercase[::-1] will step backwards, starting at the
end and finishing at the start.

So to reverse a string, you would only need to do the following:

>>> print 'hello world'[::-1]
dlrow olleh

I had to do the string-to-list-then-reverse-string-then-back-to-string
process myself before knowing about this marvelous operand.
It works on tuples (all immutable objects) too:

>>> digits = (0,1,2,3,4,5,6,7,8,9)
>>> print digits[::-1]
(9, 8, 7, 6, 5, 4, 3, 2, 1, 0)

Best of Luck
Victor

On Thu, 2006-01-19 at 08:26 +0100, János Juhász wrote:
> Hi Ryan,
> 
> I just extended Adam's code with a speech-to-text recepi from
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/114216.
> 
> On 18/01/06, ryan luna <[EMAIL PROTECTED]> wrote:
> >
> > Hello, what i need to do is get user input and then
> > print the string backwards ^^ i have no idea how to do
> > that,
> >
> > print "Enter a word and i well tell you how to say it
> > backwards"
> >
> > word = raw_input("Your word: ")
> >
> > print word
> >
> > all that is simple enough im sure printing it out
> > backwards is to, just dont know how ^^, thanks for any help.
> 
> import sys
> from win32com.client import constants
> import win32com.client
> import string
> 
> speaker = win32com.client.Dispatch("SAPI.SpVoice")
> print "Type word or phrase, then enter."
> print "Ctrl+Z then enter to exit."
> 
> def backword(word):
>l = list(word)
>l.reverse()
>return ''.join(l)
> 
> def backsentence(sentence):
>words = sentence.split(' ')
>words = [backword(word) for word in words]
>return ' '.join(words)
> 
> while 1:
>try:
>   s = raw_input()
>   rev = backsentence(s)
>   print 'I would say: ', rev
>   speaker.Speak(rev)
>except:
>   if sys.exc_type is EOFError:
>  sys.exit()
> 
> It works on my xp :)
> 
> 
> Yours sincerely,
> __
> János Juhász
> 
> ___
> 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] How to get terminal settings

2006-01-19 Thread Vincent Zee
Hi,

say you want to write a more-like program.
How do you know how many lines the terminal window
can display.

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


Re: [Tutor] Links for programming using MySQL

2006-01-19 Thread Alan Gauld
>I  wanted  to try out python with MySQL databases

What do you need to know about? 
Do you already know about MySql and just want to know how 
to connect to a database and execute a SQL statement? 
Or do you need to know about databases too?

If the latter you can try the database topic in my tutor.

If its the former look at the Python DBI documentation 
and then the python MySql data base driver docs. 
Between them they should sort things out.

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


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


Re: [Tutor] Python + MySQL , my first simple program does not gives results

2006-01-19 Thread Alan Gauld
> I was trying to get the  some result , eg
> describe table, select * from table
>   but my program does not give the expected results ,
> nor it gives any error

First of all you have only defined init() but not created an instance
so it never actually gets called! But if you do call it(by creating
an instance of learnpython_db)...

You are fetching the results into the cursor but you never access them!
So the second execute call will overwrite the first execute with the
SELECT results. But then you exit the init() function so cursor
(a local variable) is garbage collected and the results die with it..

> import MySQLdb
> class learnpython_db:
>def __init__(self):
>db =
> MySQLdb.connect(host="localhost",user =
> "john",password = "asdlkj", db = learnpython)
>cursor = db.cursor()
>cursor.execute(" describe contact" )
>cursor.execute(" SELECT * from
> contact" )

You probably want to make cursor (and maybe db too) an instance variable.
Then you can access the results of the cursor in other methods of the 
object.

You will see this illustrated in my tutorial topic albeit using SQLite but 
the
cursor hjandling is nearly identical.

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


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


[Tutor] escaping spaces in a directoryname

2006-01-19 Thread Rinzwind
Hmm, a very newby question but I never had to deal with escaping spaces etc.I want to read a directory with spaces in it and it errors out (because of the space).I need to escape it with a \ I guess. I saw alot about that on some websites but they all talk about why and how you escape and not what function can do that. Is there one? Or do I have scan the string and add them myself.
*goes back to searching on the web*If I find it before I get an answer I'll post it :=)Wim
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to get terminal settings

2006-01-19 Thread Bill Campbell
On Thu, Jan 19, 2006, Vincent Zee wrote:
>Hi,
>
>say you want to write a more-like program.
>How do you know how many lines the terminal window
>can display.

Use the curses library, and it will take care of this for you.

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

The most serious doubt that has been thrown on the authenticity of the
biblical miracles is the fact that most of the witnesses in regard to
them were fishermen.
-- Arthur Binstead
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to get terminal settings

2006-01-19 Thread Vincent Zee
On Thursday, 19 January 2006 at 11:29:29 -0800, Bill Campbell wrote:
> On Thu, Jan 19, 2006, Vincent Zee wrote:
> >Hi,
> >
> >say you want to write a more-like program.
> >How do you know how many lines the terminal window
> >can display.
> 
> Use the curses library, and it will take care of this for you.
> 
Hi Bill,

thanks for your answer.

Is there, except from using the curses library, any other method?

I'm a bit afraid of using curses at the moment(;-))

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


Re: [Tutor] References and list aliasing in Perl and Python [Was: Re: Dictionaries]

2006-01-19 Thread Victor Bouffier
On Wed, 2006-01-18 at 23:03 -0800, Danny Yoo wrote:
> > > There are tradeoffs here.  On the one hand, Python folks get caught
> > > off guard when they first encounter list aliasing.  On the other, Perl
> > > folks get caught off guard when they first try to make a hash whose
> > > values are themselves lists.  *grin*
> > >
> > WOW. Great explanation. Don't worry about a deeper hole.
> >
> > Your examples once again reminded me of one of reasons I started looking
> > into Python instead of continuing with Perl. It is not the
> > functionality, but the convoluted scripts can get. One can hardly
> > understand the code.
> 
> Hi Victor,
> 
> That might be an unfair judgement.
> 
> One can write really convoluted and ugly programs in any programming
> language.  And although I do think that our choice in what programming
> language we us can affect a program's clarity, I also believe that people
> matter much more than the programming language.
> 
> Otherwise, what would be the point of a mailing list like this?  *grin*
> 
> 
> Best of wishes!
> 
> 

Yes, it is true.
Take care.
Victor


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


Re: [Tutor] How to get terminal settings

2006-01-19 Thread Danny Yoo


On Thu, 19 Jan 2006, Vincent Zee wrote:

> say you want to write a more-like program. How do you know how many
> lines the terminal window can display.

Hi Vincent,

It's possible that this information might already be in your environment.
If you're using the 'bash' shell, and if the 'checkwinsize' option is set
in bash, then bash should keep track of the window size through LINES and
COLUMNS.  According to the "Art of Unix Programming":

http://www.faqs.org/docs/artu/ch10s04.html

those variables are fairly standard and lots of programs use them.  But I
don't know if other shells go out of their way to maintain consistancy
with the current terminal size on terminal resizing.

If you want to get at the environment variables, take a look at the
'os.environ' dictionary:

http://www.python.org/doc/lib/os-procinfo.html#l2h-1508


Alternatively, if you're on Unix, the 'curses' module will get you the
information you want.

http://www.python.org/doc/lib/module-curses.html

On Windows, it looks like you can use the following cookbook recipe:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440694



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


Re: [Tutor] How to get terminal settings

2006-01-19 Thread Vincent Zee
On Thursday, 19 January 2006 at 12:37:38 -0800, Danny Yoo wrote:
> 
> 
> On Thu, 19 Jan 2006, Vincent Zee wrote:
> 
> > say you want to write a more-like program. How do you know how many
> > lines the terminal window can display.
> 
> Hi Vincent,
> 
> It's possible that this information might already be in your environment.
> If you're using the 'bash' shell, and if the 'checkwinsize' option is set
> in bash, then bash should keep track of the window size through LINES and
> COLUMNS.  According to the "Art of Unix Programming":
> 
> http://www.faqs.org/docs/artu/ch10s04.html
> 
> those variables are fairly standard and lots of programs use them.  But I
> don't know if other shells go out of their way to maintain consistancy
> with the current terminal size on terminal resizing.
> 
> If you want to get at the environment variables, take a look at the
> 'os.environ' dictionary:
> 
> http://www.python.org/doc/lib/os-procinfo.html#l2h-1508
> 
> 
> Alternatively, if you're on Unix, the 'curses' module will get you the
> information you want.
> 
> http://www.python.org/doc/lib/module-curses.html

Hi Danny,

thank you for your reply.

I want the program to run on Freebsd and on MacOSX.
On FreeBSD I use the tcsh and on Mac its bash or tcsh.

I looked at the curses module and also to the cursus howto on
python.org but I find it still a bit unclear on how to use it.
There being curses, ncurses and a curses wrapper.
I'm a little confused.

The os.environ didn't give me any hints to screen size so maybe
curses is the way to go.

Any pointers to other curses howto's?

/\
Vincent

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


[Tutor] Simple MS Windows Shell Extension?

2006-01-19 Thread bernd
Hi,

I have a python script that I want my users to execute with a
"Right-Mouse-Click" on a file under Windows XP. 

(If possible without changing the default "Open with ..." behavior from 
Windows.)

Does anybody has a simple example on how to do that?

Thanks,
-- Bernd

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


Re: [Tutor] [Re] Fwd: Strings backwards

2006-01-19 Thread Orri Ganel
Victor Bouffier wrote:

>I had to do the string-to-list-then-reverse-string-then-back-to-string
>process myself before knowing about this marvelous operand.
>It works on tuples (all immutable objects) too:
>
[SNIP]

Not all immutable objects, just those that define __getslice__ 
(basically, those that use indexes: sequences).  Ints, for example, are 
immutable and don't work:

 >>> 12[::-1]

Traceback (most recent call last):
  File "", line 1, in -toplevel-
12[::-1]
TypeError: unsubscriptable object


 - Orri

-- 
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.

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


Re: [Tutor] How to get terminal settings

2006-01-19 Thread Alan Gauld
Assuming you are on a Unix style OS/terminal you can read the 
output of stty. Look at the rows value

Here are a couple of runs of rows at different terminal sizes:

$ stty -a | grep rows
speed 38400 baud; rows 41; columns 80; line = 0;

$ stty -a | grep rows
speed 38400 baud; rows 26; columns 80; line = 0;

A call to Popen should get you what you want.

An alternative technique, and the one useed by the real 
more/less programmes is to use curses to open a display 
window.

HTH,

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

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


Re: [Tutor] How to get terminal settings

2006-01-19 Thread Terry Carroll
On Thu, 19 Jan 2006, Vincent Zee wrote:

> Any pointers to other curses howto's?

There's http://heather.cs.ucdavis.edu/~matloff/Python/PyCurses.pdf ; but 
it's mostly a couple of example programs, without a lot of explanation.

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


Re: [Tutor] getting text within an element [attribute text] using elementtree

2006-01-19 Thread ps python
Dear group, 
In my XML file some attributes have text within an
element. I want to get that text. How can I do that. 
I looked into ElementTree -bits and pieces: and there
is a small function. 

>>> def gettext(elem):
... text = elem.text or ""
... for e in elem:
... text += gettext(e)
... if e.tail:
... text += e.tail
... return text

>>> for m in
tree.findall('//{org:hprd:dtd:hprdr2}proteinInteractor'):
... k = gettext(m)
... print k
...
>>>

I got nothing out of it. 

I tried more preliminary way:

>>> for m in
tree.findall('//{org:hprd:dtd:hprdr2}proteinIn
... k = 
m.findtext('{org:hprd:dtd:hprdr2}secondaryRef'
... print k
...
>>> for m in
tree.findall('//{org:hprd:dtd:hprdr2}proteinIn
... print m
...
>>>

The part of the xml file is listd below. 

Could any one you help me please. 

I want to get :
 

id value:

Thanks
w
 


  
http://www.w3.org/2001/XMLSchema-instance";
  xsi:schemaLocation="net:sf:psidev:mi
http://psidev.sourceforge.net/mi/xml/src/MIF.xsd";
  level="1" version="1">



HPRD
Human Protein Reference
Database



 
 









 Histone H3



   
  Human
  Homo
sapiens
   







Minichromosome
maintenance protein 2



   
  Mouse
  Mus
musculus
   







MCM3



   
  Mouse
 Mus musculus
   







MCM4



   
  Mouse
  Mus
musculus
   





Send instant messages to your online friends http://in.messenger.yahoo.com 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] getting text within an element [attribute text] using elementtree

2006-01-19 Thread Danny Yoo


On Fri, 20 Jan 2006, ps python wrote:

> In my XML file some attributes have text within an element. I want to
> get that text. How can I do that.


Hello,

The problems you have don't have to do with the calls to gettext, but to
selecting namespaced nodes as with your previous questions.  Let's look at
some of the code:

> >>> for m in
> tree.findall('//{org:hprd:dtd:hprdr2}proteinInteractor'):
> ... k = gettext(m)
> ... print k
> ...

The XML that you show us appears to use a different namespace than
'org:hprd:dtd:hprdr2':

##
http://effbot.org/zone/element.htm#attributes


Here's a small example:

##
>>> text = """
...   Hello world
...   This has attributes
...   """
>>> from elementtree import ElementTree
>>> tree = ElementTree.fromstring(text)
>>> tree

>>>
>>> for msg in tree:
... if msg.get('name'):
... print msg.get('name')
... print msg.text
...
attr1
This has attributes
##


Good luck!

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


Re: [Tutor] glibc error while Python script runs - Solved

2006-01-19 Thread Bernard Lebel
Hello,

For the record, in case anyone would like to know what happened with
this issue...


It seems that the problem was related to the way I managed MySQL
connections. There was the main thread that would query every 5
seconds the database to see if a someone wanted to abort the job
running on the render node.

However, the actual rendering was managed by a child thread, who would
perform many MySQL transactions, depending on the output produced by
the rendering software.

So there were two separate threads doing MySQL queries. I noticed by
reading my debug logs that some of these queries would become
interlaced, that is, one query would try to update while another would
try to select-fetch. In turned out that this would severe the
connection with the database, and soon after Python would crash
altogether.

So the solution was to start some sort of queue server in a separate
thread. This queue would consist of a list, and each time the program
would want to perform a MySQL operation, it would add it to the queue.
Then, the caller would enter a while loop that would wait for the
server to carry the operation.

The server would run a while loop, that check the queue once every
iteration to see if there is something to do. When it finds something,
it would carry the entire transaction, then put the result in a
dictionary, using an ID number assigned when the transaction was
submitted to the queue.

The "submitter" would then pick up the result, and return it to the
original caller.
The result is that no two queries would take place at the same time.

Once I did that, my program stopped crashing, and actually has been
running very smooth since then. In fact my progam is now very very
close to completion.



Kent: I took your suggestion and changed the program design and
splitted the code into separate modules. It was tricky to "re-wire"
everything together (it took me at least 4 days), but past that, I'm
glad I did it.


Thanks everyone for the help, it has been a great learning experience!


Bernard





On 1/4/06, Bernard Lebel <[EMAIL PROTECTED]> wrote:
> Hi Danny,
> See [Bernard] below...
>
> On 1/4/06, Danny Yoo <[EMAIL PROTECTED]> wrote:
> >
> > > rn200.bbfxa.com Wed Jan  4 16:23:36 2006 [jobid: 9]: Get status of all
> > > local jobs for this job...
> > >
> > > *** glibc detected *** double free or corruption: 0x09484d58 ***
> > > Aborted
> >
> >
> > Hi Bernard,
> >
> > Ugh.  I hate memory allocation bugs.
> >
> > Is it reproducable? Can you run this through a debugger like GDB to find
> > out where we are when this happens?  A stack trace will be invaluable
> > because we need to know who to blame.
>
> [Bernard] I am quite unfamiliar with Linux in general and a lot more
> with these tools. Where can I find information about GDB?
>
>
> > *grin* We need to know if it's
> > Python that's doing this, or if it's MySQLdb, or if it's something else
> > entirely...
> >
> > Just checking up on this: what version of MySQLdb do you have on those
> > systems?  I do remember some ugly memory-leaking bugs that haunted ancient
> > versions of MySQLdb, so I want to make sure we're not hitting those.
>
> [Bernard] I am using 1.2.0, with Python 2.3.4.
>
>
> >
> > Analyzing this might goes out of Tutor's scope, so you may want to bring
> > this up on a more general forum like comp.lang.python instead.
>
> [Bernard] Okay thanks a lot. I'll check it out, but if you have any idea... 
> :-)
>
>
> Bernard
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] glibc error while Python script runs - Solved

2006-01-19 Thread Kent Johnson
Hi Bernard,

I'm glad you got it working but kind of surprised at what you had to do. 
You shouldn't have to have a single thread to access the database. In 
your original desing were you sharing a connection between threads? That 
could cause trouble. But if each connection has its own thread and you 
are using transactions and isolation levels appropriately, they 
shouldn't stomp on each other.

There are some good recipes for queuing up tasks and getting callbacks 
that might be simpler than your dictionary solution. For example see
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/435883
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/203871

You could also use a second queue to return results to the main thread.

Kent

Bernard Lebel wrote:
> Hello,
> 
> For the record, in case anyone would like to know what happened with
> this issue...
> 
> 
> It seems that the problem was related to the way I managed MySQL
> connections. There was the main thread that would query every 5
> seconds the database to see if a someone wanted to abort the job
> running on the render node.
> 
> However, the actual rendering was managed by a child thread, who would
> perform many MySQL transactions, depending on the output produced by
> the rendering software.
> 
> So there were two separate threads doing MySQL queries. I noticed by
> reading my debug logs that some of these queries would become
> interlaced, that is, one query would try to update while another would
> try to select-fetch. In turned out that this would severe the
> connection with the database, and soon after Python would crash
> altogether.
> 
> So the solution was to start some sort of queue server in a separate
> thread. This queue would consist of a list, and each time the program
> would want to perform a MySQL operation, it would add it to the queue.
> Then, the caller would enter a while loop that would wait for the
> server to carry the operation.
> 
> The server would run a while loop, that check the queue once every
> iteration to see if there is something to do. When it finds something,
> it would carry the entire transaction, then put the result in a
> dictionary, using an ID number assigned when the transaction was
> submitted to the queue.
> 
> The "submitter" would then pick up the result, and return it to the
> original caller.
> The result is that no two queries would take place at the same time.
> 
> Once I did that, my program stopped crashing, and actually has been
> running very smooth since then. In fact my progam is now very very
> close to completion.
> 
> 
> 
> Kent: I took your suggestion and changed the program design and
> splitted the code into separate modules. It was tricky to "re-wire"
> everything together (it took me at least 4 days), but past that, I'm
> glad I did it.
> 
> 
> Thanks everyone for the help, it has been a great learning experience!
> 
> 
> Bernard

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


Re: [Tutor] glibc error while Python script runs - Solved

2006-01-19 Thread Bernard Lebel
On 1/19/06, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Hi Bernard,
>
> I'm glad you got it working but kind of surprised at what you had to do.
> You shouldn't have to have a single thread to access the database. In
> your original desing were you sharing a connection between threads? That
> could cause trouble. But if each connection has its own thread and you
> are using transactions and isolation levels appropriately, they
> shouldn't stomp on each other.

I'm not sure what you mean by transaction and isolation levels. I get
some sort of an idea, but could you elaborate on the idea?

I have not considered having one connection per thread, and have not
tested the idea. The way it works right now is that there is only one
connection, as a class instance attribute. All transaction go through
that connection.


>
> There are some good recipes for queuing up tasks and getting callbacks
> that might be simpler than your dictionary solution. For example see
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/435883
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/203871
>
> You could also use a second queue to return results to the main thread.

Thanks I'll check these out.

Bernard



>
> Kent
>
> Bernard Lebel wrote:
> > Hello,
> >
> > For the record, in case anyone would like to know what happened with
> > this issue...
> >
> >
> > It seems that the problem was related to the way I managed MySQL
> > connections. There was the main thread that would query every 5
> > seconds the database to see if a someone wanted to abort the job
> > running on the render node.
> >
> > However, the actual rendering was managed by a child thread, who would
> > perform many MySQL transactions, depending on the output produced by
> > the rendering software.
> >
> > So there were two separate threads doing MySQL queries. I noticed by
> > reading my debug logs that some of these queries would become
> > interlaced, that is, one query would try to update while another would
> > try to select-fetch. In turned out that this would severe the
> > connection with the database, and soon after Python would crash
> > altogether.
> >
> > So the solution was to start some sort of queue server in a separate
> > thread. This queue would consist of a list, and each time the program
> > would want to perform a MySQL operation, it would add it to the queue.
> > Then, the caller would enter a while loop that would wait for the
> > server to carry the operation.
> >
> > The server would run a while loop, that check the queue once every
> > iteration to see if there is something to do. When it finds something,
> > it would carry the entire transaction, then put the result in a
> > dictionary, using an ID number assigned when the transaction was
> > submitted to the queue.
> >
> > The "submitter" would then pick up the result, and return it to the
> > original caller.
> > The result is that no two queries would take place at the same time.
> >
> > Once I did that, my program stopped crashing, and actually has been
> > running very smooth since then. In fact my progam is now very very
> > close to completion.
> >
> >
> >
> > Kent: I took your suggestion and changed the program design and
> > splitted the code into separate modules. It was tricky to "re-wire"
> > everything together (it took me at least 4 days), but past that, I'm
> > glad I did it.
> >
> >
> > Thanks everyone for the help, it has been a great learning experience!
> >
> >
> > Bernard
>
> ___
> 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] glibc error while Python script runs - Solved

2006-01-19 Thread Danny Yoo


On Thu, 19 Jan 2006, Kent Johnson wrote:


> In your original desing were you sharing a connection between threads?
> That could cause trouble. But if each connection has its own thread and
> you are using transactions and isolation levels appropriately, they
> shouldn't stomp on each other.

Hi Kent and Bernard,

It's possible that MySQLdb was linked against the non-thread-safe
mysqlclient (rather than mysqlclient_r) library; that would probably cause
havoc.


> > So the solution was to start some sort of queue server in a separate
> > thread. This queue would consist of a list, and each time the program
> > would want to perform a MySQL operation, it would add it to the queue.

We may want to use the Queue module here instead of a list; the way the
program is described now sounds like the server is busy-spinning when it
looks for new things to do.  The thing that makes busy-spinning slightly
not-nice is that it consumes CPU regardless if the system's doing anything
or not.

But a more serious problem than busy-waiting is one of thread-safety: the
object that's used to communicate between two threads --- a shared list
--- might be unreliable if the list methods aren't thread-safe.  And I'm
not certain that all the list methods are thread-safe.

That is, the problem with mutual exclusion may have just been pushed up
the program's structure, from the MySQL queries up to the shared queue
list access.  *grin*


The synchronized Queue described in:

http://www.python.org/doc/lib/module-Queue.html

is designed to be a reliable communication medium between threads, and I
strongly recommend you look at it, especially because you've seen
first-hand the weird things that can happen with threads.  *grin*


Here's a small example that shows what a different Queue can make:


from threading import Thread

class Server:
def __init__(self):
self.queue = []

def acceptJob(self, query):
self.queue.append((query,))

def shutdownOnIdle(self):
self.queue.append("QUIT!")

def jobLoop(self):
while True:
print "looping"
if len(self.queue) > 0:
   nextJob = self.queue.pop(0)
   if nextJob == "QUIT!":
   return
   print "I should do", nextJob

def startServer(self):
Thread(target=self.jobLoop).start()

if __name__ == '__main__':
server = Server()
server.startServer()
server.acceptJob("a")
server.acceptJob("b")
server.acceptJob("c")
server.shutdownOnIdle()



Running this will show just how much work a busy-waiting thread does.


But if we change a few methods to use Queues instead of lists:

##
from threading import Thread
from Queue import Queue

class Server:
def __init__(self):
self.queue = Queue()

def acceptJob(self, query):
self.queue.put((query,))

def shutdownOnIdle(self):
self.queue.put("QUIT!")

def jobLoop(self):
while True:
print "looping"
nextJob = self.queue.get()
if nextJob == "QUIT!":
return
print "I should do", nextJob

def startServer(self):
Thread(target=self.jobLoop).start()

if __name__ == '__main__':
server = Server()
server.startServer()
server.acceptJob("a")
server.acceptJob("b")
server.acceptJob("c")
server.shutdownOnIdle()
##

and compare the output of this to the original implementation, it should
be clearer why Queues are cool.  *grin*


Does this make sense?  I hope this helps!

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


Re: [Tutor] glibc error while Python script runs - Solved

2006-01-19 Thread Bernard Lebel
Thanks a lot Danny,

That certainly does make sense. I'll look into implementing the Queue
approach in my program tomorrow. I remember you recommending me this
module as well not long ago, although in a different discussion (where
I suspected problem with file access from multiple thread, but I guess
it's pretty much a similar problem, isn't it? :-)


Thanks again
Bernard



On 1/19/06, Danny Yoo <[EMAIL PROTECTED]> wrote:
>
>
> On Thu, 19 Jan 2006, Kent Johnson wrote:
>
>
> > In your original desing were you sharing a connection between threads?
> > That could cause trouble. But if each connection has its own thread and
> > you are using transactions and isolation levels appropriately, they
> > shouldn't stomp on each other.
>
> Hi Kent and Bernard,
>
> It's possible that MySQLdb was linked against the non-thread-safe
> mysqlclient (rather than mysqlclient_r) library; that would probably cause
> havoc.
>
>
> > > So the solution was to start some sort of queue server in a separate
> > > thread. This queue would consist of a list, and each time the program
> > > would want to perform a MySQL operation, it would add it to the queue.
>
> We may want to use the Queue module here instead of a list; the way the
> program is described now sounds like the server is busy-spinning when it
> looks for new things to do.  The thing that makes busy-spinning slightly
> not-nice is that it consumes CPU regardless if the system's doing anything
> or not.
>
> But a more serious problem than busy-waiting is one of thread-safety: the
> object that's used to communicate between two threads --- a shared list
> --- might be unreliable if the list methods aren't thread-safe.  And I'm
> not certain that all the list methods are thread-safe.
>
> That is, the problem with mutual exclusion may have just been pushed up
> the program's structure, from the MySQL queries up to the shared queue
> list access.  *grin*
>
>
> The synchronized Queue described in:
>
> http://www.python.org/doc/lib/module-Queue.html
>
> is designed to be a reliable communication medium between threads, and I
> strongly recommend you look at it, especially because you've seen
> first-hand the weird things that can happen with threads.  *grin*
>
>
> Here's a small example that shows what a different Queue can make:
>
> 
> from threading import Thread
>
> class Server:
> def __init__(self):
> self.queue = []
>
> def acceptJob(self, query):
> self.queue.append((query,))
>
> def shutdownOnIdle(self):
> self.queue.append("QUIT!")
>
> def jobLoop(self):
> while True:
> print "looping"
> if len(self.queue) > 0:
>nextJob = self.queue.pop(0)
>if nextJob == "QUIT!":
>return
>print "I should do", nextJob
>
> def startServer(self):
> Thread(target=self.jobLoop).start()
>
> if __name__ == '__main__':
> server = Server()
> server.startServer()
> server.acceptJob("a")
> server.acceptJob("b")
> server.acceptJob("c")
> server.shutdownOnIdle()
> 
>
>
> Running this will show just how much work a busy-waiting thread does.
>
>
> But if we change a few methods to use Queues instead of lists:
>
> ##
> from threading import Thread
> from Queue import Queue
>
> class Server:
> def __init__(self):
> self.queue = Queue()
>
> def acceptJob(self, query):
> self.queue.put((query,))
>
> def shutdownOnIdle(self):
> self.queue.put("QUIT!")
>
> def jobLoop(self):
> while True:
> print "looping"
> nextJob = self.queue.get()
> if nextJob == "QUIT!":
> return
> print "I should do", nextJob
>
> def startServer(self):
> Thread(target=self.jobLoop).start()
>
> if __name__ == '__main__':
> server = Server()
> server.startServer()
> server.acceptJob("a")
> server.acceptJob("b")
> server.acceptJob("c")
> server.shutdownOnIdle()
> ##
>
> and compare the output of this to the original implementation, it should
> be clearer why Queues are cool.  *grin*
>
>
> Does this make sense?  I hope this helps!
>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor