From doug.shawhan at gmail.com Thu Jun 1 00:16:28 2006
From: doug.shawhan at gmail.com (doug shawhan)
Date: Wed, 31 May 2006 17:16:28 -0500
Subject: [Tutor] XML Parsing Woes.
Message-ID: <5e1ceb8a0605311516n2b0a909h9aa2452f408ad4c8@mail.gmail.com>
Having been dragged kicking and screaming into the fussy, fussy world of
XML, I find myself in a pickle.
I keep getting an error complaining of a missing end-tag:
: XML Parse error.
XML Error Text: "; nested exception is:
org.xml.sax.SAXParseException: The element type "Description" must
be terminated by the matching end-tag "".".
Now of course, I have saved my output and found the end-tag to be there. I
have stripped out everything I can think of that might cause the parser to
puke. The string enclosed by the tags varies from a few
characters to a couple of thousand: all fail with the same error.
I am very new to XML and find it's jargon fairly impenetrable. Is there a
handy python module that can one can use to scan XML output for errors? I
know the mistake is probably mine ... or perhaps I have actually run on to a
bug in the remote application? :-) (Riiiiight!)
Thanks!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060531/f07d7a06/attachment.html
From kent37 at tds.net Thu Jun 1 02:09:52 2006
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 31 May 2006 20:09:52 -0400
Subject: [Tutor] XML Parsing Woes.
In-Reply-To: <5e1ceb8a0605311516n2b0a909h9aa2452f408ad4c8@mail.gmail.com>
References: <5e1ceb8a0605311516n2b0a909h9aa2452f408ad4c8@mail.gmail.com>
Message-ID: <447E3050.7040908@tds.net>
doug shawhan wrote:
> Having been dragged kicking and screaming into the fussy, fussy world of
> XML, I find myself in a pickle.
>
> I keep getting an error complaining of a missing end-tag:
>
> : XML Parse error.
>
XML Error Text: "; nested exception is:
> org.xml.sax.SAXParseException: The element type "Description"
> must be terminated by the matching end-tag "".".
>
> Now of course, I have saved my output and found the end-tag to be there.
> I have stripped out everything I can think of that might cause the
> parser to puke. The string enclosed by the tags varies
> from a few characters to a couple of thousand: all fail with the same error.
>
> I am very new to XML and find it's jargon fairly impenetrable. Is there
> a handy python module that can one can use to scan XML output for
> errors? I know the mistake is probably mine ... or perhaps I have
> actually run on to a bug in the remote application? :-) (Riiiiight!)
Both Internet Explorer and Firefox do a good job of displaying XML and
showing any errors.
XML tags are case sensitive, make sure the case matches on the start and
end tags. And of course spelling counts ;)
XML tags must nest properly, both of these will cause an error, one of
them possibly the error you are seeing:
textmore text
textmore text
If you are just starting with Python and XML do yourself a favor and use
ElementTreee instead of the stuff in the standard lib.
http://effbot.org/zone/element.htm
HTH
Kent
From gnulinuxgeek at rochester.rr.com Thu Jun 1 04:01:38 2006
From: gnulinuxgeek at rochester.rr.com (GNULinuxGeek)
Date: Wed, 31 May 2006 22:01:38 -0400
Subject: [Tutor] Another fine mess
Message-ID: <447E4A82.70401@rochester.rr.com>
All,
I posted some time back for another task.
Have a new task now. You were all so kind with advice that I thought I
might check my thoughts on this.
Being an old guy and a newbie to Python is the double-whammy, but here goes:
I get a CSV file with ~26 fields and ~7000 records. This data needs to
be parsed based on specific field values.
So, here is my "draft" set of steps that I think need to be performed.
1. Select the "file" of data
2. Clean the data with "strip" to make sure there is no extraneous
whitespace
3. Write the file back to a temp file.
4. On the new file, select records based on the value of some of the
fields (like a "sort on" in a spreadsheet.
5. Parse to obtain the matching records
6. Do a little math based on how many records and the data in one
field (success vs. fail)
7. Output the results of the math so it can be used in a spreadsheet
to make cute graphics.
We have a PERL guy in the division, but I am trying to use Python only
to get this done. My question is
"What is a good way to read and process the lines of the CSV file?"
Do I pull them in one line at a time and write them to an output file?
Do I read the whole shebang, clean the data and write an output file,
then re-open the cleaned file?
Thanking you all prematurely,
Regards,
Ralph
From kent37 at tds.net Thu Jun 1 04:22:49 2006
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 31 May 2006 22:22:49 -0400
Subject: [Tutor] Another fine mess
In-Reply-To: <447E4A82.70401@rochester.rr.com>
References: <447E4A82.70401@rochester.rr.com>
Message-ID: <447E4F79.1060807@tds.net>
GNULinuxGeek wrote:
> All,
>
> I posted some time back for another task.
>
> Have a new task now. You were all so kind with advice that I thought I
> might check my thoughts on this.
>
> Being an old guy and a newbie to Python is the double-whammy, but here goes:
>
> I get a CSV file with ~26 fields and ~7000 records. This data needs to
> be parsed based on specific field values.
Do you know about the csv module? It will take care of all the parsing
and turn each line into a list of values. You can filter these as you
like and make a list of lists of row values. This can be sorted and
otherwise processed. I don't think you will need a temp file, it sounds
like you can easily fit your data in memory.
Kent
>
> So, here is my "draft" set of steps that I think need to be performed.
>
> 1. Select the "file" of data
> 2. Clean the data with "strip" to make sure there is no extraneous
> whitespace
> 3. Write the file back to a temp file.
> 4. On the new file, select records based on the value of some of the
> fields (like a "sort on" in a spreadsheet.
> 5. Parse to obtain the matching records
> 6. Do a little math based on how many records and the data in one
> field (success vs. fail)
> 7. Output the results of the math so it can be used in a spreadsheet
> to make cute graphics.
>
> We have a PERL guy in the division, but I am trying to use Python only
> to get this done. My question is
>
> "What is a good way to read and process the lines of the CSV file?"
> Do I pull them in one line at a time and write them to an output file?
> Do I read the whole shebang, clean the data and write an output file,
> then re-open the cleaned file?
>
>
> Thanking you all prematurely,
>
> Regards,
>
> Ralph
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
From treed at ultraviolet.org Fri Jun 2 03:00:38 2006
From: treed at ultraviolet.org (Tracy R Reed)
Date: Thu, 01 Jun 2006 18:00:38 -0700
Subject: [Tutor] implementing config files
Message-ID: <447F8DB6.1040409@ultraviolet.org>
Hello all!
I am writing some code to implement a bunch of passive checks for the
nagios network monitoring system. It runs some checks on the local
machine and reports the results back to the nagios server using rpc
calls via Perspective Broker from the Twisted module. This code and
associated config file is distributed to all of the machines in my
infrastructure by cfengine. This part all works quite well. Now I need
to refactor my code into a more general and flexible infrastructure and
provide a way to configure the services being checked instead of hard
coding them (as they currently are).
I need to implement a config file which will provide hostnames, the
names of checks to run on those hosts, and the options to those checks.
These things are sets which are nested inside each other which we can
think of like nested objects. I could make a dictionary containing the
host names each of which is a dictionary containing the services to be
checked etc.
But rather than just make dictionaries of dictionaries (which could get
confusing) I was wondering if I could make it more robust by somehow
defining objects nested inside of other objects in the config file with
certain attributes. For example I would like to be able to have a
check_tcp object which would have two attributes: hostname and port. If
you try to assign it anything else you get an error. If port isn't a
number between 0 and 2^16 you get an error. Etc. Basically I don't want
errors in the config file to propagate all the way to the client machine
on which the code is going to be executed and have wrong arguments
passed to the program which we os.popen() and read the results from.
Anyone have suggestions on how to proceed? I'm sure the problem of
parsing config files into useful objects must be a solved one...
I will eventually be posting a link to my code for others to use and
critique. It has been a neat project so far.
--
Tracy R Reed http://ultraviolet.org
A: Because we read from top to bottom, left to right
Q: Why should I start my reply below the quoted text
From clsdaniel at gmail.com Fri Jun 2 08:36:27 2006
From: clsdaniel at gmail.com (Carlos Daniel Ruvalcaba Valenzuela)
Date: Thu, 1 Jun 2006 23:36:27 -0700
Subject: [Tutor] implementing config files
In-Reply-To: <447F8DB6.1040409@ultraviolet.org>
References: <447F8DB6.1040409@ultraviolet.org>
Message-ID: <4fae7dfa0606012336k1999a7e7w3c5a290b4d413272@mail.gmail.com>
Your could try to use XML files to store configuration files, I
already coded something like that, using expat parser and loading the
XML contents to objects and attributes, this is a sample code of how
works my module:
Lets supouse we have this file config.xml with the following contents:
MySQL
localhost
21
username
and in our code:
from objxml import *
fd = file('config.xml', 'r')
p = XMLParser(fd)
root = p.Root
port = str(root.connection.port)
user = str(root.connection.username)
All nodes are objects, converting them to strings gets you the
content, you can also access the atributes as normal object
attributes.
This code can be useful for what you want, take a look.
Regards
Carlos Daniel Ruvalcaba Valenzuela
On 6/1/06, Tracy R Reed wrote:
> Hello all!
>
> I am writing some code to implement a bunch of passive checks for the
> nagios network monitoring system. It runs some checks on the local
> machine and reports the results back to the nagios server using rpc
> calls via Perspective Broker from the Twisted module. This code and
> associated config file is distributed to all of the machines in my
> infrastructure by cfengine. This part all works quite well. Now I need
> to refactor my code into a more general and flexible infrastructure and
> provide a way to configure the services being checked instead of hard
> coding them (as they currently are).
>
> I need to implement a config file which will provide hostnames, the
> names of checks to run on those hosts, and the options to those checks.
> These things are sets which are nested inside each other which we can
> think of like nested objects. I could make a dictionary containing the
> host names each of which is a dictionary containing the services to be
> checked etc.
>
> But rather than just make dictionaries of dictionaries (which could get
> confusing) I was wondering if I could make it more robust by somehow
> defining objects nested inside of other objects in the config file with
> certain attributes. For example I would like to be able to have a
> check_tcp object which would have two attributes: hostname and port. If
> you try to assign it anything else you get an error. If port isn't a
> number between 0 and 2^16 you get an error. Etc. Basically I don't want
> errors in the config file to propagate all the way to the client machine
> on which the code is going to be executed and have wrong arguments
> passed to the program which we os.popen() and read the results from.
>
> Anyone have suggestions on how to proceed? I'm sure the problem of
> parsing config files into useful objects must be a solved one...
>
> I will eventually be posting a link to my code for others to use and
> critique. It has been a neat project so far.
>
> --
> Tracy R Reed http://ultraviolet.org
> A: Because we read from top to bottom, left to right
> Q: Why should I start my reply below the quoted text
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: objxml.py
Type: text/x-python
Size: 1989 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20060601/6a4b77db/attachment.py
From samrobertsmith at gmail.com Fri Jun 2 11:29:32 2006
From: samrobertsmith at gmail.com (linda.s)
Date: Fri, 2 Jun 2006 02:29:32 -0700
Subject: [Tutor] a question about symbol
In-Reply-To: <447A466A.8040909@alum.rpi.edu>
References: <1d987df30605280127m484ca6ddhb1a735d4806d82d9@mail.gmail.com>
<447A466A.8040909@alum.rpi.edu>
Message-ID: <1d987df30606020229m2da74291hdecea42ed7f1deca@mail.gmail.com>
On 5/28/06, Bob Gailer wrote:
>
> linda.s wrote:
> When I test the following code,
> I got something like (use 80 as argument):
> 80?F=27?C
> Why '?' appear?
>
> # code
> import string, sys
>
> # If no arguments were given, print a helpful message
> if len(sys.argv)==1:
> print 'Usage: celsius temp1 temp2 ...'
> sys.exit(0)
>
> # Loop over the arguments
> for i in sys.argv[1:]:
> try:
> fahrenheit=float(string.atoi(i))
> except string.atoi_error:
> print repr(i), "not a numeric value"
> else:
> celsius=(fahrenheit-32)*5.0/9.0
> print '%i\260F = %i\260C' % (int(fahrenheit), int(celsius+.5))
>
> On my computer I get the desired result. I paste it here 80?F = 27?C and I
> see degree symbols.
>
> What operating system / terminal hardware are you using?
> --
> Bob Gailer
> 510-978-4454
mac and terminal.
From kent37 at tds.net Fri Jun 2 11:51:42 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 02 Jun 2006 05:51:42 -0400
Subject: [Tutor] a question about symbol
In-Reply-To: <1d987df30606020229m2da74291hdecea42ed7f1deca@mail.gmail.com>
References: <1d987df30605280127m484ca6ddhb1a735d4806d82d9@mail.gmail.com> <447A466A.8040909@alum.rpi.edu>
<1d987df30606020229m2da74291hdecea42ed7f1deca@mail.gmail.com>
Message-ID: <44800A2E.1060208@tds.net>
linda.s wrote:
> On 5/28/06, Bob Gailer wrote:
>> linda.s wrote:
>> When I test the following code,
>> I got something like (use 80 as argument):
>> 80?F=27?C
>> Why '?' appear?
>>
>> # code
>> print '%i\260F = %i\260C' % (int(fahrenheit), int(celsius+.5))
>>
>> On my computer I get the desired result. I paste it here 80?F = 27?C and I
>> see degree symbols.
>>
>> What operating system / terminal hardware are you using?
>> --
>> Bob Gailer
>> 510-978-4454
>
> mac and terminal.
\260 represesents the character with octal value 260, hex B0. In Latin-1
and Unicode this is a degree sign. My guess is that your terminal is set
to display UTF-8 characters rather than latin-1; in UTF-8 B0 by itself
is an error. It's also possible it is set to MacRoman but in that case I
think you would see an infinity sign instead of a question mark.
From the Python interpreter prompt, type
import sys
sys.stdout.encoding
to see what encoding your terminal is set to. If it is UTF-8, change the
\260 to \xc2\xb0 which is the correct sequence for a degree sign in
UTF-8. If it is MacRoman, change the \260 to \xa1
Kent
From kent37 at tds.net Fri Jun 2 12:08:50 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 02 Jun 2006 06:08:50 -0400
Subject: [Tutor] implementing config files
In-Reply-To: <447F8DB6.1040409@ultraviolet.org>
References: <447F8DB6.1040409@ultraviolet.org>
Message-ID: <44800E32.6070009@tds.net>
Tracy R Reed wrote:
> I need to implement a config file which will provide hostnames, the
> names of checks to run on those hosts, and the options to those checks.
> These things are sets which are nested inside each other which we can
> think of like nested objects. I could make a dictionary containing the
> host names each of which is a dictionary containing the services to be
> checked etc.
>
> But rather than just make dictionaries of dictionaries (which could get
> confusing) I was wondering if I could make it more robust by somehow
> defining objects nested inside of other objects in the config file with
> certain attributes. For example I would like to be able to have a
> check_tcp object which would have two attributes: hostname and port. If
> you try to assign it anything else you get an error. If port isn't a
> number between 0 and 2^16 you get an error.
One possibility is to make the config file be an actual Python module.
Then it can instantiate objects directly. The class constructors can do
as much checking as you like. Your config file might look like this:
import testdefs
host1 = testdefs.Host('192.168.0.53', '80')
host2 = testdefs.Host('192.168.0.55', '27')
tests = [
testdefs.check_tcp(host1),
testdefs.check_http(host1),
testdefs.check_tcp(host2),
testdefs.check_ftp(host2),
]
testdefs.Host is a class which validates and stores the hostname and
port, raising an exception if there is a problem.
testdefs.check_tcp() etc are classes that validate and remember their
init parameters and have an execute() method to actually do the test. So
just by importing the above module you validate all the parameters. To
run the tests, use something like
for test in tests:
test.execute()
> Basically I don't want
> errors in the config file to propagate all the way to the client machine
> on which the code is going to be executed and have wrong arguments
> passed to the program which we os.popen() and read the results from.
You obviously have to import the file to get the error checking, but you
could do that on a test machine before you distribute it.
Kent
From Barry.Carroll at psc.com Fri Jun 2 19:45:17 2006
From: Barry.Carroll at psc.com (Carroll, Barry)
Date: Fri, 2 Jun 2006 10:45:17 -0700
Subject: [Tutor] implementing config files
Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C36AB@eugsrv400.psc.pscnet.com>
Carlos:
Where does one find the objxml module? I have looked on python.org and
Google and can't find it.
Thanks in advance,
Barry
barry.carroll at psc.com
541-302-1107
________________________
We who cut mere stones must always be envisioning cathedrals.
-Quarry worker's creed
> -----Original Message-----
> Date: Thu, 1 Jun 2006 23:36:27 -0700
> From: "Carlos Daniel Ruvalcaba Valenzuela"
> Subject: Re: [Tutor] implementing config files
> To: "Tracy R Reed"
> Cc: tutor at python.org
> Message-ID:
> <4fae7dfa0606012336k1999a7e7w3c5a290b4d413272 at mail.gmail.com>
> Content-Type: text/plain; charset="iso-8859-1"
>
> Your could try to use XML files to store configuration files, I
> already coded something like that, using expat parser and loading the
> XML contents to objects and attributes, this is a sample code of how
> works my module:
>
> Lets supouse we have this file config.xml with the following contents:
>
>
>
> MySQL
> localhost
> 21
> username
>
>
>
>
> and in our code:
>
> from objxml import *
>
> fd = file('config.xml', 'r')
> p = XMLParser(fd)
>
> root = p.Root
> port = str(root.connection.port)
> user = str(root.connection.username)
>
> All nodes are objects, converting them to strings gets you the
> content, you can also access the atributes as normal object
> attributes.
>
> This code can be useful for what you want, take a look.
>
> Regards
> Carlos Daniel Ruvalcaba Valenzuela
>
>
> On 6/1/06, Tracy R Reed wrote:
> > Hello all!
> >
> > I am writing some code to implement a bunch of passive checks for
the
> > nagios network monitoring system.
<>
> >
> > --
> > Tracy R Reed http://ultraviolet.org
> > A: Because we read from top to bottom, left to right
> > Q: Why should I start my reply below the quoted text
From Barry.Carroll at psc.com Sat Jun 3 01:23:15 2006
From: Barry.Carroll at psc.com (Carroll, Barry)
Date: Fri, 2 Jun 2006 16:23:15 -0700
Subject: [Tutor] Trouble with os.path.isfile
Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C36AC@eugsrv400.psc.pscnet.com>
Greetings:
One of the functions of my test system web server program is to allow
the user to view the contents of the image file directories and select
files to load onto the hardware. Obviously, a central part of this
function is to identify and display the names of directories and files
in a specified directory. I haven't been able to find any canned code
or cookbook entries that do this, so I'm making one from scratch. Here
is the helper function that gets and returns the directory and file
names:
>>>>>>>>>>>>>>>>>>>>>>>>>>
def lstdirsnfiles(tdir):
flst = os.listdir(tdir)
flst.sort()
fnames = []
dnames = ['.', '..']
for name in flst:
absfn = os.path.join(tdir, name)
if os.path.isdir(absfn):
dnames.append(name)
elif os.path.isfile(absfn):
fnames.append(name)
return dnames, fnames
>>>>>>>>>>>>>>>>>>>>>>>>>>
The root of the image file directory tree is "/home/iip/images". When
lstdirsnfiles is run with tdir set appropriately, the lists returned
contain no additional information: dnames = ['.', '..'] and fnames = [].
I added some tracing statements to see what was happening inside the
function:
>>>>>>>>>>>>>>>>>>>>>>>>>>
def lstdirsnfiles(tdir):
global DEBUG, dbgfname
DEBUG = True
flst = os.listdir(tdir)
flst.sort()
fnames = []
dnames = ['.', '..']
if DEBUG:
dbgf = open(dbgfname,mode="a")
dbgf.write("\n"+str (time.localtime())+"\n")
dbgf.write("Entering lstdirsnfiles\n")
dbgf.write("The directory = %s\n" % tdir)
dbgf.write("The file list = %s\n" % flst)
for name in flst:
absfn = os.path.join(tdir, name)
if DEBUG:
dbgf.write("File path = %s, isfile = %s\n" %
(absfn, os.path.isfile(absfn)))
if os.path.isdir(absfn):
dnames.append(name)
elif os.path.isfile(absfn):
fnames.append(name)
if DEBUG:
dbgf.write("dnames = %s\n" % dnames)
dbgf.write("fnames = %s\n" % fnames)
dbgf.close()
DEBUG = False
return dnames, fnames
>>>>>>>>>>>>>>>>>>>>>>>>>>
The log vile received the following:
>>>>>>>>>>>>>>>>>>>>>>>>>>
(2006, 6, 2, 15, 23, 4, 4, 153, 1)
Entering lstdirsnfiles
The directory = /home/iip/images
The file list = ['test1.bmp', 'test2.bmp', 'test3.bmp', 'test4.bmp',
'test5.bmp', 'test6.bmp']
File path = /home/iip/images/test1.bmp, isfile = False
File path = /home/iip/images/test2.bmp, isfile = False
File path = /home/iip/images/test3.bmp, isfile = False
File path = /home/iip/images/test4.bmp, isfile = False
File path = /home/iip/images/test5.bmp, isfile = False
File path = /home/iip/images/test6.bmp, isfile = False
dnames = ['.', '..']
fnames = []
>>>>>>>>>>>>>>>>>>>>>>>>>>
So there are entries in the directory, but the function doesn't
recognize them as files.
Finally, I opened the interpreter and tried doing this, as nearly as
possible, interactively. I got this:
>>>>>>>>>>>>>>>>>>>>>>>>>>
>>> import os
>>> tdir = '/home/iip/images'
>>> os.listdir(tdir)
['test4.bmp', 'test3.bmp', 'test2.bmp', 'test1.bmp', 'test5.bmp',
'test6.bmp']
>>> flst = os.listdir(tdir)
>>> flst.sort()
>>> flst
['test1.bmp', 'test2.bmp', 'test3.bmp', 'test4.bmp', 'test5.bmp',
'test6.bmp']
>>> for name in flst:
... absfn = os.path.join(tdir,name)
... print absfn, "is",
... if not os.path.isfile(absfn):
... print "NOT",
... print "a file"
...
/home/iip/images/test1.bmp is a file
/home/iip/images/test2.bmp is a file
/home/iip/images/test3.bmp is a file
/home/iip/images/test4.bmp is a file
/home/iip/images/test5.bmp is a file
/home/iip/images/test6.bmp is a file
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
As you can see, the interpreter correctly identifies the strings in the
list as names of files, but my function does not. I can't see anything
wrong with the logic in the function. Can any or you see the problem
I'm missing?
As always, thanks in advance for your help.
Barry
barry.carroll at psc.com
541-302-1107
________________________
We who cut mere stones must always be envisioning cathedrals.
-Quarry worker's creed
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060602/f2ba27b8/attachment-0001.htm
From clsdaniel at gmail.com Sat Jun 3 08:28:21 2006
From: clsdaniel at gmail.com (Carlos Daniel Ruvalcaba Valenzuela)
Date: Fri, 2 Jun 2006 23:28:21 -0700
Subject: [Tutor] Trouble with os.path.isfile
In-Reply-To: <4fae7dfa0606022310g66f902b1j5b038ac940edff2c@mail.gmail.com>
References: <2BBAEE949D384D40A2B851287ADB6A432C36AC@eugsrv400.psc.pscnet.com>
<4fae7dfa0606022310g66f902b1j5b038ac940edff2c@mail.gmail.com>
Message-ID: <4fae7dfa0606022328k57c6a5cewee68fa1a33537e6b@mail.gmail.com>
From: Carlos Daniel Ruvalcaba Valenzuela
Date: Jun 2, 2006 11:10 PM
Subject: Re: [Tutor] Trouble with os.path.isfile
To: "Carroll, Barry"
Here is the problem IMO:
I did some modifications to your code (very minimal on ifs) and it worked:
import os
def lstdirsnfiles(tdir):
flst = os.listdir(tdir)
flst.sort()
fnames = []
dnames = ['.', '..']
for name in flst:
absfn = os.path.join(tdir, name)
if os.path.isdir(absfn):
dnames.append(name)
if os.path.isfile(absfn):
fnames.append(name)
return (dnames, fnames)
(dirs, files) = lstdirsnfiles('/home/clsdaniel')
It returns correctly all directories and files.
Regards
Carlos Daniel Ruvalcaba Valenzuela
On 6/2/06, Carroll, Barry wrote:
>
>
>
>
> Greetings:
>
>
>
> One of the functions of my test system web server program is to allow the
> user to view the contents of the image file directories and select files to
> load onto the hardware. Obviously, a central part of this function is to
> identify and display the names of directories and files in a specified
> directory. I haven't been able to find any canned code or cookbook entries
> that do this, so I'm making one from scratch. Here is the helper function
> that gets and returns the directory and file names:
>
>
>
> >>>>>>>>>>>>>>>>>>>>>>>>>>
>
> def lstdirsnfiles(tdir):
>
> flst = os.listdir(tdir)
>
> flst.sort()
>
> fnames = []
>
> dnames = ['.', '..']
>
> for name in flst:
>
> absfn = os.path.join(tdir, name)
>
> if os.path.isdir(absfn):
>
> dnames.append(name)
>
> elif os.path.isfile(absfn):
>
> fnames.append(name)
>
> return dnames, fnames
>
> >>>>>>>>>>>>>>>>>>>>>>>>>>
>
>
>
> The root of the image file directory tree is "/home/iip/images". When
> lstdirsnfiles is run with tdir set appropriately, the lists returned
> contain no additional information: dnames = ['.', '..'] and fnames = []. I
> added some tracing statements to see what was happening inside the
> function:
>
>
>
> >>>>>>>>>>>>>>>>>>>>>>>>>>
>
> def lstdirsnfiles(tdir):
>
> global DEBUG, dbgfname
>
> DEBUG = True
>
>
>
> flst = os.listdir(tdir)
>
> flst.sort()
>
> fnames = []
>
> dnames = ['.', '..']
>
>
>
> if DEBUG:
>
> dbgf = open(dbgfname,mode="a")
>
> dbgf.write("\n"+str (time.localtime())+"\n")
>
> dbgf.write("Entering lstdirsnfiles\n")
>
> dbgf.write("The directory = %s\n" % tdir)
>
> dbgf.write("The file list = %s\n" % flst)
>
>
>
> for name in flst:
>
> absfn = os.path.join(tdir, name)
>
>
>
> if DEBUG:
>
> dbgf.write("File path = %s, isfile = %s\n" %
>
> (absfn, os.path.isfile(absfn)))
>
>
>
> if os.path.isdir(absfn):
>
> dnames.append(name)
>
> elif os.path.isfile(absfn):
>
> fnames.append(name)
>
>
>
> if DEBUG:
>
> dbgf.write("dnames = %s\n" % dnames)
>
> dbgf.write("fnames = %s\n" % fnames)
>
> dbgf.close()
>
> DEBUG = False
>
>
>
> return dnames, fnames
>
> >>>>>>>>>>>>>>>>>>>>>>>>>>
>
>
>
> The log vile received the following:
>
> >>>>>>>>>>>>>>>>>>>>>>>>>>
>
> (2006, 6, 2, 15, 23, 4, 4, 153, 1)
>
> Entering lstdirsnfiles
>
> The directory = /home/iip/images
>
> The file list = ['test1.bmp', 'test2.bmp', 'test3.bmp', 'test4.bmp',
> 'test5.bmp', 'test6.bmp']
>
> File path = /home/iip/images/test1.bmp, isfile = False
>
> File path = /home/iip/images/test2.bmp, isfile = False
>
> File path = /home/iip/images/test3.bmp, isfile = False
>
> File path = /home/iip/images/test4.bmp, isfile = False
>
> File path = /home/iip/images/test5.bmp, isfile = False
>
> File path = /home/iip/images/test6.bmp, isfile = False
>
> dnames = ['.', '..']
>
> fnames = []
>
> >>>>>>>>>>>>>>>>>>>>>>>>>>
>
>
>
> So there are entries in the directory, but the function doesn't recognize
> them as files.
>
>
>
> Finally, I opened the interpreter and tried doing this, as nearly as
> possible, interactively. I got this:
>
>
>
> >>>>>>>>>>>>>>>>>>>>>>>>>>
>
> >>> import os
>
> >>> tdir = '/home/iip/images'
>
> >>> os.listdir(tdir)
>
> ['test4.bmp', 'test3.bmp', 'test2.bmp', 'test1.bmp', 'test5.bmp',
> 'test6.bmp']
>
> >>> flst = os.listdir(tdir)
>
> >>> flst.sort()
>
> >>> flst
>
> ['test1.bmp', 'test2.bmp', 'test3.bmp', 'test4.bmp', 'test5.bmp',
> 'test6.bmp']
>
> >>> for name in flst:
>
> ... absfn = os.path.join(tdir,name)
>
> ... print absfn, "is",
>
> ... if not os.path.isfile(absfn):
>
> ... print "NOT",
>
> ... print "a file"
>
> ...
>
> /home/iip/images/test1.bmp is a file
>
> /home/iip/images/test2.bmp is a file
>
> /home/iip/images/test3.bmp is a file
>
> /home/iip/images/test4.bmp is a file
>
> /home/iip/images/test5.bmp is a file
>
> /home/iip/images/test6.bmp is a file
>
> >>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>
>
>
> As you can see, the interpreter correctly identifies the strings in the list
> as names of files, but my function does not. I can't see anything wrong
> with the logic in the function. Can any or you see the problem I'm missing?
>
>
>
> As always, thanks in advance for your help.
>
>
>
> Barry
>
> barry.carroll at psc.com
>
> 541-302-1107
>
> ________________________
>
> We who cut mere stones must always be envisioning cathedrals.
>
> ?Quarry worker's creed
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
From oztriking at hotmail.com Sun Jun 4 15:33:48 2006
From: oztriking at hotmail.com (John Connors)
Date: Sun, 04 Jun 2006 23:33:48 +1000
Subject: [Tutor] Not Really Questions
Message-ID:
G'day,
While the list is kind of slow I thought I'd post a few thoughts on a couple
of things in Python that bug me. They're not really questions but maybe
someone can help me understand.
The first one is lists... I can't for the life of me understand why a list
starts at zero. In everything else in life other than programming the 1st
item in a list is always 1.
The next thing I don't understand is why the last number in a range is not
used...
For a in range(1,6):
print a,
1 2 3 4 5
Once again it defies the logic of everything else we are taught in life.
The 3rd whinge is object oriented programming. I think I understand the
principle behind OOP but in practise, to me, it just makes programs jumbled,
unreadable and bloated. Just about every summary I have read on Python says
it is designed to have a simple syntax and is easy to learn. As a beginner I
can look at Python code and have a very good idea of what is happening and
why unless it's written in OOP style in which case I have no idea.
John
_________________________________________________________________
Read, write and reply to Hotmail on your mobile. Find out more.
http://mobilecentral.ninemsn.com.au/mcmobileHotmail/home.aspx
From dustin at ywlcs.org Sun Jun 4 17:15:43 2006
From: dustin at ywlcs.org (Dustin J.Mitchell)
Date: Sun, 4 Jun 2006 10:15:43 -0500
Subject: [Tutor] Not Really Questions
In-Reply-To:
References:
Message-ID: <130596e7576f948efc8bc8165788edc2@ywlcs.org>
Let me see if I can tackle these..
On Jun 4, 2006, at 8:33 AM, John Connors wrote:
> The first one is lists... I can't for the life of me understand why a
> list
> starts at zero. In everything else in life other than programming the
> 1st
> item in a list is always 1.
>
> The next thing I don't understand is why the last number in a range is
> not
> used...
> Once again it defies the logic of everything else we are taught in
> life.
This is basically a historical precedent. At one point, long long ago,
lists were implemented as a sequence of bytes in memory. The "list"
was really the address of the first byte. So the index meant "look
this many bytes after the first byte". The first byte was zero bytes
after the first byte, so its index was zero. The range thing is
similar -- think of the arguments to range being (first index to
include, first index to exclude).
There have been a few programming languages that have changed this
(Pascal comes to mind), but none have fared well.
You'll get used to it :)
> The 3rd whinge is object oriented programming. I think I understand the
> principle behind OOP but in practise, to me, it just makes programs
> jumbled,
> unreadable and bloated. Just about every summary I have read on Python
> says
> it is designed to have a simple syntax and is easy to learn. As a
> beginner I
> can look at Python code and have a very good idea of what is happening
> and
> why unless it's written in OOP style in which case I have no idea.
I will be one of the first to say that OOP is grossly overused in
commercial programming -- at some point, middle-management learned that
"OOP is good", and demanded that programmers start using it everywhere.
Sometimes it's the right tool for the job, and sometimes it isn't. I
won't get into the details of that distinction, except to say that
simpler tasks tend to not require OOP, while more complex tasks often
do. Thus, the non-OOP programs you're looking at are probably
performing simpler tasks than the OOP programs.
Again, you'll get used to it. One of the nice things about Python is
that it lets you write both OOP and non-OOP programs, so you've got a
lot of room to experiment and learn OOP style. Java, on the other
hand, requires OOP for everything, making it much harder to learn when
OOP is and is not appropriate.
Dustin
--
# Dustin J. Mitchell
# dustin at ywlcs.org/djmitche at alumni.uchicago.edu
From bgailer at alum.rpi.edu Sun Jun 4 19:30:24 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Sun, 04 Jun 2006 10:30:24 -0700
Subject: [Tutor] Not Really Questions
In-Reply-To:
References:
Message-ID: <448318B0.6080305@alum.rpi.edu>
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060604/6900108c/attachment.html
-------------- next part --------------
A non-text attachment was scrubbed...
Name: show
Type: image/gif
Size: 43 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20060604/6900108c/attachment.gif
From kent37 at tds.net Sun Jun 4 20:05:08 2006
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 04 Jun 2006 14:05:08 -0400
Subject: [Tutor] Not Really Questions
In-Reply-To:
References:
Message-ID: <448320D4.7080201@tds.net>
John Connors wrote:
> G'day,
>
> While the list is kind of slow I thought I'd post a few thoughts on a couple
> of things in Python that bug me. They're not really questions but maybe
> someone can help me understand.
Maybe I can give you some not-really answers ;)
>
> The first one is lists... I can't for the life of me understand why a list
> starts at zero. In everything else in life other than programming the 1st
> item in a list is always 1.
Many programming languages start indexes at zero. It makes sense if you
think of a list being stored as sequential values in memory, and the
index as the offset from the start of the list. (This is in fact how
arrays are often implemented.)
>
> The next thing I don't understand is why the last number in a range is not
> used...
>
> For a in range(1,6):
> print a,
>
> 1 2 3 4 5
>
> Once again it defies the logic of everything else we are taught in life.
This actually prevents many types of errors. Alex Martelli has a good
explanation here (also see his other posts in the same thread):
http://groups.google.com/group/comp.lang.python/msg/579b53de640190cd
>
> The 3rd whinge is object oriented programming. I think I understand the
> principle behind OOP but in practise, to me, it just makes programs jumbled,
> unreadable and bloated. Just about every summary I have read on Python says
> it is designed to have a simple syntax and is easy to learn. As a beginner I
> can look at Python code and have a very good idea of what is happening and
> why unless it's written in OOP style in which case I have no idea.
OOP does take some getting used to, it is a different way of thinking
about the structure of a program. Done badly, it is a good way to make a
mess. Done well, it is a tool for creating a highly modular program
where the responsibilities of each piece are well defined.
Kent
From hugonz-lists at h-lab.net Sun Jun 4 22:54:36 2006
From: hugonz-lists at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=)
Date: Sun, 04 Jun 2006 15:54:36 -0500
Subject: [Tutor] Not Really Questions
In-Reply-To:
References:
Message-ID: <4483488C.1040506@h-lab.net>
John Connors wrote:
>
> The first one is lists... I can't for the life of me understand why a list
> starts at zero. In everything else in life other than programming the 1st
> item in a list is always 1.
Hi,
Exactly, everything else other than programming. Zero indexed arrays are
the norm in everything but moronic old VB. I guess it's just a defacto
standard now.
>
> The next thing I don't understand is why the last number in a range is not
> used...
>
> For a in range(1,6):
> print a,
>
> 1 2 3 4 5
>
This relates to the previous issue. This comes from the fact that
range(3) = [0, 1, 2]
This is extremely useful for iterating indices, and I can suppose that
when range() was first extended, it had to remain consistent.
> The 3rd whinge is object oriented programming. I think I understand the
> principle behind OOP but in practise, to me, it just makes programs jumbled,
> unreadable and bloated. Just about every summary I have read on Python says
> it is designed to have a simple syntax and is easy to learn. As a beginner I
> can look at Python code and have a very good idea of what is happening and
> why unless it's written in OOP style in which case I have no idea.
>
OOP is a rare beast to me: it makes suitable problems very very easy
(think about GUI programming without OOP) and unsuitable problems
extremely convoluted. I guess it's just the fact that it is a paradigm
and not just a programming technique.
Fortunately, unless other languages which *force* you to use OOP (think
Java), Python allows you to use at least 3 different paradigms (OOP,
functional(like Lisp et al) and structured(like Pascal and C))
Just my 2 cents,
Hugo
From alan.gauld at btinternet.com Mon Jun 5 01:01:08 2006
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Mon, 5 Jun 2006 00:01:08 +0100
Subject: [Tutor] Not Really Questions
References:
Message-ID:
Hi John,
I'll pitch in although I've read most of the other answers
too so I'll be adding to them mostly.
> The first one is lists... I can't for the life of me understand why
> a list
> starts at zero. In everything else in life other than programming
Not quite. In math zero is usually the starting point, its generally
viewed as a positive number(although it is obviously neither positive
or negative) and proofs and definitions usually start by consideriung
zero - or at least defining whether zero is in or out of scope.
This math point is important because programming was originally
a branch of math and it was mathematicians who laid the ground
rules.
But, it was by no means cast in stone until implementations
of list indexing started to be based on the start addressof the
list in memory.
In C this is even explicitly visible.
We can declare anm array of numbers like this
int anArray[] = {1,3,5};
and then a pointer to an integer like this
int* intPtr;
We can now set intPtr to point at the array:
intPtr = anArray;
If we printed thevcontents of intPtr we would get 1
Now increment the pointer:
intPtr == 1
Now id we print iojntPtr we will get 5, the next value in the array.
We can also get the 3rd element by using
intPtr = anArray + 2
printf("%d",*intPtr) // print the content of intPtr
and of course we get the same result with
printf("%d",intArray[2]) // print the 3rd element of intArray
So in C you can see that indexing is really a very thin
wrapper around memory aroithmetic.
> The next thing I don't understand is why the last number in a range
> is not
> used...
>
> For a in range(1,6):
> print a,
>
> 1 2 3 4 5
This is to make range match with the indexing.
We can do stuff like
for index in range(len(alist)):
print alist[index]
If the two did not match you would do something like:
for index in range(len(alist)):
print alist[index-1]
If you are going to be weird at least be consistently weird!
Finally some languages allow us to use "normal"! indexing
Pascal for example allows:
program test(output)
var
anArray : array [1..5] of integer;
n : integer;
begin
for n := 1 to 5 do
begin
anArray[n] = 2 * n
end;
writeln anArray[1];
writeln anArray[3];
writeln anArray[5]
end.
Which populates an array with indices from 1 through 5
> The 3rd whinge is object oriented programming. I think I understand
> the
> principle behind OOP but in practise, to me, it just makes programs
> jumbled,
Further to the previous comments, OOP has several purposes and
is used to achieve difgfferent things. But fundamentally OOP is used
to control the complexity of large programs. If you are writing
program
of less than 100 lines you almost never need to use OOP (You may
choose to for some of the other reasons below, but its not needed).
Between 100 and 1000 lines you are more likely to find OOP coming
in handy. Between 1000 lines and 10,000 lines you will almost
certainly
find at least some of your code that benefits. Beyond 10,000 lines
(and I'm, talking Python code here) OOP will be almost indispensible
in helping you keep the structure of the code clear in your mind
(and in your code too!)
There are other ways to control complexity and very large programs
have been written without it. It fact its fairly safe to say that all
the
biggest programs are OOP free being written in COBOL. But COBOL
has its own mechanisms for managing complexity and there is now
an object oriented COBOL available to combine the best of both worlds.
[On a personal note the two biggest programs I've worked on have both
been COBOL - 10 million and 6 million lines respectively. The 3rd
biggest was C++ at 3.5 million lines. The COBOL was easier... But
I've also worked on a 500K lines C program(with no OOP) and that
was the hardest of all of them! So OOP works but its not the holy
grail that some pundits would have you believe]
Other reasons to use OOP are that it definitely makes reuse easier
both within a project and between projects. It also can reduce the
code size on some types of project. It definitely makes code more
flexible by allowing objects to be swapped in and out if they have the
same "interface" or protocol.
Also some people find objects more easy to think about.
It seems more logical to move the table than to change the
table's x and y coordinates... However folks brought up with
a math or science background, or who have already programmed
find it very hard to make the mental switch to seeing the world as
communicating objects rather than data being maniupulated by
functions...
And thats way more than I set out to write!!!
HTH
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
From yi at yiqiang.net Mon Jun 5 03:43:25 2006
From: yi at yiqiang.net (Yi Qiang)
Date: Sun, 04 Jun 2006 18:43:25 -0700
Subject: [Tutor] Not Really Questions
In-Reply-To:
References:
Message-ID: <44838C3D.9010907@yiqiang.net>
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Alan Gauld wrote, On 06/04/2006 04:01 PM:
> Hi John,
>
> I'll pitch in although I've read most of the other answers
> too so I'll be adding to them mostly.
>
>> The first one is lists... I can't for the life of me understand why
>> a list
>> starts at zero. In everything else in life other than programming
>
> Not quite. In math zero is usually the starting point, its generally
> viewed as a positive number(although it is obviously neither positive
> or negative) and proofs and definitions usually start by consideriung
> zero - or at least defining whether zero is in or out of scope.
That is just not true. A number is positive if and only if it is
strictly greater than 0 by definition. Zero is not considered positive
in mathematics. In fact, the set of positive integers, Z+, is the set
{1,2,3,....}.
- --
Yi Qiang (yi at yiqiang.net)
Web: http://www.yiqiang.net
Tel: (206) 661-8469
PGP: 0xB515564B
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2.2 (GNU/Linux)
iD8DBQFEg4w9tXlIMrUVVksRAn9RAJ9KAuaKvNvkXFwPNSn0+tMCKwOWMQCdHx6j
L8pOPQRJMv8GcnypMblCIgI=
=dtF3
-----END PGP SIGNATURE-----
From tim at johnsons-web.com Mon Jun 5 03:21:04 2006
From: tim at johnsons-web.com (Tim Johnson)
Date: Sun, 4 Jun 2006 17:21:04 -0800
Subject: [Tutor] Not Really Questions
In-Reply-To: <4483488C.1040506@h-lab.net>
References:
<4483488C.1040506@h-lab.net>
Message-ID: <20060605012104.GC31550@johnsons-web.com>
* Hugo Gonz?lez Monteverde [060604 13:04]:
>
> Exactly, everything else other than programming. Zero indexed arrays are
> the norm in everything but moronic old VB. I guess it's just a defacto
> standard now.
I make equal parts of my income from writing python code and from
writing code in rebol. Rebol starts indexes with 1. It also uses the
'first function (like lisp). This has prompted me to write and use
the following:
def first(v):
return v[0]
(-: Regardless of where you start counting, there you are!
> OOP is a rare beast to me: it makes suitable problems very very easy
> (think about GUI programming without OOP) and unsuitable problems
> extremely convoluted. I guess it's just the fact that it is a paradigm
> and not just a programming technique.
comparing rebol and python - rebol is more productive, line for line,
from my experience. But because of python's OOP engineering it, it
scales better, enabling more maintainable code in larger projects.
Consequently, I use python for big projects, rebol for small.
"""
The right tool for the right job
"""
tim
--
Tim Johnson
http://www.alaska-internet-solutions.com
From rondosxx at yahoo.com Mon Jun 5 04:02:48 2006
From: rondosxx at yahoo.com (ron)
Date: Sun, 4 Jun 2006 19:02:48 -0700 (PDT)
Subject: [Tutor] Not Really Questions
Message-ID: <20060605020248.76721.qmail@web52508.mail.yahoo.com>
I think we should say that the number set is zero
through nine (not 1-10 as we were taught in school),
making "zero" the first number in the set; thus the
offset by one. Of course zero is not a number, but a
placeholder for a number. Thankfully this concept was
invented a few centuries ago in India and brought to
the West by Arab scholars. Unfortunately I think it's
still not widely understood.
__________________________________________________
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
http://mail.yahoo.com
From wescpy at gmail.com Mon Jun 5 07:29:12 2006
From: wescpy at gmail.com (w chun)
Date: Sun, 4 Jun 2006 22:29:12 -0700
Subject: [Tutor] Not Really Questions
In-Reply-To:
References:
Message-ID: <78b3a9580606042229v232c2380xf43ef9fa0f9594e7@mail.gmail.com>
hi john,
everyone else has posted great replies to your inquiries, so i'll keep
mine brief.
> While the list is kind of slow I thought I'd post a few thoughts on a couple
> of things in Python that bug me.
my 1st comment is that you are not talking about Python alone.
everything you state pertains to most other programming languages.
> The first one is lists... I can't for the life of me understand why a list
> starts at zero. In everything else in life other than programming the 1st
> item in a list is always 1.
sequences, arrays, etc., in most other languages do start at zero, and
have a strong tie to that addressing stuff that's already been
mentioned. this is just a fact of programming.
> The next thing I don't understand is why the last number in a range is not
> used...
>
> For a in range(1,6):
> print a,
>
> 1 2 3 4 5
>
> Once again it defies the logic of everything else we are taught in life.
this is partially due to your 1st issue, that things start at zero. a
sequence of length 5, for example, or range(5) means: 0, 1, 2, 3, 4.
even tho the counting is up to 4, you will see that this is a
collection of five items.
this feature of "i up-to-but-not-including j" also mirrors other
languages, say counting in C for example: for (i = 0; i < 5; i++);
> The 3rd whinge is object oriented programming.
like all programming tools, one must investigate whether it is the
right tool for the job. if it's a simple one-off script, then probly
not; but if it is a huge framework where you want to most code reuse,
least amount of code to maintain, minimization of the number of bugs,
and being able to lump functionality/logic with data, OOP is the way
to go.
a simple example would be shapes and functions like finding an area.
like objects can share the same functions (called "methods"), i.e.
square.area(), rectangle.area(), whereas for other objects that aren't
similar, i wouldn't want the wrong functionality but i *would* want to
use the same name, circle.area().
the good news, as others have mentioned, is that Python is flexible,
letting you build the application as you see fit, and not locked to
any specific paradigm except perhaps KISS.
good luck!
-- 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
From yi at yiqiang.net Mon Jun 5 08:03:32 2006
From: yi at yiqiang.net (Yi Qiang)
Date: Sun, 04 Jun 2006 23:03:32 -0700
Subject: [Tutor] problem with unpickling an object
Message-ID: <4483C934.40003@yiqiang.net>
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Hi list,
I am pickling a dictionary that has as one of it's values an object I
create on the fly. When I try to unpickle that object, cPickle attempts
to recreate that object but of course that module is not present
anymore. How can I just make it skip over that particular key and just
set the value to None?
Thanks,
- --
Yi Qiang (yi at yiqiang.net)
Web: http://www.yiqiang.net
Tel: (206) 661-8469
PGP: 0xB515564B
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2.2 (GNU/Linux)
iD8DBQFEg8k0tXlIMrUVVksRAt2tAJ4hq/3KmDo6BbS3p3AwhKf4Ga52DQCfXFtx
GERJqs3IcLXuKaRcq/zuRUE=
=SEZ6
-----END PGP SIGNATURE-----
From alan.gauld at freenet.co.uk Mon Jun 5 08:46:58 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Mon, 5 Jun 2006 07:46:58 +0100
Subject: [Tutor] Not Really Questions
References:
<44838C3D.9010907@yiqiang.net>
Message-ID: <001401c6886b$d7aac8d0$0a01a8c0@XPpro>
>> Not quite. In math zero is usually the starting point, its
>> generally
>> viewed as a positive number(although it is obviously neither
>> positive
>> or negative)
> That is just not true. A number is positive if and only if it is
> strictly greater than 0 by definition. Zero is not considered
> positive
> in mathematics. In fact, the set of positive integers, Z+, is the
> set
> {1,2,3,....}.
Quite so (as I pointed out in parens) but I'll retract the comment
about it being viewed as positive and say it is viewed as being
not negative (which is of course true!). Thus zero is frequently
treated as the first significant number when considering sequences
and ranges of numbers (Z+ not withstanding! :-) The introduction
of zero into math was a huge step and as a result a lot of classical
math does not consider it but in practical day to day math and science
zero is treated as the first number. That's all I was really trying to
say...
Alan G.
From kent37 at tds.net Mon Jun 5 12:12:24 2006
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 05 Jun 2006 06:12:24 -0400
Subject: [Tutor] problem with unpickling an object
In-Reply-To: <4483C934.40003@yiqiang.net>
References: <4483C934.40003@yiqiang.net>
Message-ID: <44840388.2090803@tds.net>
From a quick read of the docs, it looks like you should set the
unpickler's find_global attribute to a function you define. This
function can first attempt to load the desired class (see
pickle.find_class() for an example). If the load fails, then return a
placeholder class that you define.
This won't give exactly the result you ask for, instead of None in the
dictionary you will have instances of the placeholder. You could then
post-process the dict to change the placeholder instances to None if you
like.
Kent
Yi Qiang wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> Hi list,
> I am pickling a dictionary that has as one of it's values an object I
> create on the fly. When I try to unpickle that object, cPickle attempts
> to recreate that object but of course that module is not present
> anymore. How can I just make it skip over that particular key and just
> set the value to None?
>
> Thanks,
> - --
> Yi Qiang (yi at yiqiang.net)
> Web: http://www.yiqiang.net
> Tel: (206) 661-8469
> PGP: 0xB515564B
> -----BEGIN PGP SIGNATURE-----
> Version: GnuPG v1.4.2.2 (GNU/Linux)
>
> iD8DBQFEg8k0tXlIMrUVVksRAt2tAJ4hq/3KmDo6BbS3p3AwhKf4Ga52DQCfXFtx
> GERJqs3IcLXuKaRcq/zuRUE=
> =SEZ6
> -----END PGP SIGNATURE-----
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
From yi at yiqiang.net Mon Jun 5 16:14:12 2006
From: yi at yiqiang.net (Yi Qiang)
Date: Mon, 05 Jun 2006 07:14:12 -0700
Subject: [Tutor] problem with unpickling an object
In-Reply-To: <44840388.2090803@tds.net>
References: <4483C934.40003@yiqiang.net> <44840388.2090803@tds.net>
Message-ID: <44843C34.2050502@yiqiang.net>
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Kent Johnson wrote, On 06/05/2006 03:12 AM:
> From a quick read of the docs, it looks like you should set the
> unpickler's find_global attribute to a function you define. This
> function can first attempt to load the desired class (see
> pickle.find_class() for an example). If the load fails, then return a
> placeholder class that you define.
>
> This won't give exactly the result you ask for, instead of None in the
> dictionary you will have instances of the placeholder. You could then
> post-process the dict to change the placeholder instances to None if you
> like.
Interesting, so if I used this method I won't be able to use cPickle
anymore. The documentation just says that cPickle is "faster", but can
anyone quantify how much speed I am losing if I move to the regular
pickle module?
- --
Yi Qiang (yi at yiqiang.net)
Web: http://www.yiqiang.net
Tel: (206) 661-8469
PGP: 0xB515564B
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2.2 (GNU/Linux)
iD8DBQFEhDw0tXlIMrUVVksRApzBAJ427uRcMuQk6TgqGfWGZu8GjlZWBgCbBTBP
83oVZ9NNswfGrzk58Bat57k=
=J5gs
-----END PGP SIGNATURE-----
From dyoo at hkn.eecs.berkeley.edu Mon Jun 5 16:15:31 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 5 Jun 2006 07:15:31 -0700 (PDT)
Subject: [Tutor] Not Really Questions
In-Reply-To:
References:
Message-ID:
On Sun, 4 Jun 2006, John Connors wrote:
> The first one is lists... I can't for the life of me understand why a
> list starts at zero. In everything else in life other than programming
> the 1st item in a list is always 1.
Edsger Dijkstra wrote a technical note on why zero is a more natural
starting point:
http://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF
Also, programming is one of those fields where appreciating the null case
can be advantageous.
From kent37 at tds.net Mon Jun 5 16:25:36 2006
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 05 Jun 2006 10:25:36 -0400
Subject: [Tutor] problem with unpickling an object
In-Reply-To: <44843C34.2050502@yiqiang.net>
References: <4483C934.40003@yiqiang.net> <44840388.2090803@tds.net>
<44843C34.2050502@yiqiang.net>
Message-ID: <44843EE0.2080007@tds.net>
Yi Qiang wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> Kent Johnson wrote, On 06/05/2006 03:12 AM:
>> From a quick read of the docs, it looks like you should set the
>> unpickler's find_global attribute to a function you define. This
>> function can first attempt to load the desired class (see
>> pickle.find_class() for an example). If the load fails, then return a
>> placeholder class that you define.
>>
>> This won't give exactly the result you ask for, instead of None in the
>> dictionary you will have instances of the placeholder. You could then
>> post-process the dict to change the placeholder instances to None if you
>> like.
>
> Interesting, so if I used this method I won't be able to use cPickle
> anymore. The documentation just says that cPickle is "faster", but can
> anyone quantify how much speed I am losing if I move to the regular
> pickle module?
No, the find_global() hook is for cPickle. See the next-to-last
paragraph on this page:
http://docs.python.org/lib/pickle-sub.html
As far as speed, the best thing is just to try it with your data. pickle
and cPickle have the same API so it should be easy to switch your code
to use pickle and run a timing test.
Kent
From Barry.Carroll at psc.com Mon Jun 5 21:16:18 2006
From: Barry.Carroll at psc.com (Carroll, Barry)
Date: Mon, 5 Jun 2006 12:16:18 -0700
Subject: [Tutor] Trouble with os.path.isfile
Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C36AF@eugsrv400.psc.pscnet.com>
Carlos:
Thank you for your response.
It turns out that Python and os.path.isfile() are working as expected.
A permissions conflict on my Linux-based system caused the isfile
function to return false for all the entries in the directory. The web
server is running as user apache. The files were owned by user iip. I
don't have all the details worked out yet, but it appears that adding
apache to iip's group list resolves the conflict.
It would be nice if the library entries for os.path.is* (where * is one
of {file, dir, link, mount) mentioned this restriction.
Regards,
Barry
barry.carroll at psc.com
541-302-1107
________________________
We who cut mere stones must always be envisioning cathedrals.
-Quarry worker's creed
> -----Original Message-----
> Date: Fri, 2 Jun 2006 23:28:21 -0700
> From: "Carlos Daniel Ruvalcaba Valenzuela"
> Subject: Re: [Tutor] Trouble with os.path.isfile
> To: tutor at python.org
> Message-ID:
> <4fae7dfa0606022328k57c6a5cewee68fa1a33537e6b at mail.gmail.com>
> Content-Type: text/plain; charset=WINDOWS-1252; format=flowed
>
> From: Carlos Daniel Ruvalcaba Valenzuela
> Date: Jun 2, 2006 11:10 PM
> Subject: Re: [Tutor] Trouble with os.path.isfile
> To: "Carroll, Barry"
>
>
> Here is the problem IMO:
>
> I did some modifications to your code (very minimal on ifs) and it
worked:
>
> import os
>
> def lstdirsnfiles(tdir):
> flst = os.listdir(tdir)
> flst.sort()
>
> fnames = []
> dnames = ['.', '..']
>
> for name in flst:
> absfn = os.path.join(tdir, name)
>
> if os.path.isdir(absfn):
> dnames.append(name)
>
> if os.path.isfile(absfn):
> fnames.append(name)
> return (dnames, fnames)
>
> (dirs, files) = lstdirsnfiles('/home/clsdaniel')
>
> It returns correctly all directories and files.
>
> Regards
> Carlos Daniel Ruvalcaba Valenzuela
<>
From Barry.Carroll at psc.com Mon Jun 5 22:11:14 2006
From: Barry.Carroll at psc.com (Carroll, Barry)
Date: Mon, 5 Jun 2006 13:11:14 -0700
Subject: [Tutor] [Off topic] Is Zero Positive (was: Not Really Questions)
Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C36B1@eugsrv400.psc.pscnet.com>
Greetings:
> -----Original Message-----
> Date: Sun, 04 Jun 2006 18:43:25 -0700
> From: Yi Qiang
> Subject: Re: [Tutor] Not Really Questions
> To: tutor at python.org
> Message-ID: <44838C3D.9010907 at yiqiang.net>
> Content-Type: text/plain; charset=ISO-8859-1
>
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> Alan Gauld wrote, On 06/04/2006 04:01 PM:
> > Hi John,
> >
> > I'll pitch in although I've read most of the other answers
> > too so I'll be adding to them mostly.
> >
> >> The first one is lists... I can't for the life of me understand why
> >> a list
> >> starts at zero. In everything else in life other than programming
> >
> > Not quite. In math zero is usually the starting point, its generally
> > viewed as a positive number(although it is obviously neither
positive
> > or negative) and proofs and definitions usually start by
consideriung
> > zero - or at least defining whether zero is in or out of scope.
> That is just not true. A number is positive if and only if it is
> strictly greater than 0 by definition. Zero is not considered
positive
> in mathematics. In fact, the set of positive integers, Z+, is the set
> {1,2,3,....}.
> - --
> Yi Qiang (yi at yiqiang.net)
> Web: http://www.yiqiang.net
> Tel: (206) 661-8469
> PGP: 0xB515564B
[Somewhat off topic]
Strictly speaking, Yi Qiang is correct, of course. The set Z+ (which BTW
is identical with the set of natural numbers, N), does not include 0. 0
is neither positive nor negative. However, the set of non-negative
numbers does include 0, as does the set of non-positive numbers. The
former set, {0, 1, 2, ...}, is the one associated with lists, arrays,
etc, as it is possible to have 0 or more elements in a list, while it is
not possible to have less than 0 elements.
[Back on topic]
Like John, I find the half-open range concept to be 'unnatural'. When
waiting for checkout at the market, I don't think of myself as being
'zeroth' in line; I'm either 'first' or 'next' in line.
For me, it's a matter of context. When programming, it helps remind
myself that I'm not in the 'natural' universe where 'natural numbers'
are the rule. I'm in the computer's mathematical universe, where
'zeroth' in line is perfectly natural. =8^)
HTH
Barry
barry.carroll at psc.com
541-302-1107
________________________
We who cut mere stones must always be envisioning cathedrals.
-Quarry worker's creed
From yi at yiqiang.net Mon Jun 5 22:22:46 2006
From: yi at yiqiang.net (Yi Qiang)
Date: Mon, 05 Jun 2006 13:22:46 -0700
Subject: [Tutor] problem with unpickling an object
In-Reply-To: <44843EE0.2080007@tds.net>
References: <4483C934.40003@yiqiang.net>
<44840388.2090803@tds.net> <44843C34.2050502@yiqiang.net>
<44843EE0.2080007@tds.net>
Message-ID: <44849296.3060307@yiqiang.net>
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Kent Johnson wrote, On 06/05/2006 07:25 AM:
> No, the find_global() hook is for cPickle. See the next-to-last
> paragraph on this page:
> http://docs.python.org/lib/pickle-sub.html
Sorry, I don't follow. How does one get access to the find_global
attribute for cPickle? I created an cPickle.Unpickler object, and the
only attributes that I have access to are .load and .noload. What am I
missing here?
- --
Yi Qiang (yi at yiqiang.net)
Web: http://www.yiqiang.net
Tel: (206) 661-8469
PGP: 0xB515564B
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2.2 (GNU/Linux)
iD8DBQFEhJKWtXlIMrUVVksRAhCYAJ9NFNc601e0QdqUAWOFi1yUrKSvNQCdE/eE
NJGCtVG6kYx89bsuLnCmIeo=
=CRYn
-----END PGP SIGNATURE-----
From rondosxx at yahoo.com Mon Jun 5 22:48:45 2006
From: rondosxx at yahoo.com (ron)
Date: Mon, 5 Jun 2006 13:48:45 -0700 (PDT)
Subject: [Tutor] [Off topic] Is Zero Positive (was: Not Really Questions)
Message-ID: <20060605204845.43600.qmail@web52506.mail.yahoo.com>
It seems that the confusion is exacerbated by the fact
that we're using the theoretical number set to
reference the common one. I suppose this is a
carry-over from binary, since in binary if you don't
have a zero, you also won't have a bunch of other
numbers like 2, 4 and so forth.
__________________________________________________
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
http://mail.yahoo.com
From dustin at ywlcs.org Mon Jun 5 23:14:51 2006
From: dustin at ywlcs.org (Dustin Mitchell)
Date: Mon, 5 Jun 2006 16:14:51 -0500
Subject: [Tutor] [Off topic] Is Zero Positive (was: Not Really Questions)
In-Reply-To: <20060605204845.43600.qmail@web52506.mail.yahoo.com>
References: <20060605204845.43600.qmail@web52506.mail.yahoo.com>
Message-ID: <9738732e349662598606b194c3d663c7@ywlcs.org>
Wait, all of this "not really a number" and "carry-over from binary"
stuff deals with the *numeral* zero, which is neither here nor there.
We could use a picture of a bunny-rabbit instead of the numeral zero,
making this year 26.
The discussion here is over the *value* zero -- the identity element
under addition, and the number A such that A * X = A for all X. It's
the first of those properties that makes it important in computer
programming, and in more general terms considering the null (i.e.,
zero) case is always important in programming.
Dustin
On Jun 5, 2006, at 3:48 PM, ron wrote:
> It seems that the confusion is exacerbated by the fact
> that we're using the theoretical number set to
> reference the common one. I suppose this is a
> carry-over from binary, since in binary if you don't
> have a zero, you also won't have a bunch of other
> numbers like 2, 4 and so forth.
From yi at yiqiang.net Mon Jun 5 22:33:18 2006
From: yi at yiqiang.net (Yi Qiang)
Date: Mon, 05 Jun 2006 13:33:18 -0700
Subject: [Tutor] problem with unpickling an object
In-Reply-To: <44849296.3060307@yiqiang.net>
References: <4483C934.40003@yiqiang.net> <44840388.2090803@tds.net> <44843C34.2050502@yiqiang.net> <44843EE0.2080007@tds.net>
<44849296.3060307@yiqiang.net>
Message-ID: <4484950E.30809@yiqiang.net>
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Yi Qiang wrote, On 06/05/2006 01:22 PM:
> Kent Johnson wrote, On 06/05/2006 07:25 AM:
>>> No, the find_global() hook is for cPickle. See the next-to-last
>>> paragraph on this page:
>>> http://docs.python.org/lib/pickle-sub.html
> Sorry, I don't follow. How does one get access to the find_global
> attribute for cPickle? I created an cPickle.Unpickler object, and the
> only attributes that I have access to are .load and .noload. What am I
> missing here?
Ok, it looks I have to create that attribute. Now, the next confusing
part is that the documentation says: 'If it [find_global] is None then
any attempts to unpickle instances will raise an UnpicklingError.' What
exactly is considered an instance in this context? I tried unpickling a
dictionary, and it unpickled just fine. Please, someone explain :)
- --
Yi Qiang (yi at yiqiang.net)
Web: http://www.yiqiang.net
Tel: (206) 661-8469
PGP: 0xB515564B
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.2.2 (GNU/Linux)
iD8DBQFEhJUOtXlIMrUVVksRAm8lAJwI1IKZlwiXDRVC+1c73c+ieOmYewCghceY
F8Pqth3M/1ufF3hdkPufHv0=
=Uavt
-----END PGP SIGNATURE-----
From pjlists at gmail.com Tue Jun 6 00:47:32 2006
From: pjlists at gmail.com (Peter Jessop)
Date: Tue, 6 Jun 2006 00:47:32 +0200
Subject: [Tutor] Reference a variable from a string whose value is the name
of the variable
Message-ID: <7a8d5a0c0606051547x51bb9216j20c04defefbdf323@mail.gmail.com>
The best way to explain my problem is with an example
f0_n = "field0"
f0_v ="value0"
f1_n="field1"
f1_v="value1"
...
f100_n = "field100"
f100_v = "value100"
I now want to define a list of 2ples of the form
[(f0_n,f0_v),(f1_n,f1_v),...,(f100_n,f100_v)]
I wish to define the list using a for loop, i.e.
data = [ ]
for i in xrange(1,101):
data = data.append((f %i _n, f %i_v))
I have put the % sign above. Obviously it is not like that but how
does one do it?
The aim is to reference the s variable whose name is the string that I
create concatenating "f" + str(i)+"_n" and "f"+str(i)+"_v"
Thanks
Peter Jessop
From andre.roberge at gmail.com Tue Jun 6 01:09:56 2006
From: andre.roberge at gmail.com (Andre Roberge)
Date: Mon, 5 Jun 2006 20:09:56 -0300
Subject: [Tutor] Reference a variable from a string whose value is the
name of the variable
In-Reply-To: <7a8d5a0c0606051547x51bb9216j20c04defefbdf323@mail.gmail.com>
References: <7a8d5a0c0606051547x51bb9216j20c04defefbdf323@mail.gmail.com>
Message-ID: <7528bcdd0606051609x5d2b8525l45e7be367c93e952@mail.gmail.com>
I'm not sure if it's exactly what you need, but here's something that may
come close.
On 6/5/06, Peter Jessop wrote:
>
> The best way to explain my problem is with an example
>
> f0_n = "field0"
> f0_v ="value0"
> f1_n="field1"
> f1_v="value1"
> ...
>
> f100_n = "field100"
> f100_v = "value100"
Ok, I'm going to recreate this fake example, rather than typing it all out
:-)
for i in range(101):
print 'f%d_n = "field%d"'%(i, i)
print 'f%d_v = "value%d"'%(i, i)
I then cut-and-paste the result in the editor window and start again.
data1 = ["(f%d_n, f%d_v)"%(i, i) for i in range(101)]
print data1
# This shows: ['(f0_n, f0_v)', '(f1_n, f1_v)', '(f2_n, f2_v)' ... '(f100_n,
f100_v)']
data2 = ','.join(data1)
data2 = '[' + data2 + ']'
print eval(data2)
The result is: [('field0', 'value0'), ('field1', 'value1'), ...,
('field100', 'value100')]
i.e. it is a list of 2ples that contains the values of the variable, rather
than the variables themselves. For most applications, this should be the
same thing, right?
Andr?
I now want to define a list of 2ples of the form
>
> [(f0_n,f0_v),(f1_n,f1_v),...,(f100_n,f100_v)]
>
> I wish to define the list using a for loop, i.e.
>
> data = [ ]
> for i in xrange(1,101):
> data = data.append((f %i _n, f %i_v))
>
> I have put the % sign above. Obviously it is not like that but how
> does one do it?
> The aim is to reference the s variable whose name is the string that I
> create concatenating "f" + str(i)+"_n" and "f"+str(i)+"_v"
>
> Thanks
>
> Peter Jessop
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060605/15de327f/attachment.htm
From pjlists at gmail.com Tue Jun 6 01:28:01 2006
From: pjlists at gmail.com (Peter Jessop)
Date: Tue, 6 Jun 2006 01:28:01 +0200
Subject: [Tutor] Reference a variable from a string whose value is the
name of the variable
In-Reply-To: <7a8d5a0c0606051547x51bb9216j20c04defefbdf323@mail.gmail.com>
References: <7a8d5a0c0606051547x51bb9216j20c04defefbdf323@mail.gmail.com>
Message-ID: <7a8d5a0c0606051628n546a87ebm91b3cbae3cc25dda@mail.gmail.com>
Thanks Andre
I realise now I did not make it too clear.
Basically the variable names are predictable but the values aren't.
Maybe I should have expressed it like this
f0_n = "arbitrayValue"
f0_v ="another valule"
f1_n="something else"
f1_v="etc.."
...
f100_n = "another value"
f100_v = "nexvalue"
I then wish to pass the list of 2ples as an argument to a function and
thus I need the variable themselves and not the string values.
From andre.roberge at gmail.com Tue Jun 6 01:47:19 2006
From: andre.roberge at gmail.com (Andre Roberge)
Date: Mon, 5 Jun 2006 20:47:19 -0300
Subject: [Tutor] Reference a variable from a string whose value is the
name of the variable
In-Reply-To: <7a8d5a0c0606051628n546a87ebm91b3cbae3cc25dda@mail.gmail.com>
References: <7a8d5a0c0606051547x51bb9216j20c04defefbdf323@mail.gmail.com>
<7a8d5a0c0606051628n546a87ebm91b3cbae3cc25dda@mail.gmail.com>
Message-ID: <7528bcdd0606051647o30024fd3o30657a59cb8ce32e@mail.gmail.com>
On 6/5/06, Peter Jessop wrote:
>
> Thanks Andre
>
> I realise now I did not make it too clear.
> Basically the variable names are predictable but the values aren't.
I assumed that. I just recreated the list as you gave it because it was
easy :-)
Maybe I should have expressed it like this
>
> f0_n = "arbitrayValue"
> f0_v ="another valule"
> f1_n="something else"
> f1_v="etc.."
> ...
>
> f100_n = "another value"
> f100_v = "nexvalue"
>
> I then wish to pass the list of 2ples as an argument to a function and
> thus I need the variable themselves and not the string values.
Ok, the approach I gave you would produce instead:
data = [ ("arbitraryValue", "another valule"), ("something else", .... ]
Why couldn't you pass this to your function?
Ok, here's another experiment...
1. I will first generate a whole bunch of arbitrary numerical values:
import random
for i in range(101):
print 'f%d_n = %d'%(i, random.randint(0, 100))
print 'f%d_v = %d'%(i, random.randint(0, 100))
===
f0_n = 40
f0_v = 28
f1_n = 49
f1_v = 5
...
====================
2. Next, I will use the approach I gave you before, but with these values,
and I will do it with a one-liner:
data = '[' + ','.join(["(f%d_n, f%d_v)"%(i, i) for i in range(101)]) + ']'
big_list = eval(data)
3. Next, I will define a function that works on these values
def find_special(data):
for item in data:
if item[0] < 10:
print item[1],
find_special(big_list)
=========
The result in my case turns out to be:
49 50 57 96 98 23 69 16 4
====================
Of course this result on its own is meaningless :-)
Nonetheless, does this help? Or do you really, absolutely need to pass the
named variables, not their values?
Andr?
_______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060605/9df13d9e/attachment.html
From pjlists at gmail.com Tue Jun 6 02:00:22 2006
From: pjlists at gmail.com (Peter Jessop)
Date: Tue, 6 Jun 2006 02:00:22 +0200
Subject: [Tutor] Reference a variable from a string whose value is the
name of the variable
In-Reply-To: <7a8d5a0c0606051547x51bb9216j20c04defefbdf323@mail.gmail.com>
References: <7a8d5a0c0606051547x51bb9216j20c04defefbdf323@mail.gmail.com>
Message-ID: <7a8d5a0c0606051700r48df0a27j7b5bedfe840ea484@mail.gmail.com>
Andr?
Thanks a lot for clearing this up for me.
Regards
Peter Jessop
From kent37 at tds.net Tue Jun 6 02:03:32 2006
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 05 Jun 2006 20:03:32 -0400
Subject: [Tutor] Reference a variable from a string whose value is the
name of the variable
In-Reply-To: <7a8d5a0c0606051628n546a87ebm91b3cbae3cc25dda@mail.gmail.com>
References: <7a8d5a0c0606051547x51bb9216j20c04defefbdf323@mail.gmail.com>
<7a8d5a0c0606051628n546a87ebm91b3cbae3cc25dda@mail.gmail.com>
Message-ID: <4484C654.8040504@tds.net>
Peter Jessop wrote:
> Thanks Andre
>
> I realise now I did not make it too clear.
> Basically the variable names are predictable but the values aren't.
>
> Maybe I should have expressed it like this
>
> f0_n = "arbitrayValue"
> f0_v ="another valule"
> f1_n="something else"
> f1_v="etc.."
> ...
>
> f100_n = "another value"
> f100_v = "nexvalue"
Generally the best way to do something like this is not to use named
variables at all, rather to use some kind of data structure to store the
values. In this case, you seem to have 101 pairs of values. Perhaps your
primary data structure should be the list of (fx_n, fx_v) values, rather
than trying to access the named variables.
Alternately, it looks like your data pairs are actually (name, value)
pairs. If so, and if the order of pairs is not important, you could
store them in a dictionary using the name as the key and the value as,
well, the value ;)
> I then wish to pass the list of 2ples as an argument to a function and
> thus I need the variable themselves and not the string values.
Hmm, I don't know what you mean by "the variable themselves". Do you
mean you want the called function to change the value of the variable?
That is hard to do in Python. But it's easy for a function to modify a
list or dictionary passed to it.
A little more context might be helpful here. Where do all these values
come from? What are you trying to do with them?
Kent
From keosophon at khmeros.info Tue Jun 6 04:20:29 2006
From: keosophon at khmeros.info (Keo Sophon)
Date: Tue, 6 Jun 2006 09:20:29 +0700
Subject: [Tutor] FileDialogBox in Tkinter
Message-ID: <200606060920.29837.keosophon@khmeros.info>
Hi all,
What to do in order to get FileDialogBox in Tkinter for using? Where to find a
complete reference of Tkinter?
Thanks,
Phon
From 3dbernard at gmail.com Tue Jun 6 05:23:21 2006
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Mon, 5 Jun 2006 23:23:21 -0400
Subject: [Tutor] FileDialogBox in Tkinter
In-Reply-To: <200606060920.29837.keosophon@khmeros.info>
References: <200606060920.29837.keosophon@khmeros.info>
Message-ID: <61d0e2b40606052023x61de799awcabfd9a9a92f8161@mail.gmail.com>
Hi Phon,
This is the most complete Tkinter reference I could find (although
it's not exactly "complete"):
http://www.pythonware.com/library/tkinter/introduction/
As to how to make the file dialog box to work, I found this
introduction tutorial extremely helpful to get started with the
Tkinter widgets, methods and options:
http://www.aqzj33.dsl.pipex.com/how_i_learned_tkinter/contents.htm
The file dialog classes should not pose a problem, they work exactly
like other Tkinter widgets.
Cheers
Bernard
On 6/5/06, Keo Sophon wrote:
> Hi all,
>
> What to do in order to get FileDialogBox in Tkinter for using? Where to find a
> complete reference of Tkinter?
>
> Thanks,
> Phon
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
From soumitr_sidd at yahoo.co.in Tue Jun 6 06:44:55 2006
From: soumitr_sidd at yahoo.co.in (soumitr siddharth)
Date: Tue, 6 Jun 2006 05:44:55 +0100 (BST)
Subject: [Tutor] doubt plz help
Message-ID: <20060606044455.28423.qmail@web8515.mail.in.yahoo.com>
how do i clear the scseer ??
suppose i have two pages to display one
after the other ,how should i do it ?
---------------------------------
Yahoo! India Answers: Share what you know. Learn something new Click here
Send free SMS to your Friends on Mobile from your Yahoo! Messenger Download now
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060606/b3125819/attachment.htm
From john at fouhy.net Tue Jun 6 07:24:39 2006
From: john at fouhy.net (John Fouhy)
Date: Tue, 6 Jun 2006 17:24:39 +1200
Subject: [Tutor] FileDialogBox in Tkinter
In-Reply-To: <200606060920.29837.keosophon@khmeros.info>
References: <200606060920.29837.keosophon@khmeros.info>
Message-ID: <5e58f2e40606052224n446ddc8ya1a40558bceeaca8@mail.gmail.com>
On 06/06/06, Keo Sophon wrote:
> What to do in order to get FileDialogBox in Tkinter for using? Where to find a
> complete reference of Tkinter?
Fredrik Lundh's guide (which Bernard linked) is a good Tkinter
reference. For the FileDialogBox, you will need another import
statement --- 'import Tkinter' or 'from Tkinter import *' won't bring
it in.
New Mexico Tech has a good reference too:
http://infohost.nmt.edu/tcc/help/lang/python/tkinter.html It's a bit
old, but a lot of it is still accurate, and it goes into more detail
than the pythonware one.
--
John.
From hokkakada at khmeros.info Tue Jun 6 08:39:21 2006
From: hokkakada at khmeros.info (kakada)
Date: Tue, 06 Jun 2006 13:39:21 +0700
Subject: [Tutor] combo box
Message-ID: <44852319.1080804@khmeros.info>
Dear Friends,
I am now working on GUI python (Tkinter).
I want to use combobox as my widget, but I cannot find it in any document.
Does anybody have experience with that?
Thanks,
da
From alan.gauld at freenet.co.uk Tue Jun 6 09:49:05 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue, 6 Jun 2006 08:49:05 +0100
Subject: [Tutor] FileDialogBox in Tkinter
References: <200606060920.29837.keosophon@khmeros.info>
Message-ID: <002701c6893d$af9c3c20$0a01a8c0@XPpro>
> What to do in order to get FileDialogBox in Tkinter for using?
>>> import tkFileDialog
>>> res = tkFileDialog.asksaveasfilename(defaultextension=".txt")
Does that help?
> Where to find a complete reference of Tkinter?
I assume you have checked the Tkinter section of the Python
web site? It points at several resources.
Fred Lundh's site is the best online resource I think.
The most complete resource is Grayson's Book on Tkinter
published by Manning.
Alan G
From pjlists at gmail.com Tue Jun 6 10:31:52 2006
From: pjlists at gmail.com (Peter Jessop)
Date: Tue, 6 Jun 2006 10:31:52 +0200
Subject: [Tutor] Reference a variable from a string whose value is the
name of the variable
In-Reply-To: <7a8d5a0c0606051700r48df0a27j7b5bedfe840ea484@mail.gmail.com>
References: <7a8d5a0c0606051547x51bb9216j20c04defefbdf323@mail.gmail.com>
<7a8d5a0c0606051700r48df0a27j7b5bedfe840ea484@mail.gmail.com>
Message-ID: <7a8d5a0c0606060131o7eabf223gd63c459e95133c10@mail.gmail.com>
Kent
Thanks for your reply.
The structure is for sending form variables and values to a web server
with POST.
I am using urllib.urlencode which accepts a list or dictionary as argument.
The idea is to look for airline tickets.
The airline I buy from only lets me search by data but I want to
automate the process by POSTing the form for a range of dates so that
effectively I can search by price not by date.
I will then parse the returned HTML using HTMLParser or BeautifulSoup.
The form has a large number of variables and I just want to find a
tidy way to organise the information.
Peter
From keosophon at khmeros.info Tue Jun 6 10:36:55 2006
From: keosophon at khmeros.info (Keo Sophon)
Date: Tue, 6 Jun 2006 15:36:55 +0700
Subject: [Tutor] FileDialogBox in Tkinter
In-Reply-To: <002701c6893d$af9c3c20$0a01a8c0@XPpro>
References: <200606060920.29837.keosophon@khmeros.info>
<002701c6893d$af9c3c20$0a01a8c0@XPpro>
Message-ID: <200606061536.56067.keosophon@khmeros.info>
On Tuesday 06 June 2006 14:49, you wrote:
> > What to do in order to get FileDialogBox in Tkinter for using?
> >
> >>> import tkFileDialog
> >>> res = tkFileDialog.asksaveasfilename(defaultextension=".txt")
>
> Does that help?
>
> > Where to find a complete reference of Tkinter?
>
> I assume you have checked the Tkinter section of the Python
> web site? It points at several resources.
>
> Fred Lundh's site is the best online resource I think.
> The most complete resource is Grayson's Book on Tkinter
> published by Manning.
>
> Alan G
Yes, it helps and does what I want. I had read some also your document, but
they don't talk deeply and widely about Tkinter. However, they are good
resource to start.
Thanks.
Phon
From alan.gauld at freenet.co.uk Tue Jun 6 10:56:45 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Tue, 6 Jun 2006 09:56:45 +0100
Subject: [Tutor] FileDialogBox in Tkinter
References: <200606060920.29837.keosophon@khmeros.info>
<002701c6893d$af9c3c20$0a01a8c0@XPpro>
<200606061536.56067.keosophon@khmeros.info>
Message-ID: <000301c68947$237bff50$0a01a8c0@XPpro>
> Yes, it helps and does what I want. I had read some also your
> document, but
> they don't talk deeply and widely about Tkinter. However, they are
> good
> resource to start.
Yes, the GUI topic in my tutor only introduces some of the
language and the most basic principles. I then leave you
to read Fred's tutorial for more depth.
But its one area where I keep toying with adding a new topic
on "Advanced GUI programming" but I'm not really qualified to
write that since I do very little GUI work! (For example I just
realized the other day that I've never actually created a menu
bar in any of my Tkinter programs to date! ;-)
Alan G
From python at kapitalisten.no Tue Jun 6 12:26:07 2006
From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=)
Date: Tue, 6 Jun 2006 12:26:07 +0200 (CEST)
Subject: [Tutor] elif
Message-ID: <50458.193.71.38.142.1149589567.squirrel@mail.sporck.net>
Hello.
I need to make a program that does certain things every 5 minutes
mon-friday. I have started writing it like this:
if strftime('%w') == 1:
if strftime('%M') % 5 == 0:
n.start()
elif strftime('%w') == 2:
if strftime('%M') % 5 == 0:
n.start()
........
This seems kind of a redundant way of writing the code.
I haven't gotten any statement like this to work:
if strftime('%w') == 1 or 2 or 3:
or
for strftime('%w') in range(1,5):
What would be a more efficient way of writing it without writing it
several times?
Thanks in advance,
?yvind
--
This email has been scanned for viruses & spam by Decna as - www.decna.no
Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no
From python at kapitalisten.no Tue Jun 6 12:30:39 2006
From: python at kapitalisten.no (=?iso-8859-1?Q?=D8yvind?=)
Date: Tue, 6 Jun 2006 12:30:39 +0200 (CEST)
Subject: [Tutor] doubt plz help
Message-ID: <10833.193.71.38.142.1149589839.squirrel@mail.sporck.net>
Try to rephrase that question. I don't think I was the only one not
understanding what you are asking?
>how do i clear the scseer ??
>suppose i have two pages to display one
>after the other ,how should i do it ?
--
This email has been scanned for viruses & spam by Decna as - www.decna.no
Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no
From m_webber_sydney at yahoo.com.au Tue Jun 6 13:26:22 2006
From: m_webber_sydney at yahoo.com.au (Matthew Webber)
Date: Tue, 6 Jun 2006 12:26:22 +0100
Subject: [Tutor] doubt plz help
In-Reply-To: <10833.193.71.38.142.1149589839.squirrel@mail.sporck.net>
Message-ID: <002f01c6895c$09eecf80$0200a8c0@kookaburra>
>> Try to rephrase that question. I don't think I was the only one not
understanding what you are asking?
Try to rephrase that response. I'm sure that you understand the double
negative in the second sentence, but many who speak English as a second
language (including, possibly, the original poster) will not!
From kent37 at tds.net Tue Jun 6 14:07:03 2006
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 06 Jun 2006 08:07:03 -0400
Subject: [Tutor] Reference a variable from a string whose value is the
name of the variable
In-Reply-To: <7a8d5a0c0606060131o7eabf223gd63c459e95133c10@mail.gmail.com>
References: <7a8d5a0c0606051547x51bb9216j20c04defefbdf323@mail.gmail.com> <7a8d5a0c0606051700r48df0a27j7b5bedfe840ea484@mail.gmail.com>
<7a8d5a0c0606060131o7eabf223gd63c459e95133c10@mail.gmail.com>
Message-ID: <44856FE7.9080808@tds.net>
Peter Jessop wrote:
> Kent
>
> Thanks for your reply.
> The structure is for sending form variables and values to a web server
> with POST.
> I am using urllib.urlencode which accepts a list or dictionary as argument.
>
> The idea is to look for airline tickets.
> The airline I buy from only lets me search by data but I want to
> automate the process by POSTing the form for a range of dates so that
> effectively I can search by price not by date.
> I will then parse the returned HTML using HTMLParser or BeautifulSoup.
>
> The form has a large number of variables and I just want to find a
> tidy way to organise the information.
It sounds like you should use a dictionary directly as your primary data
structure. For data that is fixed just use a literal dictionary, for example
args = dict(origin='SJO', destination='MHO')
For dates, you presumably have some kind of loop to generate dates in a
range, then insert them into the dict:
for date in :
args['date'] = date
# fetch and parse the URL with args as the POST data
Kent
From kent37 at tds.net Tue Jun 6 14:09:33 2006
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 06 Jun 2006 08:09:33 -0400
Subject: [Tutor] doubt plz help
In-Reply-To: <20060606044455.28423.qmail@web8515.mail.in.yahoo.com>
References: <20060606044455.28423.qmail@web8515.mail.in.yahoo.com>
Message-ID: <4485707D.2010403@tds.net>
soumitr siddharth wrote:
> how do i clear the scseer ??
> suppose i have two pages to display one
> after the other ,how should i do it ?
It depends on the OS and the type of display. For a console application
on Windows, use
os.system('cls')
On Linux I think the corresponding command is
os.system('clear')
If you are using a GUI toolkit then tell us which one and a bit more
details about what you want to do.
Kent
From kent37 at tds.net Tue Jun 6 14:17:53 2006
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 06 Jun 2006 08:17:53 -0400
Subject: [Tutor] elif
In-Reply-To: <50458.193.71.38.142.1149589567.squirrel@mail.sporck.net>
References: <50458.193.71.38.142.1149589567.squirrel@mail.sporck.net>
Message-ID: <44857271.1060202@tds.net>
?yvind wrote:
> Hello.
>
> I need to make a program that does certain things every 5 minutes
> mon-friday. I have started writing it like this:
>
> if strftime('%w') == 1:
> if strftime('%M') % 5 == 0:
> n.start()
>
> elif strftime('%w') == 2:
> if strftime('%M') % 5 == 0:
> n.start()
>
> ........
>
> This seems kind of a redundant way of writing the code.
>
> I haven't gotten any statement like this to work:
> if strftime('%w') == 1 or 2 or 3:
> or
> for strftime('%w') in range(1,5):
>
> What would be a more efficient way of writing it without writing it
> several times?
First, I don't think the code you show is correct, the result of
strftime() is a string so you should compare to a string:
if strftime('%w') == '1':
You have to repeat the entire condition, so you could write:
if strftime('%w') == '1' or strftime('%w') == '2':
This could be cleaned up with a temporary variable:
dow = strftime('%w')
if dow == '1' or dow == '2':
You could also write this as
if dow in ['1', '2']:
Rather than (ab)using strftime() in this fashion, you might want to look
at datetime.datetime. You could write
now = datetime.datetime.now()
if now.weekday() in [1, 2, 3] and now.minute % 5 == 0:
Kent
From kermit at polaris.net Tue Jun 6 15:07:40 2006
From: kermit at polaris.net (Kermit Rose)
Date: Tue, 6 Jun 2006 09:07:40 -0400 (Eastern Daylight Time)
Subject: [Tutor] Reading characters from file in binary mode
Message-ID: <44857E1C.000003.00468@YOUR-4105E587B6>
Hello.
I wish to translate a SAS data file to text, and do not have the
professional
version of SAS to do so.
I have the student version of SAS, and have translated the shortest of 4 SAS
data sets given.
For the other 3, I wish to construct a python program to read the characters
in, one
at a time, translate them to hexadecimal, then figure out how the data
matches
the data dictionary that I have.
I experimented with writing code in C++ to do this.
My first experiment, in C++ is
#include
#include
#define TRUE 1 /* Define some handy constants */
#define FALSE 0 /* Define some handy constants */
ifstream f("CMT_MCAID",ios_base::binary);
ofstream G("mcaid.txt",ios_base::app);
char ch
int k
int kh,kl
int limit
limit = 1000
for (int I=1;I<= limit;I++)
{
f >> ch;
k = ch;
kl = k%16;
kh = (k -kl)/16;
G << kh," ",kl," ";
}
How can I begin to experiment using python? What would be python code
equivalent
to the above C++ code?
Kermit < kermit at Polaris.net >
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060606/92862444/attachment.html
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: image/jpeg
Size: 1431 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20060606/92862444/attachment.jpe
From ezra.taylor at gmail.com Tue Jun 6 18:05:37 2006
From: ezra.taylor at gmail.com (Ezra Taylor)
Date: Tue, 6 Jun 2006 12:05:37 -0400
Subject: [Tutor] doubt plz help
In-Reply-To: <20060606044455.28423.qmail@web8515.mail.in.yahoo.com>
References: <20060606044455.28423.qmail@web8515.mail.in.yahoo.com>
Message-ID:
Siddhart:
Kent is correct, I tried the os.system('clear')
on my Debian linux box and the screen clears. Don't forget to use
import os. Also, I 'm new to Python. Hello community.
Ezra Taylor
On 6/6/06, soumitr siddharth wrote:
>
> how do i clear the scseer ??
> suppose i have two pages to display one
> after the other ,how should i do it ?
>
>
> ________________________________
> Yahoo! India Answers: Share what you know. Learn something new Click here
> Send free SMS to your Friends on Mobile from your Yahoo! Messenger Download
> now
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
--
Ezra Taylor
From kent37 at tds.net Tue Jun 6 18:21:51 2006
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 06 Jun 2006 12:21:51 -0400
Subject: [Tutor] Reading characters from file in binary mode
In-Reply-To: <44857E1C.000003.00468@YOUR-4105E587B6>
References: <44857E1C.000003.00468@YOUR-4105E587B6>
Message-ID: <4485AB9F.5050106@tds.net>
Kermit Rose wrote:
> Hello.
>
> I wish to translate a SAS data file to text, and do not have the
> professional
> version of SAS to do so.
>
> I have the student version of SAS, and have translated the shortest of 4 SAS
> data sets given.
>
> For the other 3, I wish to construct a python program to read the
> characters in, one
> at a time, translate them to hexadecimal, then figure out how the data
> matches
> the data dictionary that I have.
>
> I experimented with writing code in C++ to do this.
>
> My first experiment, in C++ is
>
> #include
> #include
> #define TRUE 1 /* Define some handy constants */
> #define FALSE 0 /* Define some handy constants */
> ifstream f("CMT_MCAID",ios_base::binary);
> ofstream G("mcaid.txt",ios_base::app);
> char ch
> int k
> int kh,kl
> int limit
> limit = 1000
>
> for (int I=1;I<= limit;I++)
>
> {
> f >> ch;
> k = ch;
> kl = k%16;
> kh = (k -kl)/16;
> G << kh," ",kl," ";
> }
>
>
> How can I begin to experiment using python? What would be python code
> equivalent
> to the above C++ code?
Hmm, my C++ is remarkably rusty but I think you want something like this:
inp = open("CMT_MCAID", "rb")
out = open("mcaid.txt", "w")
for i in range(1000):
ch = inp.read(1)
if not ch: break # EOF
k = ord(ch) # convert to integer
kl = k % 16
kh = k / 16
out.write('%x %x ' % (kh, kl))
out.close()
If your input file will fit in memory, there is no need to read a byte
at a time, you could change the for / read /test to this:
for ch in inp.read()[:1000]:
If you can live without the space between the two digits you could use
out.write('%02x' % k)
With these two changes the entire loop becomes
for ch in inp.read()[:1000]:
out.write('%02x' % ord(ch))
If your input files are in a well-understood format, you might be
interested in the struct module in the standard lib, which will unpack
fixed format binary data, or pyconstruct which I think is a bit more
flexible:
http://pyconstruct.wikispaces.com/
Kent
From jsmith at medplus.com Tue Jun 6 18:22:28 2006
From: jsmith at medplus.com (Smith, Jeff)
Date: Tue, 6 Jun 2006 12:22:28 -0400
Subject: [Tutor] Truly generic database API
Message-ID: <3B05FA2AD704244BB0CAB99D8026F55501076781@medexch2.medplus.com>
I'm looking for a truly generic database API in that the underlying DB
could be text, XML, SQL engine, etc.
For instance, initially, the underlying database will probably be text
files but we may at some point want to move to a real database server or
possibly an XML file without having to recode all of the upper level
access.
Is anyone aware of such a thing?
Thanks,
Jeff
From jfabiani at yolo.com Tue Jun 6 19:25:01 2006
From: jfabiani at yolo.com (johnf)
Date: Tue, 6 Jun 2006 10:25:01 -0700
Subject: [Tutor] Truly generic database API
In-Reply-To: <3B05FA2AD704244BB0CAB99D8026F55501076781@medexch2.medplus.com>
References: <3B05FA2AD704244BB0CAB99D8026F55501076781@medexch2.medplus.com>
Message-ID: <200606061025.02022.jfabiani@yolo.com>
On Tuesday 06 June 2006 09:22, Smith, Jeff wrote:
> I'm looking for a truly generic database API in that the underlying DB
> could be text, XML, SQL engine, etc.
>
> For instance, initially, the underlying database will probably be text
> files but we may at some point want to move to a real database server or
> possibly an XML file without having to recode all of the upper level
> access.
>
> Is anyone aware of such a thing?
>
> Thanks,
> Jeff
Jeff is looking for the holy grail. You might want to look at 'dabo' as a
frame work. They currently support Postgres, MySQL, SQLite, Firebird, XML
all with the same code base.
John
From kent37 at tds.net Tue Jun 6 19:32:01 2006
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 06 Jun 2006 13:32:01 -0400
Subject: [Tutor] Truly generic database API
In-Reply-To: <3B05FA2AD704244BB0CAB99D8026F55501076781@medexch2.medplus.com>
References: <3B05FA2AD704244BB0CAB99D8026F55501076781@medexch2.medplus.com>
Message-ID: <4485BC11.9080403@tds.net>
Smith, Jeff wrote:
> I'm looking for a truly generic database API in that the underlying DB
> could be text, XML, SQL engine, etc.
>
> For instance, initially, the underlying database will probably be text
> files but we may at some point want to move to a real database server or
> possibly an XML file without having to recode all of the upper level
> access.
I don't know of any database API that spans even text files and a
conventional database.
The broadest Python database API I know of is the standard Python DB-API
which give mostly portable access to a wide variety of databases. You
will still have to deal with differences in data types, differing
options in the API, and different SQL dialects but you can use a
database as light as SQLite or as high-powered as Oracle or SQL Server
or (insert your favorite high-end database here).
http://www.python.org/dev/peps/pep-0249/
http://www.python.org/doc/topics/database/modules/
Object/relational layers like SQLObject and SQLAlchemy give you a
higher-level API and more insulation from the variation between
databases at the cost of a more limited selection of supported databases.
http://www.sqlobject.org/
http://www.sqlalchemy.org/
I think to get the level of portability you are asking for you will have
to write your own domain-specific data access module. This is a good
idea anyway - you don't want to be spreading SQL code all over your
program, for example. Your first implementation might be built on text
files, maybe using the csv module. Later you can write new
implementations for other back ends. If you write unit tests for the
module it will ease the transition to a new back end greatly.
I do question why you need such broad portability. Are you sure you
can't start with something simple like SQLite with the option of MySQL,
PostgreSQL or a commercial product later?
Kent
From patrick.john.wheeler at gmail.com Tue Jun 6 20:08:20 2006
From: patrick.john.wheeler at gmail.com (Patrick Wheeler)
Date: Tue, 6 Jun 2006 13:08:20 -0500
Subject: [Tutor] Reference a variable from a string whose value is the
name of the variable
Message-ID: <78951a820606061108h3d31a6bcvaf0a63b6e5423cbe@mail.gmail.com>
>data = [ ]
>for i in xrange(1,101):
> data = data.append((f %i _n, f %i_v))
The function locals() will return a dictionary of variables in the current
scope. This can then be used to reference variables by name.
x=1
xname = 'x'
print locals()['x']
print locals()[xname]
This prints:
1
1
or for your example.
data = [ ]
for i in xrange(1,101):
data = data.append
((locals()['f'+str(i)+'_n'],locals()['f'+str(i)+'_v']{}))
Hope this helps.
pjw
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060606/d71a4352/attachment.html
From sean.fioritto at gmail.com Tue Jun 6 21:04:14 2006
From: sean.fioritto at gmail.com (Sean Fioritto)
Date: Tue, 6 Jun 2006 12:04:14 -0700
Subject: [Tutor] elif
In-Reply-To: <50458.193.71.38.142.1149589567.squirrel@mail.sporck.net>
References: <50458.193.71.38.142.1149589567.squirrel@mail.sporck.net>
Message-ID: <5f1d9b0c0606061204y634e4a69y83e19b56b4fe62e4@mail.gmail.com>
?yvind,
I know this isn't Python advice, but in general it seems as if setting
up a cron job would be easier. If you don't know how, I could gladly
help.
- Sean
On 6/6/06, ?yvind wrote:
> Hello.
>
> I need to make a program that does certain things every 5 minutes
> mon-friday. I have started writing it like this:
>
> if strftime('%w') == 1:
> if strftime('%M') % 5 == 0:
> n.start()
>
> elif strftime('%w') == 2:
> if strftime('%M') % 5 == 0:
> n.start()
>
> ........
>
> This seems kind of a redundant way of writing the code.
>
> I haven't gotten any statement like this to work:
> if strftime('%w') == 1 or 2 or 3:
> or
> for strftime('%w') in range(1,5):
>
> What would be a more efficient way of writing it without writing it
> several times?
>
> Thanks in advance,
> ?yvind
>
>
> --
> This email has been scanned for viruses & spam by Decna as - www.decna.no
> Denne e-posten er sjekket for virus & spam av Decna as - www.decna.no
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
From kermit at polaris.net Tue Jun 6 21:25:44 2006
From: kermit at polaris.net (Kermit Rose)
Date: Tue, 6 Jun 2006 15:25:44 -0400 (Eastern Daylight Time)
Subject: [Tutor] Tutor Digest, Vol 28, Issue 10
References:
Message-ID: <4485D6B7.000001.03568@YOUR-4105E587B6>
From: tutor-request at python.org
Date: 06/06/06 12:31:25
To: tutor at python.org
Subject: Tutor Digest, Vol 28, Issue 10
Message: 9
Date: Tue, 06 Jun 2006 12:21:51 -0400
From: Kent Johnson
Subject: Re: [Tutor] Reading characters from file in binary mode
To: Python Tutor
Hmm, my C++ is remarkably rusty but I think you want something like this:
inp = open("CMT_MCAID", "rb")
out = open("mcaid.txt", "w")
for i in range(1000):
ch = inp.read(1)
if not ch: break # EOF
k = ord(ch) # convert to integer
kl = k % 16
kh = k / 16
out.write('%x %x ' % (kh, kl))
out.close()
*******
Thank you very much. It looks exactly what I wished to know.
But now, I realize that I don't know how to invoke Python to compile and
execute the
program file.
I will be making rapid changes to the file, and recompiling over and over
again as
I change the program during my experimentation.
I guess that in the open command, the rb stands for read and something
else.
what is that something else?
Kermit < kermit at polaris.net >
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060606/798770c9/attachment.htm
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: image/jpeg
Size: 1431 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20060606/798770c9/attachment.jpe
From puzzld_me at yahoo.com Tue Jun 6 19:24:30 2006
From: puzzld_me at yahoo.com (Puzzled Me)
Date: Tue, 6 Jun 2006 10:24:30 -0700 (PDT)
Subject: [Tutor] python application on a web page
Message-ID: <20060606172431.13283.qmail@web55012.mail.re4.yahoo.com>
Hi,
I am so new to everything, I don't even know where to post my question... do bear...
I made this Python calculator that will take an equation as an input and will display the computed curves on a shiny Tkinter interface
Now, I'd like to make this application available on a public web page... and all I could come up with was this post
Hints?!
I'd also appreciate a link to a beginner forum
Thanks
Puzzled Me
__________________________________________________
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
http://mail.yahoo.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060606/d6ed556f/attachment.htm
From kent37 at tds.net Wed Jun 7 01:50:01 2006
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 06 Jun 2006 19:50:01 -0400
Subject: [Tutor] Tutor Digest, Vol 28, Issue 10
In-Reply-To: <4485D6B7.000001.03568@YOUR-4105E587B6>
References:
<4485D6B7.000001.03568@YOUR-4105E587B6>
Message-ID: <448614A9.706@tds.net>
Kermit Rose wrote:
> Thank you very much. It looks exactly what I wished to know.
>
> But now, I realize that I don't know how to invoke Python to compile and
> execute the
> program file.
There is no separate compile step, Python does that automatically. The
details of running a program vary depending on your OS and how you
create the file. Here are some directions:
http://www.byteofpython.info/read/source-file.html
http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html
>
> I will be making rapid changes to the file, and recompiling over and
> over again as
> I change the program during my experimentation.
Python is great for quick-turnaround incremental development.
>
> I guess that in the open command, the rb stands for read and something
> else.
> what is that something else?
Binary. When a file is read in text mode, any line ending (CR, LF or
CRLF) is converted to a newline (\n) character.
Kent
PS The standard on most public mailing lists is to send text email
rather than HTML. I for one would appreciate it if you would lose the
background graphics!
From kermit at polaris.net Wed Jun 7 02:38:01 2006
From: kermit at polaris.net (Kermit Rose)
Date: Tue, 6 Jun 2006 20:38:01 -0400 (Eastern Daylight Time)
Subject: [Tutor] How do I get Dos to recognize python command?
Message-ID: <44861FE9.00000E.03972@YOUR-4105E587B6>
I followed the model in
http://www.byteofpython.info/read/source-file.html
and saw following results.
C:\DavidKaremera\June2006\SAS>python med.py
'python' is not recognized as an internal or external command,
operable program or batch file.
What do I do to make DOS recognize python as a command?
The link http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html
that you suggested
shows information about the idle.
I've used idle for development until now, but it has the annoyance
that I must close it and reopen it in order for it to import the changed
copy
of the program.
Besides, I already have one default module saved, and it would seem
complicated to have more than one.
It would be simpler if I can get the dos prompt to work.
Kermit < kermit at Polaris.net >
From kermit at polaris.net Wed Jun 7 02:43:42 2006
From: kermit at polaris.net (Kermit Rose)
Date: Tue, 6 Jun 2006 20:43:42 -0400 (Eastern Daylight Time)
Subject: [Tutor] bounced email
Message-ID: <4486213C.000012.03972@YOUR-4105E587B6>
My last email to you bounced.
Why?
From: tutor-bounces at python.org
Date: 06/06/06 20:30:49
To: kermit at polaris.net
Subject: The results of your email commands
The results of your email command are provided below. Attached is your
original message.
- Unprocessed:
Why am I getting the following after my reply to you?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python
org/pipermail/tutor/attachments/20060606/798770c9/attachment.HTML
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: image/jpeg
Size: 1431 bytes
Desc: not available
Url : http://mail.python
org/pipermail/tutor/attachments/20060606/798770c9/attachment-0001.jpe
******
>>>>>>
Message: 8
Date: Tue, 06 Jun 2006 19:50:01 -0400
From: Kent Johnson
Subject: Re: [Tutor] Tutor Digest, Vol 28, Issue 10
- Ignored:
Cc: tutor at python.org
There is no separate compile step, Python does that automatically. The
details of running a program vary depending on your OS and how you
create the file. Here are some directions:
http://www.byteofpython.info/read/source-file.html
http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html
****
Thanks. I will study those links.
****
>>>>>>>
PS The standard on most public mailing lists is to send text email
rather than HTML. I for one would appreciate it if you would lose the
background graphics!
*****
I know.
It annoys me that my current email program sends HTML by
default. I don't like the different sized letters that it makes.
I did not know anything about background graphics.
I will attempt to make this one message plain text, and
keep on guard for making each message plain text.
If I can't find the option to make it automatically plain text,
I will need to develop the habit to change every message to plain text.
Kermit < kermit at Polaris.net >
- Done.
From kent37 at tds.net Wed Jun 7 02:59:11 2006
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 06 Jun 2006 20:59:11 -0400
Subject: [Tutor] How do I get Dos to recognize python command?
In-Reply-To: <44861FE9.00000E.03972@YOUR-4105E587B6>
References: <44861FE9.00000E.03972@YOUR-4105E587B6>
Message-ID: <448624DF.8020908@tds.net>
Kermit Rose wrote:
>
> I followed the model in
>
> http://www.byteofpython.info/read/source-file.html
>
> and saw following results.
>
>
> C:\DavidKaremera\June2006\SAS>python med.py
> 'python' is not recognized as an internal or external command,
> operable program or batch file.
>
>
> What do I do to make DOS recognize python as a command?
You have to add the Python directory (C:\Python24) to your PATH
environment variable. There are some directions here:
http://www.python.org/doc/faq/windows.html#how-do-i-run-a-python-program-under-windows
>
> The link http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html
> that you suggested
>
> shows information about the idle.
>
> I've used idle for development until now, but it has the annoyance
> that I must close it and reopen it in order for it to import the changed
> copy
> of the program.
I don't think you have to do that. If you open your file in an editing
window you can run from there with Run / Run Module (F5). If you are
importing into the shell window you can use Shell / Restart Shell to
clear any imports, or use reload() to get a fresh copy.
>
> Besides, I already have one default module saved, and it would seem
> complicated to have more than one.
I don't know what you mean by this, what is a default module?
Kent
PS thanks for losing the graphics...
From kent37 at tds.net Wed Jun 7 03:03:22 2006
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 06 Jun 2006 21:03:22 -0400
Subject: [Tutor] bounced email
In-Reply-To: <4486213C.000012.03972@YOUR-4105E587B6>
References: <4486213C.000012.03972@YOUR-4105E587B6>
Message-ID: <448625DA.5080505@tds.net>
Kermit Rose wrote:
>
>
> My last email to you bounced.
>
>
> Why?
I don't know, it seems to be complaining about the HTML and missing some
image?
Kent
From tim.peters at gmail.com Wed Jun 7 03:16:14 2006
From: tim.peters at gmail.com (Tim Peters)
Date: Tue, 6 Jun 2006 21:16:14 -0400
Subject: [Tutor] bounced email
In-Reply-To: <4486213C.000012.03972@YOUR-4105E587B6>
References: <4486213C.000012.03972@YOUR-4105E587B6>
Message-ID: <1f7befae0606061816h730ec0e7o92b6260f701ef13d@mail.gmail.com>
[Kermit Rose]
> My last email to you bounced.
>
>
> Why?
>
> From: tutor-bounces at python.org
> Date: 06/06/06 20:30:49
> To: kermit at polaris.net
> Subject: The results of your email commands
>
>
> The results of your email command are provided below. Attached is your
> original message.
>
> - Unprocessed:
> ...
Looks like you sent your original email to tutor-request at python.org
instead of to the correct address (tutor at python.org). tutor-request
is looking for Mailman commands in the body of your message, and can't
make sense of what you wrote. Send messages to the right address and
you shouldn't see this again.
From kermit at polaris.net Wed Jun 7 04:05:17 2006
From: kermit at polaris.net (Kermit Rose)
Date: Tue, 6 Jun 2006 22:05:17 -0400 (Eastern Daylight Time)
Subject: [Tutor] end of line character seems to be invisible. why?
Message-ID: <4486345D.00001C.03972@YOUR-4105E587B6>
I ran the program
# inp = open("CMT_MCAID", "rb")
# out = open("mcaid.txt", "w")
# for I in range(1,1000):
# if I I%60=== 0:
# out.write('\n')
# ch = inp.read(1)
# if not ch: break # EOF
# k = ord(ch) # convert to integer
# kl = k % 16
# kh = k / 16
# out.write('%d %d ' % (kh, kl))
# out.close()
I added the lines
# if I%60 == 0:
# out.write('\n')
because the output was one long line, and I wanted to be able to see the
output when
I opened the file with notepad.
I expected that it would break the line at every 60 characters.
It made no difference. The output file is still one long line.
Kermit < kermit at polaris.net >
From keosophon at khmeros.info Wed Jun 7 04:06:39 2006
From: keosophon at khmeros.info (Keo Sophon)
Date: Wed, 7 Jun 2006 09:06:39 +0700
Subject: [Tutor] Combo Box in Tkinter
Message-ID: <200606070906.39468.keosophon@khmeros.info>
Hi,
Is there any Combo Box in Tkinter? I looked for it but only found list box.
Might it be list box having any option to make itself as a combo box?
Thanks,
Phon
From kermit at polaris.net Wed Jun 7 04:11:18 2006
From: kermit at polaris.net (Kermit Rose)
Date: Tue, 6 Jun 2006 22:11:18 -0400 (Eastern Daylight Time)
Subject: [Tutor] Apologies
Message-ID: <448635C6.000020.03972@YOUR-4105E587B6>
I%60
should have been
I%12
My previous request has been solved.
From: Kermit Rose
Date: 06/06/06 22:05:17
To: tutor at python.org
Subject: end of line character seems to be invisible. why?
I ran the program
# inp = open("CMT_MCAID", "rb")
# out = open("mcaid.txt", "w")
# for I in range(1,1000):
# if I I%60=== 0:
On reflection, I realized that more than one character is being written with
each character input,
so I should have divided 60 by the number of characters output per character
input.
Thanks for all your assistance.
Kermit < kermit at Polaris.net >
From john at fouhy.net Wed Jun 7 04:23:31 2006
From: john at fouhy.net (John Fouhy)
Date: Wed, 7 Jun 2006 14:23:31 +1200
Subject: [Tutor] Combo Box in Tkinter
In-Reply-To: <200606070906.39468.keosophon@khmeros.info>
References: <200606070906.39468.keosophon@khmeros.info>
Message-ID: <5e58f2e40606061923o147d7652y473af11d1f147f6b@mail.gmail.com>
Check out Python MegaWidgets (pmw.sourceforge.net).
On 07/06/06, Keo Sophon wrote:
> Hi,
>
> Is there any Combo Box in Tkinter? I looked for it but only found list box.
> Might it be list box having any option to make itself as a combo box?
>
> Thanks,
> Phon
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
From emilia12 at mail.bg Wed Jun 7 08:20:16 2006
From: emilia12 at mail.bg (emilia12 at mail.bg)
Date: Wed, 07 Jun 2006 09:20:16 +0300
Subject: [Tutor] [tutor] dictionary
Message-ID: <1149661216.3da261df05f98@mail.bg>
Hi,
how can i print a dictionary, sorted by the values?
-----------------------------
??????? 666.
???? ? ??????.
From govilakanksha at yahoo.com Wed Jun 7 09:01:17 2006
From: govilakanksha at yahoo.com (Akanksha Govil)
Date: Wed, 7 Jun 2006 00:01:17 -0700 (PDT)
Subject: [Tutor] Affect of doc strings on performance
Message-ID: <20060607070117.27718.qmail@web36505.mail.mud.yahoo.com>
Hi,
I wanted to know if we give large doc strings in the python scripts, does it slow down the script execution?
Should we always keep those doc strings to minimum if we want fast script execution?
Thanks
Akanksha
__________________________________________________
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
http://mail.yahoo.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060607/5d37ad71/attachment.html
From kent37 at tds.net Wed Jun 7 11:48:34 2006
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 07 Jun 2006 05:48:34 -0400
Subject: [Tutor] Affect of doc strings on performance
In-Reply-To: <20060607070117.27718.qmail@web36505.mail.mud.yahoo.com>
References: <20060607070117.27718.qmail@web36505.mail.mud.yahoo.com>
Message-ID: <4486A0F2.8000405@tds.net>
i don't think it makes any difference. I suppose it will slow down the
parsing of the file by a tiny amount, and increase memory usage by the
size of the strings, but I don't think it will change execution time.
The Python standard library has lots of doc strings. Type help(dict) at
the interpreter prompt for an example. The dict class is highly
optimized so if doc strings affected speed that would be a problem.
If you have a time critical function, you could always time it with and
without doc strings to be sure! In Python it's always best to answer
"which is faster" questions with real data.
Kent
Akanksha Govil wrote:
> Hi,
>
> I wanted to know if we give large doc strings in the python scripts,
> does it slow down the script execution?
>
> Should we always keep those doc strings to minimum if we want fast
> script execution?
>
> Thanks
> Akanksha
>
> __________________________________________________
> Do You Yahoo!?
> Tired of spam? Yahoo! Mail has the best spam protection around
> http://mail.yahoo.com
>
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
From kent37 at tds.net Wed Jun 7 11:56:50 2006
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 07 Jun 2006 05:56:50 -0400
Subject: [Tutor] [tutor] dictionary
In-Reply-To: <1149661216.3da261df05f98@mail.bg>
References: <1149661216.3da261df05f98@mail.bg>
Message-ID: <4486A2E2.9020908@tds.net>
emilia12 at mail.bg wrote:
> how can i print a dictionary, sorted by the values?
A dictionary itself is an unordered collection and can't be sorted. But
you can sort and print the list of key, value pairs returned by
dict.items(). For example:
In [3]: from operator import itemgetter
In [4]: d = { 1 : 'one', 2 : 'two', 3 : 'three', 4 : 'four' }
In [5]: for k, v in sorted(d.items(), key=itemgetter(1)):
...: print k, '=', v
...:
...:
4 = four
1 = one
3 = three
2 = two
d.items() returns a list of (key, value) pairs:
In [6]: d.items()
Out[6]: [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
itemgetter(1) actually returns a function which, when called with an
argument x, returns x[1]:
In [7]: get1 = itemgetter(1)
In [8]: get1(d.items())
Out[8]: (2, 'two')
In [9]: get1('abc')
Out[9]: 'b'
Using itemgetter(1) as the key argument to sorted() makes the sort
happen on the second item of each pair, the value.
(This example requires Python 2.4; Python 2.3 has no sorted() function,
you have to do the sort in a separate step using list.sort(). In earlier
Python you have to use a different trick called DSU to sort by key.)
Kent
From pjlists at gmail.com Wed Jun 7 12:00:15 2006
From: pjlists at gmail.com (Peter Jessop)
Date: Wed, 7 Jun 2006 12:00:15 +0200
Subject: [Tutor] (OT) Monitorising WEB POSTs
Message-ID: <7a8d5a0c0606070300h4b51265ci4a1fb51da78fbae5@mail.gmail.com>
I am building a python application to automate information capture
from a web site.
I want to use a python application to request and process the
information instead of using the site's WEB page.
However I am having problems finding out exactly what data the server expects.
I have a firefox add-in called Web Developer that gives me good
information about the form (fields names etc..)
But what I want to do is find out exactly what POST data my browser is sending.
I am aware of two ways of doing this.
a) A sniffer to read the udp packet sent from my computer
b) Send the page to my own WEB server
Is there a program or add in that will give me this information
without resorting to the solutions above.
Peter Jessop
From pjlists at gmail.com Wed Jun 7 12:17:09 2006
From: pjlists at gmail.com (Peter Jessop)
Date: Wed, 7 Jun 2006 12:17:09 +0200
Subject: [Tutor] python application on a web page
In-Reply-To: <20060606172431.13283.qmail@web55012.mail.re4.yahoo.com>
References: <20060606172431.13283.qmail@web55012.mail.re4.yahoo.com>
Message-ID: <7a8d5a0c0606070317w73c49c21m72b9449b54a056e5@mail.gmail.com>
Tkinter is a multiplatform toolkit for producing programs with
graphical interface.
But multiplatform refers to BSD, Linux, Mackintosh, Windows etc.
If you want to produce the output on the WEB you need to produce the
output in HTML or in some way that most users can see it in their
Browsers. (Java Script, Flash, etc...)
This forum caters well for beginners (and more advanced) and the
quality and helpfulness are very high.
Here are a some links that may be useful.
http://wiki.python.org/moin/BeginnersGuide/NonProgrammers
http://www.python.org/doc/Intros.html
http://diveintopython.org/
From pjlists at gmail.com Wed Jun 7 12:37:56 2006
From: pjlists at gmail.com (Peter Jessop)
Date: Wed, 7 Jun 2006 12:37:56 +0200
Subject: [Tutor] Truly generic database API
In-Reply-To: <3B05FA2AD704244BB0CAB99D8026F55501076781@medexch2.medplus.com>
References: <3B05FA2AD704244BB0CAB99D8026F55501076781@medexch2.medplus.com>
Message-ID: <7a8d5a0c0606070337y38a0c329i9f183f2d018dbb7@mail.gmail.com>
It depends on your system constraints.
If you are only developing on Windows then you can use ODBC.
ODBC supports writing to text files. It is an old fashioned technology
and is not very fast. However it is well supported and mature.
From m_webber_sydney at yahoo.com.au Wed Jun 7 13:01:12 2006
From: m_webber_sydney at yahoo.com.au (Matthew Webber)
Date: Wed, 7 Jun 2006 12:01:12 +0100
Subject: [Tutor] (OT) Monitorising WEB POSTs
In-Reply-To: <7a8d5a0c0606070300h4b51265ci4a1fb51da78fbae5@mail.gmail.com>
Message-ID: <001501c68a21$b049ac90$0200a8c0@kookaburra>
Install the Firefox extension called "Live HTTP headers", and look at the
"Generator" tab. This appears to be what you want.
-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf
Of Peter Jessop
Sent: 07 June 2006 11:00
To: tutor at python.org
Subject: [Tutor] (OT) Monitorising WEB POSTs
I am building a python application to automate information capture
from a web site.
I want to use a python application to request and process the
information instead of using the site's WEB page.
However I am having problems finding out exactly what data the server
expects.
I have a firefox add-in called Web Developer that gives me good
information about the form (fields names etc..)
But what I want to do is find out exactly what POST data my browser is
sending.
I am aware of two ways of doing this.
a) A sniffer to read the udp packet sent from my computer
b) Send the page to my own WEB server
Is there a program or add in that will give me this information
without resorting to the solutions above.
Peter Jessop
From pjlists at gmail.com Wed Jun 7 13:15:51 2006
From: pjlists at gmail.com (Peter Jessop)
Date: Wed, 7 Jun 2006 13:15:51 +0200
Subject: [Tutor] (OT) Monitorising WEB POSTs
In-Reply-To: <001501c68a21$b049ac90$0200a8c0@kookaburra>
References: <7a8d5a0c0606070300h4b51265ci4a1fb51da78fbae5@mail.gmail.com>
<001501c68a21$b049ac90$0200a8c0@kookaburra>
Message-ID: <7a8d5a0c0606070415n1a605772wf3251b081707cca8@mail.gmail.com>
Matthew
Fantastic!
Exactly what I needed
From kermit at polaris.net Wed Jun 7 13:59:18 2006
From: kermit at polaris.net (Kermit Rose)
Date: Wed, 7 Jun 2006 07:59:18 -0400 (Eastern Daylight Time)
Subject: [Tutor] default module
Message-ID: <4486BF96.000005.00248@YOUR-4105E587B6>
Message: 3
Date: Tue, 06 Jun 2006 20:59:11 -0400
From: Kent Johnson
Subject: Re: [Tutor] How do I get Dos to recognize python command?
To: Python Tutor
>
> Besides, I already have one default module saved, and it would seem
> complicated to have more than one.
I don't know what you mean by this, what is a default module?
Kent
******
Hello Kent.
A while back in time, I wanted to make a library of subroutines.
Someone showed me how to tell python to declare the file a module.
I don't remember how I did it.
Now whenever I want to make the library available,
in idle,
I type
import factor30
from factor30 import factor00, gcd, ksqrt # what ever subroutines I
wish to have local
I assumed that I could have only one library.
That why I called it the default module.
Kermit < kermit at polaris.net >
From kent37 at tds.net Wed Jun 7 14:12:59 2006
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 07 Jun 2006 08:12:59 -0400
Subject: [Tutor] default module
In-Reply-To: <4486BF96.000005.00248@YOUR-4105E587B6>
References: <4486BF96.000005.00248@YOUR-4105E587B6>
Message-ID: <4486C2CB.9020001@tds.net>
Kermit Rose wrote:
> From: Kent Johnson
>> Besides, I already have one default module saved, and it would seem
>> complicated to have more than one.
>
> I don't know what you mean by this, what is a default module?
>
> A while back in time, I wanted to make a library of subroutines.
>
> Someone showed me how to tell python to declare the file a module.
>
> I don't remember how I did it.
>
> Now whenever I want to make the library available,
>
> in idle,
>
> I type
>
> import factor30
> from factor30 import factor00, gcd, ksqrt # what ever subroutines I
> wish to have local
>
> I assumed that I could have only one library.
>
> That why I called it the default module.
Hi Kermit,
To make a module available for import, you just have to save it
somewhere on your Python path. There are several ways to do this, but if
you want to make another importable module just save it in the same
location as factor30.py. There is no practical limit on how many modules
you can have - just RAM and disk space limits, AFAIK. You already have
many modules installed as part of the standard library and any
third-party add-ons you have installed.
If you are working with a module from the interpreter and you make
changes to the module, you have to reload it with the command
>>> reload(factor30)
This won't work for local names (from factor30 import xx)! Just use the
full name to access any elements of factor30, e.g. factor30.gcd. Read
more here:
http://www.python.org/doc/faq/programming/#when-i-edit-an-imported-module-and-reimport-it-the-changes-don-t-show-up-why-does-this-happen
Kent
From doug.shawhan at gmail.com Wed Jun 7 18:55:57 2006
From: doug.shawhan at gmail.com (doug shawhan)
Date: Wed, 7 Jun 2006 11:55:57 -0500
Subject: [Tutor] Offtopic observation
Message-ID: <5e1ceb8a0606070955y24116d92jc55aa17c94a0409c@mail.gmail.com>
This marks the third time this week I have been typing in a question for the
group, and have made the answer apparent just by trying to explain my
question clearly.
This suggests that either I think better in text, or Proust was onto
something ... but then again, I majored in english.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060607/d933845c/attachment.htm
From dyoo at hkn.eecs.berkeley.edu Wed Jun 7 19:28:39 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Wed, 7 Jun 2006 10:28:39 -0700 (PDT)
Subject: [Tutor] Offtopic observation
In-Reply-To: <5e1ceb8a0606070955y24116d92jc55aa17c94a0409c@mail.gmail.com>
References: <5e1ceb8a0606070955y24116d92jc55aa17c94a0409c@mail.gmail.com>
Message-ID:
On Wed, 7 Jun 2006, doug shawhan wrote:
> This marks the third time this week I have been typing in a question for
> the group, and have made the answer apparent just by trying to explain
> my question clearly.
Yes. *grin* It's a very powerful technique. Writing does this for me as
well.
From ms at cerenity.org Wed Jun 7 21:10:54 2006
From: ms at cerenity.org (Michael)
Date: Wed, 7 Jun 2006 20:10:54 +0100
Subject: [Tutor] Offtopic observation
In-Reply-To: <5e1ceb8a0606070955y24116d92jc55aa17c94a0409c@mail.gmail.com>
References: <5e1ceb8a0606070955y24116d92jc55aa17c94a0409c@mail.gmail.com>
Message-ID: <200606072010.54704.ms@cerenity.org>
On Wednesday 07 June 2006 17:55, doug shawhan wrote:
> This marks the third time this week I have been typing in a question for
> the group, and have made the answer apparent just by trying to explain my
> question clearly.
>
> This suggests that either I think better in text, or Proust was onto
> something ... but then again, I majored in english.
It's also called confessional debugging :-)
It's also something that actually tends to apply outside programming as well.
The act of understanding the problem often leads to a solution :-)
Michael.
From kent37 at tds.net Wed Jun 7 21:24:43 2006
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 7 Jun 2006 15:24:43 -0400
Subject: [Tutor] Offtopic observation
Message-ID: <20060607192443.NHIM20006.outaamta01.mail.tds.net@smtp.tds.net>
> From: Danny Yoo
> On Wed, 7 Jun 2006, doug shawhan wrote:
>
> > This marks the third time this week I have been typing in a question for
> > the group, and have made the answer apparent just by trying to explain
> > my question clearly.
>
> Yes. *grin* It's a very powerful technique. Writing does this for me as
> well.
For me it's often talking. I have a friend in the office I go to when I am stuck on something. He's a very powerful listener - often by the time I am done describing the problem and the available options I have settled on an answer.
Kent
From klappnase at freenet.de Wed Jun 7 23:52:15 2006
From: klappnase at freenet.de (Michael Lange)
Date: Wed, 7 Jun 2006 23:52:15 +0200
Subject: [Tutor] combo box
In-Reply-To: <44852319.1080804@khmeros.info>
References: <44852319.1080804@khmeros.info>
Message-ID: <20060607235215.04540800.klappnase@freenet.de>
On Tue, 06 Jun 2006 13:39:21 +0700
kakada wrote:
> Dear Friends,
>
> I am now working on GUI python (Tkinter).
> I want to use combobox as my widget, but I cannot find it in any document.
>
> Does anybody have experience with that?
>
There is no ComboBox widget in plain Tkinter.
Probably the easiest way to get one is to use Tix which is included in the windows python
distribution and should be available in any recent linux distro.
If you want to use Tix simply replace the import line
from Tkinter import *
with
from Tix import *
You then can use your Tknter widgets as usual, plus a nice set of extra widgets (ComboBox, NoteBook, DirTree etc.) .
I hope this helps
Michael
From kermit at polaris.net Thu Jun 8 00:44:08 2006
From: kermit at polaris.net (Kermit Rose)
Date: Wed, 7 Jun 2006 18:44:08 -0400 (Eastern Daylight Time)
Subject: [Tutor] module versus file
Message-ID: <448756B8.00001D.03044@YOUR-4105E587B6>
Message: 7
Date: Wed, 07 Jun 2006 08:12:59 -0400
From: Kent Johnson
Subject: Re: [Tutor] default module
>>>>>>>>>>
Hi Kermit,
To make a module available for import, you just have to save it
somewhere on your Python path. There are several ways to do this,
*******
Yes. By some means that I don't remember I declared the file factor30.py
in directory
math\factoring
to be a module.
>>>>>>>>>>>>
but if
you want to make another importable module just save it in the same
location as factor30.py.
***************
Are you saying that any .py file that I save in math\factoring
can be imported?
>>>>>>>>
There is no practical limit on how many modules
you can have - just RAM and disk space limits,
AFAIK.
******
Had to look up the acronyn.
What is AFAIK?
It's an acronym for As Far As I Know.
>>>>>>>>>>
You already have
many modules installed as part of the standard library and any
third-party add-ons you have installed.
**********
Yes. I'm impressed with the listing in built_in.
I assumed system modules were handled in a different way than user modules.
*********
>>>>>>>>
If you are working with a module from the interpreter and you make
changes to the module, you have to reload it with the command
>>> reload(factor30)
*****
I will try the reload command next time I work with factor30.
>>>>>>
This won't work for local names (from factor30 import xx)! Just use the
full name to access any elements of factor30, e.G. factor30.gcd. Read
******
In order to have the shorter name,
gcd
instead of factor30.gcd,
I prepare by
typing
from factor30 import gcd
Once someone said that modules and files are not the same thing.
This statement left me puzzled. Why not?
Kermit < kermit at polaris.net >
From john at fouhy.net Thu Jun 8 00:45:41 2006
From: john at fouhy.net (John Fouhy)
Date: Thu, 8 Jun 2006 10:45:41 +1200
Subject: [Tutor] Offtopic observation
In-Reply-To: <5e1ceb8a0606070955y24116d92jc55aa17c94a0409c@mail.gmail.com>
References: <5e1ceb8a0606070955y24116d92jc55aa17c94a0409c@mail.gmail.com>
Message-ID: <5e58f2e40606071545k2eb930e6v79d92d08cf75fe8f@mail.gmail.com>
On 08/06/06, doug shawhan wrote:
> This marks the third time this week I have been typing in a question for the
> group, and have made the answer apparent just by trying to explain my
> question clearly.
I'm usually a step back from that --- the answer becomes apparent
approximately five seconds _after_ I send off my question..
--
John.
From sisson.j at gmail.com Wed Jun 7 21:32:25 2006
From: sisson.j at gmail.com (Jonathon Sisson)
Date: Wed, 07 Jun 2006 20:32:25 +0100
Subject: [Tutor] Offtopic observation
In-Reply-To: <20060607192443.NHIM20006.outaamta01.mail.tds.net@smtp.tds.net>
References: <20060607192443.NHIM20006.outaamta01.mail.tds.net@smtp.tds.net>
Message-ID: <448729C9.2030108@gmail.com>
Kent Johnson wrote:
>> From: Danny Yoo
>> On Wed, 7 Jun 2006, doug shawhan wrote:
>>
>>> This marks the third time this week I have been typing in a question for
>>> the group, and have made the answer apparent just by trying to explain
>>> my question clearly.
>> Yes. *grin* It's a very powerful technique. Writing does this for me as
>> well.
>
> For me it's often talking. I have a friend in the office I go to when I am stuck on something. He's a very powerful listener - often by the time I am done describing the problem and the available options I have settled on an answer.
>
> Kent
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
I want one of those...hahaha...someone who would listen long enough for
me to settle on an answer on my own? God, you're a lucky person. If I
so much as shape my mouth like the word "computer" is going to come out,
my wife runs for cover...my friends do their best, but most of them
aren't great listeners so we end up getting off topic and never do find
a solution. My daughter listens, but I have to wait for her to start
pre-school for hope of any real response. Consider yourself quite
lucky, Kent.
Jon
From dkuhlman at rexx.com Thu Jun 8 05:10:52 2006
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Wed, 7 Jun 2006 20:10:52 -0700
Subject: [Tutor] module versus file
In-Reply-To: <448756B8.00001D.03044@YOUR-4105E587B6>
References: <448756B8.00001D.03044@YOUR-4105E587B6>
Message-ID: <20060608031052.GA29650@cutter.rexx.com>
On Wed, Jun 07, 2006 at 06:44:08PM -0400, Kermit Rose wrote:
[snip]
>
>
> Yes. By some means that I don't remember I declared the file factor30.py
> in directory
> math\factoring
>
> to be a module.
>
If you are importing a module from a directory other than your
current directory, then the directory is effectively a package.
In order to make a directory into a package, the directory must
contain a file named __init__.py.
The file __init__.py can be empty or can contain code. It will be
evaluated the first time (and only the first time) an application
imports the package or something in it.
Dave
[snip]
--
Dave Kuhlman
http://www.rexx.com/~dkuhlman
From dkuhlman at rexx.com Thu Jun 8 05:15:48 2006
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Wed, 7 Jun 2006 20:15:48 -0700
Subject: [Tutor] Offtopic observation
In-Reply-To: <5e58f2e40606071545k2eb930e6v79d92d08cf75fe8f@mail.gmail.com>
References: <5e1ceb8a0606070955y24116d92jc55aa17c94a0409c@mail.gmail.com>
<5e58f2e40606071545k2eb930e6v79d92d08cf75fe8f@mail.gmail.com>
Message-ID: <20060608031548.GB29650@cutter.rexx.com>
On Thu, Jun 08, 2006 at 10:45:41AM +1200, John Fouhy wrote:
> On 08/06/06, doug shawhan wrote:
> > This marks the third time this week I have been typing in a question for the
> > group, and have made the answer apparent just by trying to explain my
> > question clearly.
1. That's why we write and ask questions: to make things clear to
ourselves.
2. And the reason we teach (Python etc) is so that students ask us
questions and we are forced to explain ourselves, which enables
us to understand what we are talking about.
Dave
>
> I'm usually a step back from that --- the answer becomes apparent
> approximately five seconds _after_ I send off my question..
>
You are one of the quick ones.
Dave
--
Dave Kuhlman
http://www.rexx.com/~dkuhlman
From kent37 at tds.net Thu Jun 8 11:54:42 2006
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 8 Jun 2006 5:54:42 -0400
Subject: [Tutor] module versus file
Message-ID: <20060608095442.TOQR20006.outaamta01.mail.tds.net@smtp.tds.net>
> From: Dave Kuhlman
>
> If you are importing a module from a directory other than your
> current directory, then the directory is effectively a package.
> In order to make a directory into a package, the directory must
> contain a file named __init__.py.
That's not quite right. If the module is in a directory that is in sys.path, it is just a plain module, not a package. If the module is in a subdirectory of a directory in sys.path, then the subdirectory is a package and requires an __init__.py file to be recognized as a package. There is a good discussion of modules and packages in the tutorial:
http://docs.python.org/tut/node8.html
Kent
From kermit at polaris.net Thu Jun 8 14:59:24 2006
From: kermit at polaris.net (Kermit Rose)
Date: Thu, 8 Jun 2006 08:59:24 -0400 (Eastern Daylight Time)
Subject: [Tutor] directory as package
Message-ID: <44881F2C.000007.03652@YOUR-4105E587B6>
Message: 4
Date: Wed, 7 Jun 2006 20:10:52 -0700
From: Dave Kuhlman
Subject: Re: [Tutor] module versus file
To: tutor at python.org
Hello Dave.
>>>>>>>>>>
If you are importing a module from a directory other than your
current directory, then the directory is effectively a package.
In order to make a directory into a package, the directory must
contain a file named __init__.py.
The file __init__.py can be empty or can contain code. It will be
evaluated the first time (and only the first time) an application
imports the package or something in it.
Dave
*******
It must be someother method that I used, because
there is no file named _init_.py is directory math\factoring
Is it that the convention must be different for a windows machine?
C:\Math\Factoring>dir *init*
Volume in drive C has no label.
Volume Serial Number is 4748-654D
Directory of C:\Math\Factoring
File Not Found
Kermit < kermit at polaris.net >
From kent37 at tds.net Thu Jun 8 15:28:27 2006
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 08 Jun 2006 09:28:27 -0400
Subject: [Tutor] module versus file
In-Reply-To: <448756B8.00001D.03044@YOUR-4105E587B6>
References: <448756B8.00001D.03044@YOUR-4105E587B6>
Message-ID: <448825FB.7030600@tds.net>
Kermit Rose wrote:
> Are you saying that any .py file that I save in math\factoring
> can be imported?
Yes
> You already have
> many modules installed as part of the standard library and any
> third-party add-ons you have installed.
>
> **********
>
> Yes. I'm impressed with the listing in built_in.
>
> I assumed system modules were handled in a different way than user modules.
Many system modules are written in Python and handled the same way as
user modules - they are found by searching sys.path. The actual files
are in C:\Python24\Lib
Some system modules are written in C, they are still on sys.path but the
modules are called .pyd.
Some system modules are built-in to Python and don't correspond to an
actual file in the file system.
>
> *********
>
>
> If you are working with a module from the interpreter and you make
> changes to the module, you have to reload it with the command
> >>> reload(factor30)
>
> *****
>
> I will try the reload command next time I work with factor30.
>
> This won't work for local names (from factor30 import xx)! Just use the
> full name to access any elements of factor30, e.G. factor30.gcd. Read
>
> ******
>
> In order to have the shorter name,
>
> gcd
>
> instead of factor30.gcd,
>
> I prepare by
>
> typing
>
> from factor30 import gcd
If you do this, reload(factor30) will not get you a new copy of gcd
because gcd is bound to the old function.
>
>
> Once someone said that modules and files are not the same thing.
>
> This statement left me puzzled. Why not?
Most modules do have corresponding files. The exceptions are the ones
built-in to Python. In fact modules have a __file__ attribute that tells
you where it came from; try typing
factor30.__file__
Kent
From emily.fortuna at nist.gov Thu Jun 8 15:19:58 2006
From: emily.fortuna at nist.gov (Emily Fortuna)
Date: Thu, 08 Jun 2006 09:19:58 -0400
Subject: [Tutor] making a python program part of xhtml
Message-ID: <448823FE.6080504@nist.gov>
Hola everyone,
I'm working on creating a webpage in which a user can submit data into
fields to be held in a database (there are other details, but this is
the gist of the idea), and I need to use python. I am unfamiliar with
manipulating data and web apps as a whole (and new to python), so I have
been encountering much unfamiliar terrain. I _think_ I want to somehow
embed the python into the page, but I'm really not sure how to do it.
After googling I found some programs that generate xhtml from python,
but I don't think that is what I want, or is it? Your help is appreciated!
Emily
From cspears2002 at yahoo.com Thu Jun 8 18:44:24 2006
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Thu, 8 Jun 2006 09:44:24 -0700 (PDT)
Subject: [Tutor] PyGTK on cygwin
Message-ID: <20060608164424.66786.qmail@web51604.mail.yahoo.com>
Does PyGTK work well on cygwin?
From mhansen at cso.atmel.com Thu Jun 8 18:59:57 2006
From: mhansen at cso.atmel.com (Mike Hansen)
Date: Thu, 08 Jun 2006 10:59:57 -0600
Subject: [Tutor] making a python program part of xhtml
In-Reply-To: <448823FE.6080504@nist.gov>
Message-ID: <000601c68b1c$f8aa66e0$28645f0a@mikehansen>
> -----Original Message-----
> From: tutor-bounces at python.org
> [mailto:tutor-bounces at python.org] On Behalf Of Emily Fortuna
> Sent: Thursday, June 08, 2006 7:20 AM
> To: tutor at python.org
> Subject: [Tutor] making a python program part of xhtml
>
> Hola everyone,
> I'm working on creating a webpage in which a user can submit
> data into
> fields to be held in a database (there are other details, but this is
> the gist of the idea), and I need to use python. I am
> unfamiliar with
> manipulating data and web apps as a whole (and new to
> python), so I have
> been encountering much unfamiliar terrain. I _think_ I want
> to somehow
> embed the python into the page, but I'm really not sure how
> to do it.
> After googling I found some programs that generate xhtml from python,
> but I don't think that is what I want, or is it? Your help
> is appreciated!
> Emily
>
Although you can embed python in a web page to be run on a server, you
probably don't want to do that.(It can get pretty messy.)
What I'd suggest is creating a web page that calls a python program on the
server and processes form fields in the web page. The python program would
save the data in the database.
[web page] -> [python program on server] -> [database]
Look at the FORM tag in HTML/XHTML. Also look at the cgi module for Python.
I think there's some web topics on the Python web site that might point to
articles about doing simple cgi stuff in Python.
http://wiki.python.org/moin/CgiScripts
http://www.devshed.com/index2.php?option=content&task=view&id=198&pop=1&page
=0&hide_js=1
Is an article on cgi programming with Python.
Mike
From clsdaniel at gmail.com Thu Jun 8 19:37:14 2006
From: clsdaniel at gmail.com (Carlos Daniel Ruvalcaba Valenzuela)
Date: Thu, 8 Jun 2006 10:37:14 -0700
Subject: [Tutor] PyGTK on cygwin
In-Reply-To: <20060608164424.66786.qmail@web51604.mail.yahoo.com>
References: <20060608164424.66786.qmail@web51604.mail.yahoo.com>
Message-ID: <4fae7dfa0606081037x4e283ed9i3cef04858e9613b8@mail.gmail.com>
There is a PyGTK package for win32, don't know if it uses cygwin or
mingw but works pretty well on windows, it only needs the gtk runtime.
http://www.pcpm.ucl.ac.be/~gustin/win32_ports/
Altough I might been misunderstanding your question ;)
On 6/8/06, Christopher Spears wrote:
> Does PyGTK work well on cygwin?
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
From cspears2002 at yahoo.com Fri Jun 9 05:15:51 2006
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Thu, 8 Jun 2006 20:15:51 -0700 (PDT)
Subject: [Tutor] What is a widget?
Message-ID: <20060609031551.70362.qmail@web51601.mail.yahoo.com>
I'm a bit embarassed to ask this...I am looking at a
tutorial for PyGTK+ that is discussing widgets. What
are widgets?
-Chris
From bgailer at alum.rpi.edu Fri Jun 9 05:20:48 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Thu, 08 Jun 2006 20:20:48 -0700
Subject: [Tutor] What is a widget?
In-Reply-To: <20060609031551.70362.qmail@web51601.mail.yahoo.com>
References: <20060609031551.70362.qmail@web51601.mail.yahoo.com>
Message-ID: <4488E910.6040605@alum.rpi.edu>
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060608/771436c6/attachment.html
-------------- next part --------------
A non-text attachment was scrubbed...
Name: show
Type: image/gif
Size: 43 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20060608/771436c6/attachment.gif
From starredheeler at hotmail.com Fri Jun 9 09:52:42 2006
From: starredheeler at hotmail.com (Desk Jet)
Date: Fri, 09 Jun 2006 02:52:42 -0500
Subject: [Tutor] layout ( i guess)
Message-ID:
uh ive been wondering if with python you would be able to make layouts?
_________________________________________________________________
Express yourself instantly with MSN Messenger! Download today - it's FREE!
http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/
From etrade.griffiths at dsl.pipex.com Fri Jun 9 11:42:03 2006
From: etrade.griffiths at dsl.pipex.com (Etrade Griffiths)
Date: Fri, 09 Jun 2006 10:42:03 +0100
Subject: [Tutor] Confused about globals
Message-ID: <6.1.2.0.2.20060609102904.037ce960@pop.dsl.pipex.com>
Hi
I have a series of python programs that plot stuff using PYX. Common to
these is the need to read in a list of (well) locations in (X,Y) coords so
I put that code in a separate module called shared_funcs.py. The coords
are stored in dictionaries which I want to use later in the "main" program
- every time I find a well with data, I can get the well's (x,y) coords by
looking up the well name in the dictionary. The code snippet looks like this:
=== main.py ====
# define coord dictionaries for global use
DE={}
DN={}
import shared_funcs()
shared_funcs.get_xy_data() # Get coords from file
... do plotting stuff
=== shared_funcs.py ===
def get_xy_data():
in_file=open("well_xy.txt","r")
for line in in_file
L=line.split()
well=L[0]
x=L[1]
y=L[2]
DE[well]=x
DN[well]=y
in_file.close()
The problem is that DE and DN appear not to be accessible to get_xy_data -
presumably this is because shared_funcs.py and main.py don't share the same
scope. So, is there any way to let get_xy_data change DE and DN? I guess
the obvious way is to pass them to get_xy_data as arguments - but is there
a more "pythonic" method? Thanks in advance!
From kent37 at tds.net Fri Jun 9 12:04:53 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 09 Jun 2006 06:04:53 -0400
Subject: [Tutor] layout ( i guess)
In-Reply-To:
References:
Message-ID: <448947C5.1010501@tds.net>
Desk Jet wrote:
> uh ive been wondering if with python you would be able to make layouts?
What's a layout? For a web site, magazine page, printed circuit board...
Kent
From RPhillips at engineer.co.summit.oh.us Fri Jun 9 13:17:02 2006
From: RPhillips at engineer.co.summit.oh.us (Ron Phillips)
Date: Fri, 09 Jun 2006 07:17:02 -0400
Subject: [Tutor] making a python program part of xhtml
Message-ID:
>>> Emily Fortuna < emily.fortuna at nist.gov > 6/8/2006 9:19 AM >>>
Hola everyone,
I'm working on creating a webpage in which a user can submit data into
fields to be held in a database (there are other details, but this is
the gist of the idea), and I need to use python. I am unfamiliar with
manipulating data and web apps as a whole (and new to python), so I
have
been encountering much unfamiliar terrain. I _think_ I want to somehow
embed the python into the page, but I'm really not sure how to do it.
After googling I found some programs that generate xhtml from python,
but I don't think that is what I want, or is it? Your help is
appreciated!
Emily
You might look at http://karrigell.sourceforge.net/: karrigell lets you
embed python in xhtml, xhtml in python, execute straight python scripts,
or execute python from a karrigell application server. Even if you don't
choose karrigell for some reason, at least the documentation can help
you sort out the variations on the python/xhtml theme!
Ron
From kieran.flanagan at gmail.com Fri Jun 9 14:52:23 2006
From: kieran.flanagan at gmail.com (kieran flanagan)
Date: Fri, 9 Jun 2006 13:52:23 +0100
Subject: [Tutor] Maintain SessionID with AMARA
Message-ID:
Hi
I want to have a script that can browse through a website and retrieve
information upon request. If I use AMARA for this, in the form i.e.
for subtree in binderytools.pushbind('panel', source='file1.xml'):
print subtree.name
And then once on this page 'file1.xml', need to peform an ACTION to change
the page to file2.xml and retrieve information from there. How can I do the
following:
1. Peform the actionURL using AMARA so it returns a different xml screen
that I can parse i.e. peforms a click of a URL and then parses the resulting
xml.
2. Maintain the sessionID across different pages.
Are there any examples of this ?.
Thanks
Kieran
--
"Behind every great man, there is a great woman. Behind that woman is Mr.T."
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060609/c6b3add5/attachment.htm
From dustin at ywlcs.org Fri Jun 9 16:19:42 2006
From: dustin at ywlcs.org (Dustin Mitchell)
Date: Fri, 9 Jun 2006 09:19:42 -0500
Subject: [Tutor] Confused about globals
In-Reply-To: <6.1.2.0.2.20060609102904.037ce960@pop.dsl.pipex.com>
References: <6.1.2.0.2.20060609102904.037ce960@pop.dsl.pipex.com>
Message-ID:
As a note, the "import" should be
import shared_funcs
In Python, most globals aren't really global -- they're local to the
module. If you split your modules by functionality, then variables
should naturally relate to a specific module, and be located there.
So, for example, you could move those global variables to
shared_funcs.py, renamed to wells.py:
=== wells.py ==
DE={}
DN={}
def get_xy_data():
in_file=open("well_xy.txt","r")
for line in in_file
L=line.split()
well=L[0]
x=L[1]
y=L[2]
DE[well]=x
DN[well]=y
in_file.close()
def lookup_well(well):
return (DE.get(well, None), DN.get(well, None))
=== main.py ===
import wells
def func_that_needs_wells():
...
for e n wells.DE.keys():
...
...
etc.
On Jun 9, 2006, at 4:42 AM, Etrade Griffiths wrote:
> Hi
>
> I have a series of python programs that plot stuff using PYX. Common
> to
> these is the need to read in a list of (well) locations in (X,Y)
> coords so
> I put that code in a separate module called shared_funcs.py. The
> coords
> are stored in dictionaries which I want to use later in the "main"
> program
> - every time I find a well with data, I can get the well's (x,y)
> coords by
> looking up the well name in the dictionary. The code snippet looks
> like this:
>
> === main.py ====
>
> # define coord dictionaries for global use
>
> DE={}
> DN={}
>
> import shared_funcs()
>
> shared_funcs.get_xy_data() # Get coords from file
>
> ... do plotting stuff
>
>
> === shared_funcs.py ===
>
> def get_xy_data():
> in_file=open("well_xy.txt","r")
> for line in in_file
> L=line.split()
> well=L[0]
> x=L[1]
> y=L[2]
>
> DE[well]=x
> DN[well]=y
> in_file.close()
>
> The problem is that DE and DN appear not to be accessible to
> get_xy_data -
> presumably this is because shared_funcs.py and main.py don't share the
> same
> scope. So, is there any way to let get_xy_data change DE and DN? I
> guess
> the obvious way is to pass them to get_xy_data as arguments - but is
> there
> a more "pythonic" method? Thanks in advance!
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
From kent37 at tds.net Fri Jun 9 16:44:42 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 09 Jun 2006 10:44:42 -0400
Subject: [Tutor] Confused about globals
In-Reply-To: <6.1.2.0.2.20060609102904.037ce960@pop.dsl.pipex.com>
References: <6.1.2.0.2.20060609102904.037ce960@pop.dsl.pipex.com>
Message-ID: <4489895A.4010106@tds.net>
Etrade Griffiths wrote:
> Hi
>
> I have a series of python programs that plot stuff using PYX. Common to
> these is the need to read in a list of (well) locations in (X,Y) coords so
> I put that code in a separate module called shared_funcs.py. The coords
> are stored in dictionaries which I want to use later in the "main" program
> - every time I find a well with data, I can get the well's (x,y) coords by
> looking up the well name in the dictionary.
You don't need a global variable in shared_funcs.get_xy_data() at all.
It is reading a file and creating two dicts. I would write it to create
and return the dicts. Then you can save them where you like in the
caller. Also, I would use one dict whose values are (x, y) pairs, rather
than two parallel dicts. Then your code looks like this:
=== shared_funcs.py ===
def get_xy_data():
D = {}
in_file=open("well_xy.txt","r")
for line in in_file
L=line.split()
well=L[0]
x=L[1]
y=L[2]
D[well]=(x, y)
in_file.close()
return D
=== main.py ===
import shared_funcs
D = shared_funcs.get_xy_data()
though I suggest a more descriptive name than D...
If there are other related bits of data or operations other than lookup,
that might point to using a class to wrap the dict, the other data and
operations.
Kent
From kermit at polaris.net Fri Jun 9 16:48:46 2006
From: kermit at polaris.net (Kermit Rose)
Date: Fri, 9 Jun 2006 10:48:46 -0400 (Eastern Daylight Time)
Subject: [Tutor] file attribute of module
Message-ID: <44898A4E.00001D.00376@YOUR-4105E587B6>
Message: 2
Date: Thu, 08 Jun 2006 09:28:27 -0400
From: Kent Johnson
Subject: Re: [Tutor] module versus file
Most modules do have corresponding files. The exceptions are the ones
built-in to Python. In fact modules have a __file__ attribute that tells
you where it came from; try typing
factor30.__file__
Kent
*******
>>> import factor30
>>> factor30._file_
Traceback (most recent call last):
File "", line 1, in -toplevel-
factor30._file_
AttributeError: 'module' object has no attribute '_file_'
>>>
>>> factor30.__file__
'c:\\math\\factoring\\factor30.py'
>>>
Ok. Now I understand it.
The module is named factor30.
The file is named factor30.py
I presume that if I created another library in the same directory
in a file named factor31.py
that it would create a module named factor31. ???
From kent37 at tds.net Fri Jun 9 17:02:44 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 09 Jun 2006 11:02:44 -0400
Subject: [Tutor] file attribute of module
In-Reply-To: <44898A4E.00001D.00376@YOUR-4105E587B6>
References: <44898A4E.00001D.00376@YOUR-4105E587B6>
Message-ID: <44898D94.4030405@tds.net>
Kermit Rose wrote:
>>>> factor30.__file__
> 'c:\\math\\factoring\\factor30.py'
>
> Ok. Now I understand it.
>
> The module is named factor30.
>
> The file is named factor30.py
>
> I presume that if I created another library in the same directory
> in a file named factor31.py
> that it would create a module named factor31. ???
Yes. Try it and see!
Kent
From paul.kraus at gmail.com Fri Jun 9 17:02:50 2006
From: paul.kraus at gmail.com (Paul D. Kraus)
Date: Fri, 9 Jun 2006 11:02:50 -0400
Subject: [Tutor] pyexcelerator
Message-ID: <4e2aea430606090802o2da53fa2tfa5b364e2ba8ea52@mail.gmail.com>
Are their docs anywhere for pyexcelerator? the built in docs are a bit
lacking.
For instance I can't figure out how to set a column width.
I am just reading the examples and they kind of help but I don't follow this
...
ws.col(i).width = 0x0d00 + i
where i is an incrementing integer.
so to me it reads if i = 0.
set col 0's width to hexnumber plus 0
why the hex number? does it have to be written this way?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060609/bcf1f7db/attachment.htm
From kent37 at tds.net Fri Jun 9 17:20:17 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 09 Jun 2006 11:20:17 -0400
Subject: [Tutor] pyexcelerator
In-Reply-To: <4e2aea430606090802o2da53fa2tfa5b364e2ba8ea52@mail.gmail.com>
References: <4e2aea430606090802o2da53fa2tfa5b364e2ba8ea52@mail.gmail.com>
Message-ID: <448991B1.3070505@tds.net>
Paul D. Kraus wrote:
> Are their docs anywhere for pyexcelerator? the built in docs are a bit
> lacking.
>
> For instance I can't figure out how to set a column width.
> I am just reading the examples and they kind of help but I don't follow
> this ...
>
> ws.col(i).width = 0x0d00 + i
>
> where i is an incrementing integer.
> so to me it reads if i = 0.
>
> set col 0's width to hexnumber plus 0
>
> why the hex number? does it have to be written this way?
Maybe just try without the 0x0d00 and see what happens? or try the
pyExcelerator mailing list on SourceForge...
Kent
From doug.shawhan at gmail.com Fri Jun 9 17:46:25 2006
From: doug.shawhan at gmail.com (doug shawhan)
Date: Fri, 9 Jun 2006 10:46:25 -0500
Subject: [Tutor] errno vs. sys.exc_info
Message-ID: <5e1ceb8a0606090846s1dc4f45ei52ec6ecf851d9faf@mail.gmail.com>
I am in need of a clear way to return exceptions within a try loop.
I have been looking at both errno and sys.exc_info. I know that using errno
is not encouraged in threaded programs, but this is no big deal for my
purposes.
I found a good, clear example for translating the rather cryptic output from
sys.exc_info:
def formatExceptionInfo(maxTBlevel=5):
cla, exc, trbk = sys.exc_info()
excName = cla.__name__
try:
excArgs = exc.__dict__["args"]
except KeyError:
excArgs = ""
excTb = traceback.format_tb(trbk, maxTBlevel)
return (excName, excArgs, excTb)
Which seems to cover most of the bases, but I have yet to find a good
example of using errno.
Can someone provide a quick cut? :-)
Thanks!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060609/be906a2c/attachment.htm
From dkuhlman at rexx.com Fri Jun 9 17:57:59 2006
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Fri, 9 Jun 2006 08:57:59 -0700
Subject: [Tutor] making a python program part of xhtml
In-Reply-To:
References:
Message-ID: <20060609155759.GA90220@cutter.rexx.com>
On Fri, Jun 09, 2006 at 07:17:02AM -0400, Ron Phillips wrote:
> >>> Emily Fortuna < emily.fortuna at nist.gov > 6/8/2006 9:19 AM >>>
[snip]
> ... I _think_ I want to somehow
> embed the python into the page, but I'm really not sure how to do it.
> After googling I found some programs that generate xhtml from python,
> but I don't think that is what I want, or is it? Your help is
> appreciated!
> Emily
>
> You might look at http://karrigell.sourceforge.net/: karrigell lets you
> embed python in xhtml, xhtml in python, execute straight python scripts,
> or execute python from a karrigell application server. Even if you don't
> choose karrigell for some reason, at least the documentation can help
> you sort out the variations on the python/xhtml theme!
>
You may also want to visit the following Web page, then scroll
down and look for "Templating Engines":
http://wiki.python.org/moin/WebProgramming
Dave
--
Dave Kuhlman
http://www.rexx.com/~dkuhlman
From mail.roma1 at gmail.com Fri Jun 9 18:20:25 2006
From: mail.roma1 at gmail.com (Ivan Furone)
Date: Fri, 9 Jun 2006 18:20:25 +0200
Subject: [Tutor] layout ( i guess)
Message-ID: <6122a57a0606090920m5e13cab8i5e91d9eefb43c5e3@mail.gmail.com>
Desk Jet wrote:
> uh ive been wondering if with python you would be able to make layouts?
Hello,I premise that i don't get the exact meaning you are using for
'layouts',GUI-enabled applications (i.e. those with windows,buttons,progress
bars,notebooks..) could it be?
Well,sure Python can :) In the majority of case,programming graphical user
interfaces will require you to install additional packages,but there is one
that comes along with Python :
Tkinter.
Cheers,
Ivan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060609/d87384e6/attachment.html
From paul.kraus at gmail.com Fri Jun 9 19:34:32 2006
From: paul.kraus at gmail.com (Paul D. Kraus)
Date: Fri, 9 Jun 2006 13:34:32 -0400
Subject: [Tutor] pyexcelerator
In-Reply-To: <448991B1.3070505@tds.net>
References: <4e2aea430606090802o2da53fa2tfa5b364e2ba8ea52@mail.gmail.com>
<448991B1.3070505@tds.net>
Message-ID: <4e2aea430606091034s413df90ve4c15703928eabab@mail.gmail.com>
>
>
> Maybe just try without the 0x0d00 and see what happens? or try the
> pyExcelerator mailing list on SourceForge...
Mailing list looks dead only 2 messages.
Man this is the exact module i need to finish converting about 20 scripts
from perl and I have no idea how to use most of it. This is very
frustrating.
Is there another excel writer module that has documentation?
Or on a broader topic is their a CPAN equivalent?
Paul
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060609/4becd62d/attachment.html
From Barry.Carroll at psc.com Fri Jun 9 19:33:24 2006
From: Barry.Carroll at psc.com (Carroll, Barry)
Date: Fri, 9 Jun 2006 10:33:24 -0700
Subject: [Tutor] Files and Modules
Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C36B5@eugsrv400.psc.pscnet.com>
Kermit:
> ------------------------------
>
> Message: 7
> Date: Fri, 09 Jun 2006 11:02:44 -0400
> From: Kent Johnson
> Subject: Re: [Tutor] file attribute of module
> Cc: tutor at python.org
> Message-ID: <44898D94.4030405 at tds.net>
> Content-Type: text/plain; charset=ISO-8859-1; format=flowed
>
> Kermit Rose wrote:
> >>>> factor30.__file__
> > 'c:\\math\\factoring\\factor30.py'
> >
> > Ok. Now I understand it.
> >
> > The module is named factor30.
> >
> > The file is named factor30.py
> >
> > I presume that if I created another library in the same directory
> > in a file named factor31.py
> > that it would create a module named factor31. ???
>
> Yes. Try it and see!
>
> Kent
>
If by "it" you mean "Python", you are correct. As you are finding out,
the distinction between 'file' and 'module' in Python is subtle but
important. The words are often used synonymously, but they actually
have very different meanings. Here is the best short description I have
found of the distinction. It is from
Learning Python, 2nd Edition
By David Ascher, Mark Lutz
Publisher: O'Reilly
Modules are probably best understood as simply packages
of
names-places to define names you want to make visible to
the
rest of a system. In Python, modules are a namespace-a
place
where names are created. Names that live in a module are
called
its attributes. Technically, modules usually correspond
to
files, and Python creates a module object to contain all
the
names assigned in the file; but in simple terms, modules
are
just namespaces.
So, in your example above, Python uses the contents of the file
"factor31.py" to create the module "factor31".
As others have hinted, Python can use things other than files, and types
of files other than "???.py", to make a module, but you don't need to
worry about that yet.
HTH.
Barry
barry.carroll at psc.com
541-302-1107
________________________
We who cut mere stones must always be envisioning cathedrals.
-Quarry worker's creed
From kent37 at tds.net Fri Jun 9 19:52:53 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 09 Jun 2006 13:52:53 -0400
Subject: [Tutor] pyexcelerator
In-Reply-To: <4e2aea430606091034s413df90ve4c15703928eabab@mail.gmail.com>
References: <4e2aea430606090802o2da53fa2tfa5b364e2ba8ea52@mail.gmail.com>
<448991B1.3070505@tds.net>
<4e2aea430606091034s413df90ve4c15703928eabab@mail.gmail.com>
Message-ID: <4489B575.3080809@tds.net>
Paul D. Kraus wrote:
>
> Maybe just try without the 0x0d00 and see what happens? or try the
> pyExcelerator mailing list on SourceForge...
>
>
> Mailing list looks dead only 2 messages.
> Man this is the exact module i need to finish converting about 20
> scripts from perl and I have no idea how to use most of it. This is very
> frustrating.
>
> Is there another excel writer module that has documentation?
If you are running on Windows and have Excel installed you can talk to
Excel using COM. Take a look here:
http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.html
If no one on tutor knows about this you can probably get help with COM
on the python-win32 list or comp.lang.python.
Kent
From jeffpeery at yahoo.com Fri Jun 9 20:06:38 2006
From: jeffpeery at yahoo.com (Jeff Peery)
Date: Fri, 9 Jun 2006 11:06:38 -0700 (PDT)
Subject: [Tutor] numpy speed problems
Message-ID: <20060609180638.42689.qmail@web30505.mail.mud.yahoo.com>
hello, I am having some trouble with the speed of numpy. I'm crunching some numbers (see the attached script) and in total I have 1,000,000 grid points over which I am integrating. I'm doing a bunch of adding, mulitply, divide, powers, etc, but in total there are 1,000,000 points to do these operations over and it really shouldn't take this long... as far as I know. my last simulation took about 8+ hours.
What might I be doing wrong in my code to cause this to be so slow? big thanks!!
Jeff
__________________________________________________
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
http://mail.yahoo.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060609/e24716e2/attachment.htm
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: HW 5c.py
Url: http://mail.python.org/pipermail/tutor/attachments/20060609/e24716e2/attachment.asc
From bgailer at alum.rpi.edu Fri Jun 9 20:34:55 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Fri, 09 Jun 2006 11:34:55 -0700
Subject: [Tutor] pyexcelerator
In-Reply-To: <4e2aea430606090802o2da53fa2tfa5b364e2ba8ea52@mail.gmail.com>
References: <4e2aea430606090802o2da53fa2tfa5b364e2ba8ea52@mail.gmail.com>
Message-ID: <4489BF4F.7000102@alum.rpi.edu>
Paul D. Kraus wrote:
> Are their docs anywhere for pyexcelerator? the built in docs are a bit
> lacking.
>
> For instance I can't figure out how to set a column width.
> I am just reading the examples and they kind of help but I don't
> follow this ...
>
> ws.col(i).width = 0x0d00 + i
>
> where i is an incrementing integer.
> so to me it reads if i = 0.
>
> set col 0's width to hexnumber plus 0
>
> why the hex number? does it have to be written this way?
Nothing has to be written in hex. Judging from some of the modules the
author used hex a lot.
I just looked at my copy of PyExcelerator. It seems to be in poor shape.
I tried running some of the modules that have if __name__ == '__main__':
(i.e. self-testing) and they failed with errors! And I find no visible
documentation or working examples. Sigh.
The only thing I've used it for is parsing an existing Excel Workbook.
--
Bob Gailer
510-978-4454
From cspears2002 at yahoo.com Fri Jun 9 20:35:45 2006
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Fri, 9 Jun 2006 11:35:45 -0700 (PDT)
Subject: [Tutor] problems using PyGTK on cygwin
Message-ID: <20060609183545.74165.qmail@web51609.mail.yahoo.com>
I have been trying to work throught the PyGTK tutorial
using cygwin, but I have been having problems. For
example when I try to launch the helloworld.py program
(http://www.pygtk.org/pygtk2tutorial/ch-GettingStarted.html#sec-HelloWorld),
I get this:
$ python helloworld.py
No fonts found; this probably means that the
fontconfig
library is not correctly configured. You may need to
edit the fonts.conf configuration file. More
information
about fontconfig can be found in the fontconfig(3)
manual
page and on http://fontconfig.org
I located the files, but the content is Greek to me!
Likewise, I tried running pygtkconsole.py program
(http://www.pygtk.org/pygtk2tutorial/examples/pygtkconsole.py)
and got
$ python pygtkconsole.py
5 [main] python2.4 1360
C:\cygwin\bin\python2.4.exe: *** fatal error - unable
to remap C:\cygwin\usr\X11R6\bin\cygXcursor-1.dll to
same address as parent(0x18870000) != 0x188A0000
6 [main] python 1588 child_copy: loaded dll data
write copy failed, 0x60084000..0x60085150, done 0,
windows pid 2286452, Win32 error 5
Traceback (most recent call last):
File "pygtkconsole.py", line 119, in ?
interact()
File "pygtkconsole.py", line 101, in interact
gi = GtkInterpreter()
File "pygtkconsole.py", line 81, in __init__
child_pid = os.fork()
OSError: [Errno 11] Resource temporarily unavailable
Any suggestions? I have been seriously thinking of
just downloading PyGTK for Windows instead of trying
to run it in the faux Unix environment of cygwin.
-Chris
From bgailer at alum.rpi.edu Fri Jun 9 20:44:44 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Fri, 09 Jun 2006 11:44:44 -0700
Subject: [Tutor] pyexcelerator CORRECTION
In-Reply-To: <4489BF4F.7000102@alum.rpi.edu>
References: <4e2aea430606090802o2da53fa2tfa5b364e2ba8ea52@mail.gmail.com>
<4489BF4F.7000102@alum.rpi.edu>
Message-ID: <4489C19C.10601@alum.rpi.edu>
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060609/03abed3b/attachment.htm
From paul.kraus at gmail.com Fri Jun 9 20:52:57 2006
From: paul.kraus at gmail.com (Paul D. Kraus)
Date: Fri, 9 Jun 2006 14:52:57 -0400
Subject: [Tutor] pyexcelerator
In-Reply-To: <4489BF4F.7000102@alum.rpi.edu>
References: <4e2aea430606090802o2da53fa2tfa5b364e2ba8ea52@mail.gmail.com>
<4489BF4F.7000102@alum.rpi.edu>
Message-ID: <4e2aea430606091152sc5ac5a2rc9ed426daa4f75b3@mail.gmail.com>
>
>
>
> I just looked at my copy of PyExcelerator. It seems to be in poor shape.
> I tried running some of the modules that have if __name__ == '__main__':
> (i.e. self-testing) and they failed with errors! And I find no visible
> documentation or working examples. Sigh.
>
You might want to check out the recent source from sourceforge its seems
very functional and it has a bunch of examples. Not very useful for ones as
far as I am concrened.
I have not tried to run the modules by themselves.
I hate the idea of having to pass or make a call to a perl script to handle
the excel stuff its just seems wrong. I wish there was some kind of *open*
format that i could write the spreadsheets to that both open office and
excel 2000/2003 could read natively.
Paul
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060609/c31f1bdc/attachment.html
From bgailer at alum.rpi.edu Fri Jun 9 20:57:32 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Fri, 09 Jun 2006 11:57:32 -0700
Subject: [Tutor] numpy speed problems
In-Reply-To: <20060609180638.42689.qmail@web30505.mail.mud.yahoo.com>
References: <20060609180638.42689.qmail@web30505.mail.mud.yahoo.com>
Message-ID: <4489C49C.8040800@alum.rpi.edu>
Jeff Peery wrote:
> hello, I am having some trouble with the speed of numpy. I'm crunching
> some numbers (see the attached script) and in total I have 1,000,000
> grid points over which I am integrating. I'm doing a bunch of adding,
> mulitply, divide, powers, etc, but in total there are 1,000,000 points
> to do these operations over and it really shouldn't take this long...
> as far as I know. my last simulation took about 8+ hours.
>
> What might I be doing wrong in my code to cause this to be so slow?
> big thanks!!
I don't have time to analyze all your code but I'll point out that it is
repeating some calculations many times. Example:
x_coord[ii])**2.0
y_coord[jj])**2.0
are calculated every time GetPressure is called. I suggest you calculate
these one time outside any loops and pass the result into GetPressure.
Inside GetPressure:
1j*w_mn*rho
exp(1j*k_mn*r)*dx*dy/(2.0*pi*r
are repeatedly calculated inside the for loop. Move them out of the loop.
Then look for other "loop invariants".
sin(n[mode_n]*pi*(L/2.0+x_coord[i]))*sin(m[mode_m]*pi*(W/2.0+y_coord[j]))
is another place to look.
>
> ------------------------------------------------------------------------
>
> from numpy import *
>
> """
> function definitions
> """
> def GetPressure(x_coord, y_coord, x_r, y_r, z_r, dx, dy, w_mn, rho, v_mn, k_mn, n, m):
> # intialize pressure
> p = 0.0 + 1j
>
> # sum contributions from all point sources to receiver
> for ii in range(n):
> for jj in range(m):
> r = ((x_r - x_coord[ii])**2.0 + (y_r - y_coord[jj])**2.0 + (z_r - 0.0)**2)**0.5
> p += (1j*w_mn*rho*v_mn[ii][jj])*exp(1j*k_mn*r)*dx*dy/(2.0*pi*r)
>
> p = sqrt(p*conjugate(p))
> return abs(p)
>
>
> """
> vaiables and constants
> """
>
> """problem definition parameter"""
> n = arange(1,70) #mode number in x direction
> m = arange(1,70) #mode number in y direction
> mode_n = 10 #mode number - 1
> mode_m = 10 #mode number - 1
> L = 1.2 #piston length (m)
> W = 0.6 #piston width (m)
>
> """material properties fluid"""
> c = 343.0 #speed sound in water (m/s)
> rho_a = 1.21 #density of air (kg/m^3)
>
> """piston material properties"""
> E = 7.0e10 #youngs modulus (N/m^2) (stainless steel)
> nu = 0.29 #poisson's ratio (stainless steel
> rho = 2700.0 #density of piston (stainless steel) (kg/m^3)
> t = 0.0015 #piston thickness (m)
>
> """wave speed, wave number, frequency"""
> c_l = (E/(rho*(1 - nu**2)))**0.5 #longitudinal wave speed in piston
> k_x = n*pi/W #wave number x direction
> k_y = m*pi/L #wave number y direction
> k_mn = (k_x[mode_n]**2 + k_y[mode_m]**2)**0.5 #bending wave number for n and m mode
> w_c = (c**2)/(1.8*c_l*t) #critical frequency (Hz)
> w_mn = (k_mn**2)*1.8*c_l*t/(2.0*pi)**2 #frequency for n and m (see notes 5/15/06)
> k_c = 2.0*pi*(w_c/(1.8*c_l*t))**0.5 #critical wave number
> k_a = 2.0*pi*w_mn/c #wave number in acoustic medium (air)
>
> """piston grid"""
> dx = 1.0/k_a #x direction step in space (m)
> dy = 1.0/k_a #y direction step in space (m)
>
> if dx < 0.005:
> dx = 0.005
> dy = 0.005
>
> num_y = int(L/dy) #number of nodes in y direction
> num_x = int(W/dx) #number of nodes in x direction
>
> #piston grid coordinates
> x_coord = arange(num_x, dtype=float)*W/num_x - W/2.0
> y_coord = arange(num_y, dtype=float)*L/num_y - L/2.0
>
> """field grid"""
> a = 1
> b = 50
> d = 50
> x_r = arange(a, dtype=float)*1.0/float(a) #x position of receiver (m)
> y_r = arange(b, dtype=float)*1.0/float(b) #y position of receiver (m)
> z_r = arange(d, dtype=float)*10.0/float(d) #z position of receiver (m)
>
> """acoustic variables"""
> p = 0 #amplitude of pressure at receiver (Pa)
> r = 0 #distance from origin to receiver (m)
> p_field = zeros((a,b,d), dtype=float) #pressure field (m)
>
> """calculate piston surface velocity amplitude"""
> U_mn = zeros((len(x_coord), len(y_coord)), dtype=float)
> for i in range(len(x_coord)):
> for j in range(len(y_coord)):
> #amplitude of piston surface displacement
> U_mn[i][j] = sin(n[mode_n]*pi*(L/2.0+x_coord[i]))*sin(m[mode_m]*pi*(W/2.0+y_coord[j]))
> #amplitude of piston surface velocity (m/s)
> V_mn = w_mn*U_mn
>
>
> """
> numerical integration of Raleigh's equation
> """
> for i in range(a):
> for j in range(b):
> for k in range(d):
> p_field[i][j][k] = GetPressure(x_coord, y_coord, x_r[i], y_r[j], z_r[k], dx, dy, w_mn, rho, V_mn, k_mn, num_x, num_y)
> print '%d Percent Complete'%(100.0*j/b)
>
> p_field = 20.0*log10(p_field)
>
> fileHandle = file('beam pattern.dat', "w")
> fileHandle.write('TITLE = "HW 4"\n')
> fileHandle.write('VARIABLES = "x"\n"y"\n"z"\n"pressure"\n')
> fileHandle.write('ZONE T="%s"\n' % 'pressure field')
> fileHandle.write('I=%d, J=1, ZONETYPE=Ordered\n' % (a*b*d))
> fileHandle.write('DATAPACKING=POINT DT=(DOUBLE DOUBLE DOUBLE DOUBLE)\n')
> for ii in range(a):
> for jj in range(b):
> for kk in range(d):
> fileHandle.write('%f %f %f %f\n' % (x_r[ii], y_r[jj], z_r[kk], p_field[ii][jj][kk]))
> fileHandle.close()
>
>
>
> """
> contour of surface velocity
> """
>
> fileHandle = file('mode shape.dat', "w")
> fileHandle.write('TITLE = "HW 4"\n')
> fileHandle.write('VARIABLES = "x"\n"y"\n"velocity"\n')
> fileHandle.write('ZONE T="%s"\n' % 'velocity field')
> fileHandle.write('I=%d, J=1, ZONETYPE=Ordered\n' % (num_y*num_x))
> fileHandle.write('DATAPACKING=POINT DT=(DOUBLE DOUBLE DOUBLE)\n')
> for ii in range(num_x):
> for jj in range(num_y):
> fileHandle.write('%f %f %f\n' % (x_coord[ii], y_coord[jj], V_mn[ii][jj]))
> fileHandle.close()
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
--
Bob Gailer
510-978-4454
From 3dbernard at gmail.com Fri Jun 9 21:38:58 2006
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Fri, 9 Jun 2006 15:38:58 -0400
Subject: [Tutor] Difference between popens
Message-ID: <61d0e2b40606091238s43bfbf0am17075776829b5d3c@mail.gmail.com>
Hi,
I'd like to know what are the differences at the various os.popenX
flavors. I read the documentation and I can see they return file
objects..... so what can you do with these file objects? I mean, why
would you need a set of file objects rather than another?
Sorry the difference is very not clear to me.
Thanks
Bernard
From michael at espersunited.com Fri Jun 9 21:42:25 2006
From: michael at espersunited.com (Michael Sullivan)
Date: Fri, 09 Jun 2006 14:42:25 -0500
Subject: [Tutor] An Introduction and a question
Message-ID: <1149882145.10792.37.camel@camille.espersunited.com>
My name is Michael Sullivan. I am a 26 year-old college student in
Oklahoma. My wife and I have a small (three PCs) computer network that
we operate out of our home. We have our own domain (as one could tell
by examining my email address) I have novice-level experience with VB,
C/C++, Java, and PHP, but I'm just starting out with Python.
Here's the situation: My wife likes to play the game Chuzzle, found at
Yahoo Games. We use primarily Linux, however Chuzzle is written as an
ActiveX control, which only works on Windows. I have not been able to
get Internet Explorer to work correctly through Wine, so I determined to
write a Chuzzle-like game (with many of my own enhancements) for Linux.
I've been playing around with some Pygame examples lately, and thought
that I'd try writing the game in Python (I've been meaning to learn
Python for years, but just never got around to it.) Today I started on
writing the game. I've decided (at least for now) to call my version,
LinePuzzle. For those of you unfamiliar with Chuzzle, here's the basic
concept: There are individual pieces of different colors arranged on a
grid. The pieces can be moved on a line either vertically or
horizontally. The object of the game is to position three similarly
colored pieces ajacent to each other. At this point the three pieces
will disappear, and the pieces above them will fall to take their place.
As the levels progress, locks are added so that the player cannot move a
locked piece either horizontally or vertically. The game is over when
no more pieces can be removed.
I started my script by creating a class called LinePuzzlePiece which
represents a single coloured piece. I wanted a random colour chosen
from a list to be assigned to the piece, and then to prove that I had it
set up correctly, I wanted to call a method that would print out the
color of the piece. Here is my code:
#!/usr/bin/env python
import random
import time
import math
class LinePuzzlePiece:
"""This class defines a single playing piece for LinePuzzle"""
def __init__(self):
seed(time)
index = int(math.floor(uniform(1, 10))) colorlist = ["red",
"blue", "green" "yellow", "purple"] self.color = colorlist[index]
def printcolor():
print self.color
mypiece = LinePuzzlePiece
mypiece.printcolor
I saved the script and made it chmod +x. However, when I run it, I get
this:
michael at camille ~ $ ./linepuzzle.py
michael at camille ~ $
Now, I'm no expert, but I really think something should have been
printed, if even a blank line. What am I doing wrong here? Why is
nothing printing? Is my printcolor method even being called
successfully?
-Michael Sullivan-
From andre.roberge at gmail.com Fri Jun 9 22:00:48 2006
From: andre.roberge at gmail.com (Andre Roberge)
Date: Fri, 9 Jun 2006 17:00:48 -0300
Subject: [Tutor] An Introduction and a question
In-Reply-To: <1149882145.10792.37.camel@camille.espersunited.com>
References: <1149882145.10792.37.camel@camille.espersunited.com>
Message-ID: <7528bcdd0606091300p2bd41ee6je99c14b153a3565b@mail.gmail.com>
On 6/9/06, Michael Sullivan wrote:
> My name is Michael Sullivan. I am a 26 year-old college student in
> Oklahoma. My wife and I have a small (three PCs) computer network that
> we operate out of our home. We have our own domain (as one could tell
> by examining my email address) I have novice-level experience with VB,
> C/C++, Java, and PHP, but I'm just starting out with Python.
>
> Here's the situation: My wife likes to play the game Chuzzle, found at
> Yahoo Games. We use primarily Linux, however Chuzzle is written as an
> ActiveX control, which only works on Windows. I have not been able to
> get Internet Explorer to work correctly through Wine, so I determined to
> write a Chuzzle-like game (with many of my own enhancements) for Linux.
> I've been playing around with some Pygame examples lately, and thought
> that I'd try writing the game in Python (I've been meaning to learn
> Python for years, but just never got around to it.) Today I started on
> writing the game. I've decided (at least for now) to call my version,
> LinePuzzle. For those of you unfamiliar with Chuzzle, here's the basic
> concept: There are individual pieces of different colors arranged on a
> grid. The pieces can be moved on a line either vertically or
> horizontally. The object of the game is to position three similarly
> colored pieces ajacent to each other. At this point the three pieces
> will disappear, and the pieces above them will fall to take their place.
> As the levels progress, locks are added so that the player cannot move a
> locked piece either horizontally or vertically. The game is over when
> no more pieces can be removed.
>
> I started my script by creating a class called LinePuzzlePiece which
> represents a single coloured piece. I wanted a random colour chosen
> from a list to be assigned to the piece, and then to prove that I had it
> set up correctly, I wanted to call a method that would print out the
> color of the piece. Here is my code:
>
> #!/usr/bin/env python
>
> import random
> import time
> import math
>
> class LinePuzzlePiece:
> """This class defines a single playing piece for LinePuzzle"""
> def __init__(self):
> seed(time)
> index = int(math.floor(uniform(1, 10))) colorlist = ["red",
> "blue", "green" "yellow", "purple"] self.color = colorlist[index]
>
> def printcolor():
> print self.color
>
> mypiece = LinePuzzlePiece
> mypiece.printcolor
>
1. try mypiece.printcolor() instead.
2. I'm cc-ing the pygame user group. I suggest that future questions
related to pygame be sent over to that group instead. They are just
as friendly as the folks on the tutor list.
Andr?
>
> I saved the script and made it chmod +x. However, when I run it, I get
> this:
>
> michael at camille ~ $ ./linepuzzle.py
> michael at camille ~ $
>
> Now, I'm no expert, but I really think something should have been
> printed, if even a blank line. What am I doing wrong here? Why is
> nothing printing? Is my printcolor method even being called
> successfully?
> -Michael Sullivan-
>
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
From kent37 at tds.net Fri Jun 9 22:08:25 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 09 Jun 2006 16:08:25 -0400
Subject: [Tutor] An Introduction and a question
In-Reply-To: <1149882145.10792.37.camel@camille.espersunited.com>
References: <1149882145.10792.37.camel@camille.espersunited.com>
Message-ID: <4489D539.9020402@tds.net>
Michael Sullivan wrote:
> Here is my code:
>
> #!/usr/bin/env python
>
> import random
> import time
> import math
>
> class LinePuzzlePiece:
> """This class defines a single playing piece for LinePuzzle"""
> def __init__(self):
> seed(time)
> index = int(math.floor(uniform(1, 10))) colorlist = ["red",
> "blue", "green" "yellow", "purple"] self.color = colorlist[index]
>
> def printcolor():
> print self.color
>
> mypiece = LinePuzzlePiece
> mypiece.printcolor
>
>
> I saved the script and made it chmod +x. However, when I run it, I get
> this:
>
> michael at camille ~ $ ./linepuzzle.py
> michael at camille ~ $
>
> Now, I'm no expert, but I really think something should have been
> printed, if even a blank line. What am I doing wrong here? Why is
> nothing printing? Is my printcolor method even being called
> successfully?
No, you have not created a LinePuzzlePiece or called printcolor.
In Python, parentheses are required for function calls. A class or
function name without the parentheses is a reference to the class or
function object itself, not a call to the object. This can be very
useful but it's not what you want!
mypiece = LinePuzzlePiece # This makes mypiece refer to the class, not
an instace
mypiece.printcolor # This is a reference to a method of the class, but
you don't do anything with the reference
What you really want:
mypiece = LinePuzzlePiece()
mypiece.printcolor()
Kent
From paul.kraus at gmail.com Fri Jun 9 22:41:40 2006
From: paul.kraus at gmail.com (Paul D. Kraus)
Date: Fri, 9 Jun 2006 16:41:40 -0400
Subject: [Tutor] Function list that might have a tuple that might have one
of its indexs set to 's'
Message-ID: <4e2aea430606091341m19267352s32b1051c96ccde09@mail.gmail.com>
I am writing my first python program(at least in a really long time). Its
purpose is to take csv or pipe delimintaed files and convert them to html
pages. Was going to be excel but its just not worth the headache. Everyone
viewing the reports is doing just that viewing simple tables.
I need to scan through a list that contains headers to my table.
If one of the elements is a tuple and one of the elements of the tuple is
"s" set self.sort to the index of the tuple in the header list and then
replace the element in header with a two field tuple containing everything
that was not 's'.
header = ['my first column',('my second num column','s','r'),(' my third num
column','r') ]
I pass header to a function actually a method but lets pretend its just a
plain old function. Be careful reading the below code may cause random
strokes. I have woken up twice laying on the floor disoriented.... :)
Actual code in my working example used to call function ...
report.set_header(
['','Ext','Name','',('Calls','r','s'),('Ring','r'),('Talk','r'),('Wait','r'),('Max
Talk','r') ] )
def set_header(self,header):
list = []
for cindex in range(len(header)):
if type(()) == type(header[cindex]):
for index in range(len(header[cindex]) ):
if header[cindex][index] == 's':
self.sort = cindex
for tindex in range(len(header[cindex])):
if tindex != index: list.append
(header[cindex][tindex])
header[cindex] = tuple(list)
self.header = header
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060609/af757925/attachment.htm
From dkuhlman at rexx.com Fri Jun 9 23:26:52 2006
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Fri, 9 Jun 2006 14:26:52 -0700
Subject: [Tutor] Difference between popens
In-Reply-To: <61d0e2b40606091238s43bfbf0am17075776829b5d3c@mail.gmail.com>
References: <61d0e2b40606091238s43bfbf0am17075776829b5d3c@mail.gmail.com>
Message-ID: <20060609212652.GB92694@cutter.rexx.com>
On Fri, Jun 09, 2006 at 03:38:58PM -0400, Bernard Lebel wrote:
> Hi,
>
> I'd like to know what are the differences at the various os.popenX
> flavors. I read the documentation and I can see they return file
> objects..... so what can you do with these file objects? I mean, why
> would you need a set of file objects rather than another?
>
See documentation at
http://docs.python.org/lib/os-newstreams.html#l2h-1552.
And, notice how the return values from the various versions of
popen are different file types: stdin, stdout, and stderr.
A summary:
- popen() gives you either an input pipe (stdin) or an output
pipe (stdout) but not both.
- popen2() gives you both an input pipe (stdin) and output pipe
(stdout).
- popen3() gives you an input pipe (stdin) and output pipe
(stdout) and an error pipe (stderr).
- popen4() gives you an input pipe and a pipe that combines output
and errors (stdout and stderr).
Specifically, if you want to run a command, just like you would
with os.system(), but:
1. You want to *either* feed (pipe) text to your command *or* read
results from your command, use os.popen() and use mode= 'w' or
'r'.
2. You want to both feed (pipe) text to your command *and* read
results from your command, use os.popen2().
Etc.
If you get an input pipe, you should write text to that pipe, then
close that stream. Doing close() is what triggers execution of the
command.
If you get an output pipe, then (after the command runs), read
from that pipe to get the results of your command (i.e. the text
that the command wrote to stdout).
Here is a simple example that uses popen2::
import os
def test():
instream, outstream = os.popen2('grep dave')
instream.write('Line #1\n')
instream.write('Line #2 dave is here\n')
instream.write('Line #3\n')
instream.write('Line #4 dave is also here\n')
instream.write('Line #5\n')
instream.close()
for line in outstream:
print 'Line: %s' % line.rstrip()
test()
Note that there is also a popen module, which has functions with
the same names and functionality:
"This functionality is also available in the popen2 module
using functions of the same names, but the return values of
those functions have a different order."
See: http://docs.python.org/lib/module-popen2.html
Hope this helps.
Dave
--
Dave Kuhlman
http://www.rexx.com/~dkuhlman
From 3dbernard at gmail.com Fri Jun 9 23:27:37 2006
From: 3dbernard at gmail.com (Bernard Lebel)
Date: Fri, 9 Jun 2006 17:27:37 -0400
Subject: [Tutor] Difference between popens
In-Reply-To: <7e5ba9220606091423r4b16b548m48546a401c718abe@mail.gmail.com>
References: <61d0e2b40606091238s43bfbf0am17075776829b5d3c@mail.gmail.com>
<7e5ba9220606091423r4b16b548m48546a401c718abe@mail.gmail.com>
Message-ID: <61d0e2b40606091427y3c7cabcax94e28c5c0f60d4cb@mail.gmail.com>
Hey, thanks for the nice explanation Michael!
Bernard
On 6/9/06, Michael P. Reilly wrote:
> Excuse the slightly pedantic discussion before I get to a real-world
> example, but the differences get into something a bit deeper than Python and
> into what is called "interprocess communication". Each program that's
> running has an input data stream and an output data steam and on many modern
> computer systems there is a third stream for error messages. The idea is
> that the program doesn't need to know that the input is coming from a user
> or a keyboard; it could be coming from a file or another program - the
> program shouldn't care. The same thing with the output and the error
> messages.
>
> These three data streams have traditionally been called "stdin" (standard
> input), "stdout" (standard output) and "stderr" (standard error). And in
> Python, they are known by the same names in the 'sys' module.
>
> Now before I said that the concept of these is that the program should not
> care where its data is going to or coming from, including another program.
> This is where interprocess communication comes into play. Specifically,
> this is accomplished with a data construct called "pipes" (the name 'popen'
> comes from "pipe open" in the C world, akin to 'fopen' for "file open").
> Pipes are created between the programs to redirect data between inputs and
> outputs. The most well known and viewed form of this is the vertical bar
> "|" on command-lines in UNIX, then DOS had to adopt it: type README.txt |
> more.
>
> Back to the question at hand: why and how would you use the files returned.
> Let's say you have a large dictionary of values in your Python program, and
> the system has a very nice spelling program out there. You would like to
> use that program so you don't have to write you own routine. How the
> spelling program is normally called is that words are sent to its standard
> input (stdin) stream, separated by newlines, and the misspelled words are
> printed on its stdout, also separated by newlines. We want to start the
> program (called "spawning"), write our dictionary values to its stdin and
> read its stdout. For this, we need to gain access to the program's stdin
> and stdout. Since we are spawning it, it is called our "child" process.
>
> def verify_dictionary(dict_o_words):
> reverse_dict = {} # to get back to the keys
> (child_stdin, child_stdout) = os.popen2('spell')
> for (key, value) in dict_o_words.items():
> if reverse_dict.has_key(value):
> reverse_dict[value].append(key)
> else:
> reverse_dict[value] = [key]
> child_stdin.write('%s\n' % value)
> child_stdin.close() # close the data stream to tell other program we're
> finished
> misspellings = []
> for line in child_stdout.readlines():
> value = line.strip()
> if reverse_dict.has_key(value):
> misspellings.extend(reverse_dict[value])
> close_stdout.close() # tells other program we're finished reading from
> it
> return misspellings
>
> I hope this discussion answers your questions and hasn't been too beneath
> you. :) Some of it might be arcane history now, but I always feel it is
> good to know the roots to understand where you are going.
> -Michael
>
>
> On 6/9/06, Bernard Lebel <3dbernard at gmail.com> wrote:
> >
> Hi,
>
> I'd like to know what are the differences at the various os.popenX
> flavors. I read the documentation and I can see they return file
> objects..... so what can you do with these file objects? I mean, why
> would you need a set of file objects rather than another?
>
> Sorry the difference is very not clear to me.
>
>
> Thanks
> Bernard
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
> --
> There's so many different worlds,
> So many different suns.
> And we have just one world,
> But we live in different ones.
From michael at espersunited.com Fri Jun 9 23:28:43 2006
From: michael at espersunited.com (Michael Sullivan)
Date: Fri, 09 Jun 2006 16:28:43 -0500
Subject: [Tutor] An Introduction and a question (continuing)
In-Reply-To: <1149882145.10792.37.camel@camille.espersunited.com>
References: <1149882145.10792.37.camel@camille.espersunited.com>
Message-ID: <1149888523.10792.50.camel@camille.espersunited.com>
OK. I've got it working this far. Now I want the script to generate
eight pieces, each with a random colour. Here's my current code:
#!/usr/bin/env python
import random
import time
import math
class LinePuzzlePiece:
"""This class defines a single playing piece for LinePuzzle"""
def __init__(self):
random.seed(time)
index = int(math.floor(random.uniform(0, 8)))
colorlist = ["red", "blue", "green", "yellow", "purple", "cyan",
"orange", "white"]
self.color = colorlist[index]
def printcolor(self):
print self.color
piececount = 0
mypiece = ["", "", "", "", "", "", "", "", ""]
while (piececount < 9):
mypiece[piececount] = LinePuzzlePiece()
mypiece[piececount].printcolor()
piececount += 1
The problem is that while eight pieces are created and assigned a
colour, the colour is always the same. I need the colours of the pieces
to be in a somewhat random order. What am I doing wrong?
From dkuhlman at rexx.com Fri Jun 9 23:33:18 2006
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Fri, 9 Jun 2006 14:33:18 -0700
Subject: [Tutor] numpy speed problems
In-Reply-To: <4489C49C.8040800@alum.rpi.edu>
References: <20060609180638.42689.qmail@web30505.mail.mud.yahoo.com>
<4489C49C.8040800@alum.rpi.edu>
Message-ID: <20060609213318.GC92694@cutter.rexx.com>
On Fri, Jun 09, 2006 at 11:57:32AM -0700, Bob Gailer wrote:
> Jeff Peery wrote:
> > hello, I am having some trouble with the speed of numpy. I'm crunching
> > some numbers (see the attached script) and in total I have 1,000,000
> > grid points over which I am integrating. I'm doing a bunch of adding,
> > mulitply, divide, powers, etc, but in total there are 1,000,000 points
> > to do these operations over and it really shouldn't take this long...
> > as far as I know. my last simulation took about 8+ hours.
> >
> > What might I be doing wrong in my code to cause this to be so slow?
> > big thanks!!
> I don't have time to analyze all your code but I'll point out that it is
> repeating some calculations many times. Example:
>
> x_coord[ii])**2.0
> y_coord[jj])**2.0
>
>
> are calculated every time GetPressure is called. I suggest you calculate
> these one time outside any loops and pass the result into GetPressure.
>
> Inside GetPressure:
>
> 1j*w_mn*rho
> exp(1j*k_mn*r)*dx*dy/(2.0*pi*r
>
>
> are repeatedly calculated inside the for loop. Move them out of the loop.
>
> Then look for other "loop invariants".
>
> sin(n[mode_n]*pi*(L/2.0+x_coord[i]))*sin(m[mode_m]*pi*(W/2.0+y_coord[j]))
>
> is another place to look.
>
Also, if you are serious about SciPy, NumPy, etc, be sure to visit
http://scipy.org/, *and* check into the mailing lists there.
That's not just for your benefit; if there are problems with
SciPy, the people at that list will want to know about them.
[snip]
Dave
--
Dave Kuhlman
http://www.rexx.com/~dkuhlman
From mail.roma1 at gmail.com Sat Jun 10 00:05:34 2006
From: mail.roma1 at gmail.com (Ivan Furone)
Date: Sat, 10 Jun 2006 00:05:34 +0200
Subject: [Tutor] Fwd: Difference between popens
In-Reply-To: <61d0e2b40606091238s43bfbf0am17075776829b5d3c@mail.gmail.com>
References: <61d0e2b40606091238s43bfbf0am17075776829b5d3c@mail.gmail.com>
Message-ID: <6122a57a0606091505p378d2edw279cbef337ae7da3@mail.gmail.com>
2006/6/9, Bernard Lebel <3dbernard at gmail.com>:
>
> Hi,
>
> I'd like to know what are the differences at the various os.popenX
> flavors. I read the documentation and I can see they return file
> objects..... so what can you do with these file objects? I mean, why
> would you need a set of file objects rather than another?
>
> Sorry the difference is very not clear to me.
>
>
> Thanks
> Bernard
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
Hello,
The common idea behind the various popen implementation is to provide the
creation of pipes.A pipe is a flavor of a file object.A pipe serves the job
to address data from a process to another,but what if sometimes you want to
execute a command
out of the parent process on a child process?You should be able to issue the
command,catch the result and even to know which way the thing has ended,at
times.
If you are familiar with the concept of 'streams',the "input","output" and
"error" stream are the resource of communication provided by Unix to handle
these tasks,respectively.Nevertheless,at times you don't need to gather data
from all the streams,but just to control two of them out of three,for
example.The reason could be that of sparing system resources,time or just
that you don't need or want to.popen2,popen3 and popen4 are designed to
catch exactly the streams you want to control.So:
popen2:
returns the file objects corresponding to the child stdin and stdout;
popen3:
returns the file objects corresponding to the child stdin,stdout and stderr;
popen4:
returns the file objects corresponding to the child stdout and stderr (together
as a single object) and stdin.
The file objects,you see,are what you normally make use to manipulate data
within processes.
They are memory structures which assume peculiar names based on their type :
Queues,Semaphores,Pipes and so on...
And they can persist a) in the scope of a process b) of a machine session c)
on the filesystem (the strongest kind of persistence).
Choosing the right one for each task a matter depending on what you want to
do with them.
I recognize I'm not being exhaustive but hope that helps.
Cheers,
Ivan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060610/49c8ba12/attachment.html
From python at venix.com Sat Jun 10 00:10:28 2006
From: python at venix.com (Python)
Date: Fri, 09 Jun 2006 18:10:28 -0400
Subject: [Tutor] An Introduction and a question (continuing)
In-Reply-To: <1149888523.10792.50.camel@camille.espersunited.com>
References: <1149882145.10792.37.camel@camille.espersunited.com>
<1149888523.10792.50.camel@camille.espersunited.com>
Message-ID: <1149891028.24742.204.camel@www.venix.com>
On Fri, 2006-06-09 at 16:28 -0500, Michael Sullivan wrote:
> OK. I've got it working this far. Now I want the script to generate
> eight pieces, each with a random colour. Here's my current code:
>
> #!/usr/bin/env python
>
> import random
> import time
> import math
>
> class LinePuzzlePiece:
> """This class defines a single playing piece for LinePuzzle"""
> def __init__(self):
> random.seed(time)
The seed allows you to reuse a particular set of random numbers - which
can be highly useful in testing so that successive runs use the same
numbers. In general, there is no need to call seed.
You are calling seed with the same value every time, a reference to the
time module. You really wanted:
random.seed(time.time())
I'd recommend simply deleting the call to random.seed.
If you do find you want to re-use the same set of "random" numbers, call
seed once right after you import random with a known value. If your
computer really needs to call seed to randomize effectively, then you
can try seeding with time.time().
> index = int(math.floor(random.uniform(0, 8)))
> colorlist = ["red", "blue", "green", "yellow", "purple", "cyan",
> "orange", "white"]
> self.color = colorlist[index]
>
> def printcolor(self):
> print self.color
>
> piececount = 0
> mypiece = ["", "", "", "", "", "", "", "", ""]
> while (piececount < 9):
> mypiece[piececount] = LinePuzzlePiece()
> mypiece[piececount].printcolor()
> piececount += 1
A suggestion:
mypieces = [] # pluralize container names
piececount = 9
for x in range(piececount):
>
> The problem is that while eight pieces are created and assigned a
> colour, the colour is always the same. I need the colours of the pieces
> to be in a somewhat random order. What am I doing wrong?
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
--
Lloyd Kvam
Venix Corp
From bgailer at alum.rpi.edu Sat Jun 10 00:13:07 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Fri, 09 Jun 2006 15:13:07 -0700
Subject: [Tutor] An Introduction and a question (continuing)
In-Reply-To: <1149888523.10792.50.camel@camille.espersunited.com>
References: <1149882145.10792.37.camel@camille.espersunited.com>
<1149888523.10792.50.camel@camille.espersunited.com>
Message-ID: <4489F273.9050400@alum.rpi.edu>
Michael Sullivan wrote:
> OK. I've got it working this far. Now I want the script to generate
> eight pieces, each with a random colour. Here's my current code:
>
> #!/usr/bin/env python
>
> import random
> import time
> import math
>
> class LinePuzzlePiece:
> """This class defines a single playing piece for LinePuzzle"""
> def __init__(self):
> random.seed(time)
> index = int(math.floor(random.uniform(0, 8)))
> colorlist = ["red", "blue", "green", "yellow", "purple", "cyan",
> "orange", "white"]
> self.color = colorlist[index]
>
> def printcolor(self):
> print self.color
>
> piececount = 0
> mypiece = ["", "", "", "", "", "", "", "", ""]
> while (piececount < 9):
> mypiece[piececount] = LinePuzzlePiece()
> mypiece[piececount].printcolor()
> piececount += 1
>
> The problem is that while eight pieces are created and assigned a
> colour, the colour is always the same. I need the colours of the pieces
> to be in a somewhat random order. What am I doing wrong?
>
random.seed(time) sets the seed to the same value each time. (You are
passing a module object, whose ID becomes the seed). Try
random.seed(time.time()). Also you can set the seed once, then let each
call to uniform get the next "random" number.
Also consider:
mypiece = []
for piececount in range(8):
mypiece.append(LinePuzzlePiece())
mypiece[piececount].printcolor()
--
Bob Gailer
510-978-4454
Broadband Phone Service for local and long distance $19.95/mo plus 1 mo Free
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060609/e0b57ab8/attachment.htm
-------------- next part --------------
A non-text attachment was scrubbed...
Name: show
Type: image/gif
Size: 43 bytes
Desc: not available
Url : http://mail.python.org/pipermail/tutor/attachments/20060609/e0b57ab8/attachment.gif
From doug.shawhan at gmail.com Sat Jun 10 00:28:25 2006
From: doug.shawhan at gmail.com (doug shawhan)
Date: Fri, 9 Jun 2006 17:28:25 -0500
Subject: [Tutor] XML: Expletive Deleted
Message-ID: <5e1ceb8a0606091528i52471b44v228626e453343e4a@mail.gmail.com>
I realize XML is going to save us all from something or other, but I just
can't get my head around it.
I have been trying to do what should be a very simple action: Extract values
from element tags.
I first grab my data from a website with httplib:
>> connection = httplib.HTTPSConnection(serverUrl)
>> connection.request("POST", serverDir, buildRequestXml("ReturnAll", "1"),
buildHttpHeaders())
>> response = connection.getresponse()
>> from xml.dom.minidom import parse, parseString
>> data = response.read()
>> connection.close()
>> response = parseString(data)
>> itemIDs = response.getElementsByTagName("ItemID")
>> response.unlink()
I have tried everything I can find to extract the values from the
elements:
>> for item in itemIDs:
>> print item
yeilds
Okay, no problem. Now all I have to do is figure out which
particlular.string.of.words.interconnected.by.periods to pass to extract the
values.
>> for item in itemIDs:
>> print item.nodeValue
Seems logical:
None
None
None
None
None
Oh for crying out loud ...
Hmmm ... I have saved the output from response.read() to a file and sure
enough, amid all the other element tags, I find the expected values in
My problem is: I'm ignorant. I don't know whether my data is being returned
from parseString() as text, or a list or a beautiful rainbow made of
skittles and pixie droppings. The Python/XML howto and the bajillion other
"XML made clear to YOU!" sites I have looked at have left me more confused
... I'm just completely lost in the (apparently arbitrary) nomeclature of
lists, nodes, elements, trees, habitrails and intestines. (Yes, I'm just
complaining now, but dang it! I'm frustrated!
*ahem*
Could someone kindly point out where I am going wrong and perhaps send me to
a very *practical* introduction to reading data from a dom?
Thanks!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060609/0b888d30/attachment.htm
From paul.kraus at gmail.com Sat Jun 10 00:58:58 2006
From: paul.kraus at gmail.com (Paul D. Kraus)
Date: Fri, 9 Jun 2006 18:58:58 -0400
Subject: [Tutor] Is there a better way to write this function?
Message-ID: <4e2aea430606091558s57ab89e2jc750b6208e8a173b@mail.gmail.com>
This is a second... the first one never hit the list. *shrug* should i be
using a different interface to post? is this a gateway to newsgroup?
I am writing my first python program(at least in a really long time). Its
purpose is to take csv or pipe delimintaed files and convert them to html
pages. Was going to be excel but its just not worth the headache. Everyone
viewing the reports is doing just that viewing simple tables.
I need to scan through a list that contains headers to my table.
If one of the elements is a tuple and one of the elements of the tuple is
"s" set self.sort to the index of the tuple in the header list and then
replace the element in header with a two field tuple containing everything
that was not 's'.
header = ['my first column',('my second num column','s','r'),(' my third num
column','r') ]
I pass header to a function actually a method but lets pretend its just a
plain old function. Be careful reading the below code may cause random
strokes. I have woken up twice laying on the floor disoriented.... :)
Actual code in my working example used to call function ...
report.set_header(
['','Ext','Name','',('Calls','r','s'),('Ring','r'),('Talk','r'),('Wait','r'),('Max
Talk','r') ] )
def set_header(self,header):
list = []
for cindex in range(len(header)):
if type(()) == type(header[cindex]):
for index in range(len(header[cindex]) ):
if header[cindex][index] == 's':
self.sort = cindex
for tindex in range(len(header[cindex])):
if tindex != index: list.append
(header[cindex][tindex])
header[cindex] = tuple(list)
self.header = header
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060609/6e820b5c/attachment.html
From alan.gauld at freenet.co.uk Sat Jun 10 01:04:16 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sat, 10 Jun 2006 00:04:16 +0100
Subject: [Tutor] Difference between popens
References: <61d0e2b40606091238s43bfbf0am17075776829b5d3c@mail.gmail.com>
Message-ID: <00e701c68c19$08b357c0$0301a8c0@XPpro>
> I'd like to know what are the differences at the various os.popenX
> flavors. I read the documentation and I can see they return file
> objects..... so what can you do with these file objects? I mean, why
> would you need a set of file objects rather than another?
My OS topic covers some of the popen variants with explanation.
It might help.
Here are the most relevant two paragraphs:
--------------
In fact there are several variations of the popen command called
popen, popen2, popen3 and popen4. The numbers refer to the various
data stream combinations that are made available. The standard data
streams were described in a sidebar in the Talking to the User topic.
The basic version of popen simply creates a single data stream where
all input/output is sent/received depending on a mode parameter passed
to the function. In essence it tries to make executing a command look
like using a file object.
By contrast, popen2 offers two streams, one for standard output and
another for standard input, so we can send data to the process and
read the output without closing the process. popen3 provides stderr
access in addition to stdin/stdout. Finally there is popen4 that
combines stderr and stdout into a single stream which appears very
like normal console output. In Python 2.4 all of these popen calls
have been superseded by a new Popen class found in a new subprocess
module which we will look at later. For now we will only look at the
standard os.popen() function, the others I will leave as a research
exercise!
---------------
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
From alan.gauld at btinternet.com Sat Jun 10 01:07:29 2006
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Sat, 10 Jun 2006 00:07:29 +0100
Subject: [Tutor] Expletive Deleted
References: <5e1ceb8a0606091528i52471b44v228626e453343e4a@mail.gmail.com>
Message-ID:
"doug shawhan" wrote in message
>I realize XML is going to save us all from something or other, but I
>just
> can't get my head around it.
Nope its only going to save Sun and IBM and Cisco etc by forcing
us all to buy really powerful computers and really big networks!
Alan (with only slightly tongue in cheek) G.
From dyoo at hkn.eecs.berkeley.edu Sat Jun 10 02:55:19 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Fri, 9 Jun 2006 17:55:19 -0700 (PDT)
Subject: [Tutor] XML: Expletive Deleted
In-Reply-To: <5e1ceb8a0606091528i52471b44v228626e453343e4a@mail.gmail.com>
References: <5e1ceb8a0606091528i52471b44v228626e453343e4a@mail.gmail.com>
Message-ID:
>>> from xml.dom.minidom import parse, parseString
>
>>> data = response.read()
>>> connection.close()
>>> response = parseString(data)
>>> itemIDs = response.getElementsByTagName("ItemID")
>>> response.unlink()
^^^^^^^^^^^^^^^^^
Hi Doug,
What's going on here? Why unlink()?
> Okay, no problem. Now all I have to do is figure out which
> particlular.string.of.words.interconnected.by.periods to pass to extract
> the values.
>
>>> for item in itemIDs:
>>> print item.nodeValue
You may want to look at the minidom example here:
http://www.python.org/doc/lib/dom-example.html
Does this help?
From paul.kraus at gmail.com Sat Jun 10 04:22:11 2006
From: paul.kraus at gmail.com (Paul D. Kraus)
Date: Fri, 9 Jun 2006 22:22:11 -0400
Subject: [Tutor] Function list that might have a tuple that might have one
of its indexs set to 's'
Message-ID: <4e2aea430606091922k6a5a2a0ar37b06b8e9edda289@mail.gmail.com>
I am writing my first python program(at least in a really long time). Its
purpose is to take csv or pipe delimited files and convert them to html
pages. Was going to be excel but its just not worth the headache. Everyone
viewing the reports is doing just that viewing simple tables.
I need to scan through a list that contains headers to my table.
If one of the elements is a tuple and one of the elements of the tuple is
"s" set self.sort to the index of the tuple in the header list and then
replace the element in header with a two field tuple containing everything
that was not 's'.
header = ['my first column',('my second num column','s','r'),(' my third num
column','r') ]
I pass header to a function actually a method but lets pretend its just a
plain old function. Be careful reading the below code may cause random
strokes. I have woken up twice laying on the floor disoriented.... :)
Actual code in my working example used to call function ...
report.set_header(
['','Ext','Name','',('Calls','r','s'),('Ring','r'),('Talk','r'),('Wait','r'),('Max
Talk','r') ] )
def set_header(self,header):
list = []
for cindex in range(len(header)):
if type(()) == type(header[cindex]):
for index in range(len(header[cindex]) ):
if header[cindex][index] == 's':
self.sort = cindex
for tindex in range(len(header[cindex])):
if tindex != index: list.append
(header[cindex][tindex])
header[cindex] = tuple(list)
self.header = header
TIA,
Paul
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060609/e8af7256/attachment.html
From levity at gmail.com Sat Jun 10 08:31:55 2006
From: levity at gmail.com (lawrence wang)
Date: Sat, 10 Jun 2006 02:31:55 -0400
Subject: [Tutor] XML: Expletive Deleted
In-Reply-To: <5e1ceb8a0606091528i52471b44v228626e453343e4a@mail.gmail.com>
References: <5e1ceb8a0606091528i52471b44v228626e453343e4a@mail.gmail.com>
Message-ID: <22e13a220606092331r772a848dvf4a98d3f61a1d8ef@mail.gmail.com>
> >> for item in itemIDs:
> >> print item
>
> yeilds
>
>
>
>
>
>
>
> Okay, no problem. Now all I have to do is figure out which
> particlular.string.of.words.interconnected.by.periods to
> pass to extract the values.
>
> >> for item in itemIDs:
> >> print item.nodeValue
>
> Seems logical:
>
> None
> None
> None
> None
> None
try dir(item) to see what attributes the item has, and try the ones
that sound right. e.g.:
>>> from xml.dom.minidom import parse, parseString
>>> resp = parseString("foo")
>>> bottom = resp.getElementsByTagName("bottom")
>>> bottom
[]
>>> dir(bottom[0])
['ATTRIBUTE_NODE', ...long list snipped..., 'writexml']
>>> bottom[0].hasChildNodes()
True
>>> bottom[0].childNodes
[]
>>> dir(bottom[0].childNodes[0])
['ATTRIBUTE_NODE', ...long list snipped..., 'writexml']
>>> bottom[0].childNodes[0].data
u'foo'
so you see, with "value", there's an invisible text node.
it's one of the quirks of xml, i guess. then the attribute you're
looking for is "data", not "nodeValue".
in summary: instead of item.nodeValue, item.childNodes[0].data.
--lawrence
From sisson.j at gmail.com Sat Jun 10 04:27:08 2006
From: sisson.j at gmail.com (Jonathon Sisson)
Date: Sat, 10 Jun 2006 03:27:08 +0100
Subject: [Tutor] An Introduction and a question
In-Reply-To: <1149882145.10792.37.camel@camille.espersunited.com>
References: <1149882145.10792.37.camel@camille.espersunited.com>
Message-ID: <448A2DFC.9030403@gmail.com>
Michael Sullivan wrote:
> Here's the situation: My wife likes to play the game Chuzzle, found at
> Yahoo Games. We use primarily Linux, however Chuzzle is written as an
> ActiveX control, which only works on Windows. I have not been able to
> get Internet Explorer to work correctly through Wine,
This might not be a Python topic, but I figured I'd respond with what I
know on this particular subject...
ActiveX can be run in Linux using the WINDOWS version of Mozilla in Wine
and a little bit of coaxing as per this HOWTO on the Gentoo Forums (make
sure you install the ActiveX control in Wine...):
http://forums.gentoo.org/viewtopic-t-246098-highlight-warcraft.html
World of Warcraft uses ActiveX in it's patch updater, and although I've
never personally run it I've had many people tell me this method works.
Now if I could just figure out how to convince my wife to try Linux (as
you apparently have done) then I'd be set...kudos to you on that.
Jonathon
so I determined to
> write a Chuzzle-like game (with many of my own enhancements) for Linux.
> I've been playing around with some Pygame examples lately, and thought
> that I'd try writing the game in Python (I've been meaning to learn
> Python for years, but just never got around to it.) Today I started on
> writing the game. I've decided (at least for now) to call my version,
> LinePuzzle. For those of you unfamiliar with Chuzzle, here's the basic
> concept: There are individual pieces of different colors arranged on a
> grid. The pieces can be moved on a line either vertically or
> horizontally. The object of the game is to position three similarly
> colored pieces ajacent to each other. At this point the three pieces
> will disappear, and the pieces above them will fall to take their place.
> As the levels progress, locks are added so that the player cannot move a
> locked piece either horizontally or vertically. The game is over when
> no more pieces can be removed.
>
> I started my script by creating a class called LinePuzzlePiece which
> represents a single coloured piece. I wanted a random colour chosen
> from a list to be assigned to the piece, and then to prove that I had it
> set up correctly, I wanted to call a method that would print out the
> color of the piece. Here is my code:
>
> #!/usr/bin/env python
>
> import random
> import time
> import math
>
> class LinePuzzlePiece:
> """This class defines a single playing piece for LinePuzzle"""
> def __init__(self):
> seed(time)
> index = int(math.floor(uniform(1, 10))) colorlist = ["red",
> "blue", "green" "yellow", "purple"] self.color = colorlist[index]
>
> def printcolor():
> print self.color
>
> mypiece = LinePuzzlePiece
> mypiece.printcolor
>
>
> I saved the script and made it chmod +x. However, when I run it, I get
> this:
>
> michael at camille ~ $ ./linepuzzle.py
> michael at camille ~ $
>
> Now, I'm no expert, but I really think something should have been
> printed, if even a blank line. What am I doing wrong here? Why is
> nothing printing? Is my printcolor method even being called
> successfully?
> -Michael Sullivan-
>
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
From kent37 at tds.net Sat Jun 10 13:08:04 2006
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 10 Jun 2006 07:08:04 -0400
Subject: [Tutor] An Introduction and a question (continuing)
In-Reply-To: <1149888523.10792.50.camel@camille.espersunited.com>
References: <1149882145.10792.37.camel@camille.espersunited.com>
<1149888523.10792.50.camel@camille.espersunited.com>
Message-ID: <448AA814.3020406@tds.net>
Michael Sullivan wrote:
> OK. I've got it working this far. Now I want the script to generate
> eight pieces, each with a random colour. Here's my current code:
>
> #!/usr/bin/env python
>
> import random
> import time
> import math
>
> class LinePuzzlePiece:
> """This class defines a single playing piece for LinePuzzle"""
> def __init__(self):
> random.seed(time)
The above statement initializes the random number generator with the
time *module*, not the current time. The time module never changes. So
every time you need a random number your are initializing the generator
with the same constant. That's why you always get the same number.
The docs for random.seed() say, "If x is omitted or None, current system
time is used; current system time is also used to initialize the
generator when the module is first imported." So you could omit the time
argument to use the actual time; better is to omit the call completely
and let the module init itself when you load it.
> index = int(math.floor(random.uniform(0, 8)))
> colorlist = ["red", "blue", "green", "yellow", "purple", "cyan",
> "orange", "white"]
> self.color = colorlist[index]
random.choice() would be simpler here.
Kent
>
> def printcolor(self):
> print self.color
>
> piececount = 0
> mypiece = ["", "", "", "", "", "", "", "", ""]
> while (piececount < 9):
> mypiece[piececount] = LinePuzzlePiece()
> mypiece[piececount].printcolor()
> piececount += 1
>
> The problem is that while eight pieces are created and assigned a
> colour, the colour is always the same. I need the colours of the pieces
> to be in a somewhat random order. What am I doing wrong?
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
From kent37 at tds.net Sat Jun 10 13:25:08 2006
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 10 Jun 2006 07:25:08 -0400
Subject: [Tutor] Function list that might have a tuple that might have
one of its indexs set to 's'
In-Reply-To: <4e2aea430606091341m19267352s32b1051c96ccde09@mail.gmail.com>
References: <4e2aea430606091341m19267352s32b1051c96ccde09@mail.gmail.com>
Message-ID: <448AAC14.4080301@tds.net>
Paul D. Kraus wrote:
> I need to scan through a list that contains headers to my table.
> If one of the elements is a tuple and one of the elements of the tuple
> is "s" set self.sort to the index of the tuple in the header list and
> then replace the element in header with a two field tuple containing
> everything that was not 's'.
>
> Actual code in my working example used to call function ...
>
> report.set_header(
> ['','Ext','Name','',('Calls','r','s'),('Ring','r'),('Talk','r'),('Wait','r'),('Max
> Talk','r') ] )
>
> def set_header(self,header):
> list = []
> for cindex in range(len(header)):
> if type(()) == type(header[cindex]):
> for index in range(len(header[cindex]) ):
> if header[cindex][index] == 's':
> self.sort = cindex
> for tindex in range(len(header[cindex])):
> if tindex != index:
> list.append(header[cindex][tindex])
> header[cindex] = tuple(list)
> self.header = header
You didn't actually ask a question. I assume you are looking for a
version of this that is less stroke-inducing?
You are doing a lot of work that Python would happily do for you.
To iterate over a sequence h, instead of generating the indexes to h, use
for x in h:
which will return the items of h directly. If you also need the indices, use
for i, x in enumerate(h)
You can test for membership in a sequence with
if i in h:
You can filter a sequence with a list comprehension:
[ x for x in h if x != s ]
creates a new list containing all the elements of h that are not s.
Putting this all together gives this rewrite:
def set_header(self, header):
for i, item in enumerate(header):
if type(item) != type(()):
continue
if 's' in item:
self.sort = i
header[i] = tuple([x for x in item if x!='s'])
self.header = header
Note this does change the list passed in, that could be a problem
depending on if you use it for anything else.
Kent
From rstoos at rochester.rr.com Sat Jun 10 02:46:27 2006
From: rstoos at rochester.rr.com (Ralph H. Stoos Jr.)
Date: Fri, 09 Jun 2006 20:46:27 -0400
Subject: [Tutor] Expletive Deleted
Message-ID: <448A1663.7020103@rochester.rr.com>
My $.02,
First, I subscribed to this list to help learn Python as my first
language so my opinion is far from expert. In my real job, I am
attempting to get our real programmers to support exporting one of our
system logs in XML format, hence, the following opinion.
I think XML is a tool that allows non-programmers to look at structured
data and have it a in human readable form that gives us a chance of
understanding that structure.
The other strength that I can see is this: Once data is in this format,
and a tool has been written to parse it, data can be added to the
structure (more elements) and the original tool will not be broken by
this. Whatever it is parsed for is found and the extra is ignored.
Without a doubt, the overhead XML adds over say, something as simple as
CSV is considerable, and XML would appear to be rather more hard to work
with in things like Python and PERL.
So, I think XML has it's place but I will not fault anyone for trying to
make it easier to get code to work.
Good Luck in all endeavors,
Ralph
From kent37 at tds.net Sat Jun 10 13:34:00 2006
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 10 Jun 2006 07:34:00 -0400
Subject: [Tutor] XML: Expletive Deleted
In-Reply-To:
References: <5e1ceb8a0606091528i52471b44v228626e453343e4a@mail.gmail.com>
Message-ID: <448AAE28.1000701@tds.net>
In my opinion the standard DOM models are the most awkward way to deal
with XML. If you are trying to get data from HTML on a web page, look at
BeautifulSoup. For general XML processing, look at ElementTree. They are
both simpler than DOM.
http://www.crummy.com/software/BeautifulSoup/
http://effbot.org/zone/element.htm
Kent
From michael at espersunited.com Sat Jun 10 15:16:56 2006
From: michael at espersunited.com (Michael Sullivan)
Date: Sat, 10 Jun 2006 08:16:56 -0500
Subject: [Tutor] An Introduction and a question
In-Reply-To: <448A2DFC.9030403@gmail.com>
References: <1149882145.10792.37.camel@camille.espersunited.com>
<448A2DFC.9030403@gmail.com>
Message-ID: <1149945416.10792.66.camel@camille.espersunited.com>
On Sat, 2006-06-10 at 03:27 +0100, Jonathon Sisson wrote:
> Michael Sullivan wrote:
> > Here's the situation: My wife likes to play the game Chuzzle, found at
> > Yahoo Games. We use primarily Linux, however Chuzzle is written as an
> > ActiveX control, which only works on Windows. I have not been able to
> > get Internet Explorer to work correctly through Wine,
>
> This might not be a Python topic, but I figured I'd respond with what I
> know on this particular subject...
>
> ActiveX can be run in Linux using the WINDOWS version of Mozilla in Wine
> and a little bit of coaxing as per this HOWTO on the Gentoo Forums (make
> sure you install the ActiveX control in Wine...):
>
> http://forums.gentoo.org/viewtopic-t-246098-highlight-warcraft.html
>
> World of Warcraft uses ActiveX in it's patch updater, and although I've
> never personally run it I've had many people tell me this method works.
> Now if I could just figure out how to convince my wife to try Linux (as
> you apparently have done) then I'd be set...kudos to you on that.
>
> Jonathon
My wife says that she actually prefers Linux over Windows. The only
thing we use Windows for is playing Civilizations II and The Sims,
although she also uses it for playing Internet games that don't work on
Linux. She's said that if I can make Linux versions of those games she
plays on Windows, she won't use Windows at home anymore. When I first
started with Linux, she was kinda iffy about it, but now she loves it.
We've only used it since fall of 2003...
From arcege at gmail.com Sat Jun 10 15:17:33 2006
From: arcege at gmail.com (Michael P. Reilly)
Date: Sat, 10 Jun 2006 09:17:33 -0400
Subject: [Tutor] Difference between popens
In-Reply-To: <61d0e2b40606091427y3c7cabcax94e28c5c0f60d4cb@mail.gmail.com>
References: <61d0e2b40606091238s43bfbf0am17075776829b5d3c@mail.gmail.com>
<7e5ba9220606091423r4b16b548m48546a401c718abe@mail.gmail.com>
<61d0e2b40606091427y3c7cabcax94e28c5c0f60d4cb@mail.gmail.com>
Message-ID: <7e5ba9220606100617m3251f9ddpe36c278bccf5b62@mail.gmail.com>
On 6/9/06, Bernard Lebel <3dbernard at gmail.com> wrote:
>
> Hey, thanks for the nice explanation Michael!
>
>
> Bernard
>
Whoops.. Hit "reply" instead of "reply to all". My apologies to the group.
Dang gmail.
-Michael
--
There's so many different worlds,
So many different suns.
And we have just one world,
But we live in different ones.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060610/ba883bf7/attachment.html
From eu_alfonso at yahoo.es Sat Jun 10 20:48:49 2006
From: eu_alfonso at yahoo.es (Alfonso)
Date: Sat, 10 Jun 2006 20:48:49 +0200
Subject: [Tutor] problems with python and glade
Message-ID: <448B1411.70408@yahoo.es>
Hi,
I'm trying to learn to use python with glade. As start I have tried to
run a program from a tutorial, but when I run it I become this
exception: class GladeXML(_gtk.GtkData): AttributeError: 'module'
object has no attribute 'GtkData'
This ist the program:
import pygtk
pygtk.require('2.0')
import gtk
import libglade
import gtk.glade
class HellowWorldGTK:
"""This is an Hello World GTK application"""
def __init__(self):
#Set the Glade file
self.gladefile = "proyecto2.glade"
self.wTree = gtk.glade.XML(self.gladefile)
#Get the Main Window, and connect the "destroy" event
self.window = self.wTree.get_widget("MainWindow")
if (self.window):
self.window.connect("destroy", gtk.main_quit)
Does anyone know what could be wrong? Thank you for your attention.
______________________________________________
LLama Gratis a cualquier PC del Mundo.
Llamadas a fijos y m?viles desde 1 c?ntimo por minuto.
http://es.voice.yahoo.com
From sisson.j at gmail.com Sat Jun 10 19:07:36 2006
From: sisson.j at gmail.com (Jonathon Sisson)
Date: Sat, 10 Jun 2006 18:07:36 +0100
Subject: [Tutor] An Introduction and a question
In-Reply-To: <1149945416.10792.66.camel@camille.espersunited.com>
References: <1149882145.10792.37.camel@camille.espersunited.com>
<448A2DFC.9030403@gmail.com>
<1149945416.10792.66.camel@camille.espersunited.com>
Message-ID: <448AFC58.70806@gmail.com>
've triedMichael Sullivan wrote:
> On Sat, 2006-06-10 at 03:27 +0100, Jonathon Sisson wrote:
>> Michael Sullivan wrote:
>>> Here's the situation: My wife likes to play the game Chuzzle, found at
>>> Yahoo Games. We use primarily Linux, however Chuzzle is written as an
>>> ActiveX control, which only works on Windows. I have not been able to
>>> get Internet Explorer to work correctly through Wine,
>> This might not be a Python topic, but I figured I'd respond with what I
>> know on this particular subject...
>>
>> ActiveX can be run in Linux using the WINDOWS version of Mozilla in Wine
>> and a little bit of coaxing as per this HOWTO on the Gentoo Forums (make
>> sure you install the ActiveX control in Wine...):
>>
>> http://forums.gentoo.org/viewtopic-t-246098-highlight-warcraft.html
>>
>> World of Warcraft uses ActiveX in it's patch updater, and although I've
>> never personally run it I've had many people tell me this method works.
>> Now if I could just figure out how to convince my wife to try Linux (as
>> you apparently have done) then I'd be set...kudos to you on that.
>>'ve triedi
>> Jonathon
>
> My wife says that she actually prefers Linux over Windows. The only
> thing we use Windows for is playing Civilizations II and The Sims,
> although she also uses it for playing Internet games that don't work on
> Linux. She's said that if I can make Linux versions of those games she
> plays on Windows, she won't use Windows at home anymore. When I first
> started with Linux, she was kinda iffy about it, but now she loves it.
> We've only used it since fall of 2003...
>
>
Part of my reasoning behind learning Python is that Python used so
heavily in the Gentoo Linux package management system "Portage." I love
portage because of it's flexibility and configurability, and I hope
someday to make a contribution back to the OS that really got me hooked
on Linux. (I started out with RedHat around May of 2002, but I grew
tired of it pretty quickly. I moved from there to try out SuSE,
Slackware, Mandrake, Fedora (after giving RedHat a break for a few
months), and a few others (haven't tried out Debian...I hear it's really
nice, too), but when I saw Gentoo's optimization and configuration
capabilities, I was in for life...).
Therein lies the difference...I'm an efficiency nut (no I really do not
mind compiling the entire OS from source, as long as I can compile it
*exactly* how I want, using *only* what I want), and my wife just wants
to kick people's a$$es online. She got a bad first impression of Linux
from the start because I was constantly tweaking (and breaking) my Linux
system, so the chances of her using Linux are rather slim, even though
as I progress with my Computer Science degree, I break my Linux system
less and less...hahaha.
Jonathon
From kermit at polaris.net Sun Jun 11 08:28:58 2006
From: kermit at polaris.net (Kermit Rose)
Date: Sun, 11 Jun 2006 02:28:58 -0400 (Eastern Daylight Time)
Subject: [Tutor] buggy bug in my program
Message-ID: <448BB82A.000003.04032@YOUR-4105E587B6>
# def insertw(j1,k,w1,w2,jar,limit):
# trace = 1
# if k == 0:
# jar[k][0] = k
# jar[k][1] = w1
# jar[k][2] = w2
# return
# if j1 > k:
# jar[j1][0] = k
# jar[j1][1] = w1
# jar[j1][2] = w2
# return
#
# for j2 in range(j1+1,k+1):
# j3 = k + j1 - j2
# if trace > 0:
# print " insertw: move jar[",j3,"] up one"," j1 = ",j1," k = "
k," w1 = ",w1," w2 = ",w2
# f = jar[j3]
# jar[j3+1] = f
# if trace > 0:
# print " insertw: jar[",j3+1," is now ",jar[j3+1]
#
#
# jar[j1][0] = k
# jar[j1][1] = w1
# jar[j1][2] = w2
#
# if trace > 0:
# for j in range(k+1):
# print " insertw: jar[",j,"] = ",jar[j]
# return
#
debug trace shows the following puzzling behavior.
fermat2: before insertw: jar[ 0 ] = [0, 2, 4]
fermat2: before insertw: jar[ 1 ] = [1, 4, 16]
fermat2: before insertw: jar[ 2 ] = [-1, -1, -1]
I show the array jar before going into insert.
remember the heading of insertw is
# def insertw(j1,k,w1,w2,jar,limit):
insertw: move jar[ 1 ] up one j1 = 1 k = 2 w1 = 16 w2 = 13
This shows that insert made one shift, and sifted jar[1] to jar[2].
j1 = 1 means that insertw was supposed to insert new value into jar[1]
insertw: jar[ 2] is now [1, 4, 16]
I print out jar[2] to show that insertw really did shift jar[1] to jar[2].
insertw: jar[ 0 ] = [0, 2, 4]
insertw: jar[ 1 ] = [2, 16, 13]
insertw: jar[ 2 ] = [2, 16, 13]
Now, outside the loop,
I set jar[j1] to the new values.
And I print the resulting array, still within the routine insertw.
jar[1] has been set to the new values.
BUT, and this is the problem,
jar[2] has been also set to the new values.
WHY???????????
From alan.gauld at freenet.co.uk Sun Jun 11 09:55:17 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sun, 11 Jun 2006 08:55:17 +0100
Subject: [Tutor] Expletive Deleted
References: <448A1663.7020103@rochester.rr.com>
Message-ID: <001d01c68d2c$62077090$0301a8c0@XPpro>
> I think XML is a tool that allows non-programmers to look at
> structured
> data and have it a in human readable form that gives us a chance of
> understanding that structure.
Thats not a great reason to choose a file format IMHO.
Tools can be written to display data in a readable format.
For example SQL can be used to view the data in a database.
File formats should be designed to store data, compactly
and with easy access.
> The other strength that I can see is this: Once data is in this
> format,
> and a tool has been written to parse it, data can be added to the
> structure (more elements) and the original tool will not be broken
> by
> this. Whatever it is parsed for is found and the extra is ignored.
But this is a very real plus point for XML.
And this IMHO is the biggest single reason for using it, if you have
data where the very structure itself is changing yet the same file
has to be readable by old and new clients then XML is a good choice.
> Without a doubt, the overhead XML adds over say, something as simple
> as
> CSV is considerable, and XML would appear to be rather more hard to
> work
> with in things like Python and PERL.
Considerable is an understatement, its literally up to 10 or 20 times
more space and that means bandwidth and CPU resource to
process it.
Using XML as a storage medium - a file - is not too bad, you suck
it up, process it and foirget the file. MY big gripe is that people
are
inceasingly trying to use XML as the payload in comms systems,
sending XML messages around. This is crazy! The extra cost of the
network and hardware needed to process that kind of architecture
is usually far higher than the minimal savings it gives in developer
time.
[As an example I recently had to uplift the bandwidth of the
intranet pipe in one of our buildings from 4Mb to a full ATM pipe
of 34Mb just to accomodate a system 'upgrade' that now used XML.
That raised the network operations cost of that one building
from $10k per year to over $100k! - The software upgrade by
contrast was only a one-off cost of $10K]
> So, I think XML has it's place but I will not fault anyone for
> trying to
> make it easier to get code to work.
Absolutely agree with that. Just be careful how you use it and
think of the real cost impact you may be having if its your choice.
Your customers will thank you.
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
From alan.gauld at freenet.co.uk Sun Jun 11 09:58:49 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sun, 11 Jun 2006 08:58:49 +0100
Subject: [Tutor] problems with python and glade
References: <448B1411.70408@yahoo.es>
Message-ID: <002d01c68d2c$dfb3ae50$0301a8c0@XPpro>
Can you send the complete error trace. The line you have
copied looks like it is from inside GTk somewhere, we
need the stack trace to see where it originates in your code.
But I'm no GTk expert so I probably can't help anyway! :-)
Alan G.
----- Original Message -----
From: "Alfonso"
To:
Sent: Saturday, June 10, 2006 7:48 PM
Subject: [Tutor] problems with python and glade
> Hi,
> I'm trying to learn to use python with glade. As start I have tried
> to
> run a program from a tutorial, but when I run it I become this
> exception: class GladeXML(_gtk.GtkData): AttributeError: 'module'
> object has no attribute 'GtkData'
>
>
> This ist the program:
>
> import pygtk
> pygtk.require('2.0')
> import gtk
> import libglade
> import gtk.glade
>
> class HellowWorldGTK:
> """This is an Hello World GTK application"""
>
> def __init__(self):
>
> #Set the Glade file
> self.gladefile = "proyecto2.glade"
> self.wTree = gtk.glade.XML(self.gladefile)
>
> #Get the Main Window, and connect the "destroy" event
> self.window = self.wTree.get_widget("MainWindow")
> if (self.window):
> self.window.connect("destroy", gtk.main_quit)
>
>
> Does anyone know what could be wrong? Thank you for your attention.
>
>
>
>
> ______________________________________________
> LLama Gratis a cualquier PC del Mundo.
> Llamadas a fijos y m?viles desde 1 c?ntimo por minuto.
> http://es.voice.yahoo.com
>
>
From kent37 at tds.net Sun Jun 11 12:58:39 2006
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 11 Jun 2006 06:58:39 -0400
Subject: [Tutor] buggy bug in my program
In-Reply-To: <448BB82A.000003.04032@YOUR-4105E587B6>
References: <448BB82A.000003.04032@YOUR-4105E587B6>
Message-ID: <448BF75F.3020709@tds.net>
Kermit Rose wrote:
> # def insertw(j1,k,w1,w2,jar,limit):
> # trace = 1
> # if k == 0:
> # jar[k][0] = k
> # jar[k][1] = w1
> # jar[k][2] = w2
> # return
> # if j1 > k:
> # jar[j1][0] = k
> # jar[j1][1] = w1
> # jar[j1][2] = w2
> # return
> #
> # for j2 in range(j1+1,k+1):
> # j3 = k + j1 - j2
> # if trace > 0:
> # print " insertw: move jar[",j3,"] up one"," j1 = ",j1," k = "
> k," w1 = ",w1," w2 = ",w2
> # f = jar[j3]
> # jar[j3+1] = f
I think you want to copy jar[j3] here. In your code, jar[j3] and
jar[j3+1] both refer to the same list! If you change the list, you will
see it in both places.
Assignment in Python is not a copy, it is a name binding. Assignment
creates a name for an object. If you assign the same object to two
names, they both are bound to the same thing. If the object is mutable,
like a list, changes to the object will be seen regardless of which name
you use to refer to it.
For example:
In [14]: d = [1, 2, 3]
In [15]: e=d
d and e are now references to the same list
In [18]: d[0]=55
The changes the list, the change can be seen regardless of which
reference to the list is used to access it.
In [19]: d
Out[19]: [55, 2, 3]
In [20]: e
Out[20]: [55, 2, 3]
Here is one way to make a copy; d and f refer to different lists:
In [21]: f=d[:]
In [22]: f
Out[22]: [55, 2, 3]
Changing f doesn't affect d or e:
In [23]: f[1]=23
In [24]: f
Out[24]: [55, 23, 3]
In [25]: d
Out[25]: [55, 2, 3]
In [26]: e
Out[26]: [55, 2, 3]
This may help:
http://www.effbot.org/zone/python-objects.htm
Kent
> # if trace > 0:
> # print " insertw: jar[",j3+1," is now ",jar[j3+1]
> #
> #
> # jar[j1][0] = k
> # jar[j1][1] = w1
> # jar[j1][2] = w2
> #
> # if trace > 0:
> # for j in range(k+1):
> # print " insertw: jar[",j,"] = ",jar[j]
> # return
> #
>
>
> debug trace shows the following puzzling behavior.
>
>
> fermat2: before insertw: jar[ 0 ] = [0, 2, 4]
> fermat2: before insertw: jar[ 1 ] = [1, 4, 16]
> fermat2: before insertw: jar[ 2 ] = [-1, -1, -1]
>
>
> I show the array jar before going into insert.
>
> remember the heading of insertw is
>
> # def insertw(j1,k,w1,w2,jar,limit):
>
>
>
> insertw: move jar[ 1 ] up one j1 = 1 k = 2 w1 = 16 w2 = 13
>
> This shows that insert made one shift, and sifted jar[1] to jar[2].
> j1 = 1 means that insertw was supposed to insert new value into jar[1]
>
> insertw: jar[ 2] is now [1, 4, 16]
>
> I print out jar[2] to show that insertw really did shift jar[1] to jar[2].
>
>
>
>
> insertw: jar[ 0 ] = [0, 2, 4]
> insertw: jar[ 1 ] = [2, 16, 13]
> insertw: jar[ 2 ] = [2, 16, 13]
>
> Now, outside the loop,
> I set jar[j1] to the new values.
>
> And I print the resulting array, still within the routine insertw.
>
> jar[1] has been set to the new values.
>
> BUT, and this is the problem,
>
> jar[2] has been also set to the new values.
>
> WHY???????????
>
>
>
>
>
>
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
From patriciap.gu at gmail.com Sun Jun 11 17:19:06 2006
From: patriciap.gu at gmail.com (Patricia)
Date: Sun, 11 Jun 2006 15:19:06 +0000 (UTC)
Subject: [Tutor] connect to a remote machine - Linux
Message-ID:
Hi All,
I need to connect to a remote computer on the same network to store data into
its mysql database, and I need to do this using python script.
Although I've used mysql and python before, I have no idea how to access a
remote computer with Python. Also, I would have to enter a passphrase and
password to successfully connect to it..
I'd appreciate any help.
Thanks!!
Patricia
From michael at espersunited.com Sun Jun 11 17:38:01 2006
From: michael at espersunited.com (Michael Sullivan)
Date: Sun, 11 Jun 2006 10:38:01 -0500
Subject: [Tutor] connect to a remote machine - Linux
In-Reply-To:
References:
Message-ID: <1150040281.10761.16.camel@camille.espersunited.com>
On Sun, 2006-06-11 at 15:19 +0000, Patricia wrote:
> Hi All,
>
> I need to connect to a remote computer on the same network to store data into
> its mysql database, and I need to do this using python script.
>
> Although I've used mysql and python before, I have no idea how to access a
> remote computer with Python. Also, I would have to enter a passphrase and
> password to successfully connect to it..
>
> I'd appreciate any help.
> Thanks!!
>
> Patricia
From python at venix.com Mon Jun 12 00:48:50 2006
From: python at venix.com (Python)
Date: Sun, 11 Jun 2006 18:48:50 -0400
Subject: [Tutor] connect to a remote machine - Linux
In-Reply-To:
References:
Message-ID: <1150066130.24742.254.camel@www.venix.com>
On Sun, 2006-06-11 at 15:19 +0000, Patricia wrote:
> Hi All,
>
> I need to connect to a remote computer on the same network to store data into
> its mysql database, and I need to do this using python script.
>
> Although I've used mysql and python before, I have no idea how to access a
> remote computer with Python. Also, I would have to enter a passphrase and
> password to successfully connect to it..
I could not simply cut and paste working code, but this should get you
started. There is no programming difference in using a remote sql
server.
import MySQLdb
dbparms = {
'host':'dbserver.example.com', # name of sql server
# (localhost for your local computer)
'user':'dbusername', # your identifier
'passwd':'dbpassword', # your password
'db':'dbname_to_use', # initial database
}
conn = MySQLdb.connect( **dbparms)
>
> I'd appreciate any help.
> Thanks!!
>
> Patricia
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
--
Lloyd Kvam
Venix Corp
From roymac1 at ntlworld.com Mon Jun 12 00:41:19 2006
From: roymac1 at ntlworld.com (Roy Mac)
Date: Sun, 11 Jun 2006 23:41:19 +0100
Subject: [Tutor] connect to a remote machine - Linux
In-Reply-To:
Message-ID: <20060611224126.EYTT24467.aamtaout02-winn.ispmail.ntl.com@ROYXP1>
Try looking at PyDO - This provides an interface between Python and your
database. This allows you to change your database at a later time and not
have to change any Python.
The excerpt below is from:
http://skunkweb.sourceforge.net/PyDO2/api/html/public/pydo-module.html
PyDO (Python Data Objects) is an object-relational wrapper for
relational databases. It provides a convenient API for retrieving and
manipulating data without constraining in any way how the data is
persisted at the RDBMS level. Supported databases are:
* postgresql
* mysql
* sqlite
* mssql
* oracle
-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf
Of Patricia
Sent: Sunday, June 11, 2006 4:19 PM
To: tutor at python.org
Subject: [Tutor] connect to a remote machine - Linux
Hi All,
I need to connect to a remote computer on the same network to store data
into its mysql database, and I need to do this using python script.
Although I've used mysql and python before, I have no idea how to access a
remote computer with Python. Also, I would have to enter a passphrase and
password to successfully connect to it..
I'd appreciate any help.
Thanks!!
Patricia
_______________________________________________
Tutor maillist - Tutor at python.org
http://mail.python.org/mailman/listinfo/tutor
From patriciap.gu at gmail.com Mon Jun 12 01:48:06 2006
From: patriciap.gu at gmail.com (Patricia G.)
Date: Sun, 11 Jun 2006 19:48:06 -0400
Subject: [Tutor] connect to a remote machine - Linux
In-Reply-To: <20060611224126.EYTT24467.aamtaout02-winn.ispmail.ntl.com@ROYXP1>
References:
<20060611224126.EYTT24467.aamtaout02-winn.ispmail.ntl.com@ROYXP1>
Message-ID: <18f27cbe0606111648h1a257f53q2fbc8061c3938d4f@mail.gmail.com>
I'm sorry. I think I didn't explain myself well. My problem is not with the
database.. The part I'm not sure how to do is connect to the remote
computer.. I read somewhere that os.popen would work, but I'm not sure if
that will do for me because I have to enter a passphrase and password to
connect to the remote machine.
Any ideas??
Thanks,
Patricia
On 6/11/06, Roy Mac wrote:
>
> Try looking at PyDO - This provides an interface between Python and your
> database. This allows you to change your database at a later time and not
> have to change any Python.
>
> The excerpt below is from:
> http://skunkweb.sourceforge.net/PyDO2/api/html/public/pydo-module.html
>
> PyDO (Python Data Objects) is an object-relational wrapper for
> relational databases. It provides a convenient API for retrieving and
> manipulating data without constraining in any way how the data is
> persisted at the RDBMS level. Supported databases are:
>
> * postgresql
> * mysql
> * sqlite
> * mssql
> * oracle
>
>
>
> -----Original Message-----
> From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf
> Of Patricia
> Sent: Sunday, June 11, 2006 4:19 PM
> To: tutor at python.org
> Subject: [Tutor] connect to a remote machine - Linux
>
> Hi All,
>
> I need to connect to a remote computer on the same network to store data
> into its mysql database, and I need to do this using python script.
>
> Although I've used mysql and python before, I have no idea how to access a
> remote computer with Python. Also, I would have to enter a passphrase and
> password to successfully connect to it..
>
> I'd appreciate any help.
> Thanks!!
>
> Patricia
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060611/adfc3566/attachment.htm
From python at venix.com Mon Jun 12 02:28:13 2006
From: python at venix.com (Python)
Date: Sun, 11 Jun 2006 20:28:13 -0400
Subject: [Tutor] connect to a remote machine - Linux
In-Reply-To: <18f27cbe0606111559vf630f2ex996e11da3504ed95@mail.gmail.com>
References:
<1150066130.24742.254.camel@www.venix.com>
<18f27cbe0606111559vf630f2ex996e11da3504ed95@mail.gmail.com>
Message-ID: <1150072093.24742.291.camel@www.venix.com>
(back on list)
On Sun, 2006-06-11 at 18:59 -0400, Patricia G. wrote:
> I'm sorry. I think I didn't explain myself well. My problem is not
> with the database.. The part I'm not sure how to do is connect to the
> remote computer..
MySQL will accept connections from other computers. It listens on port
3306. There are network setup and security issues, but those would be
outside the scope of a Python database program.
> I read somewhere that os.popen would work, but I'm not sure if that
> will do for me because I have to enter a passphrase and password to
> connect to the remote machine.
I presume that was using os.popen to talk to stdin/stdout files
connected to a telnet or ssh session established from outside Python.
That is likely to prove pretty clumsy for all but the simplest cases.
> Any ideas??
Logging on to a remote computer should not have anything to do with
accessing a remote MySQL database.
ssh would probably be the preferred way to login to a remote computer.
http://www.lag.net/paramiko/
would appear to do the trick.
If you're stuck with telnet, the stdlib has a telnetlib module that
would help.
http://pexpect.sourceforge.net/
Provides an expect like module to help manage a terminal session
conversation.
In general, program-to-program interaction between computers works best
with protocols that were designed for programs. Telnet expects a person
who will interpret error strings, not type too quickly, and understand
(and wait for) prompts.
Obviously, I don't know your situation, but scripting remote terminal
sessions should be a last resort. (I used to do it a lot (15 - 20 years
ago) over serial connections where there was no alternative protocol.)
>
> Thanks,
> Patricia
>
>
> On 6/11/06, Python wrote:
> On Sun, 2006-06-11 at 15:19 +0000, Patricia wrote:
> > Hi All,
> >
> > I need to connect to a remote computer on the same network
> to store data into
> > its mysql database, and I need to do this using python
> script.
> >
> > Although I've used mysql and python before, I have no idea
> how to access a
> > remote computer with Python. Also, I would have to enter a
> passphrase and
> > password to successfully connect to it..
>
> I could not simply cut and paste working code, but this should
> get you
> started. There is no programming difference in using a remote
> sql
> server.
>
> import MySQLdb
>
> dbparms = {
> 'host':'dbserver.example.com', # name of sql server
> # (localhost for your local
> computer)
> 'user':'dbusername', # your identifier
> 'passwd':'dbpassword', # your password
> 'db':'dbname_to_use', # initial database
> }
> conn = MySQLdb.connect( **dbparms)
>
>
> >
> > I'd appreciate any help.
> > Thanks!!
> >
> > Patricia
> >
> > _______________________________________________
> > Tutor maillist - Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> --
> Lloyd Kvam
> Venix Corp
>
>
--
Lloyd Kvam
Venix Corp
From hokkakada at khmeros.info Mon Jun 12 03:15:41 2006
From: hokkakada at khmeros.info (kakada)
Date: Mon, 12 Jun 2006 08:15:41 +0700
Subject: [Tutor] combo box
In-Reply-To: <20060607235215.04540800.klappnase@freenet.de>
References: <44852319.1080804@khmeros.info>
<20060607235215.04540800.klappnase@freenet.de>
Message-ID: <448CC03D.7000301@khmeros.info>
Michael Lange wrote:
> On Tue, 06 Jun 2006 13:39:21 +0700
> kakada wrote:
>
>
>> Dear Friends,
>>
>> I am now working on GUI python (Tkinter).
>> I want to use combobox as my widget, but I cannot find it in any document.
>>
>> Does anybody have experience with that?
>>
>>
>
> There is no ComboBox widget in plain Tkinter.
> Probably the easiest way to get one is to use Tix which is included in the windows python
> distribution and should be available in any recent linux distro.
>
> If you want to use Tix simply replace the import line
>
> from Tkinter import *
>
> with
>
> from Tix import *
>
> You then can use your Tknter widgets as usual, plus a nice set of extra widgets (ComboBox, NoteBook, DirTree etc.) .
>
> I hope this helps
>
> Michael
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
Thank Michael,
How about putting an icon on an Windows Manager, do you know?
da
From hokkakada at khmeros.info Mon Jun 12 04:01:07 2006
From: hokkakada at khmeros.info (kakada)
Date: Mon, 12 Jun 2006 09:01:07 +0700
Subject: [Tutor] icon on windows manager
Message-ID: <448CCAE3.30207@khmeros.info>
Hi everyone!
Does any body know how to put icon on windows manager using Tix module?
Thanks,
da
From kermit at polaris.net Mon Jun 12 04:14:37 2006
From: kermit at polaris.net (Kermit Rose)
Date: Sun, 11 Jun 2006 22:14:37 -0400 (Eastern Daylight Time)
Subject: [Tutor] assignment statements in python
Message-ID: <448CCE0D.00000F.01420@YOUR-4105E587B6>
Message: 1
Date: Sun, 11 Jun 2006 06:58:39 -0400
From: Kent Johnson
Subject: Re: [Tutor] buggy bug in my program
Cc: tutor at python.org
Assignment in Python is not a copy, it is a name binding. Assignment
creates a name for an object. If you assign the same object to two
names, they both are bound to the same thing. If the object is mutable,
like a list, changes to the object will be seen regardless of which name
you use to refer to it.
******
I feel a little bit better now that I know that there is a reason for what
my
program did.
However, I still don't have any idea how to copy values from one cell in
an array to the adjacent cell in the same array.
I looked at the reference ,
http://www.effbot.org/zone/python-objects.htm
that you gave,
but did not gleam any hint from it how to copy values from one place in an
array to another place within the same array.
It must be possible, for otherwise, you could not sort an array.
It is quite remarkable that my not knowing that
assignment is not a copy
gave me no difficulties before now.
Kermit < kermit at polaris.net >
From python at venix.com Mon Jun 12 04:59:04 2006
From: python at venix.com (Python)
Date: Sun, 11 Jun 2006 22:59:04 -0400
Subject: [Tutor] assignment statements in python
In-Reply-To: <448CCE0D.00000F.01420@YOUR-4105E587B6>
References: <448CCE0D.00000F.01420@YOUR-4105E587B6>
Message-ID: <1150081144.24742.310.camel@www.venix.com>
On Sun, 2006-06-11 at 22:14 -0400, Kermit Rose wrote:
> Message: 1
> Date: Sun, 11 Jun 2006 06:58:39 -0400
> From: Kent Johnson
> Subject: Re: [Tutor] buggy bug in my program
> Cc: tutor at python.org
>
> Assignment in Python is not a copy, it is a name binding. Assignment
> creates a name for an object. If you assign the same object to two
> names, they both are bound to the same thing. If the object is mutable,
> like a list, changes to the object will be seen regardless of which name
> you use to refer to it.
>
> ******
>
> I feel a little bit better now that I know that there is a reason for what
> my
> program did.
>
> However, I still don't have any idea how to copy values from one cell in
> an array to the adjacent cell in the same array.
>
> I looked at the reference ,
>
> http://www.effbot.org/zone/python-objects.htm
>
> that you gave,
>
> but did not gleam any hint from it how to copy values from one place in an
> array to another place within the same array.
>
> It must be possible, for otherwise, you could not sort an array.
>
>
> It is quite remarkable that my not knowing that
>
> assignment is not a copy
>
> gave me no difficulties before now.
The basic python objects: numbers, strings, and tuples are immutable and
can not be changed (mutated).
a = b = 3
b = 4 # binds b to a different object with value 4
# the object with value 3 is unchanged
print a
3
Container objects such as lists and dictionaries can be changed in
place.
>>> a = b = [1,2,3]
>>> b.append(4) # changes (mutates) b
>>> print a
[1, 2, 3, 4]
>>> b[2] = b[3] # positions 2 and 3 reference the same object
>>> print b
[1, 2, 4, 4]
>>> print a
[1, 2, 4, 4]
>
>
>
> Kermit < kermit at polaris.net >
>
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
--
Lloyd Kvam
Venix Corp
From dyoo at hkn.eecs.berkeley.edu Mon Jun 12 04:59:47 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Sun, 11 Jun 2006 19:59:47 -0700 (PDT)
Subject: [Tutor] connect to a remote machine - Linux
In-Reply-To: <18f27cbe0606111648h1a257f53q2fbc8061c3938d4f@mail.gmail.com>
References:
<20060611224126.EYTT24467.aamtaout02-winn.ispmail.ntl.com@ROYXP1>
<18f27cbe0606111648h1a257f53q2fbc8061c3938d4f@mail.gmail.com>
Message-ID:
> I'm sorry. I think I didn't explain myself well. My problem is not with
> the database.. The part I'm not sure how to do is connect to the remote
> computer..
Hi Patricia,
There's some confusion here. Let's get that out in the open.
It sounds like you have a remote server. That server provides login shell
service through ssh, and this login shell service runs on port 22, I
think. But if your server is running MySQL, it is very likely that it
provides network access to that MySQL database through port 3306.
I think you believe that ssh login access is required to access MySQL on
your remote network server. But this is not necessarily true: one can
access MySQL remotely without having a login shell account into the
machine. That is, rather than:
Client ----> Login through SSH ----> Execute mysql client
which is three steps, the conventional route here is:
Client ----> Connect to networked MySQL using a database driver
(MySQLdb)
which is more direct.
See:
MySQLdb: http://sourceforge.net/projects/mysql-python
as well as:
http://www.devshed.com/c/a/Python/MySQL-Connectivity-With-Python/
However, this does mean that the remote MySQL server has to be set up with
a separate MySQL username/password account. That is, MySQL keeps its own
set of usernames and passwords that can be separate from the shell
logins.
Also, mysqld --- the software that drives the MySQL server --- has to be
enabled to work across tcp. That requirement sounds obvious enough, but
it is not the default in the MySQL server installs I've seen lately, so
double check this with your database system administrator. In short: you
can not automatically assume that having login access to the machine will
give you MySQL database access, and visa-versa.
Does this make sense so far?
> I read somewhere that os.popen would work, but I'm not sure if that will
> do for me
Almost certainly no.
popen is not for external database access. People have written database
drivers to solve this problem for you already. It is perhaps possible to
bend popen() in such a way to access MySQL, but this will involve an
amount of work to get right, and there will be a lot of ways of getting it
wrong. *grin*
So I'd recommend changing this question from: "How do I get popen() to
access MySQL across a remote interface?" to a more general: "How do I
connect to MySQL from Python?" The link above to MySQLdb will give you
the software necessary to connect your client to a MySQL server, and the
link to the Devshed article is a tutorial on how to use it effectively.
Good luck!
From efoda at hotmail.com Mon Jun 12 07:26:28 2006
From: efoda at hotmail.com (graphic design)
Date: Sun, 11 Jun 2006 22:26:28 -0700
Subject: [Tutor] please remove this address from list: efoda@hotmail.com
In-Reply-To:
Message-ID:
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060611/5c151b76/attachment.htm
From kent37 at tds.net Mon Jun 12 11:59:16 2006
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 12 Jun 2006 05:59:16 -0400
Subject: [Tutor] assignment statements in python
In-Reply-To: <448CCE0D.00000F.01420@YOUR-4105E587B6>
References: <448CCE0D.00000F.01420@YOUR-4105E587B6>
Message-ID: <448D3AF4.20403@tds.net>
Kermit Rose wrote:
>
> Message: 1
> Date: Sun, 11 Jun 2006 06:58:39 -0400
> From: Kent Johnson
> Subject: Re: [Tutor] buggy bug in my program
> Cc: tutor at python.org
>
> Assignment in Python is not a copy, it is a name binding. Assignment
> creates a name for an object. If you assign the same object to two
> names, they both are bound to the same thing. If the object is mutable,
> like a list, changes to the object will be seen regardless of which name
> you use to refer to it.
>
> ******
>
> I feel a little bit better now that I know that there is a reason for what
> my
> program did.
>
> However, I still don't have any idea how to copy values from one cell in
> an array to the adjacent cell in the same array.
You need to copy the value stored in the list, which is itself a list.
> It must be possible, for otherwise, you could not sort an array.
Actually sorting doesn't require copying the values in the list, it just
requires moving values to different locations of the list.
A list element is somewhat like a name - it is a reference to a value,
not a container for a value.
If you say
a=[1,2,3]
b=a
then a and b refer to the same list. Likewise, if you say
x=[ [1,2,3], [4,5,6] ]
x[1] = x[0]
then x[1] and x[0] refer to the same list. If you want x[1] (or b) to
refer to a new list, you have to copy the old list:
x[1] = x[0][:]
list[:] is the slice of the list that goes from the beginning to the end
- a copy.
Kent
From andrew.arobert at gmail.com Mon Jun 12 13:53:05 2006
From: andrew.arobert at gmail.com (Andrew Robert)
Date: Mon, 12 Jun 2006 07:53:05 -0400
Subject: [Tutor] Python related mags
Message-ID: <448D55A1.6010002@gmail.com>
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Hi everyone,
Does anyone know of any Python related magazines available that would be
worth subscribing to?
Ideally, a free one, but I would not object to a reasonably priced one
either.
I was able to find pyzine located at www.pyzine.com but it appears to be
defunct.
- --
Thank you,
Andrew Robert
Systems Architect
Information Technologies
MFS Investment Management
Phone: 617-954-5882
E-mail: arobert at mfs.com
Linux User Number: #201204
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (MingW32)
Comment: GnuPT 2.7.2
iD8DBQFEjVWhDvn/4H0LjDwRAtsnAJwJ6I6elkmzCwmJUNC3CxDPxjR3bQCeOwL6
IMxn+qVOqe4uwuaCrGA8Qww=
=hJPj
-----END PGP SIGNATURE-----
From patriciap.gu at gmail.com Mon Jun 12 15:32:33 2006
From: patriciap.gu at gmail.com (Patricia G.)
Date: Mon, 12 Jun 2006 09:32:33 -0400
Subject: [Tutor] connect to a remote machine - Linux
In-Reply-To:
References:
<20060611224126.EYTT24467.aamtaout02-winn.ispmail.ntl.com@ROYXP1>
<18f27cbe0606111648h1a257f53q2fbc8061c3938d4f@mail.gmail.com>
Message-ID: <18f27cbe0606120632x7ebc390ay6074c2eaa8312920@mail.gmail.com>
Thank you for the great explanation, Danny.. I was confused...
Thank you all for your help!
Patricia
On 6/11/06, Danny Yoo wrote:
>
>
>
> > I'm sorry. I think I didn't explain myself well. My problem is not with
> > the database.. The part I'm not sure how to do is connect to the remote
> > computer..
>
> Hi Patricia,
>
> There's some confusion here. Let's get that out in the open.
>
> It sounds like you have a remote server. That server provides login shell
> service through ssh, and this login shell service runs on port 22, I
> think. But if your server is running MySQL, it is very likely that it
> provides network access to that MySQL database through port 3306.
>
> I think you believe that ssh login access is required to access MySQL on
> your remote network server. But this is not necessarily true: one can
> access MySQL remotely without having a login shell account into the
> machine. That is, rather than:
>
> Client ----> Login through SSH ----> Execute mysql client
>
> which is three steps, the conventional route here is:
>
> Client ----> Connect to networked MySQL using a database driver
> (MySQLdb)
>
> which is more direct.
>
>
> See:
>
> MySQLdb: http://sourceforge.net/projects/mysql-python
>
> as well as:
>
> http://www.devshed.com/c/a/Python/MySQL-Connectivity-With-Python/
>
>
> However, this does mean that the remote MySQL server has to be set up with
> a separate MySQL username/password account. That is, MySQL keeps its own
> set of usernames and passwords that can be separate from the shell
> logins.
>
> Also, mysqld --- the software that drives the MySQL server --- has to be
> enabled to work across tcp. That requirement sounds obvious enough, but
> it is not the default in the MySQL server installs I've seen lately, so
> double check this with your database system administrator. In short: you
> can not automatically assume that having login access to the machine will
> give you MySQL database access, and visa-versa.
>
> Does this make sense so far?
>
>
> > I read somewhere that os.popen would work, but I'm not sure if that will
> > do for me
>
> Almost certainly no.
>
> popen is not for external database access. People have written database
> drivers to solve this problem for you already. It is perhaps possible to
> bend popen() in such a way to access MySQL, but this will involve an
> amount of work to get right, and there will be a lot of ways of getting it
> wrong. *grin*
>
>
> So I'd recommend changing this question from: "How do I get popen() to
> access MySQL across a remote interface?" to a more general: "How do I
> connect to MySQL from Python?" The link above to MySQLdb will give you
> the software necessary to connect your client to a MySQL server, and the
> link to the Devshed article is a tutorial on how to use it effectively.
>
>
> Good luck!
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060612/98ba0d73/attachment.htm
From jfabiani at yolo.com Mon Jun 12 15:47:23 2006
From: jfabiani at yolo.com (johnf)
Date: Mon, 12 Jun 2006 06:47:23 -0700
Subject: [Tutor] Wondering is there a pyQT list
Message-ID: <200606120647.23493.jfabiani@yolo.com>
Hi,
I was wondering if there is a pyqt list like the
wxPython-users at lists.wxwidgets.org list?
Thanks
John
From andrew.arobert at gmail.com Mon Jun 12 15:56:09 2006
From: andrew.arobert at gmail.com (Andrew Robert)
Date: Mon, 12 Jun 2006 09:56:09 -0400
Subject: [Tutor] Odd traceback - invalid token when extracting contents of
XML data element
Message-ID: <448D7279.4040600@gmail.com>
Hi Everyone,
Attached are three scripts that I intend to use for transporting a file
via IBM's WebSphere MQSeries middle-ware.
The sender script uses a regular expression to replace characters not
[a-z][A-Z][0-9] or white space with their hex value equivalents.
The purpose of this is to make the contents of a transported file
viewable inside MQSeries queues.
The attached code works just fine for transporting ASCII text files but
it bombs with the following trace when run against binary files.
Does anyone know why this might be occurring?
Traceback (most recent call last):
File "M:\MQ\MQ\Scripts\receiver.py", line 267, in ?
receiver.run()
File "M:\MQ\MQ\Scripts\receiver.py", line 110, in run
self.get()
File "M:\MQ\MQ\Scripts\receiver.py", line 139, in get
tree = ElementTree(file=buff)
File "C:\Python24\Lib\site-packages\elementtree\ElementTree.py", line
543, in __init__
self.parse(file)
File "C:\Python24\Lib\site-packages\elementtree\ElementTree.py", line
583, in parse
parser.feed(data)
File "C:\Python24\Lib\site-packages\elementtree\ElementTree.py", line
1242, in feed
self._parser.Parse(data, 0)
xml.parsers.expat.ExpatError: not well-formed (invalid token): line 3,
column 39
I think that a particular character is perhaps not being translated to
ascii as required but I don't know which one it mught be.
Part of the reason for this encoding mechanism is so that it plays nice
with existing perl code already in place.
Not my choice, but what can you do.
Any help you can provide on this would be greatly appreciated.
--
Thank you,
Andrew Robert
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: sender.py
Url: http://mail.python.org/pipermail/tutor/attachments/20060612/6c17823d/attachment-0002.pot
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: file_encoder.py
Url: http://mail.python.org/pipermail/tutor/attachments/20060612/6c17823d/attachment-0001.asc
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: receiver.py
Url: http://mail.python.org/pipermail/tutor/attachments/20060612/6c17823d/attachment-0003.pot
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 208 bytes
Desc: OpenPGP digital signature
Url : http://mail.python.org/pipermail/tutor/attachments/20060612/6c17823d/attachment-0001.pgp
From michael at espersunited.com Mon Jun 12 15:56:46 2006
From: michael at espersunited.com (Michael Sullivan)
Date: Mon, 12 Jun 2006 08:56:46 -0500
Subject: [Tutor] assignment statements in python
In-Reply-To: <448CCE0D.00000F.01420@YOUR-4105E587B6>
References: <448CCE0D.00000F.01420@YOUR-4105E587B6>
Message-ID: <1150120606.10767.6.camel@camille.espersunited.com>
On Sun, 2006-06-11 at 22:14 -0400, Kermit Rose wrote:
> Message: 1
> Date: Sun, 11 Jun 2006 06:58:39 -0400
> From: Kent Johnson
> Subject: Re: [Tutor] buggy bug in my program
> Cc: tutor at python.org
>
> Assignment in Python is not a copy, it is a name binding. Assignment
> creates a name for an object. If you assign the same object to two
> names, they both are bound to the same thing. If the object is mutable,
> like a list, changes to the object will be seen regardless of which name
> you use to refer to it.
>
> ******
In that case, is it possible to copy a variable by value, instead of by
reference, in Python?
From dyoo at hkn.eecs.berkeley.edu Mon Jun 12 16:20:19 2006
From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo)
Date: Mon, 12 Jun 2006 07:20:19 -0700 (PDT)
Subject: [Tutor] assignment statements in python
In-Reply-To: <1150120606.10767.6.camel@camille.espersunited.com>
References: <448CCE0D.00000F.01420@YOUR-4105E587B6>
<1150120606.10767.6.camel@camille.espersunited.com>
Message-ID:
>> Assignment in Python is not a copy, it is a name binding. Assignment
>> creates a name for an object. If you assign the same object to two
>> names, they both are bound to the same thing. If the object is mutable,
>> like a list, changes to the object will be seen regardless of which
>> name you use to refer to it.
>>
>> ******
>
> In that case, is it possible to copy a variable by value, instead of by
> reference, in Python?
The 'copy' module is available,
http://www.python.org/doc/lib/module-copy.html
So in a pinch, if we're really paranoid, we can pass copies of our
argument values to a function. In general, though, a function should
really document if it mutates its arguments, because that's generally a
very rude thing to do unless it's the expected behavior.
From doug.shawhan at gmail.com Mon Jun 12 16:34:23 2006
From: doug.shawhan at gmail.com (doug shawhan)
Date: Mon, 12 Jun 2006 09:34:23 -0500
Subject: [Tutor] XML: Expletive Deleted
In-Reply-To: <448AAE28.1000701@tds.net>
References: <5e1ceb8a0606091528i52471b44v228626e453343e4a@mail.gmail.com>
<448AAE28.1000701@tds.net>
Message-ID: <5e1ceb8a0606120734y489cf1bdt63f6258dd652f7ba@mail.gmail.com>
Kent, Danny, Lawrence, et. al.
Thanks!
I was kind of cringing as I sent this plaint/rant, but it seems I'm not the
only one who has had trouble grokking DOM. I spanked the problem temporarily
with regex, but can now actually fix it properly.
Appreciate all the help!
On 6/10/06, Kent Johnson wrote:
>
> In my opinion the standard DOM models are the most awkward way to deal
> with XML. If you are trying to get data from HTML on a web page, look at
> BeautifulSoup. For general XML processing, look at ElementTree. They are
> both simpler than DOM.
> http://www.crummy.com/software/BeautifulSoup/
> http://effbot.org/zone/element.htm
>
> Kent
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060612/3b828444/attachment.htm
From python at venix.com Mon Jun 12 17:20:55 2006
From: python at venix.com (Python)
Date: Mon, 12 Jun 2006 11:20:55 -0400
Subject: [Tutor] assignment statements in python
In-Reply-To: <448D6E09.000001.03656@YOUR-4105E587B6>
References: <1150081144.24742.310.camel@www.venix.com>
<448D6E09.000001.03656@YOUR-4105E587B6>
Message-ID: <1150125655.24742.328.camel@www.venix.com>
On Mon, 2006-06-12 at 09:37 -0400, Kermit Rose wrote:
>
> From: Python
> Date: 06/11/06 22:59:38
> To: Kermit Rose
> Cc: Tutor Python
> Subject: Re: [Tutor] assignment statements in python
>
>
> The basic python objects: numbers, strings, and tuples are immutable and
> can not be changed (mutated).
> a = B = 3
> B = 4 # binds B to a different object with value 4
> # the object with value 3 is unchanged
> print a
> 3
>
> **
> If I write
>
> a = 3
> a = 4
> a = 5
>
> Are the objects containing 3 and 4 erased when they no longer have a name?
Yes
>
> **
>
> >>>>>
>
> Container objects such as lists and dictionaries can be changed in
> place.
> >>> a = B = [1,2,3]
> >>> B.append(4) # changes (mutates) B
> >>> print a
> [1, 2, 3, 4]
>
> ******
>
> Good. Now I know a more efficient way to extend an array.
>
> I had been creating an entire new array, and equivalencing the old array to
> it.
>
> ******
> >>>>>>
>
> >>> B[2] = B[3] # positions 2 and 3 reference the same object
> >>> print B
> [1, 2, 4, 4]
> >>> print a
> [1, 2, 4, 4]
>
> ******
>
> I still don't know how to make it so that
>
> If B = [ 1,2,4,5]
>
> B.append(value of B[4])
There is no B[4]
B[0] is 1
B[1] is 2
B[2] is 4
B[3] is 5
Perhaps you mean to search B looking for the value 4 and then append
that value?
index_of_4 = B.index(4) # returns index to location of first 4
B.append( B[index_of_4]) # appends the 4 to the end of B
> copy the value of B[2] into B[3]
>>> import copy
>>> B = [ 1,2,4,5]
>>> B[3] = copy.copy(B[2])
>>> B
[1, 2, 4, 4]
Since 4 is immutable, there is no need to use the copy module, but it is
there for when you need to make copies of an object.
> copy the value 3 into B[2].
B[2] = 3 # no need for a copy since 3 is immutable
>
>
> Or, equivalently,
>
> If B = [1,2,4,5]
>
> Insert the value 3 between
> B[1] and b[2],
>
>>> B = [ 1,2,4,5]
>>> B.insert(2,3) # inserts 3 before B[2]
>>> B
[1, 2, 3, 4, 5]
>>> help(B.insert)
insert(...)
L.insert(index, object) -- insert object before index
(Use q to leave the help screen)
> so that B
> becomes
> [1,2,3,4,5].
> > Kermit < kermit at polaris.net >
> >
> >
> >
> > _______________________________________________
> > Tutor maillist - Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
--
Lloyd Kvam
Venix Corp
From kermit at polaris.net Mon Jun 12 17:26:33 2006
From: kermit at polaris.net (Kermit Rose)
Date: Mon, 12 Jun 2006 11:26:33 -0400 (Eastern Daylight Time)
Subject: [Tutor] sorting in python
Message-ID: <448D87A8.00000D.03656@YOUR-4105E587B6>
Message: 6
Date: Mon, 12 Jun 2006 05:59:16 -0400
From: Kent Johnson
Subject: Re: [Tutor] assignment statements in python
Actually sorting doesn't require copying the values in the list, it just
requires moving values to different locations of the list.
*****
Yes. I wish to know how I can , for examplem,
given
B = [1,2,4,5],
move B[3] to a position of newly created B[4],
move B[2] to position of B[3]
Assign value 3 to position B[2].
That is, I wish to insert the value 3, into it's sorted place within the
already sorted list B.
****
>>>>>
A list element is somewhat like a name - it is a reference to a value,
not a container for a value.
If you say
a=[1,2,3]
B=a
then a and B refer to the same list. Likewise, if you say
x=[ [1,2,3], [4,5,6] ]
x[1] = x[0]
then x[1] and x[0] refer to the same list.
***
>>> x = [ [1,2,3],[4,5,6]]
>>> x
[[1, 2, 3], [4, 5, 6]]
>>> x[1] = x[0]
>>> x
[[1, 2, 3], [1, 2, 3]]
>>>
Needed to make sure I understood what would happen.
Does the value [4,5,6] get erased at this point?
********
If you want x[1] (or B) to
refer to a new list, you have to copy the old list:
x[1] = x[0][:]
list[:] is the slice of the list that goes from the beginning to the end
- a copy.
*****
I missed the significance of the [:] slice until you explained it.
So, now I could write my code as
# to insert 3 between 2 and 4 in
B = [1,2,4,5]
B.append(B[3:3])
# I expected B[4] to have the value 5 at this point.
# It is empty. Why?
# So, I compensate by making the next line
B[4] = B[3:3]
# B[4] is still an empty list. Why?
# I try
B[4] = B[3]
# That seemed to work.
B[3] = B[2]
# Now I try
B[2] = 3
That worked.
However, I don't see the difference between this code,
and what I had before that did not work.
Kermit < kermit at polaris.net >
Kent
From python at venix.com Mon Jun 12 17:44:50 2006
From: python at venix.com (Python)
Date: Mon, 12 Jun 2006 11:44:50 -0400
Subject: [Tutor] sorting in python
In-Reply-To: <448D87A8.00000D.03656@YOUR-4105E587B6>
References: <448D87A8.00000D.03656@YOUR-4105E587B6>
Message-ID: <1150127090.24742.340.camel@www.venix.com>
On Mon, 2006-06-12 at 11:26 -0400, Kermit Rose wrote:
> # to insert 3 between 2 and 4 in
>
> B = [1,2,4,5]
>
> B.append(B[3:3])
>>> B[3:3]
[]
>>> B[3:4]
[5]
>>> B[0:1]
[1]
>>> B[:2]
[1, 2]
>>> B.append(B[3:3])
>>> B
[1, 2, 4, 5, []]
>
> # I expected B[4] to have the value 5 at this point.
> # It is empty. Why?
You appended an empty list.
Note that slice notation returns a list, so you would more commonly use
B.extend(B[0:3]) to avoid nested lists.
The number before the : is the index to include from
The number after the : is the index to exclude
Slices are half-open intervals. The lower-bound is included while the
upper-bound is excluded.
http://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF
Provides an excellent justification for this approach
(cited recently on this list)
--
Lloyd Kvam
Venix Corp
From Barry.Carroll at psc.com Mon Jun 12 18:55:53 2006
From: Barry.Carroll at psc.com (Carroll, Barry)
Date: Mon, 12 Jun 2006 09:55:53 -0700
Subject: [Tutor] XML: Expletive Deleted (OT)
Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C36B8@eugsrv400.psc.pscnet.com>
Alan, Ralph, et al:
This is a little off-topic, I guess, being not directly related to
Python. Oh, well. Here are a couple of personal opinions and a
question about XML.
> -----Original Message-----
> Date: Sun, 11 Jun 2006 08:55:17 +0100
> From: "Alan Gauld"
> Subject: Re: [Tutor] Expletive Deleted
> To: "Ralph H. Stoos Jr." ,
> Message-ID: <001d01c68d2c$62077090$0301a8c0 at XPpro>
> Content-Type: text/plain; format=flowed; charset="iso-8859-1";
> reply-type=original
>
> > I think XML is a tool that allows non-programmers to look at
> > structured
> > data and have it a in human readable form that gives us a chance of
> > understanding that structure.
>
> Thats not a great reason to choose a file format IMHO.
> Tools can be written to display data in a readable format.
> For example SQL can be used to view the data in a database.
> File formats should be designed to store data, compactly
> and with easy access.
One reason to for choosing a human-readable format is the desire to
visually confirm the correctness of the stored data and format. This
can be invaluable when troubleshooting a bug involving stored data. If
there is a tool between the user and the data, one must then rely upon
the correctness of the tool to determine the correctness of the data.
In a case like this, nothing beats the evidence of one's eyes, IMHO.
In their book, "The Pragmatic Programmer: From Journeyman to Master"
(Addison Wesley Professional), Andrew Hunt and David Thomas give another
reason for storing data in human readable form:
The problem with most binary formats is that the context necessary
to understand the data is separate from the data itself. You are
artificially divorcing the data from its meaning. The data may
as well be encrypted; it is absolutely meaningless without the
application logic to parse it. With plain text, however, you can
achieve a self-describing data stream that is independent of the
application that created it.
Tip 20
Keep Knowledge in Plain Text
> > The other strength that I can see is this: Once data is in this
> > format,
> > and a tool has been written to parse it, data can be added to the
> > structure (more elements) and the original tool will not be broken
> > by
> > this. Whatever it is parsed for is found and the extra is ignored.
>
> But this is a very real plus point for XML.
> And this IMHO is the biggest single reason for using it, if you have
> data where the very structure itself is changing yet the same file
> has to be readable by old and new clients then XML is a good choice.
No argument there.
> > Without a doubt, the overhead XML adds over say, something as simple
> > as
> > CSV is considerable, and XML would appear to be rather more hard to
> > work
> > with in things like Python and PERL.
>
> Considerable is an understatement, its literally up to 10 or 20 times
> more space and that means bandwidth and CPU resource to
> process it.
>
> Using XML as a storage medium - a file - is not too bad, you suck
> it up, process it and foirget the file. MY big gripe is that people
> are
> inceasingly trying to use XML as the payload in comms systems,
> sending XML messages around. This is crazy! The extra cost of the
> network and hardware needed to process that kind of architecture
> is usually far higher than the minimal savings it gives in developer
> time.
> [As an example I recently had to uplift the bandwidth of the
> intranet pipe in one of our buildings from 4Mb to a full ATM pipe
> of 34Mb just to accomodate a system 'upgrade' that now used XML.
> That raised the network operations cost of that one building
> from $10k per year to over $100k! - The software upgrade by
> contrast was only a one-off cost of $10K]
This is an example of the resource balancing act that computer people
have been faced with since the beginning. The most scarce/expensive
resource dictates the program's/system's design. In Alan's example high
speed bandwidth is the limiting resource. A data transmission method
that fails to minimize use of that resource is therefore a bad solution.
Python itself is a result of this balancing act. Interpreted languages
like Basic were invented to overcome the disadvantages of writing of
programs in machine-readable, human-unfriendly formats. Compiled
languages like C were invented to overcome the slow execution speed of
interpreted programs. As processor speeds increased and execution times
dropped , interpreted languages like Python once again became viable for
large scale programs.
> > So, I think XML has it's place but I will not fault anyone for
> > trying to
> > make it easier to get code to work.
>
> Absolutely agree with that. Just be careful how you use it and
> think of the real cost impact you may be having if its your choice.
> Your customers will thank you.
So here's my off-topic question: Ajax is being touted as the 'best-known
method' (BKM) for making dynamic browser-based applications, and XML is
the BKM for transferring data in Ajax land. If XML is a bad idea for
network data-transfer, what medium should be used instead?
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
Regards,
Barry
barry.carroll at psc.com
541-302-1107
________________________
We who cut mere stones must always be envisioning cathedrals.
-Quarry worker's creed
From kent37 at tds.net Mon Jun 12 19:14:46 2006
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 12 Jun 2006 13:14:46 -0400
Subject: [Tutor] XML: Expletive Deleted (OT)
In-Reply-To: <2BBAEE949D384D40A2B851287ADB6A432C36B8@eugsrv400.psc.pscnet.com>
References: <2BBAEE949D384D40A2B851287ADB6A432C36B8@eugsrv400.psc.pscnet.com>
Message-ID: <448DA106.2030008@tds.net>
Carroll, Barry wrote:
> So here's my off-topic question: Ajax is being touted as the 'best-known
> method' (BKM) for making dynamic browser-based applications, and XML is
> the BKM for transferring data in Ajax land. If XML is a bad idea for
> network data-transfer, what medium should be used instead?
JSON is a popular alternative to XML for Ajax applications. It is much
lighter-weight than XML and easier to parse in JavaScript.
http://json.org/
Kent
From Barry.Carroll at psc.com Mon Jun 12 19:35:24 2006
From: Barry.Carroll at psc.com (Carroll, Barry)
Date: Mon, 12 Jun 2006 10:35:24 -0700
Subject: [Tutor] Python related mags
Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C36B9@eugsrv400.psc.pscnet.com>
Hello, Andrew:
> -----Original Message-----
> Date: Mon, 12 Jun 2006 07:53:05 -0400
> From: Andrew Robert
> Subject: [Tutor] Python related mags
> To: Python Tutor
> Message-ID: <448D55A1.6010002 at gmail.com>
> Content-Type: text/plain; charset=ISO-8859-1
>
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> Hi everyone,
>
> Does anyone know of any Python related magazines available that would
be
> worth subscribing to?
>
> Ideally, a free one, but I would not object to a reasonably priced one
> either.
>
> I was able to find pyzine located at www.pyzine.com but it appears to
be
> defunct.
Dr. Dobbs puts out a weekly Python related e-zine that be useful to you.
I couldn't find the URL, but I get a link to it every week in the
Python-announce-list:
http://mail.python.org/mailman/listinfo/python-announce-list.
HTH.
Barry
barry.carroll at psc.com
541-302-1107
________________________
We who cut mere stones must always be envisioning cathedrals.
-Quarry worker's creed
From simplebob at gmail.com Mon Jun 12 21:08:17 2006
From: simplebob at gmail.com (Daniel McQuay)
Date: Mon, 12 Jun 2006 15:08:17 -0400
Subject: [Tutor] please remove this address from list: efoda@hotmail.com
In-Reply-To:
References:
Message-ID: <6d87ecf40606121208o8510991h5909d6f550fb9507@mail.gmail.com>
you will need to do it yourself.
http://mail.python.org/mailman/listinfo/python-list
On 6/12/06, graphic design wrote:
>
> not sure how i got on this list. please remove my email address from it.
>
> thank you.
>
> efoda at hotmail.com
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
sorry,
--
Daniel McQuay
simplebob at gmail.com
boxster.homelinux.org
H: 814.825.0847
M: 814-341-6233
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060612/ebfc62f7/attachment.html
From doug.shawhan at gmail.com Mon Jun 12 21:46:06 2006
From: doug.shawhan at gmail.com (doug shawhan)
Date: Mon, 12 Jun 2006 14:46:06 -0500
Subject: [Tutor] datetime: What happended yesterday? :-)
Message-ID: <5e1ceb8a0606121246oe8c3cd0teeb76e9bd6897098@mail.gmail.com>
I've been looking at datetime and cannot figure out what was a very simple
operation with the time module.
How does one add or subtract 24 (or any number) of hours from a given date
and time using the datetime module?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060612/6531f220/attachment.htm
From patriciap.gu at gmail.com Mon Jun 12 21:48:14 2006
From: patriciap.gu at gmail.com (patricia)
Date: Mon, 12 Jun 2006 19:48:14 +0000 (UTC)
Subject: [Tutor] Mod-python
Message-ID:
Hi!
I have about 17 lines of text (about system information) that I need to pass to
a remote web server AND I've been asked to send this data via Apache. I have to
write a python script that will fetch a URL to pass this text. I understand that
if I want to use the POST method, I would need to have a page with a submit
button, and this is not the case. I also know that with GET, the length of the
url is limited. What is the best way to send a long string?
Hope anyone can point me to the right direction..
Thanks,
Patricia
From dustin at ywlcs.org Mon Jun 12 21:58:30 2006
From: dustin at ywlcs.org (Dustin Mitchell)
Date: Mon, 12 Jun 2006 14:58:30 -0500
Subject: [Tutor] Mod-python
In-Reply-To:
References:
Message-ID: <26b656a95a747a4effd024fce7ab319b@ywlcs.org>
Well, POST or PUT are the normal ways to do that. You need to interact
with the person running the web server to see how they need it
delivered - if they're expecting a GET and you give them a POST, it
isn't going to work very well :)
Dustin
On Jun 12, 2006, at 2:48 PM, patricia wrote:
> Hi!
>
> I have about 17 lines of text (about system information) that I need
> to pass to
> a remote web server AND I've been asked to send this data via Apache.
> I have to
> write a python script that will fetch a URL to pass this text. I
> understand that
> if I want to use the POST method, I would need to have a page with a
> submit
> button, and this is not the case. I also know that with GET, the
> length of the
> url is limited. What is the best way to send a long string?
>
> Hope anyone can point me to the right direction..
> Thanks,
> Patricia
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
From kent37 at tds.net Mon Jun 12 22:08:57 2006
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 12 Jun 2006 16:08:57 -0400
Subject: [Tutor] datetime: What happended yesterday? :-)
In-Reply-To: <5e1ceb8a0606121246oe8c3cd0teeb76e9bd6897098@mail.gmail.com>
References: <5e1ceb8a0606121246oe8c3cd0teeb76e9bd6897098@mail.gmail.com>
Message-ID: <448DC9D9.8040902@tds.net>
doug shawhan wrote:
> I've been looking at datetime and cannot figure out what was a very
> simple operation with the time module.
>
> How does one add or subtract 24 (or any number) of hours from a given
> date and time using the datetime module?
Use a datetime.timedelta:
In [1]: import datetime
In [2]: now = datetime.datetime.now()
In [3]: now
Out[3]: datetime.datetime(2006, 6, 12, 16, 7, 47, 69000)
In [4]: one_day = datetime.timedelta(hours=24)
In [5]: now-one_day
Out[5]: datetime.datetime(2006, 6, 11, 16, 7, 47, 69000)
Kent
From doug.shawhan at gmail.com Mon Jun 12 22:20:41 2006
From: doug.shawhan at gmail.com (doug shawhan)
Date: Mon, 12 Jun 2006 15:20:41 -0500
Subject: [Tutor] datetime: What happended yesterday? :-)
In-Reply-To: <448DC9D9.8040902@tds.net>
References: <5e1ceb8a0606121246oe8c3cd0teeb76e9bd6897098@mail.gmail.com>
<448DC9D9.8040902@tds.net>
Message-ID: <5e1ceb8a0606121320w1d6cb3c4o41ccf5211eceb431@mail.gmail.com>
Heh. Your example would look very, very nice in the timedelta (
http://docs.python.org/lib/datetime-timedelta.html) section of the docs! :-)
It makes perfect sense, the authors probably thought it was too easy to need
an explaination ...
On 6/12/06, Kent Johnson wrote:
>
> doug shawhan wrote:
> > I've been looking at datetime and cannot figure out what was a very
> > simple operation with the time module.
> >
> > How does one add or subtract 24 (or any number) of hours from a given
> > date and time using the datetime module?
>
> Use a datetime.timedelta:
>
> In [1]: import datetime
>
> In [2]: now = datetime.datetime.now()
>
> In [3]: now
> Out[3]: datetime.datetime(2006, 6, 12, 16, 7, 47, 69000)
>
> In [4]: one_day = datetime.timedelta(hours=24)
>
> In [5]: now-one_day
> Out[5]: datetime.datetime(2006, 6, 11, 16, 7, 47, 69000)
>
> Kent
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060612/7a16065d/attachment.html
From kent37 at tds.net Mon Jun 12 22:34:27 2006
From: kent37 at tds.net (Kent Johnson)
Date: Mon, 12 Jun 2006 16:34:27 -0400
Subject: [Tutor] datetime: What happended yesterday? :-)
In-Reply-To: <5e1ceb8a0606121320w1d6cb3c4o41ccf5211eceb431@mail.gmail.com>
References: <5e1ceb8a0606121246oe8c3cd0teeb76e9bd6897098@mail.gmail.com> <448DC9D9.8040902@tds.net>
<5e1ceb8a0606121320w1d6cb3c4o41ccf5211eceb431@mail.gmail.com>
Message-ID: <448DCFD3.9040302@tds.net>
doug shawhan wrote:
> Heh. Your example would look very, very nice in the timedelta
> (http://docs.python.org/lib/datetime-timedelta.html) section of the
> docs! :-)
>
> It makes perfect sense, the authors probably thought it was too easy to
> need an explaination ...
It is noted in the "Supported operations" for datetime, buried in the
middle of this page:
http://docs.python.org/lib/datetime-datetime.html
Kent
From pjlists at gmail.com Mon Jun 12 23:09:21 2006
From: pjlists at gmail.com (Peter Jessop)
Date: Mon, 12 Jun 2006 23:09:21 +0200
Subject: [Tutor] Mod-python
In-Reply-To:
References:
Message-ID: <7a8d5a0c0606121409r450073eav6f276b3d77f478f@mail.gmail.com>
>
> I have about 17 lines of text (about system information) that I need to pass to
> a remote web server AND I've been asked to send this data via Apache. I have to
> write a python script that will fetch a URL to pass this text. I understand that
> if I want to use the POST method, I would need to have a page with a submit
> button, and this is not the case. I also know that with GET, the length of the
> url is limited. What is the best way to send a long string?
When you say you that you want to send this data via Apache do you
mean that the web server you are sending to is running Apache or that
you are communicating from one server to another?
If you simply want to emulate a a web page with a submit button that
sends a Post you do it with code a bit like the following
import urllib, urllib2
url = "http://www.somesite.com/somefolder/exampl1.cgi"
dict = {}
dict["field1"] = "value1"
dict["field2"] = "value2"
...
dict["fieldn"] = "valuen"
urldata = urllib.urlencode(dict)
req = urllib2.Request(url)
req.add_header('User-agent','Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0')
fd = urllib2.urlopen(req,urldata)
Regards
Peter Jessop
>
> Hope anyone can point me to the right direction..
> Thanks,
> Patricia
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
From patriciap.gu at gmail.com Mon Jun 12 23:40:28 2006
From: patriciap.gu at gmail.com (Patricia G.)
Date: Mon, 12 Jun 2006 17:40:28 -0400
Subject: [Tutor] Mod-python
In-Reply-To: <7a8d5a0c0606121409r450073eav6f276b3d77f478f@mail.gmail.com>
References:
<7a8d5a0c0606121409r450073eav6f276b3d77f478f@mail.gmail.com>
Message-ID: <18f27cbe0606121440v6630fd08u98d2dd1293cb69e9@mail.gmail.com>
Hi,
>
> When you say you that you want to send this data via Apache do you
> mean that the web server you are sending to is running Apache
Yes.
If you simply want to emulate a a web page with a submit button that
> sends a Post you do it with code a bit like the following
>
> import urllib, urllib2
> url = "http://www.somesite.com/somefolder/exampl1.cgi"
> dict = {}
> dict["field1"] = "value1"
> dict["field2"] = "value2"
> ...
> dict["fieldn"] = "valuen"
> urldata = urllib.urlencode(dict)
> req = urllib2.Request(url)
> req.add_header('User-agent','Mozilla/4.0 (compatible; MSIE 5.5; Windows NT
> 5.0')
> fd = urllib2.urlopen(req,urldata)
>
> Regards
> Peter Jessop
I'll try this out. Thank you!
Patricia
>
> > Hope anyone can point me to the right direction..
> > Thanks,
> > Patricia
> >
> > _______________________________________________
> > Tutor maillist - Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060612/0a0e21de/attachment.htm
From mahansen at adelphia.net Mon Jun 12 18:56:09 2006
From: mahansen at adelphia.net (Mike Hansen)
Date: Mon, 12 Jun 2006 10:56:09 -0600
Subject: [Tutor] Python related mags
In-Reply-To: <448D55A1.6010002@gmail.com>
References: <448D55A1.6010002@gmail.com>
Message-ID: <6ba92c331537c6ac94e2bc18e2662757@adelphia.net>
On Jun 12, 2006, at 5:53 AM, Andrew Robert wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> Hi everyone,
>
> Does anyone know of any Python related magazines available that would
> be
> worth subscribing to?
>
> Ideally, a free one, but I would not object to a reasonably priced one
> either.
>
> I was able to find pyzine located at www.pyzine.com but it appears to
> be
> defunct.
>
>
I don' think there's much out there. Sometime Linux Journal will have
Python related articles, sometimes Dr. Dobbs. As popular as Python is,
it's probably not popular enough to sustain a magazine devoted just to
it.
Mike
From andrew.arobert at gmail.com Tue Jun 13 03:13:55 2006
From: andrew.arobert at gmail.com (Andrew Robert)
Date: Mon, 12 Jun 2006 21:13:55 -0400
Subject: [Tutor] Python related mags
In-Reply-To: <6ba92c331537c6ac94e2bc18e2662757@adelphia.net>
References: <448D55A1.6010002@gmail.com>
<6ba92c331537c6ac94e2bc18e2662757@adelphia.net>
Message-ID: <448E1153.1080106@gmail.com>
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Now that is a real pity.
Wish I were talented enough to do it myself.
Mike Hansen wrote:
> On Jun 12, 2006, at 5:53 AM, Andrew Robert wrote:
>
>> -----BEGIN PGP SIGNED MESSAGE-----
>> Hash: SHA1
>>
>> Hi everyone,
>>
>> Does anyone know of any Python related magazines available that would
>> be
>> worth subscribing to?
>>
>> Ideally, a free one, but I would not object to a reasonably priced one
>> either.
>>
>> I was able to find pyzine located at www.pyzine.com but it appears to
>> be
>> defunct.
>>
>>
> I don' think there's much out there. Sometime Linux Journal will have
> Python related articles, sometimes Dr. Dobbs. As popular as Python is,
> it's probably not popular enough to sustain a magazine devoted just to
> it.
>
> Mike
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
- --
Thank you,
Andrew Robert
Systems Architect
Information Technologies
MFS Investment Management
Phone: 617-954-5882
E-mail: arobert at mfs.com
Linux User Number: #201204
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (MingW32)
Comment: GnuPT 2.7.2
iD8DBQFEjhFTDvn/4H0LjDwRAq14AJ9RzCA4o5pNW6y47c1mM/Tzm0R3EACfZ0ec
KxReJbvZERlj2gHx4Y+FB58=
=kKr8
-----END PGP SIGNATURE-----
From billburns at pennswoods.net Tue Jun 13 02:51:12 2006
From: billburns at pennswoods.net (Bill Burns)
Date: Mon, 12 Jun 2006 20:51:12 -0400
Subject: [Tutor] Wondering is there a pyQT list
In-Reply-To: <200606120647.23493.jfabiani@yolo.com>
References: <200606120647.23493.jfabiani@yolo.com>
Message-ID: <448E0C00.6080607@pennswoods.net>
johnf wrote:
> Hi,
> I was wondering if there is a pyqt list like the
> wxPython-users at lists.wxwidgets.org list?
>
http://mats.imk.fraunhofer.de/mailman/listinfo/pykde
From michael at espersunited.com Tue Jun 13 04:26:12 2006
From: michael at espersunited.com (Michael Sullivan)
Date: Mon, 12 Jun 2006 21:26:12 -0500
Subject: [Tutor] Python related mags
In-Reply-To: <448E1153.1080106@gmail.com>
References: <448D55A1.6010002@gmail.com>
<6ba92c331537c6ac94e2bc18e2662757@adelphia.net>
<448E1153.1080106@gmail.com>
Message-ID: <1150165573.10769.7.camel@camille.espersunited.com>
On Mon, 2006-06-12 at 21:13 -0400, Andrew Robert wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> Now that is a real pity.
>
> Wish I were talented enough to do it myself.
Someone could do something like Tux Magazine
(http://www.tuxmagazine.org/) . Each month they put out a free Linux
magazine in the form of a downloadable pdf file. It's supposed to be
geared toward new Linux users. I particularly like the pdf format,
because it doesn't take up space in my apartment, just on my hard
drive...
From treed at ultraviolet.org Tue Jun 13 07:07:31 2006
From: treed at ultraviolet.org (Tracy R Reed)
Date: Mon, 12 Jun 2006 22:07:31 -0700
Subject: [Tutor] Python related mags
In-Reply-To: <448D55A1.6010002@gmail.com>
References: <448D55A1.6010002@gmail.com>
Message-ID: <448E4813.2000206@ultraviolet.org>
Andrew Robert wrote:
> Does anyone know of any Python related magazines available that would be
> worth subscribing to?
>
Why bother when there are many excellent websites with good python
articles? I have found that my consumption of print media has fallen to
practically zero not including things I print out myself in the years
since I discovered the Internet. The vast majority of python users are
on the net. It does not surprise me at all that there are no printed
python magazines. It is much more efficient to put it all online.
--
Tracy R Reed
http://ultraviolet.org
From emilia12 at mail.bg Tue Jun 13 08:30:40 2006
From: emilia12 at mail.bg (emilia12 at mail.bg)
Date: Tue, 13 Jun 2006 09:30:40 +0300
Subject: [Tutor] [tutor] debug process
Message-ID: <1150180240.646e307959208@mail.bg>
Hello,
Is there a way to debug (trace) the python code line by
line?
emily
-----------------------------
??????? 666.
???? ? ??????.
From kraus at hagen-partner.de Tue Jun 13 08:51:49 2006
From: kraus at hagen-partner.de (Wolfram Kraus)
Date: Tue, 13 Jun 2006 08:51:49 +0200
Subject: [Tutor] [tutor] debug process
In-Reply-To: <1150180240.646e307959208@mail.bg>
References: <1150180240.646e307959208@mail.bg>
Message-ID:
emilia12 at mail.bg schrieb:
> Hello,
>
> Is there a way to debug (trace) the python code line by line?
>
> emily
>
Hi emily!
You can use The Python Debugger or pdb, see:
http://www.python.org/doc/2.4.2/lib/module-pdb.html
HTH,
Wolfram
From kent37 at tds.net Tue Jun 13 12:09:02 2006
From: kent37 at tds.net (Kent Johnson)
Date: Tue, 13 Jun 2006 06:09:02 -0400
Subject: [Tutor] [tutor] debug process
In-Reply-To: <1150180240.646e307959208@mail.bg>
References: <1150180240.646e307959208@mail.bg>
Message-ID: <448E8EBE.9050101@tds.net>
emilia12 at mail.bg wrote:
> Hello,
>
> Is there a way to debug (trace) the python code line by
> line?
There is a simple debugger included with IDLE, the editor that comes
with Python. winpdb is a nice debugger with a GUI. Pydev and Eric3 are
Python development tools that include debuggers.
http://www.digitalpeers.com/pythondebugger/
http://pydev.sourceforge.net/
http://www.die-offenbachs.de/detlev/eric3.html
Kent
From fiveholiday55 at hotmail.com Tue Jun 13 12:12:17 2006
From: fiveholiday55 at hotmail.com (Evans Anyokwu)
Date: Tue, 13 Jun 2006 11:12:17 +0100
Subject: [Tutor] Python related mags
References: <448D55A1.6010002@gmail.com><6ba92c331537c6ac94e2bc18e2662757@adelphia.net><448E1153.1080106@gmail.com>
<1150165573.10769.7.camel@camille.espersunited.com>
Message-ID:
----- Original Message -----
From: "Michael Sullivan"
To: "Andrew Robert"
Cc: "Python Tutor"
Sent: Tuesday, June 13, 2006 3:26 AM
Subject: Re: [Tutor] Python related mags
> On Mon, 2006-06-12 at 21:13 -0400, Andrew Robert wrote:
>> -----BEGIN PGP SIGNED MESSAGE-----
>> Hash: SHA1
>>
>> Now that is a real pity.
>>
>> Wish I were talented enough to do it myself.
>
> Someone could do something like Tux Magazine
> (http://www.tuxmagazine.org/) . Each month they put out a free Linux
> magazine in the form of a downloadable pdf file. It's supposed to be
> geared toward new Linux users. I particularly like the pdf format,
> because it doesn't take up space in my apartment, just on my hard
Am a tuxmagazine subscriber and the .pdf format is a very good idea, would
be very pleased to have something like that for Python developers too.
But then again, who is going to initiate the first move??
From bgailer at alum.rpi.edu Tue Jun 13 16:36:34 2006
From: bgailer at alum.rpi.edu (Bob Gailer)
Date: Tue, 13 Jun 2006 07:36:34 -0700
Subject: [Tutor] [tutor] debug process
In-Reply-To: <448E8EBE.9050101@tds.net>
References: <1150180240.646e307959208@mail.bg> <448E8EBE.9050101@tds.net>
Message-ID: <448ECD72.2020106@alum.rpi.edu>
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060613/2bf7fea3/attachment.html
From andy.koch at pc-doctor.com Tue Jun 13 16:42:11 2006
From: andy.koch at pc-doctor.com (Andy Koch)
Date: Tue, 13 Jun 2006 07:42:11 -0700
Subject: [Tutor] die or exit function?
Message-ID:
Bkgd: I've been doing PHP for the last several years.
Q: In PHP there are functions die and exit which terminate processing of
a script with an optional string output. Is there something similar to
this in Python?
From dkuhlman at rexx.com Tue Jun 13 17:45:28 2006
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Tue, 13 Jun 2006 08:45:28 -0700
Subject: [Tutor] [tutor] debug process
In-Reply-To:
References: <1150180240.646e307959208@mail.bg>
Message-ID: <20060613154528.GA45543@cutter.rexx.com>
On Tue, Jun 13, 2006 at 08:51:49AM +0200, Wolfram Kraus wrote:
> emilia12 at mail.bg schrieb:
> > Hello,
> >
> > Is there a way to debug (trace) the python code line by line?
> >
> > emily
> >
>
> Hi emily!
>
> You can use The Python Debugger or pdb, see:
> http://www.python.org/doc/2.4.2/lib/module-pdb.html
>
Also, put the following at the location in your code where you
want to drop into the debugger:
import pdb
pdb.set_trace()
and then, at the pdb prompt, type:
(Pdb) help l
(Pdb) help b
etcetera.
You can also do:
import pdb
pdb.help()
which will show you documentation on pdb.
And, this is not a debugger but ... If you have installed
IPython, you can also easily embed a complete Python interpreter
in your program. Although it does not give you breakpoints and
other debugging features, it does enable you to do lots in the way
of inspecting objects, evaluating objects, performing tests on
objects, etc.
If you have *not* installed IPython, I recommend it. It makes a
great replacement for the standard Python interactive interpreter.
To learn about IPython, see:
IPython:
http://ipython.scipy.org/
Embedding IPython:
http://ipython.scipy.org/doc/manual/node9.html
Using the Python debugger (pdb) (with IPython):
http://ipython.scipy.org/doc/manual/node10.html
Dave
--
Dave Kuhlman
http://www.rexx.com/~dkuhlman
From ingoogni at CUT.THIS.OUT.home.nl Tue Jun 13 18:49:15 2006
From: ingoogni at CUT.THIS.OUT.home.nl (ingo)
Date: Tue, 13 Jun 2006 16:49:15 +0000 (UTC)
Subject: [Tutor] Python related mags
References: <1150165573.10769.7.camel@camille.espersunited.com>
Message-ID:
in news:BAY111-DAV2395C17A3AB158AFE4ACDAD8C0 at phx.gbl Evans Anyokwu wrote:
> But then again, who is going to initiate the first move??
>
Here's a name: Monthly Python
From michael at espersunited.com Tue Jun 13 18:56:14 2006
From: michael at espersunited.com (Michael Sullivan)
Date: Tue, 13 Jun 2006 11:56:14 -0500
Subject: [Tutor] Python related mags
In-Reply-To:
References: <1150165573.10769.7.camel@camille.espersunited.com>
Message-ID: <1150217775.10769.24.camel@camille.espersunited.com>
On Tue, 2006-06-13 at 16:49 +0000, ingo wrote:
> in news:BAY111-DAV2395C17A3AB158AFE4ACDAD8C0 at phx.gbl Evans Anyokwu wrote:
>
> > But then again, who is going to initiate the first move??
> >
>
> Here's a name: Monthly Python
Yes. They had a large influence in the birth of the language, but I'm
not so sure if they still do...
From emily.fortuna at nist.gov Tue Jun 13 18:59:47 2006
From: emily.fortuna at nist.gov (Emily Fortuna)
Date: Tue, 13 Jun 2006 12:59:47 -0400
Subject: [Tutor] Interfaces in Python
Message-ID: <448EEF03.30605@nist.gov>
Hi friends,
I am learning Python and relating to my knowledge of Java... What is (Is
there?) the equivalent of Java interfaces in Python? How could I write
my own?
Emily
From mhansen at cso.atmel.com Tue Jun 13 19:15:53 2006
From: mhansen at cso.atmel.com (Mike Hansen)
Date: Tue, 13 Jun 2006 11:15:53 -0600
Subject: [Tutor] die or exit function?
In-Reply-To:
Message-ID: <008701c68f0d$0696c9d0$28645f0a@mikehansen>
> -----Original Message-----
> From: tutor-bounces+mhansen=cso.atmel.com at python.org
> [mailto:tutor-bounces+mhansen=cso.atmel.com at python.org] On
> Behalf Of Andy Koch
> Sent: Tuesday, June 13, 2006 8:42 AM
> To: tutor at python.org
> Subject: [Tutor] die or exit function?
>
> Bkgd: I've been doing PHP for the last several years.
>
> Q: In PHP there are functions die and exit which terminate
> processing of
> a script with an optional string output. Is there something
> similar to
> this in Python?
>
sys.exit("something bad happened")
Although it's probably better to catch the exception and deal with it and
then sys.exit() if need be.
Mike
http://users.adelphia.net/~mahansen/programming/
From marichar at csusb.edu Tue Jun 13 18:23:07 2006
From: marichar at csusb.edu (Matt Richardson)
Date: Tue, 13 Jun 2006 09:23:07 -0700
Subject: [Tutor] debug process
In-Reply-To: <448ECD72.2020106@alum.rpi.edu>
References: <1150180240.646e307959208@mail.bg> <448E8EBE.9050101@tds.net>
<448ECD72.2020106@alum.rpi.edu>
Message-ID: <448EE66B.4060400@csusb.edu>
Bob Gailer wrote:
> Kent Johnson wrote:
>> emilia12 at mail.bg wrote:
>>
>>> Hello,
>>>
>>> Is there a way to debug (trace) the python code line by
>>> line?
>>>
I'll put in my $.02 for SPE. PyChecker and Tab Nanny are built in and
run as you code, which saved me from making lots of silly mistakes.
--
Matt Richardson
IT Consultant
College of Arts and Letters
CSU San Bernardino
work: (909)537-7598
fax: (909)537-5926
From dkuhlman at rexx.com Tue Jun 13 20:58:32 2006
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Tue, 13 Jun 2006 11:58:32 -0700
Subject: [Tutor] Interfaces in Python
In-Reply-To: <448EEF03.30605@nist.gov>
References: <448EEF03.30605@nist.gov>
Message-ID: <20060613185832.GA48838@cutter.rexx.com>
On Tue, Jun 13, 2006 at 12:59:47PM -0400, Emily Fortuna wrote:
> Hi friends,
> I am learning Python and relating to my knowledge of Java... What is (Is
> there?) the equivalent of Java interfaces in Python? How could I write
> my own?
> Emily
>
You may be interested in this article:
http://dirtsimple.org/2004/12/python-interfaces-are-not-java.html
And, ...
The following is more in the way of trying to keep the discussion
going than it is a real solution. Using Zope interfaces, if you
are not already using Zope, seems like more trouble than it is
worth. Still, especially for someone who is interested in
tutoring and teaching new Python programmers, possibly programmers
who are familiar with Java, Zope interfaces may be worth thinking
about.
Although this is implemented in the Zope distribution, I believe
that it is usable outside of Zope applications.
See:
http://www.zope.org/Wikis/Interfaces/FrontPage
http://svn.zope.org/Zope3/trunk/src/zope/interface/README.txt?view=markup
Here is a trivial example:
from zope.interface import Interface, implements
class IA(Interface):
def show(self, level):
"""Show this object.
"""
class A:
implements(IA)
def show(self, msg):
print '(A.show) msg: "%s"' % msg
def test():
a = A()
a.show('hello')
print IA.implementedBy(A)
test()
In order for this to work, I believe you will need:
my_zope_install/lib/python
on your PYTHONPATH.
Dave
--
Dave Kuhlman
http://www.rexx.com/~dkuhlman
From francois.schnell at gmail.com Tue Jun 13 22:05:41 2006
From: francois.schnell at gmail.com (francois schnell)
Date: Tue, 13 Jun 2006 22:05:41 +0200
Subject: [Tutor] die or exit function?
In-Reply-To: <008701c68f0d$0696c9d0$28645f0a@mikehansen>
References:
<008701c68f0d$0696c9d0$28645f0a@mikehansen>
Message-ID: <13a83ca10606131305m4db51745lc87566bc405cf826@mail.gmail.com>
On 13/06/06, Mike Hansen wrote:
>
>
>
> > -----Original Message-----
> > From: tutor-bounces+mhansen=cso.atmel.com at python.org
Wait a minute, is that "atmel" in your e-mail address the one I think of ?
http://en.wikipedia.org/wiki/Atmel
If so please thank the AVR gurus for making the best quality/price
microcontrollers in the world. I'm an happy user of an atmega8 and Python in
this project: http://www.liberlab.net/
If by any chance your going to europython 2006 I'll be glad to show you
that.
I've just been looking at your blog and I've seen the "Perl, the language I
love to hate".
Personally I love this little cartoon about Perl :
http://mirror5.escomposlinux.org/comic/ecol-13-e.png
And if you have Perl working colleges you want to protect from I found this
on the web ;)
http://scott.weston.id.au/software/pymissile-20060126/
cheers
francois
> [mailto:tutor-bounces+mhansen=cso.atmel.com at python.org] On
> > Behalf Of Andy Koch
> > Sent: Tuesday, June 13, 2006 8:42 AM
> > To: tutor at python.org
> > Subject: [Tutor] die or exit function?
> >
> > Bkgd: I've been doing PHP for the last several years.
> >
> > Q: In PHP there are functions die and exit which terminate
> > processing of
> > a script with an optional string output. Is there something
> > similar to
> > this in Python?
> >
>
>
> sys.exit("something bad happened")
>
> Although it's probably better to catch the exception and deal with it and
> then sys.exit() if need be.
>
> Mike
> http://users.adelphia.net/~mahansen/programming/
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060613/d33b8f59/attachment.html
From kent37 at tds.net Wed Jun 14 14:16:59 2006
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 14 Jun 2006 08:16:59 -0400
Subject: [Tutor] Interfaces in Python
In-Reply-To: <448EEF03.30605@nist.gov>
References: <448EEF03.30605@nist.gov>
Message-ID: <448FFE3B.4000804@tds.net>
Emily Fortuna wrote:
> Hi friends,
> I am learning Python and relating to my knowledge of Java... What is (Is
> there?) the equivalent of Java interfaces in Python? How could I write
> my own?
Explicit, formal interfaces are used much less frequently in Python than
in Java, and for beginners they are not needed at all. In Python,
interfaces are often implicit and defined only by usage and
documentation. Sometimes the usage is called a protocol. Because Python
is dynamic, there is not need to declare the type of an object, you just
use it in the desired way. This is called "duck typing".
http://c2.com/cgi/wiki?DuckTyping
For example, the Python docs often talk about a "file-like object". A
file-like object is any object that implements enough of the file
protocol to act like a file. In some contexts, it might be enough to
implement a read() method; in other contexts, the full file protocol
might be needed. The StringIO module contains a class that implements a
file-like wrapper around a memory buffer. An instance of StringIO can be
passed to any function that expects an open file. StringIO doesn't
inherit from any interface, it just implements the needed functions.
Large Python projects seem to need something more formal than this. I
think Zope, Twisted and PEAK have all invented ways to formalize this
notion, and one of them may become part of Python in the future. But for
small projects, duck typing and implicit protocols work pretty well.
I hope someone else will explain this better than me...
Kent
From doug.shawhan at gmail.com Wed Jun 14 15:17:18 2006
From: doug.shawhan at gmail.com (doug shawhan)
Date: Wed, 14 Jun 2006 08:17:18 -0500
Subject: [Tutor] die or exit function?
In-Reply-To:
References:
Message-ID: <5e1ceb8a0606140617y55b3c33aheebdea86f3e6d925@mail.gmail.com>
Hi Andy,
Putting a try:/except: loop in your __main__() (or whatever you call
your base function) with sys.exit("Message") is pretty much the way I
always do it.
try:
gak = puke + die
except:
sys.exit("Oy!")
If you would like sys.exit() to provide you with a bit more
information (like what actually happened during the failure and
where!) I found this handy function:
def formatExceptionInfo(maxTBlevel=5):
cla, exc, trbk = sys.exc_info()
excName = cla.__name__
try:
excArgs = exc.__dict__["args"]
except KeyError:
excArgs = ""
excArgsString = ''
for item in excArgs:
excArgsString = excArgsString + ' ' + str(item)
excTb = traceback.format_tb(trbk, maxTBlevel)
excTbString = ''
for item in excTb:
excTbString = excTbString + " " + str(item)
report = "%s %s %s"%(excName, excArgsString, excTbString)
return(report)
This function now goes in most of what I do that requires error reporting.
Hope this helps!
On 6/13/06, Andy Koch wrote:
> Bkgd: I've been doing PHP for the last several years.
>
> Q: In PHP there are functions die and exit which terminate processing of
> a script with an optional string output. Is there something similar to
> this in Python?
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
From andy.koch at pc-doctor.com Wed Jun 14 16:26:17 2006
From: andy.koch at pc-doctor.com (Andy Koch)
Date: Wed, 14 Jun 2006 07:26:17 -0700
Subject: [Tutor] die or exit function?
In-Reply-To: <5e1ceb8a0606140617y55b3c33aheebdea86f3e6d925@mail.gmail.com>
References:
<5e1ceb8a0606140617y55b3c33aheebdea86f3e6d925@mail.gmail.com>
Message-ID:
doug shawhan wrote:
> Hi Andy,
>
> Putting a try:/except: loop in your __main__() (or whatever you call
> your base function) with sys.exit("Message") is pretty much the way I
> always do it.
>
> try:
> gak = puke + die
> except:
> sys.exit("Oy!")
>
> If you would like sys.exit() to provide you with a bit more
> information (like what actually happened during the failure and
> where!) I found this handy function:
>
>
> def formatExceptionInfo(maxTBlevel=5):
> cla, exc, trbk = sys.exc_info()
> excName = cla.__name__
> try:
> excArgs = exc.__dict__["args"]
> except KeyError:
> excArgs = ""
>
> excArgsString = ''
> for item in excArgs:
> excArgsString = excArgsString + ' ' + str(item)
>
> excTb = traceback.format_tb(trbk, maxTBlevel)
> excTbString = ''
> for item in excTb:
> excTbString = excTbString + " " + str(item)
>
> report = "%s %s %s"%(excName, excArgsString, excTbString)
> return(report)
>
> This function now goes in most of what I do that requires error reporting.
>
> Hope this helps!
>
> On 6/13/06, Andy Koch wrote:
>> Bkgd: I've been doing PHP for the last several years.
>>
>> Q: In PHP there are functions die and exit which terminate processing of
>> a script with an optional string output. Is there something similar to
>> this in Python?
>>
>> _______________________________________________
>> Tutor maillist - Tutor at python.org
>> http://mail.python.org/mailman/listinfo/tutor
>>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
Hi Doug,
copied and pasted, thanks
although my reason for the die() was that I've started using Python to
do DB maintenance. I find it very handy (ie IDLE) and the DB api's for
all the different DB's I work with are nice and standardized (PHP could
learn a thing there). One thing that has happened, though, is that I've
clicked (via Winders Explorer) on a .py to open it for edit only to it
have run, which is not what I want when the code could start modifying
data. Thus far it hasn't caused any damage. So my safety check is to
do a raw_input from a commonly included module which does the sys.exit()
if running the code is not desired.
A basic safety catch.
From andrew.arobert at gmail.com Wed Jun 14 20:40:31 2006
From: andrew.arobert at gmail.com (Andrew Robert)
Date: Wed, 14 Jun 2006 14:40:31 -0400
Subject: [Tutor] If then else question
Message-ID: <4490581F.8080901@gmail.com>
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Hi Everyone,
In the middle of an if then else, I have the following line
elif ch_val == '040' or ch_val == '011' or ch_val == '012':
The line works but it is a little ungainly.
Anyone have a better way of accomplishing the same thing?
- --
Thank you,
Andrew Robert
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (MingW32)
Comment: GnuPT 2.7.2
iD8DBQFEkFgfDvn/4H0LjDwRAophAKCZbJaMWBr2G8dLjHO3VtOA98/+1gCbBsys
4B/Q6g9m+3DW+PzcnCpki6k=
=t0E4
-----END PGP SIGNATURE-----
From mhansen at cso.atmel.com Wed Jun 14 20:48:08 2006
From: mhansen at cso.atmel.com (Mike Hansen)
Date: Wed, 14 Jun 2006 12:48:08 -0600
Subject: [Tutor] If then else question
In-Reply-To: <4490581F.8080901@gmail.com>
Message-ID: <002a01c68fe3$13e2d9e0$28645f0a@mikehansen>
> -----Original Message-----
> From: tutor-bounces at python.org
> [mailto:tutor-bounces at python.org] On Behalf Of Andrew Robert
> Sent: Wednesday, June 14, 2006 12:41 PM
> To: Python Tutor
> Subject: [Tutor] If then else question
>
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> Hi Everyone,
>
> In the middle of an if then else, I have the following line
>
> elif ch_val == '040' or ch_val == '011' or ch_val == '012':
>
>
> The line works but it is a little ungainly.
>
> Anyone have a better way of accomplishing the same thing?
>
>
> - --
> Thank you,
> Andrew Robert
>
Maybe...
elif ch_val in ['040', '011', '012']:
Mike
http://users.adelphia.net/~mahansen/programming/
From jason.massey at gmail.com Wed Jun 14 20:50:00 2006
From: jason.massey at gmail.com (Jason Massey)
Date: Wed, 14 Jun 2006 13:50:00 -0500
Subject: [Tutor] If then else question
In-Reply-To: <4490581F.8080901@gmail.com>
References: <4490581F.8080901@gmail.com>
Message-ID: <7e3eab2c0606141150u479044ddn64f46d548be5ec28@mail.gmail.com>
How about:
elif ch_val in ['040','011','012']:
On 6/14/06, Andrew Robert wrote:
>
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> Hi Everyone,
>
> In the middle of an if then else, I have the following line
>
> elif ch_val == '040' or ch_val == '011' or ch_val == '012':
>
>
> The line works but it is a little ungainly.
>
> Anyone have a better way of accomplishing the same thing?
>
>
> - --
> Thank you,
> Andrew Robert
>
> -----BEGIN PGP SIGNATURE-----
> Version: GnuPG v1.2.1 (MingW32)
> Comment: GnuPT 2.7.2
>
> iD8DBQFEkFgfDvn/4H0LjDwRAophAKCZbJaMWBr2G8dLjHO3VtOA98/+1gCbBsys
> 4B/Q6g9m+3DW+PzcnCpki6k=
> =t0E4
> -----END PGP SIGNATURE-----
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060614/3370a503/attachment.html
From dustin at ywlcs.org Wed Jun 14 20:51:20 2006
From: dustin at ywlcs.org (Dustin Mitchell)
Date: Wed, 14 Jun 2006 13:51:20 -0500
Subject: [Tutor] If then else question
In-Reply-To: <4490581F.8080901@gmail.com>
References: <4490581F.8080901@gmail.com>
Message-ID:
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
How about
..
elif ch_val in ('040', '011', '012'):
..
On Jun 14, 2006, at 1:40 PM, Andrew Robert wrote:
> In the middle of an if then else, I have the following line
>
> elif ch_val == '040' or ch_val == '011' or ch_val == '012':
>
>
> The line works but it is a little ungainly.
>
> Anyone have a better way of accomplishing the same thing?
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (Darwin)
iD8DBQFEkFqydiVAPX8NFbERAl03AKCSkXjFB1bA0xUo4Tf8wNF462DllQCg37ir
iu+TIlJst9AjjN0Qz3rijPU=
=FF5s
-----END PGP SIGNATURE-----
From andrew.arobert at gmail.com Wed Jun 14 20:53:44 2006
From: andrew.arobert at gmail.com (Andrew Robert)
Date: Wed, 14 Jun 2006 14:53:44 -0400
Subject: [Tutor] If then else question
In-Reply-To: <002a01c68fe3$13e2d9e0$28645f0a@mikehansen>
References: <002a01c68fe3$13e2d9e0$28645f0a@mikehansen>
Message-ID: <44905B38.5000504@gmail.com>
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Excellent.. much better than testing each value independently.
Thank you.
Mike Hansen wrote:
>
>
>> -----Original Message-----
>> From: tutor-bounces at python.org
>> [mailto:tutor-bounces at python.org] On Behalf Of Andrew Robert
>> Sent: Wednesday, June 14, 2006 12:41 PM
>> To: Python Tutor
>> Subject: [Tutor] If then else question
>>
>> -----BEGIN PGP SIGNED MESSAGE-----
>> Hash: SHA1
>>
>> Hi Everyone,
>>
>> In the middle of an if then else, I have the following line
>>
>> elif ch_val == '040' or ch_val == '011' or ch_val == '012':
>>
>>
>> The line works but it is a little ungainly.
>>
>> Anyone have a better way of accomplishing the same thing?
>>
>>
>> - --
>> Thank you,
>> Andrew Robert
>>
>
> Maybe...
>
> elif ch_val in ['040', '011', '012']:
>
> Mike
> http://users.adelphia.net/~mahansen/programming/
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (MingW32)
Comment: GnuPT 2.7.2
iD8DBQFEkFs3Dvn/4H0LjDwRApi/AJ4lyyJOoHWt1NzMBPF2gF7qQsA9WgCguYcd
MmjCVxL4giSzpdA1pRKgnHc=
=y80v
-----END PGP SIGNATURE-----
From kent37 at tds.net Wed Jun 14 20:56:13 2006
From: kent37 at tds.net (Kent Johnson)
Date: Wed, 14 Jun 2006 14:56:13 -0400
Subject: [Tutor] If then else question
In-Reply-To: <4490581F.8080901@gmail.com>
References: <4490581F.8080901@gmail.com>
Message-ID: <44905BCD.9000202@tds.net>
Andrew Robert wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> Hi Everyone,
>
> In the middle of an if then else, I have the following line
>
> elif ch_val == '040' or ch_val == '011' or ch_val == '012':
>
>
> The line works but it is a little ungainly.
>
> Anyone have a better way of accomplishing the same thing?
elif ch_val in [ '040', '011', '012' ]:
or maybe you like
elif ch_val in '040 011 012'.split():
Kent
From alan.gauld at freenet.co.uk Thu Jun 15 02:06:38 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu, 15 Jun 2006 01:06:38 +0100
Subject: [Tutor] Interfaces in Python
References: <448EEF03.30605@nist.gov>
Message-ID: <001d01c6900f$92984640$0301a8c0@XPpro>
> I am learning Python and relating to my knowledge of Java... What is
> (Is there?) the equivalent of Java interfaces in Python? How could
> I write my own?
There is no direct equivalent.
Interfaces are implicit in Python, they are only really necessary in
statically typed languages. Dynamically typed languages rely on
"Duck typing" and therefore the concept of an interface is not
required.
( Interfaces are a serious impediment to good OO design IMHO, they
imply an element of fore knowledge of how a class will be used and
involve additional work that often is not needed. They are basically
a flexibility point introduced to mitigate against change in a static
typing environment)
A good example of duck typing is the concept of a "file like object"
which is
used in several places in Python. It basically means any object which
has the same message protocol as a file. This is the saqme style of
OOP used in SmallTalk, Lisp and ObjectiveC (although the latter also
supports statically typed interfaces too)
[ It is possible to create abstract classes in Python however using
some
sneaky tricks but the easiest way is probably just to throw an
exception
in the init method! Abstract classes are an alternative way to view
interfaces - interaces are cut-down abstract classes...]
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
From alan.gauld at freenet.co.uk Thu Jun 15 02:15:46 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Thu, 15 Jun 2006 01:15:46 +0100
Subject: [Tutor] Interfaces in Python
References: <448EEF03.30605@nist.gov> <448FFE3B.4000804@tds.net>
Message-ID: <004301c69010$d94d8310$0301a8c0@XPpro>
> Large Python projects seem to need something more formal than this.
> I think Zope, Twisted and PEAK have all invented ways to formalize
> this notion, and one of them may become part of Python in the
> future.
I think thats more to do with the background of the programmers
involved.
> small projects, duck typing and implicit protocols work pretty well.
Even for large projects. Lisp, SmallTalk and ObjectiveC all use duck
typing and some very large projects (several 100K of code, and a few
million line plus projects) have been built using those languages.
The important point is that duck typing needs to be combined with
exception handling and exceptions have to be written to catch the
Attribute errors that result from incorrect protocol behaviour.
Provided
that is done duck typing is no worse than static typed interfaces, its
just a different approach.
> I hope someone else will explain this better than me...
I thought you did pretty good Kent!
Alan G.
(Just back from the Enterprise Architecture 2006 conference...)
From govilakanksha at yahoo.com Thu Jun 15 12:04:10 2006
From: govilakanksha at yahoo.com (Akanksha Govil)
Date: Thu, 15 Jun 2006 03:04:10 -0700 (PDT)
Subject: [Tutor] Need info regd Singleton class implementation
Message-ID: <20060615100410.17619.qmail@web36513.mail.mud.yahoo.com>
hi,
I need to implement a singleton class in python.
Please give me some refernce sites which can help me with the same.
Also i want to know to call a destructor for a singleton class.
Thanks
Akanksha
__________________________________________________
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
http://mail.yahoo.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060615/ed4c6f58/attachment.html
From andre.roberge at gmail.com Thu Jun 15 12:25:29 2006
From: andre.roberge at gmail.com (Andre Roberge)
Date: Thu, 15 Jun 2006 07:25:29 -0300
Subject: [Tutor] Need info regd Singleton class implementation
In-Reply-To: <20060615100410.17619.qmail@web36513.mail.mud.yahoo.com>
References: <20060615100410.17619.qmail@web36513.mail.mud.yahoo.com>
Message-ID: <7528bcdd0606150325p71fc7a4u5e5b9c99c72a1a9f@mail.gmail.com>
On 6/15/06, Akanksha Govil wrote:
> hi,
>
> I need to implement a singleton class in python.
> Please give me some refernce sites which can help me with the same.
The online Python Cookbook is a good reference site. Here's the
result from a search:
http://aspn.activestate.com/ASPN/search?query=singleton&x=0&y=0§ion=PYTHONCKBK&type=Subsection
I use the following from the printed edition of the Python Cookbook:
class Singleton(object):
"""From the 2nd edition of the Python cookbook.
Ensures that only one instance is created per running script"""
def __new__(cls, *args, **kwargs):
if '_inst' not in vars(cls):
cls._inst = object.__new__(cls, *args, **kwargs)
return cls._inst
Andr?
>
> Also i want to know to call a destructor for a singleton class.
>
> Thanks
> Akanksha
>
>
>
> __________________________________________________
> Do You Yahoo!?
> Tired of spam? Yahoo! Mail has the best spam protection around
> http://mail.yahoo.com
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
From kent37 at tds.net Thu Jun 15 14:05:30 2006
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 15 Jun 2006 08:05:30 -0400
Subject: [Tutor] Need info regd Singleton class implementation
In-Reply-To: <20060615100410.17619.qmail@web36513.mail.mud.yahoo.com>
References: <20060615100410.17619.qmail@web36513.mail.mud.yahoo.com>
Message-ID: <44914D0A.5030806@tds.net>
Akanksha Govil wrote:
> I need to implement a singleton class in python.
> Please give me some refernce sites which can help me with the same.
Singletons are not used that much in Python, perhaps because the general
culture of "we're all adults here" is biased against enforcing usage
patterns.
If you want to have a master reference to an object you can just make it
a module attribute. Then any client that needs access to the object just
imports the module.
Why do you need a singleton? Is this homework?
> Also i want to know to call a destructor for a singleton class.
In Python, destructors (__del__() methods) are called on an object when
it is garbage-collected. The details of when this happens vary between
different Python implementations. In CPython (the standard Python from
python.org), an object is garbage-collected when its reference count
goes to 0 - when there are no names that refer to the object. So if you
want the __del__() method of an object to be called, you have to ensure
that there are no references to the object. In the case of a singleton,
this would mean deleting or assigning None to the name that holds the
master reference, and ensuring that no users of the singleton retain
references to it.
Kent
From tinoloc at gmail.com Thu Jun 15 15:20:23 2006
From: tinoloc at gmail.com (Tino Dai)
Date: Thu, 15 Jun 2006 09:20:23 -0400
Subject: [Tutor] Question about network server in python
Message-ID:
Hi there,
I am wondering if somebody to could answer a question about sockets. I
have a socket that
is listening, and a client program connects to it. The client program
transfers a name over, and then disconnects from the socket. Now, how that
is done is using a socket.close() call to shut down the entire socket. My
question is: Is there a way to have the socket close the connection, yet
stay open for the next client that comes along and connects to the server? I
have my already written code below for further documentation. Thanks!
while 1:
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind((self.ipAddr,self.port))
s.listen(5)
print "The port is: ", self.port
client,addr=s.accept()
while 1:
try:
if addr[0] == self.remoteIpAddr:
client.send("Connected to the server\n")
msg=client.recv(1024)
msg=msg.strip()
if msg in 'exit':
s.close() #Is there a different way
to write this?
time.sleep(30)
print "exiting"
break
if len(msg) > 0:
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060615/d00d3a39/attachment.htm
From pjlists at gmail.com Thu Jun 15 16:17:37 2006
From: pjlists at gmail.com (Peter Jessop)
Date: Thu, 15 Jun 2006 16:17:37 +0200
Subject: [Tutor] Question about network server in python
In-Reply-To:
References:
Message-ID: <7a8d5a0c0606150717s545bfa95yed3d21f948ec30d4@mail.gmail.com>
I think the problem here is the 'break' statement.
Does it not put you outside the while loop whereas in order to keep
the server socket open you need it to loop forever.
I also think that the s.accept should be inside the while loop.
From pjlists at gmail.com Thu Jun 15 16:42:33 2006
From: pjlists at gmail.com (Peter Jessop)
Date: Thu, 15 Jun 2006 16:42:33 +0200
Subject: [Tutor] Question about network server in python
In-Reply-To: <7a8d5a0c0606150717s545bfa95yed3d21f948ec30d4@mail.gmail.com>
References:
<7a8d5a0c0606150717s545bfa95yed3d21f948ec30d4@mail.gmail.com>
Message-ID: <7a8d5a0c0606150742i18e5f897ycff4bb8edf47321d@mail.gmail.com>
import socket
host = ''
port = 57000
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind((host,port))
s.listen(5)
while 1:
client,addr=s.accept()
client.send("Connected to the server\n")
#if someCondition:
# cliente.close()
From kent37 at tds.net Thu Jun 15 16:45:38 2006
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 15 Jun 2006 10:45:38 -0400
Subject: [Tutor] Question about network server in python
In-Reply-To: <7a8d5a0c0606150717s545bfa95yed3d21f948ec30d4@mail.gmail.com>
References:
<7a8d5a0c0606150717s545bfa95yed3d21f948ec30d4@mail.gmail.com>
Message-ID: <44917292.6010001@tds.net>
Peter Jessop wrote:
> I think the problem here is the 'break' statement.
> Does it not put you outside the while loop whereas in order to keep
> the server socket open you need it to loop forever.
>
> I also think that the s.accept should be inside the while loop.
There are two loops, I think you missed the outer loop.
Kent
From kent37 at tds.net Thu Jun 15 16:54:26 2006
From: kent37 at tds.net (Kent Johnson)
Date: Thu, 15 Jun 2006 10:54:26 -0400
Subject: [Tutor] Question about network server in python
In-Reply-To:
References:
Message-ID: <449174A2.5040906@tds.net>
Tino Dai wrote:
> Hi there,
>
> I am wondering if somebody to could answer a question about
> sockets. I have a socket that
> is listening, and a client program connects to it. The client program
> transfers a name over, and then disconnects from the socket. Now, how
> that is done is using a socket.close() call to shut down the entire
> socket. My question is: Is there a way to have the socket close the
> connection, yet stay open for the next client that comes along and
> connects to the server? I have my already written code below for further
> documentation. Thanks!
>
> while 1:
> s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
> s.bind((self.ipAddr,self.port))
> s.listen(5)
> print "The port is: ", self.port
> client,addr=s.accept()
> while 1:
> try:
> if addr[0] == self.remoteIpAddr:
> client.send("Connected to the server\n")
> msg=client.recv(1024)
> msg=msg.strip()
> if msg in 'exit':
> s.close() #Is there a different
> way to write this?
I think you want to close the client socket - client.close() - rather
than the master socket.
You might be interested in the SocketServer library which helps to write
simple socket servers such as this. One advantage of using SocketServer
is it makes it trivial to convert your server to a threaded or forked
server. Here are some examples:
http://www.amk.ca/python/simple/fingerd.py.html
http://examples.oreilly.com/pythonian/ see example 19-5
Kent
> time.sleep(30)
> print "exiting"
> break
> if len(msg) > 0:
>
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
From learner404 at gmail.com Thu Jun 15 21:09:00 2006
From: learner404 at gmail.com (learner404)
Date: Thu, 15 Jun 2006 21:09:00 +0200
Subject: [Tutor] WinXP IDLE -> open file : how-to change default directory ?
Message-ID: <13a83ca10606151209o2187a516pc09268930f003e24@mail.gmail.com>
Hello,
On WinXP IDLE will always 'open' in Python24 folder at startup.
A beginner friend of mine hate that (personally I use SPE) and I tried
'quickly' to find a way to configure that for him.
I found all the .cfg files in idlelib and also the .idlerc folder in the
"Documents and settings" but I don't see how to give IDLE a default
directory at startup (or kipping in memory the last one opened).
How to do that or is it just not possible ?
Thanks
learner404
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060615/1802c3e6/attachment.htm
From learner404 at gmail.com Thu Jun 15 22:48:20 2006
From: learner404 at gmail.com (learner404)
Date: Thu, 15 Jun 2006 22:48:20 +0200
Subject: [Tutor] WinXP IDLE -> open file : how-to change default
directory ?
In-Reply-To: <001001c690b7$eab7b240$0200a8c0@kookaburra>
References: <13a83ca10606151209o2187a516pc09268930f003e24@mail.gmail.com>
<001001c690b7$eab7b240$0200a8c0@kookaburra>
Message-ID: <13a83ca10606151348g602b6cc3jc25d16f7a124811e@mail.gmail.com>
On 15/06/06, Matthew Webber wrote:
>
> Try right-clicking on the shortcut, select properties, and change the
> "start
> in" value.
> Matthew
Scary, I didn't know that windows had that ...
Thanks very much Matthew !
P.S. When posting to the list, please use plain text format.
>
> ________________________________
>
> From: tutor-bounces at python.org [mailto:tutor-bounces at python.org]
> On
> Behalf Of learner404
> Sent: 15 June 2006 20:09
> To: tutor at python.org
> Subject: [Tutor] WinXP IDLE -> open file : how-to change default
> directory ?
>
>
> Hello,
>
> On WinXP IDLE will always 'open' in Python24 folder at startup.
>
> A beginner friend of mine hate that (personally I use SPE) and I
> tried 'quickly' to find a way to configure that for him.
>
> I found all the .cfg files in idlelib and also the .idlerc folder
> in
> the "Documents and settings" but I don't see how to give IDLE a default
> directory at startup (or kipping in memory the last one opened).
>
> How to do that or is it just not possible ?
>
> Thanks
>
> learner404
>
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060615/77674507/attachment-0001.html
From alan.gauld at btinternet.com Fri Jun 16 01:05:41 2006
From: alan.gauld at btinternet.com (Alan Gauld)
Date: Fri, 16 Jun 2006 00:05:41 +0100
Subject: [Tutor] XML: Expletive Deleted (OT)
References: <2BBAEE949D384D40A2B851287ADB6A432C36B8@eugsrv400.psc.pscnet.com>
Message-ID:
Just picked this up after being out for most of the week...
"Carroll, Barry" wrote in message
> One reason to for choosing a human-readable format is the desire to
> visually confirm the correctness of the stored data and format.
Thats a very dangerous asumption, how do you detect unprintable
characters, tabs instead of spaces, trailing spaces on a line etc etc.
Whole text representations are helpful you should never rely on the
human eye to validate a data file.
> can be invaluable when troubleshooting a bug involving stored data.
> If
> there is a tool between the user and the data, one must then rely
> upon
> the correctness of the tool to determine the correctness of the
> data.
Or the correctness of the eye. I know which one i prefer - a tested
tool.
The human eye is not a dta parser, but it flatters to deceive by being
nearly good enough.
> In a case like this, nothing beats the evidence of one's eyes, IMHO.
Almost anything beats the human eye IME :-)
Actually if you must use eyes do so on a hex dump of the file, that
is usually reliable enough if you can read hex...
> In their book, "The Pragmatic Programmer: From Journeyman to Master"
> (Addison Wesley Professional), Andrew Hunt and David Thomas give
> another
> reason for storing data in human readable form:
>
> The problem with most binary formats is that the context
> necessary
> to understand the data is separate from the data itself. You are
> artificially divorcing the data from its meaning. The data may
> as well be encrypted; it is absolutely meaningless without the
> application logic to parse it. With plain text, however, you can
> achieve a self-describing data stream that is independent of the
> application that created it.
But at a very high risk. I do not dislike text files BTW and am not
suggesting that text should not be used but its parsing is best left
to machines, the eye is only a rough and unreliable guide.
And if your data volumes are high go with binary, you'll need tools
to parse a lot of data anyway, you might as well save the space!
The Hunt/Thomas book is excellent BTW - I recommend it highly.
Even though I disagree witrh several of their suggestions(*) I agree
with far more.
(*)They recommend sticking with one text editor whereas I use
about 5 or 6 on a regular basis depending on the job I'm doing and
the platform I'm working on. Emacs on X Windows for new files
but vim for quick fix ups, vim on Windows for most things,
ed or ex for text based email or over a phone line.
> This is an example of the resource balancing act that computer
> people
> have been faced with since the beginning. The most scarce/expensive
> resource dictates the program's/system's design. In Alan's example
> high
> speed bandwidth is the limiting resource. A data transmission
> method
> that fails to minimize use of that resource is therefore a bad
> solution.
Unfortunately the software industry is full of people who by and large
don't understand networks so they just ignoire them. At least thats
my experience! SOA using SOAP/XML is probably the most inefficient
and unreliable set of data networking technologies you could possible
come up with. But the focus is on cutting developer cost because the
people inventing it are developers! In almost every sizewable project
the cost of development will be significantly less than the cost of
deployment - in most of my projects it usually works out something
like:
development - 15%
deployment - 30%
support - 15%
training - 25%
documentation - 5%
management overhead - 10%
Saving 25% of development costs rediuced total cost by around 4% but
if that puts deployment costs up by 10% the net gain is only 1%!
And in XML case it often puts deployment costs up by 100%
- a net loss of 24%!!
Now those figures come from a typical project that I work on which
probably has a total budget of betwen $10-100 million. If your
budget is smaller, say less than $1 million then the balance may
well change. But over 50% of the IT industry works on projects
with >$1m budgets according to both Datamation and Infoweek.
[ The only SOA/XML book that addresses this side of XML usage
is the excellent "SOA - A Field Guide" by Peter Erls. Erls also
suggests some mitigating strategies to get round it.]
> So here's my off-topic question: Ajax is being touted as the
> 'best-known
> method' (BKM) for making dynamic browser-based applications, and XML
> is
> the BKM for transferring data in Ajax land. If XML is a bad idea
> for
> network data-transfer, what medium should be used instead?
The example I gave of having to upgrade the sites network was actually
an early adopter of XML/Ajax architecture! There are lots of other
data
formats around - some are even self describing (CSV and TLV are cases)
Others simply hold the definition in an accessible library so you only
have to transport it once - eg IDL and ASN.1 - or optionally compile
it
into your code for maximum efficiency. ASN./1 is typically around 50
times more compact than XML - that makes a big difference over a
DSL line and even bigger over dial-up modem or GPRS link....
XML has its place but that place has to be guaged very carefully.
Unfortunately I don't see much acknowledgement of its weaknesses
in the industry at large, instead it is being deployed with wild
abandon!
Alan g.
From cspears2002 at yahoo.com Fri Jun 16 02:29:01 2006
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Thu, 15 Jun 2006 17:29:01 -0700 (PDT)
Subject: [Tutor] lambda and creating GUIs
Message-ID: <20060616002901.90354.qmail@web51607.mail.yahoo.com>
I have been reading though the PyGTK tutorial.
Can anyone explain how lambda is being used in this
statement:
button.connect("clicked", lambda w: gtk.main_quit())
This code might put the statement in context:
# Create "Quit" button
66 button = gtk.Button("Quit")
67
68 # When the button is clicked, we call
the main_quit function
69 # and the program exits
70 button.connect("clicked", lambda w:
gtk.main_quit())
71
72 # Insert the quit button into the both
lower quadrants of the table
73 table.attach(button, 0, 2, 1, 2)
74
75 button.show()
The complete script is located at
http://www.pygtk.org/pygtk2tutorial/sec-TablePackingExample.html.
From john at fouhy.net Fri Jun 16 03:22:02 2006
From: john at fouhy.net (John Fouhy)
Date: Fri, 16 Jun 2006 13:22:02 +1200
Subject: [Tutor] lambda and creating GUIs
In-Reply-To: <20060616002901.90354.qmail@web51607.mail.yahoo.com>
References: <20060616002901.90354.qmail@web51607.mail.yahoo.com>
Message-ID: <5e58f2e40606151822y116e0526j5fb63ef6e0a6c6ca@mail.gmail.com>
(resending to include Tutor -- sorry for the dupe, Christopher)
On 16/06/06, Christopher Spears wrote:
> I have been reading though the PyGTK tutorial.
> Can anyone explain how lambda is being used in this
> statement:
>
> button.connect("clicked", lambda w: gtk.main_quit())
Do you understand what lambda does in general?
Does it help if I rewrite the code like this:
def onQuit(w):
gtk.main_quit()
button.connect("clicked", onQuit)
?
Provided you get your indentation correct ("def onQuit" and
"button.connect" should be at the same level), and provided you aren't
using the name "onQuit" somewhere else in that method, this code
should be a dropin replacement for the line you quote.
--
John.
From sean.x.lee at gmail.com Fri Jun 16 09:24:12 2006
From: sean.x.lee at gmail.com (Sean Lee)
Date: Fri, 16 Jun 2006 02:24:12 -0500
Subject: [Tutor] detect 64-bit windows
Message-ID:
In Python, how to do that ?
sys.platform only gives 'win32', no info about 32-bit or 64 bit ?
Thanks.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060616/0652b867/attachment.html
From Matthew at CuneiformSoftware.com Thu Jun 15 22:11:40 2006
From: Matthew at CuneiformSoftware.com (Matthew Webber)
Date: Thu, 15 Jun 2006 21:11:40 +0100
Subject: [Tutor] WinXP IDLE -> open file : how-to change default
directory ?
In-Reply-To: <13a83ca10606151209o2187a516pc09268930f003e24@mail.gmail.com>
Message-ID: <001001c690b7$eab7b240$0200a8c0@kookaburra>
Try right-clicking on the shortcut, select properties, and change the "start
in" value.
Matthew
P.S. When posting to the list, please use plain text format.
________________________________
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On
Behalf Of learner404
Sent: 15 June 2006 20:09
To: tutor at python.org
Subject: [Tutor] WinXP IDLE -> open file : how-to change default
directory ?
Hello,
On WinXP IDLE will always 'open' in Python24 folder at startup.
A beginner friend of mine hate that (personally I use SPE) and I
tried 'quickly' to find a way to configure that for him.
I found all the .cfg files in idlelib and also the .idlerc folder in
the "Documents and settings" but I don't see how to give IDLE a default
directory at startup (or kipping in memory the last one opened).
How to do that or is it just not possible ?
Thanks
learner404
From alan.gauld at freenet.co.uk Fri Jun 16 12:16:53 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri, 16 Jun 2006 11:16:53 +0100
Subject: [Tutor] lambda and creating GUIs
References: <20060616002901.90354.qmail@web51607.mail.yahoo.com>
Message-ID: <001001c6912e$139e6a70$0301a8c0@XPpro>
>I have been reading though the PyGTK tutorial.
> Can anyone explain how lambda is being used in this
> statement:
>
> button.connect("clicked", lambda w: gtk.main_quit())
lambda is being used to create an anonymous function.
The code could be rewritten like this:
def f(w): gtk.main_quit()
button.connect("clicked", f)
lambda simply saves cluttering up the code with lots of tiny function
derfinitions which are never referred to apart from in the binding
operation.
You can read about lambdas in the functional programming topic in my
tutor
HTH,
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
From alan.gauld at freenet.co.uk Fri Jun 16 12:23:00 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri, 16 Jun 2006 11:23:00 +0100
Subject: [Tutor] XML: Expletive Deleted (OT)
References: <2BBAEE949D384D40A2B851287ADB6A432C36B8@eugsrv400.psc.pscnet.com>
Message-ID: <001c01c6912e$d86aaa30$0301a8c0@XPpro>
> [ The only SOA/XML book that addresses this side of XML usage
> is the excellent "SOA - A Field Guide" by Peter Erls. Erls also
> suggests some mitigating strategies to get round it.]
Oops, don't rely on memory...
That is Thomas Erl not Peter Erls.
And of course there may be other SOAP/XML books deal with these
issues, but Erl's book is the only one I've read that does so!
Alan G.
From kieran.flanagan at gmail.com Fri Jun 16 15:47:56 2006
From: kieran.flanagan at gmail.com (kieran flanagan)
Date: Fri, 16 Jun 2006 14:47:56 +0100
Subject: [Tutor] Writing to a remote file
Message-ID:
Hi
I want to run a script on one machine and log output messages to a remote
file located on another machine. Is there any easy method of doing this ?.
Thanks
Kieran
--
"Behind every great man, there is a great woman. Behind that woman is Mr.T."
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060616/0b70a262/attachment.htm
From kent37 at tds.net Fri Jun 16 16:54:34 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 16 Jun 2006 10:54:34 -0400
Subject: [Tutor] Writing to a remote file
In-Reply-To:
References:
Message-ID: <4492C62A.5070302@tds.net>
kieran flanagan wrote:
> Hi
>
> I want to run a script on one machine and log output messages to a
> remote file located on another machine. Is there any easy method of
> doing this ?.
Depends on the details, I suppose...
If the remote file is on a network file system accessible to the machine
running the script it should be easy - just open the file and write to
it. For example on Windows you should be able to write
f = open(r'\\server\path\to\logfile.txt', 'w')
print >>f, 'This is a very serious matter'
or configure the file path in your logging properties or whatever...
If the remote file system is *not* accessible from the local machine,
then you need some way to talk to the remote machine.
Kent
From amresh.kulkarni at gmail.com Fri Jun 16 17:26:34 2006
From: amresh.kulkarni at gmail.com (Amresh Kulkarni)
Date: Fri, 16 Jun 2006 10:26:34 -0500
Subject: [Tutor] Delete directories recursively
Message-ID:
Hi,
I need to delete a directory and its sub directories. However all dir's, sub
dir;s and files have read only access. How do i do this efficeintly using
the os.walk command.
I cannot run this command on the dir as it gives me an error due to the read
only attribute. Is there any other way to do this?
--
~~AMRESH~~
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060616/7d787a1c/attachment.htm
From kent37 at tds.net Fri Jun 16 17:39:37 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 16 Jun 2006 11:39:37 -0400
Subject: [Tutor] Delete directories recursively
In-Reply-To:
References:
Message-ID: <4492D0B9.8040704@tds.net>
Amresh Kulkarni wrote:
> Hi,
>
> I need to delete a directory and its sub directories. However all dir's,
> sub dir;s and files have read only access. How do i do this efficeintly
> using the os.walk command.
> I cannot run this command on the dir as it gives me an error due to the
> read only attribute. Is there any other way to do this?
Maybe I'm missing something, but I don't understand how you expect to
delete a directory if you don't have delete permission?
Kent
From mwhite3 at ttsd.k12.or.us Fri Jun 16 17:40:04 2006
From: mwhite3 at ttsd.k12.or.us (Matthew White)
Date: Fri, 16 Jun 2006 08:40:04 -0700
Subject: [Tutor] Delete directories recursively
In-Reply-To:
References:
Message-ID: <20060616154004.GN12754@ttsd.k12.or.us>
You must change the directory and file permissions before attempting to remove them;
even if you are using a python script.
Take a look at os.chmod()
-mtw
On Fri, Jun 16, 2006 at 10:26:34AM -0500, Amresh Kulkarni (amresh.kulkarni at gmail.com) wrote:
> Hi,
>
> I need to delete a directory and its sub directories. However all dir's, sub
> dir;s and files have read only access. How do i do this efficeintly using
> the os.walk command.
> I cannot run this command on the dir as it gives me an error due to the read
> only attribute. Is there any other way to do this?
>
> --
> ~~AMRESH~~
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
From lkvam at venix.com Fri Jun 16 18:24:45 2006
From: lkvam at venix.com (Lloyd Kvam)
Date: Fri, 16 Jun 2006 12:24:45 -0400
Subject: [Tutor] Writing to a remote file
In-Reply-To:
References:
Message-ID: <1150475085.27979.136.camel@www.venix.com>
On Fri, 2006-06-16 at 14:47 +0100, kieran flanagan wrote:
> Hi
>
> I want to run a script on one machine and log output messages to a
> remote file located on another machine. Is there any easy method of
> doing this ?.
http://docs.python.org/lib/module-logging.html
If the remote machine is a file server, you can use the logging module
to write to a file on the remote machine
Also the logging module can be used to easily log to a syslog handler.
If this remote file is a "normal" log file managed by a syslog process
then you should find the python part pretty easy. The syslog process
still needs to be configured to accept your logging messages, but that
should not be too difficult.
Scanning the logging module docs, it looks like you can use it to write
your own process to run on the remote machine to handle "logging
messages". Then use the logging module on the local machine to send
"logging messages" to the remote machine.
> Thanks
> Kieran
>
> --
> "Behind every great man, there is a great woman. Behind that woman is
> Mr.T."
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
--
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358
voice: 603-653-8139
fax: 320-210-3409
From kent37 at tds.net Fri Jun 16 19:21:59 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 16 Jun 2006 13:21:59 -0400
Subject: [Tutor] Writing to a remote file
In-Reply-To: <1150475085.27979.136.camel@www.venix.com>
References:
<1150475085.27979.136.camel@www.venix.com>
Message-ID: <4492E8B7.9080306@tds.net>
Lloyd Kvam wrote:
> On Fri, 2006-06-16 at 14:47 +0100, kieran flanagan wrote:
>> Hi
>>
>> I want to run a script on one machine and log output messages to a
>> remote file located on another machine. Is there any easy method of
>> doing this ?.
> Scanning the logging module docs, it looks like you can use it to write
> your own process to run on the remote machine to handle "logging
> messages". Then use the logging module on the local machine to send
> "logging messages" to the remote machine.
Cool. There's even a complete example in the docs:
http://docs.python.org/lib/network-logging.html
Kent
From Barry.Carroll at psc.com Fri Jun 16 19:33:37 2006
From: Barry.Carroll at psc.com (Carroll, Barry)
Date: Fri, 16 Jun 2006 10:33:37 -0700
Subject: [Tutor] Machine Vs. Human Parsing (Was: XML: Expletive Deleted)
(Way OT!)
Message-ID: <2BBAEE949D384D40A2B851287ADB6A432C36C7@eugsrv400.psc.pscnet.com>
Greetings:
> -----Original Message-----
> Date: Fri, 16 Jun 2006 00:05:41 +0100
> From: "Alan Gauld"
> Subject: Re: [Tutor] XML: Expletive Deleted (OT)
> To: tutor at python.org
> Message-ID:
>
> Just picked this up after being out for most of the week...
>
> "Carroll, Barry" wrote in message
>
> > One reason to for choosing a human-readable format is the desire to
> > visually confirm the correctness of the stored data and format.
>
> Thats a very dangerous asumption, how do you detect unprintable
> characters, tabs instead of spaces, trailing spaces on a line etc etc.
> Whole text representations are helpful you should never rely on the
> human eye to validate a data file.
>
> > can be invaluable when troubleshooting a bug involving stored data.
> > If
> > there is a tool between the user and the data, one must then rely
> > upon
> > the correctness of the tool to determine the correctness of the
> > data.
>
> Or the correctness of the eye. I know which one i prefer - a tested
> tool.
> The human eye is not a dta parser, but it flatters to deceive by being
> nearly good enough.
>
> > In a case like this, nothing beats the evidence of one's eyes, IMHO.
>
> Almost anything beats the human eye IME :-)
> Actually if you must use eyes do so on a hex dump of the file, that
> is usually reliable enough if you can read hex...
>
<>
>
> Alan g.
If I gave the impression that the human eye is the only useful means of
examining and verifying stored data, I apologize. I indented to say
that the human eye, and the brain that goes with it, is an invaluable
tool in evaluating data. I stand by that statement.
The most sophisticated tool is only as good as the developer(s) who made
it. Since software is ultimately written by humans, it is fallible. It
contains mistakes, gaps, holes, imperfections. When the tool gives bad,
or erroneous, or incomplete results, what do you do? You look at the
data.
A case in point. I used to test audio subsystems on PC motherboards.
The codec vendor released a new version of their chip with new driver
software. Suddenly our tests began to fail. The vendor insisted their
HW and SW were correct. The test owner insisted his SW was correct.
Somebody was mistaken.
I used an audio editing program to display the waveform of the data in
the capture buffer. The first several hundred samples were not a
waveform, but apparently random noise. I now knew why the test is
failing, but why was there noise in the buffer? It wasn't there before.
The editing SW was no help there. So I switched tools, and displayed
the capture buffer with simple file dump program. The first 2K of the
buffer was filled with text!
The story goes on, but that's enough to illustrate my point. Neither
the audio driver, nor the test SW, nor the editing tool could show the
real problem. All of them were 'tested tools', but when presented with
data they were not designed to handle, they produced incorrect or
incomplete results. I could cite other examples from other disciplines,
but this one suffices: no SW tool should be relied upon to be correct
in all cases.
I trust my eyes to see things tools can't, not because they can detect
nonprintable characters in a HEX dump (I can read HEX dumps, and binary
when necessary, but I usually just print out '\t', '[SP]', etc) but
because they are not bound by anyone else's rules as to what is correct
and incorrect. The programmer's two most valuable tools are her/his
eyes and brain. They are always useful, sometimes indispensable.
Regards,
Barry
barry.carroll at psc.com
541-302-1107
________________________
We who cut mere stones must always be envisioning cathedrals.
-Quarry worker's creed
From john.corry at ntlworld.com Fri Jun 16 19:55:56 2006
From: john.corry at ntlworld.com (John Corry)
Date: Fri, 16 Jun 2006 18:55:56 +0100
Subject: [Tutor] Delete directories recursively
In-Reply-To:
Message-ID:
Amresh,
I had this problem a few months back. I approached it backwards. Maybe not
the right way to do it. I removed all the files and directories and then
had my exception handle the file if it was read only. The exception
handler changes the file from read-only to not read only and then calls the
function again.
Is there a better way to do it? Would appreciate feedback on the code
below.
import shutil
import os
def zaps(self):
try:
shutil.rmtree('f:/m2m')
except OSError, inst:
print OSError
os.chmod(inst.filename, 0666)
self.zaps()
Regards,
John.
-----Original Message-----
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org]On Behalf
Of Amresh Kulkarni
Sent: 16 June 2006 16:27
To: tutor at python.org
Subject: [Tutor] Delete directories recursively
Hi,
I need to delete a directory and its sub directories. However all dir's,
sub dir;s and files have read only access. How do i do this efficeintly
using the os.walk command.
I cannot run this command on the dir as it gives me an error due to the
read only attribute. Is there any other way to do this?
--
~~AMRESH~~
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060616/ee8a0842/attachment.htm
From kent37 at tds.net Fri Jun 16 20:04:26 2006
From: kent37 at tds.net (Kent Johnson)
Date: Fri, 16 Jun 2006 14:04:26 -0400
Subject: [Tutor] Delete directories recursively
In-Reply-To:
References:
Message-ID: <4492F2AA.4000700@tds.net>
John Corry wrote:
>
> Amresh,
>
> I had this problem a few months back. I approached it backwards. Maybe
> not the right way to do it. I removed all the files and directories and
> then had my exception handle the file if it was read only. The
> exception handler changes the file from read-only to not read only and
> then calls the function again.
>
> Is there a better way to do it? Would appreciate feedback on the code
> below.
>
> import shutil
> import os
>
> def zaps(self):
>
> try:
> shutil.rmtree('f:/m2m')
>
>
> except OSError, inst:
> print OSError
> os.chmod(inst.filename, 0666)
> self.zaps()
I imagine this could be expensive if you have a deep directory hierarchy
with lots of read-only files - you have to start the traversal from
scratch each time you get an error. If you have more than 1000 read-only
files you will get a stack overflow from the recursion.
shutil.rmtree() actually takes an optional error handler argument.
According to the docs, "If onerror is provided, it must be a callable
that accepts three parameters: function, path, and excinfo. The first
parameter, function, is the function which raised the exception; it will
be os.listdir(), os.remove() or os.rmdir()."
So something like this should work and be faster because the directory
traversal doesn't restart each time (UNTESTED!!):
def handle_error(fn, path, excinfo):
if fn is os.rmdir:
# handle readonly dir
os.chmod(path, 0666) # ?? not sure if this is correct for a dir
os.rmdir(path) # try again
elif fn is os.remove:
os.chmod(path, 0666)
os.remove(path)
shutil.rmtree(top, onerror=handle_error)
Kent
From amresh.kulkarni at gmail.com Fri Jun 16 20:56:17 2006
From: amresh.kulkarni at gmail.com (Amresh Kulkarni)
Date: Fri, 16 Jun 2006 13:56:17 -0500
Subject: [Tutor] Delete directories recursively
In-Reply-To: <4492F2AA.4000700@tds.net>
References:
<4492F2AA.4000700@tds.net>
Message-ID:
Thanks guys,
Error handling seems to be a nice idea to approach this problem. i checked
Kent's code and it works fine.
I was using a more crude method.
def removeDir(dirName) :
#Remove any read-only permissions on file.
removePermissions(dirName)
for name in os.listdir(dirName):
file = os.path.join(dirName, name)
if not os.path.islink(file) and os.path.isdir(file):
removeDir(file)
else:
removePermissions(file)
os.remove(file)
os.rmdir(dirName)
return
def removePermissions(filePath) :
#if (os.access(filePath, os.F_OK)) : #If path exists
if (not os.access(filePath, os.W_OK)) :
os.chmod(filePath, 0666)
return
however shutil seems to be more simple and efficient here!
Regards,
Amresh
On 6/16/06, Kent Johnson wrote:
>
> John Corry wrote:
> >
> > Amresh,
> >
> > I had this problem a few months back. I approached it backwards. Maybe
> > not the right way to do it. I removed all the files and directories and
> > then had my exception handle the file if it was read only. The
> > exception handler changes the file from read-only to not read only and
> > then calls the function again.
> >
> > Is there a better way to do it? Would appreciate feedback on the code
> > below.
> >
> > import shutil
> > import os
> >
> > def zaps(self):
> >
> > try:
> > shutil.rmtree('f:/m2m')
> >
> >
> > except OSError, inst:
> > print OSError
> > os.chmod(inst.filename, 0666)
> > self.zaps()
>
> I imagine this could be expensive if you have a deep directory hierarchy
> with lots of read-only files - you have to start the traversal from
> scratch each time you get an error. If you have more than 1000 read-only
> files you will get a stack overflow from the recursion.
>
> shutil.rmtree() actually takes an optional error handler argument.
> According to the docs, "If onerror is provided, it must be a callable
> that accepts three parameters: function, path, and excinfo. The first
> parameter, function, is the function which raised the exception; it will
> be os.listdir(), os.remove() or os.rmdir()."
>
> So something like this should work and be faster because the directory
> traversal doesn't restart each time (UNTESTED!!):
>
> def handle_error(fn, path, excinfo):
> if fn is os.rmdir:
> # handle readonly dir
> os.chmod(path, 0666) # ?? not sure if this is correct for a dir
> os.rmdir(path) # try again
> elif fn is os.remove:
> os.chmod(path, 0666)
> os.remove(path)
>
> shutil.rmtree(top, onerror=handle_error)
>
> Kent
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
--
~~AMRESH~~
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060616/2a888e96/attachment.htm
From alan.gauld at freenet.co.uk Fri Jun 16 21:13:10 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri, 16 Jun 2006 20:13:10 +0100
Subject: [Tutor] Delete directories recursively
References:
Message-ID: <002701c69178$e87ee090$0301a8c0@XPpro>
> I need to delete a directory and its sub directories. However all
> dir's, sub
> dir;s and files have read only access. How do i do this efficeintly
> using
> the os.walk command.
You can'ty since the reasoin the files are read-only is to prevent
them
being over-written or deleted! You need to convert them from read-only
and then delete them. Its not too hard provided you have the relevant
access rights to change mode.
> I cannot run this command on the dir as it gives me an error due to
> the read
> only attribute. Is there any other way to do this?
You can only do from Python what you can do from the OS.
If you don't have access to the files from the OS you won't have
access
from Python - thats why access rights are there!
For more on how to do it we need to know your OS, since this is
almost certainly a job for the OS rather than Python, unless you
want to do more than just delete the files.
If you do have access rights then you can find out all the needed
steps in the OS topic in my tutor.
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
From alan.gauld at freenet.co.uk Fri Jun 16 21:37:56 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Fri, 16 Jun 2006 20:37:56 +0100
Subject: [Tutor] Machine Vs. Human Parsing (Was: XML: Expletive
Deleted)(Way OT!)
References: <2BBAEE949D384D40A2B851287ADB6A432C36C7@eugsrv400.psc.pscnet.com>
Message-ID: <003301c6917c$5e4b8e60$0301a8c0@XPpro>
> > Almost anything beats the human eye IME :-)
> > Actually if you must use eyes do so on a hex dump of the file,
> > that
> > is usually reliable enough if you can read hex...
> If I gave the impression that the human eye is the only useful means
> of
> examining and verifying stored data, I apologize. I indented to say
> that the human eye, and the brain that goes with it, is an
> invaluable
> tool in evaluating data. I stand by that statement.
>
> The most sophisticated tool is only as good as the developer(s) who
> made it.
Of course and thats why i said I trusted a *tested* tool. You have to
be sure the tool is functioning correctly before you can use it
confidently.
> Since software is ultimately written by humans
Not always, but that's a whole other OT debate :-)
> You look at the data.
I agree, thats part of testing/debugging the tool. Most specifically
you find known data, whether that be the data causing the problem
or a reference data source with which you can compare.
> A case in point. I used to test audio subsystems on PC
> motherboards.
> ...
> I used an audio editing program to display the waveform
ie a Tool.
> The editing SW was no help there. So I switched tools,
> and displayed the capture buffer with simple file dump program.
Again a tool. Why because your eyes couldn't parse the audio data.
Your eyes could parse the tool output which was intended for human
consumption.
> The story goes on, but that's enough to illustrate my point.
And mine. You needed the right tools to interpret the raw data
in the file before your eyes and brain could diagnose the problem.
The issue I was raising was that textual data on disk is
notoriously difficult to accurately interpret. Once it has passsed
through a tool that presents it in an unambiguous format the
human eye is entirely appropriate.
> the audio driver, nor the test SW, nor the editing tool could
> show the real problem. All of them were 'tested tools',
The need for the *right* tool does not obviate the need for a tool
designed to interpret the raw data. Arguably the editing SW did
highlight the real problem - the corruption at the start of the file.
Its representation was good enough to poiunt you at the hex editor.
> data they were not designed to handle, they produced incorrect
> or incomplete results.
Just like the human eye when reading raw data out of a text file!
> I could cite other examples from other disciplines,
> but this one suffices: no SW tool should be relied upon to be
> correct
> in all cases.
Indeed, diagnosing data problems is always fraught with difficulty.
Its one of the hardest problem types to track down. My point was
merely that the human eye is not reliable when reading raw text files
and other, better tools exist. I did not mean to imply that any magic
tool exists that works for any kind of data, but the eye is no better
than any other kind of tool in this regard. It is very good when
presented with data that is formatted for it but not si good when
presented with "nearly right" data.
> I trust my eyes to see things tools can't
And I trust tools to see what my eyes can't!
Neither is infallible and I need both. If I'm looking at a text file
I'll fire
it up in a text editor first for the obvious checks. But if it looks
OK I'll then either load it in a hex editor or some other tool
designed
to read that data format.
> when necessary, but I usually just print out '\t', '[SP]', etc)
I'm curious how you do that? Presumably a tool?
(Not joking, how do you get that kind of display without a specialist
tool?)
> and incorrect. The programmer's two most valuable tools are her/his
> eyes and brain. They are always useful, sometimes indispensable.
I completely agree (see my chapter on denbugging in my paper
book for a confirmation of that claim!). I was simply pointing out
that
belief that text files are somehow easy to analyse with the human
eye is a dangerous fallacy, and I've spent enough man-days
debugging plain-text to be very, very wary. OTOH I detest the
modern tendency to use binary formats where plain text makes
more sense such as in configuration files! But thats a very different
use than for bulk data.
Alan G.
From cspears2002 at yahoo.com Sat Jun 17 02:05:07 2006
From: cspears2002 at yahoo.com (Christopher Spears)
Date: Fri, 16 Jun 2006 17:05:07 -0700 (PDT)
Subject: [Tutor] lambda and creating GUIs
In-Reply-To: <001001c6912e$139e6a70$0301a8c0@XPpro>
Message-ID: <20060617000507.22905.qmail@web51611.mail.yahoo.com>
I understand this:
>
> def f(w): gtk.main_quit()
> button.connect("clicked", f)
>
> lambda simply saves cluttering up the code with lots
> of tiny function
> derfinitions which are never referred to apart from
> in the binding
> operation.
>
Now my question is what is "w"? What is being passed
to the function?
From john at fouhy.net Sat Jun 17 04:53:23 2006
From: john at fouhy.net (John Fouhy)
Date: Sat, 17 Jun 2006 14:53:23 +1200
Subject: [Tutor] lambda and creating GUIs
In-Reply-To: <20060617000507.22905.qmail@web51611.mail.yahoo.com>
References: <001001c6912e$139e6a70$0301a8c0@XPpro>
<20060617000507.22905.qmail@web51611.mail.yahoo.com>
Message-ID: <5e58f2e40606161953i7322c02cx7723b0099879e24a@mail.gmail.com>
On 17/06/06, Christopher Spears wrote:
> I understand this:
> >
> > def f(w): gtk.main_quit()
> > button.connect("clicked", f)
> >
> Now my question is what is "w"? What is being passed
> to the function?
I don't know GTK, but I would guess some kind of event class. Other
GUIs I've used (Tkinter, wxPython) pass event objects to callbacks,
which contain information like
- which mouse button was clicked
- the exact mouse coordinates (relative to the corner of the screen
or the corner of the widget)
- which key was pressed
etc.
You may know some of the information, some of it may not apply, you
may not care about the rest of it, but you usually get it anyway :-)
In this case, the program doesn't care about any of the extra
information, so it accepts the event, but it does nothing with it.
Try this:
def show(e):
print e
print 'Class:', e.__class__
print 'Members:'
for attr in dir(e):
print '%s: %s' % (attr, getattr(e, attr))
button.connect("clicked", show)
--
John.
From alan.gauld at freenet.co.uk Sat Jun 17 10:40:42 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sat, 17 Jun 2006 09:40:42 +0100
Subject: [Tutor] lambda and creating GUIs
References: <20060617000507.22905.qmail@web51611.mail.yahoo.com>
Message-ID: <000301c691e9$b86879e0$0301a8c0@XPpro>
>I understand this:
>>
>> def f(w): gtk.main_quit()
>> button.connect("clicked", f)
>>
>
> Now my question is what is "w"? What is being passed
> to the function?
That will be defined by GTk. The framework will define what
each of its event hamdler callback functions looks like in terms
of parameters. I don;t know GTk but going on the basis of other
frameworkls I'll guess that its the widget where the event
occured - a bit like self in OOP. Thus you can add the same
handler function to several widgets and at run time manipulate
the specific widget that was clicked or whatever.
But thats a guess based on experience - and the fact that the
original programmer opted to call it w!
HTH,
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
From brian at daviesinc.com Sat Jun 17 22:44:19 2006
From: brian at daviesinc.com (Brian Gustin)
Date: Sat, 17 Jun 2006 16:44:19 -0400
Subject: [Tutor] I Give Up.
In-Reply-To: <18f27cbe0606121440v6630fd08u98d2dd1293cb69e9@mail.gmail.com>
References: <7a8d5a0c0606121409r450073eav6f276b3d77f478f@mail.gmail.com>
<18f27cbe0606121440v6630fd08u98d2dd1293cb69e9@mail.gmail.com>
Message-ID: <449469A3.5060101@daviesinc.com>
I have had it. I give up.
Python's documentation sucks beyond belief.
all I want to do is parse a *SIMPLE* config file of name = value pairs
and have python objects named by the name holding the value signified by
value , and I want it to be able to work *WITHOUT* someone having to
download and install additional modules, etc, so I looked up ConfigParser
OK, cool, at least it appears capable. however:
*section of code relevant to issue*
from ConfigParser import SafeConfigParser
cfg = SafeConfigParser("/etc/local-config/myconfig.cfg")
mystuff = cfg.items("Parameters",)#kept giving me an exception that 2
values required
print mystuff
[brian at NixServer python_snips]$ ./pymon.py
Traceback (most recent call last):
File "./pymon.py", line 20, in ?
main()
File "./pymon.py", line 15, in main
myname = cfg.items("Parameters",)
File "/usr/lib/python2.3/ConfigParser.py", line 532, in items
d = self._defaults.copy()
OK.. so items doesnt appear to work (the above is my tenth attempt to
get it working) So.. "RTSL!" (Read The Source, Luke) - I grokked
/usr/lib/python2.3/ConfigParser.py" to have a look see at how it does
what it does, and found additional stuff that isnt documented *AT ALL*
.. So..
[brian at NixServer python_snips]$ ./pymon.py
Traceback (most recent call last):
File "./pymon.py", line 20, in ?
main()
File "./pymon.py", line 15, in main
myname = cfg.section()
AttributeError: SafeConfigParser instance has no attribute 'section'
OK Obviously I have no clue how the heck this is all supposed to work,
and I have wasted 3 hours of development time on this thing (it aint the
first time I have had issues with Python's Documentation)
Whatever. I give up..
I'll just go write it in Perl. Maybe some day when Python actually has
well structured documentation with *actual working code examples* I
might take another look at trying to learn more of it, but at this
point, time is money, and I can develop the same application in Perl
(probably would have it *done* by now, it's really simple)..
I just needed to vent - I cannot believe how Python ever managed to get
*anywhere* with the state of documentation at python.org
If you want an example of what I would call quality online documentation
- need look no further than php.net (or dev.mysql.com) .. or even
cpan.org (or heck, just run perldoc in commandline.. ) I tried pydoc..
it just doesnt cut the mustard..
OK..
/end rant
Now can someone explan how exactly (preferrably with an actual real
world example) that I can read a configuration file in , say
/etc/local-config/myconfig.cfg into my python script running in
/usr/bin/localscripts , and able to actually use the names as variables
(objects) with the configured values assigned to them?
This drove me nuts the past couple hours, and truthfully, as much as I
like python (I really LIKE python) .. the documentation sucks *SO* bad,
I just cannot justify attempting to learn more and use it for more
projects because of situations like this that do nothing but waste my time.
From python at venix.com Sat Jun 17 23:56:03 2006
From: python at venix.com (Python)
Date: Sat, 17 Jun 2006 17:56:03 -0400
Subject: [Tutor] I Give Up.
In-Reply-To: <449469A3.5060101@daviesinc.com>
References:
<7a8d5a0c0606121409r450073eav6f276b3d77f478f@mail.gmail.com>
<18f27cbe0606121440v6630fd08u98d2dd1293cb69e9@mail.gmail.com>
<449469A3.5060101@daviesinc.com>
Message-ID: <1150581363.27979.247.camel@www.venix.com>
On Sat, 2006-06-17 at 16:44 -0400, Brian Gustin wrote:
> I have had it. I give up.
>
> Python's documentation sucks beyond belief.
A lot of it is excellent. The ConfigParser, that you are complaining
about is woefully short on examples and does not make clear that you
*must read* the other sections.
>
> all I want to do is parse a *SIMPLE* config file of name = value pairs
> and have python objects named by the name holding the value signified by
> value , and I want it to be able to work *WITHOUT* someone having to
> download and install additional modules, etc, so I looked up ConfigParser
>
> OK, cool, at least it appears capable. however:
> *section of code relevant to issue*
>
> from ConfigParser import SafeConfigParser
> cfg = SafeConfigParser("/etc/local-config/myconfig.cfg")
The initialization is your default values!
cfg = SafeConfigParser()
cfg.read("/etc/local-config/myconfig.cfg")
> mystuff = cfg.items("Parameters",)#kept giving me an exception that 2
> values required
> print mystuff
>>> help(cfg.items)
Help on method items in module ConfigParser:
items(self, section, raw=False, vars=None) method of
ConfigParser.SafeConfigParser instance
Return a list of tuples with (name, value) for each option
in the section.
All % interpolations are expanded in the return values, based on the
defaults passed into the constructor, unless the optional argument
`raw' is true. Additional substitutions may be provided using the
`vars' argument, which must be a dictionary whose contents overrides
any pre-existing defaults.
The section DEFAULT is special.
>
>
> [brian at NixServer python_snips]$ ./pymon.py
> Traceback (most recent call last):
> File "./pymon.py", line 20, in ?
> main()
> File "./pymon.py", line 15, in main
> myname = cfg.items("Parameters",)
> File "/usr/lib/python2.3/ConfigParser.py", line 532, in items
> d = self._defaults.copy()
> OK.. so items doesnt appear to work (the above is my tenth attempt to
> get it working) So.. "RTSL!" (Read The Source, Luke) - I grokked
> /usr/lib/python2.3/ConfigParser.py" to have a look see at how it does
> what it does, and found additional stuff that isnt documented *AT ALL*
> .. So..
>
>
> [brian at NixServer python_snips]$ ./pymon.py
> Traceback (most recent call last):
> File "./pymon.py", line 20, in ?
> main()
> File "./pymon.py", line 15, in main
> myname = cfg.section()
> AttributeError: SafeConfigParser instance has no attribute 'section'
>
myname = cfg.sections()
^
Will work for you and provide a list of sections. You will need those
sections to feed into the items call.
> OK Obviously I have no clue how the heck this is all supposed to work,
> and I have wasted 3 hours of development time on this thing (it aint the
> first time I have had issues with Python's Documentation)
>
> Whatever. I give up..
No don't!
You are almost there.
>
> I'll just go write it in Perl. Maybe some day when Python actually has
> well structured documentation with *actual working code examples* I
> might take another look at trying to learn more of it, but at this
> point, time is money, and I can develop the same application in Perl
> (probably would have it *done* by now, it's really simple)..
I came to Python after Perl and lot's of other languages. I think
Python is better, but it helps to have someone to talk to when things
are going badly.
>
> I just needed to vent - I cannot believe how Python ever managed to get
> *anywhere* with the state of documentation at python.org
>
I liked the old layout better, but presumably you found this:
http://docs.python.org/lib/RawConfigParser-objects.html
> If you want an example of what I would call quality online documentation
> - need look no further than php.net (or dev.mysql.com) .. or even
> cpan.org (or heck, just run perldoc in commandline.. ) I tried pydoc..
> it just doesnt cut the mustard..
>
> OK..
> /end rant
>
> Now can someone explan how exactly (preferrably with an actual real
> world example) that I can read a configuration file in , say
> /etc/local-config/myconfig.cfg into my python script running in
> /usr/bin/localscripts , and able to actually use the names as variables
> (objects) with the configured values assigned to them?
>
> This drove me nuts the past couple hours, and truthfully, as much as I
> like python (I really LIKE python) .. the documentation sucks *SO* bad,
> I just cannot justify attempting to learn more and use it for more
> projects because of situations like this that do nothing but waste my time.
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
--
Lloyd Kvam
Venix Corp
From python at venix.com Sun Jun 18 00:30:16 2006
From: python at venix.com (Python)
Date: Sat, 17 Jun 2006 18:30:16 -0400
Subject: [Tutor] I Give Up.
In-Reply-To: <449469A3.5060101@daviesinc.com>
References:
<7a8d5a0c0606121409r450073eav6f276b3d77f478f@mail.gmail.com>
<18f27cbe0606121440v6630fd08u98d2dd1293cb69e9@mail.gmail.com>
<449469A3.5060101@daviesinc.com>
Message-ID: <1150583416.27979.263.camel@www.venix.com>
On Sat, 2006-06-17 at 16:44 -0400, Brian Gustin wrote:
> Now can someone explan how exactly (preferrably with an actual real
> world example) that I can read a configuration file in , say
> /etc/local-config/myconfig.cfg into my python script running in
> /usr/bin/localscripts , and able to actually use the names as
> variables
> (objects) with the configured values assigned to them?
This was done from the Python prompt. Sorry for the crummy names. If
you saw all the typos that have been removed, you'd understand why I
kept the names short.
>>> print open('sample.config').read()
[sect_1]
a = 1
b = 2
>>> cfg = cp.SafeConfigParser()
>>> cfg.read('sample.config')
>>> cfg.sections()
['sect_1']
>>> for s in cfg.sections():
... print cfg.items(s)
...
[('a', '1'), ('b', '2')]
>>> class A:
... pass
...
>>> a = A()
>>> for s in cfg.sections():
... setattr(a,s,A())
... as = getattr(a,s)
... for k,v in cfg.items(s):
... setattr(as,k,v)
...
>>> a
<__main__.A instance at 0xb7f0256c>
>>> a.sect_1
<__main__.A instance at 0xb7eda3ac>
>>> a.sect_1.a
'1'
>>> a.sect_1.b
'2'
>>>
Hope this helps. Note that you can build a section dictionary by:
sect_dict = dict(cfg.items('section-name'))
You can create a class to turn dict references (d.get('key')) into
object references (o.key) with this trick:
>>> class Better(object):
... def __init__(self, **kwds):
... self.__dict__.update(kwds)
sect_obj = Better( **sect_dict)
--
Lloyd Kvam
Venix Corp
From brian at daviesinc.com Sun Jun 18 01:37:40 2006
From: brian at daviesinc.com (Brian Gustin)
Date: Sat, 17 Jun 2006 19:37:40 -0400
Subject: [Tutor] I Give Up.
In-Reply-To: <1150581363.27979.247.camel@www.venix.com>
References:
<7a8d5a0c0606121409r450073eav6f276b3d77f478f@mail.gmail.com>
<18f27cbe0606121440v6630fd08u98d2dd1293cb69e9@mail.gmail.com>
<449469A3.5060101@daviesinc.com>
<1150581363.27979.247.camel@www.venix.com>
Message-ID: <44949244.7060602@daviesinc.com>
Thanks- I had to sit back and with the perl script running nicely, I
took another shot at this to see if I could get it right.. so far so
good, at least no more exceptions being raised..
The perl script runs on a cron, I am thinking I will write this in
python and then wrap it up into a main function, and run it as a daemon,
eliminating the cron..
So, I guess I'll keep trying, now that the project is done, and the
script working, and client happy , and me paid, I have a little free
time to mess around with this..
I am thinking very seriously about building a new set of python
documentation with capability for user contributions and notes, etc, and
putting it online (with searchability to boot) .. maybe a project for
another day..
The one amazing thing I found ridiculously funny:
Python "official" forums- and they actually run phpBB forums? You mean
to tell me no one has written a solid, stable forum software in Python?
OK.. maybe another project to tackle.. I guess I just need to start
building the python documentation the way I think it outta be done...
and see how it goes over..
>>>>help(cfg.items)
>
>
> Help on method items in module ConfigParser:
>
> items(self, section, raw=False, vars=None) method of
> ConfigParser.SafeConfigParser instance
> Return a list of tuples with (name, value) for each option
> in the section.
>
> All % interpolations are expanded in the return values, based on the
> defaults passed into the constructor, unless the optional argument
> `raw' is true. Additional substitutions may be provided using the
> `vars' argument, which must be a dictionary whose contents overrides
> any pre-existing defaults.
>
> The section DEFAULT is special.
>
This is still not 100% clear, and I had to experiement a little bit to
get it to work, but finally got it working.
It does *NOT* say that you must send arguments of the function as
strings, (or as object variables defined elsewhere) , and for the life
of me, I have not been able to get interpolation to work, despite the
examples I have seen.. it is quite unclear.
It would seem all of this python documentation is written assuming that
the reader thinks exactly the same way as the author, and is already
familiar with the function and objects and documentation is written as
if it's just a "reminder of how stuff works"...
Example: I had no idea as to how to do this, and if I had not already
done similar parsing of config files (.ini for example) in other
languages (perl and php both) I would not even have been able to find
this module class on google search , unless I was really lucky ..
It seems sad that the only way I can look up "what kind of function or
module might there be to do x task in Python" has to be found via a
google search.. In the PHP documentation, I can just search out a
"similar" function (say, I want to know how to take two arrays and
combine them, rejecting non-uniques.. I might go to php.net and search
the function list for array() and then I have a list of *all* array
functions that may be used, and able to pick out, for example,
array_merge() .. With python, I dont see any way of doing that, so lots
of really cool stuff that can be done in python is not found..
>
> myname = cfg.sections()
> ^
> Will work for you and provide a list of sections. You will need those
> sections to feed into the items call.
>
Yeah - serves me right for not paying attention to spelling.. :)
>
>
> No don't!
>
> You are almost there.
>
Close.. we'll see how it goes from here, now that Im not under pressure
to get this script done :)
> I came to Python after Perl and lot's of other languages. I think
> Python is better, but it helps to have someone to talk to when things
> are going badly.
>
Very true.. and sometimes talking about teh issue the solution suddenly
becomes evident :)
>
> I liked the old layout better, but presumably you found this:
> http://docs.python.org/lib/RawConfigParser-objects.html
>
Actually, no I didnt find that.. another area where Documentation sucks-
It's so very easy to miss some important thing in the way this stuff
is categorized and structured..
In fact, I actually searched for python.org Documentation
ConfigParser.read and still didnt see anything come up for python.org
documentation....
Oh well. I'll see if I can get this thing to work like the perl script I
just wrote...
From kent37 at tds.net Sun Jun 18 03:17:26 2006
From: kent37 at tds.net (Kent Johnson)
Date: Sat, 17 Jun 2006 21:17:26 -0400
Subject: [Tutor] I Give Up.
In-Reply-To: <44949244.7060602@daviesinc.com>
References: <7a8d5a0c0606121409r450073eav6f276b3d77f478f@mail.gmail.com> <18f27cbe0606121440v6630fd08u98d2dd1293cb69e9@mail.gmail.com> <449469A3.5060101@daviesinc.com> <1150581363.27979.247.camel@www.venix.com>
<44949244.7060602@daviesinc.com>
Message-ID: <4494A9A6.3060006@tds.net>
Brian Gustin wrote:
> I am thinking very seriously about building a new set of python
> documentation with capability for user contributions and notes, etc, and
> putting it online (with searchability to boot) .. maybe a project for
> another day..
Maybe something like this:
http://pyref.infogami.com/
Kent
From ismaelgf at adinet.com.uy Sun Jun 18 05:39:50 2006
From: ismaelgf at adinet.com.uy (Ismael Garrido)
Date: Sun, 18 Jun 2006 00:39:50 -0300
Subject: [Tutor] I Give Up.
In-Reply-To: <449469A3.5060101@daviesinc.com>
References: <7a8d5a0c0606121409r450073eav6f276b3d77f478f@mail.gmail.com> <18f27cbe0606121440v6630fd08u98d2dd1293cb69e9@mail.gmail.com>
<449469A3.5060101@daviesinc.com>
Message-ID: <4494CB06.3070705@adinet.com.uy>
Brian Gustin wrote:
> I'll just go write it in Perl. Maybe some day when Python actually has
> well structured documentation with *actual working code examples*
>
Indeed. I have always thought that the docs lacked working examples. I
usually do a google search, hoping to find some script showing off how
to use whatever I'm searching for.
I think there was an annotated docs proyect, but I can't find it. Does
anybody know where it was? I'm willing to go and add examples :) (at
least, for the things I know)
Ismael
From ismaelgf at adinet.com.uy Sun Jun 18 07:27:01 2006
From: ismaelgf at adinet.com.uy (Ismael Garrido)
Date: Sun, 18 Jun 2006 02:27:01 -0300
Subject: [Tutor] Performance of classes
Message-ID: <4494E425.1040605@adinet.com.uy>
Hello
I'm writing a program to find an appropiate combination of resistances
to obtain a desired value of resistance. The program takes into account
how many resistances you have available and their resistance in ohms.
A short review of physics: resistors can be arranged in series or in
parallel. To obtain the equivalent resistance (that is, you could
replace those resistors with only one that had this resistance): if in
series: sum ohms; if in parallel 1/Req = 1/R1 + 1/R2.
Since this problem (as far as I can tell) requires to generate all
possible combinations (eliminating those that are impossible -ie:
requires 3 resistances of type A and you only have 2-), I'm trying to
make it run as fast as possible. So far I discovered that:
- Calling functions that return a value (ie: just "return
self.something") is slower than just grabbing the value from the class
- If you've got recursions, and you call them multiple times, you better
remember what they returned last time, otherwise it can consume a lot of
time (or to put it another way: don't go down the same road twice :)
- Psyco is nice :)
- The Python Profiler is really useful in these cases :)
Now, I was reading about decorators and noticed that some classes can
inherit from object. I thought it should make no difference in speed,
but, just because, I tried changing my class to inherit from object. Big
surprise, it *does* change things. I was wondering if somebody could
explain why it does? I find it quite weird!
Profiling normal:
4772989 function calls (3817173 primitive calls) in 54.433 CPU
seconds
Profiling all clases inherit from object:
4772989 function calls (3817173 primitive calls) in 51.151 CPU
seconds
But what's really really strange is that if one class inherits from
object but the other does not, the amount of calls varies!
Both "normal" classes:
1051803 4.609 0.000 4.609 0.000 resistPsyco.py:65(__cmp__)
78803 0.372 0.000 0.372 0.000 resistPsyco.py:85(__cmp__)
Resistencia inherits from object:
86306 0.402 0.000 0.402 0.000 resistPsyco.py:65(__cmp__)
1044300 4.879 0.000 4.879 0.000 resistPsyco.py:85(__cmp__)
Why does this happen?
I have attached the code, I hope that's fine. If you have any further
optimization suggestions I would be very glad to hear them :)
About the code:
- generarPos generates all possible resistances
- generarResist generates all possible from the initial resistances
- unico makes sure that there are no duplicates (equal resistance) -
This method was posted on the ASPN Cookbook
- ResistenciaB is the basic resistance, the ones you have available.
- Resistencia is composed of two resistances
- checkPosible checks that you can actually build this resistor
- getBasicasIni tells you how many resistors of x type you have used.
- resorig are the resistors you begin with
- rescant is the amount of each basic resistors you have
- Don't put many different resistors or a big amount of resistors,
otherwise the program may take veeeryyy long to run.
Please forgive any broken English. It's been too long since I last wrote
in it.
Thanks for your time!
Ismael
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: resistPsyco.py
Url: http://mail.python.org/pipermail/tutor/attachments/20060618/84c6ab5d/attachment-0001.pot
From learner404 at gmail.com Sun Jun 18 10:46:11 2006
From: learner404 at gmail.com (learner404)
Date: Sun, 18 Jun 2006 10:46:11 +0200
Subject: [Tutor] I Give Up.
In-Reply-To: <44949244.7060602@daviesinc.com>
References:
<7a8d5a0c0606121409r450073eav6f276b3d77f478f@mail.gmail.com>
<18f27cbe0606121440v6630fd08u98d2dd1293cb69e9@mail.gmail.com>
<449469A3.5060101@daviesinc.com>
<1150581363.27979.247.camel@www.venix.com>
<44949244.7060602@daviesinc.com>
Message-ID: <13a83ca10606180146p1e01c281hb9f293d9d1030d76@mail.gmail.com>
On 18/06/06, Brian Gustin wrote:
>
>
>
> The one amazing thing I found ridiculously funny:
>
> Python "official" forums- and they actually run phpBB forums? You mean
> to tell me no one has written a solid, stable forum software in Python?
>
> OK.. maybe another project to tackle.. I guess I just need to start
> building the python documentation the way I think it outta be done...
> and see how it goes over..
I also was very surprised with that and I'd really love to see a "pynBB" :)
The only things I saw for "forums" in Python are:
pyBB but it seems dead and my south-korean sucks :
http://bbs.pythonworld.net:9080/pybbs.py
Zyons which look promising on a Django base but which still is in an alpha
state:
http://zyons.com/forum/
Concerning basic Perl/Python I also found that (but not complete) :
http://pleac.sourceforge.net/pleac_python/index.html
"In this document, you'll find an implementation of the Solutions of the
Perl Cookbook in the Python language."
Ooops and I also found that on perl ;)
http://mirror5.escomposlinux.org/comic/ecol-13-e.png
learner404
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060618/d701fb5e/attachment.html
From btatum at cddn.com Sun Jun 18 12:58:38 2006
From: btatum at cddn.com (Bill Tatum)
Date: Sun, 18 Jun 2006 05:58:38 -0500
Subject: [Tutor] Beginner question(s)
Message-ID: <20060618105838.0DB326318@mem01.ecsis.net>
Hi,
I'm working through Python Programming for the Absolute Beginner. One of
the challenges at the end of chapter 4 is to get a message from the user and
then print it out backwards. I have.
message = raw_input("Enter your message:")
count = len(message)
print count
which gives me the number of characters in the message. I tried to use a
for loop:
for i in range(len(message)-1,-1, -1):
print i,
but I just get the numeric values of the string. Can anyone help?
Also, does anyone know of a PDA that would run python?
TIA
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060618/6898d895/attachment.html
From ground.contro at pobox.com Sun Jun 18 14:33:38 2006
From: ground.contro at pobox.com (gc)
Date: Sun, 18 Jun 2006 22:33:38 +1000
Subject: [Tutor] socket.recvfrom() not getting data
Message-ID: <44954822.8020407@pobox.com>
I've hit the wall trying to receive some data from a socket and hope
potential cross posting won't upset too many of you. In summary, I'm
playing with a DHCP client written in python just to get a feel for it
before getting down to serious work (see the PS for more info)
This segment of code sends a packet, using tcpdump i can see a response
coming from server running on another PC but i never see any data back
from socket.recvfrom() - it just blocks:
sock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
sock.bind( (socket.gethostname(), CLI_PORT) )
sock.setsockopt( socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
cSent = sock.sendto( data, 0, ( '', SRV_PORT ) )
print 'sent: ', cSent, ', from', sock.getsockname()
print 'status:', sock.getsockopt( socket.SOL_SOCKET, socket.SO_ERROR )
(rcvd, add) = sock.recvfrom( 512 )
print 'Got', len( rcvd ), 'bytes back'
netstat tells me that the socket is still there - as long as the script
is running. BTW the script runs with root privileges - the ports used
are 67 and 68. The server response that i see with tcpdump looks
healthy. My suspicion is that the protocol stack never passes the packet
up to the socket but don't know why (the normal DHCP client daemon isn't
running on this machine).
Is there a way to turn on some debugging with sockets?
Calling sock.setsockopt( socket.SOL_SOCKET, socket.SO_DEBUG, 1) didn't
do much for me.
Any pointers appreciated.
TIA
PS
For the curious, the DHCP client is really meant to be implemented in
C/C++ on a networked embedded device (needless to say, running a
proprietary OS); there'll be lots of them and configuring IP address,
netmask, gateway etc manually is a pain. So the python code is just a
proof of concept.
From kent37 at tds.net Sun Jun 18 15:06:37 2006
From: kent37 at tds.net (Kent Johnson)
Date: Sun, 18 Jun 2006 09:06:37 -0400
Subject: [Tutor] Performance of classes
In-Reply-To: <4494E425.1040605@adinet.com.uy>
References: <4494E425.1040605@adinet.com.uy>
Message-ID: <44954FDD.8050608@tds.net>
Ismael Garrido wrote:
> Hello
>
> I'm writing a program to find an appropiate combination of resistances
> to obtain a desired value of resistance. The program takes into account
> how many resistances you have available and their resistance in ohms.
>
> Since this problem (as far as I can tell) requires to generate all
> possible combinations (eliminating those that are impossible -ie:
> requires 3 resistances of type A and you only have 2-), I'm trying to
> make it run as fast as possible. So far I discovered that:
> - Calling functions that return a value (ie: just "return
> self.something") is slower than just grabbing the value from the class
Yes, there is a cost to calling a function.
> - If you've got recursions, and you call them multiple times, you better
> remember what they returned last time, otherwise it can consume a lot of
> time (or to put it another way: don't go down the same road twice :)
This is the basic idea behind dynamic programming algorithms.
> - Psyco is nice :)
> - The Python Profiler is really useful in these cases :)
>
> Now, I was reading about decorators and noticed that some classes can
> inherit from object. I thought it should make no difference in speed,
> but, just because, I tried changing my class to inherit from object. Big
> surprise, it *does* change things. I was wondering if somebody could
> explain why it does? I find it quite weird!
Inheriting from object makes your class a "new-style class" which
changes some of the details of how the class works, so it's not really
surprising that there is a performance difference.
> I have attached the code, I hope that's fine. If you have any further
> optimization suggestions I would be very glad to hear them :)
generarResist() is doing a lot more work than necessary. Because i and j
both iterate the entire list, you will generate all pairs twice. Since
Resistencia(i,j) is equivalent to Resistencia(j,i) you would be better
off having j just go through the part of the list starting from i. You
can do this by iterating over indices instead of values.
Second, Resistencia(i,j).posible is going to be the same as
Resistencia(i,j, False).posible because they use the same resistors. So
there is no need to try Resistencia(i,j, False) if
Resistencia(i,j).posible is False.
def generarResist(listaRes):
resultado = []
for i in listaRes:
for j in listaRes:
r = Resistencia(i,j)
if r.posible:
resultado.append(r)
r = Resistencia(i,j, False)
if r.posible:
resultado.append(r)
return unico(resultado)
Kent
From michael at espersunited.com Sun Jun 18 15:18:13 2006
From: michael at espersunited.com (Michael Sullivan)
Date: Sun, 18 Jun 2006 08:18:13 -0500
Subject: [Tutor] Beginner question(s)
In-Reply-To: <20060618105838.0DB326318@mem01.ecsis.net>
References: <20060618105838.0DB326318@mem01.ecsis.net>
Message-ID: <1150636693.12107.12.camel@camille.espersunited.com>
On Sun, 2006-06-18 at 05:58 -0500, Bill Tatum wrote:
> Hi,
>
>
>
> I?m working through Python Programming for the Absolute Beginner. One
> of the challenges at the end of chapter 4 is to get a message from the
> user and then print it out backwards. I have?
>
>
>
> message = raw_input("Enter your message:")
>
> count = len(message)
>
> print count
>
>
>
> which gives me the number of characters in the message. I tried to
> use a for loop:
>
>
>
> for i in range(len(message)-1,-1, -1):
>
> print i,
>
>
>
> but I just get the numeric values of the string. Can anyone help?
>
I'm a python beginner myself, but shouldn't that last "print i" be "print message[i]? As it stands, you're only printing the numeric value 'i'.
-Michael Sullivan-
From ismaelgf at adinet.com.uy Sun Jun 18 17:02:48 2006
From: ismaelgf at adinet.com.uy (Ismael Garrido)
Date: Sun, 18 Jun 2006 12:02:48 -0300
Subject: [Tutor] Performance of classes
In-Reply-To: <44954FDD.8050608@tds.net>
References: <4494E425.1040605@adinet.com.uy> <44954FDD.8050608@tds.net>
Message-ID: <44956B18.8030103@adinet.com.uy>
Kent Johnson wrote:
> Ismael Garrido wrote:
>
>> I have attached the code, I hope that's fine. If you have any further
>> optimization suggestions I would be very glad to hear them :)
>>
>
> generarResist() is doing a lot more work than necessary. Because i and j
> both iterate the entire list, you will generate all pairs twice. Since
> Resistencia(i,j) is equivalent to Resistencia(j,i) you would be better
> off having j just go through the part of the list starting from i. You
> can do this by iterating over indices instead of values.
>
> Second, Resistencia(i,j).posible is going to be the same as
> Resistencia(i,j, False).posible because they use the same resistors. So
> there is no need to try Resistencia(i,j, False) if
> Resistencia(i,j).posible is False.
>
Thanks for your reply! You're *very* right about that! :D
Do you have any idea about the difference in calls to the compares?
Should I always inherit from object in my classes?
Thanks
Ismael
From kieran.flanagan at gmail.com Sun Jun 18 21:11:35 2006
From: kieran.flanagan at gmail.com (kieran flanagan)
Date: Sun, 18 Jun 2006 20:11:35 +0100
Subject: [Tutor] Writing to a remote file
In-Reply-To: <1150475085.27979.136.camel@www.venix.com>
References:
<1150475085.27979.136.camel@www.venix.com>
Message-ID:
Hi
Thanks for the help. I took a quick scan through the logging module and I
can't see any mention of writing to a remote file ? Could you please direct
me to the part you mentioned ?. I went through some of the examples and the
one related to remote logging is via the console (tcp port). I cannot see
any information given regarding remote logging.
Just to give some more info on what I am doing. I have a large script that
is running and outputting messages to a logfile I am storing. I want these
messages to be output to a remote file instead which can be viewed on a
browser to provide realtime data as the script processes.
So this logfile is not handled by syslog.
This is being done on a Linux machine.
Thanks for the help
Kieran
On 6/16/06, Lloyd Kvam wrote:
>
> On Fri, 2006-06-16 at 14:47 +0100, kieran flanagan wrote:
> > Hi
> >
> > I want to run a script on one machine and log output messages to a
> > remote file located on another machine. Is there any easy method of
> > doing this ?.
>
> http://docs.python.org/lib/module-logging.html
>
> If the remote machine is a file server, you can use the logging module
> to write to a file on the remote machine
>
> Also the logging module can be used to easily log to a syslog handler.
> If this remote file is a "normal" log file managed by a syslog process
> then you should find the python part pretty easy. The syslog process
> still needs to be configured to accept your logging messages, but that
> should not be too difficult.
>
> Scanning the logging module docs, it looks like you can use it to write
> your own process to run on the remote machine to handle "logging
> messages". Then use the logging module on the local machine to send
> "logging messages" to the remote machine.
>
>
> > Thanks
> > Kieran
> >
> > --
> > "Behind every great man, there is a great woman. Behind that woman is
> > Mr.T."
> > _______________________________________________
> > Tutor maillist - Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> --
> Lloyd Kvam
> Venix Corp.
> 1 Court Street, Suite 378
> Lebanon, NH 03766-1358
>
> voice: 603-653-8139
> fax: 320-210-3409
>
>
--
"Behind every great man, there is a great woman. Behind that woman is Mr.T."
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060618/6cb8343c/attachment.htm
From dkuhlman at rexx.com Sun Jun 18 21:46:36 2006
From: dkuhlman at rexx.com (Dave Kuhlman)
Date: Sun, 18 Jun 2006 12:46:36 -0700
Subject: [Tutor] I Give Up.
In-Reply-To: <44949244.7060602@daviesinc.com>
References:
<7a8d5a0c0606121409r450073eav6f276b3d77f478f@mail.gmail.com>
<18f27cbe0606121440v6630fd08u98d2dd1293cb69e9@mail.gmail.com>
<449469A3.5060101@daviesinc.com>
<1150581363.27979.247.camel@www.venix.com>
<44949244.7060602@daviesinc.com>
Message-ID: <20060618194636.GA22079@cutter.rexx.com>
On Sat, Jun 17, 2006 at 07:37:40PM -0400, Brian Gustin wrote:
[snip]
>
> OK.. maybe another project to tackle.. I guess I just need to start
> building the python documentation the way I think it outta be done...
> and see how it goes over..
At the top of the table of contents of the library reference, it
says:
Python Library Reference
Guido van Rossum
Python Software Foundation
Email: docs at python.org
Fred L. Drake, Jr., editor
So, another thing you could do is to send an email to Fred Drake
at docs at python.org in which you provide an example with a bit of
commentary and ask him to include it in the ConfigParser section.
Another suggestion: Go to the Python Wiki at
http://wiki.python.org/moin/, then search for ConfigParser. There
are already several related pages there, but I could not find a
page that gives examples. So, you could add a
ConfigParserExamples page that has one or more of the examples
provided in this thread, or some of your own code, with a bit of
explanation, and then link to it from the main ConfigParser page.
In defense of the standard docs -- Since, the standard Python
documentation (language reference, library reference, etc) are
reference docs, they do not replace tutorial books like "Learning
Python" or "Learn to Program Using Python" (by Alan Gauld, who
also posts on this list). Still I've found so much of what I need
in those documents, that I have a hard time complaining. And, my
thanks to Fred Drake.
Dave
[snip]
--
Dave Kuhlman
http://www.rexx.com/~dkuhlman
From jj_frap at hotmail.com Sun Jun 18 22:57:32 2006
From: jj_frap at hotmail.com (Josh F)
Date: Sun, 18 Jun 2006 20:57:32 +0000
Subject: [Tutor] Beginner Question
In-Reply-To:
Message-ID:
re. Beginner Question
I'm still in the fairly early stages of learning Python, but I have an
intermediate level of HTML, CSS, and VB6 knowledge along with the
fundamentals of C and C++ and a very little bit of PERL..
But enough about me...Here's the solution.
message = raw_input("Enter your message:")
print message[-1::-1]
Slicing a string takes three arguments, all of which are optional: The first
character to be sliced, the last character to be sliced, and tio slice every
nth character.
In Python strings, -1 refers to the last character in the string and thus
becomes the first argument.
You don't specify the second argument because you're printing the string
from end to beginning.
Finallly, the -1 in the 3rd argument indicates that you want the string to
be printed in reverse order (i.e. iterate backwards by one character).
>Message: 1
>Date: Sun, 18 Jun 2006 05:58:38 -0500
>From: "Bill Tatum"
>Subject: [Tutor] Beginner question(s)
>To:
>Message-ID: <20060618105838.0DB326318 at mem01.ecsis.net>
>Content-Type: text/plain; charset="us-ascii"
>
>Hi,
>
>
>
>I'm working through Python Programming for the Absolute Beginner. One of
>the challenges at the end of chapter 4 is to get a message from the user
>and
>then print it out backwards. I have.
>
>
>
>message = raw_input("Enter your message:")
>
>count = len(message)
>
>print count
>
>
>
>which gives me the number of characters in the message. I tried to use a
>for loop:
>
>
>
>for i in range(len(message)-1,-1, -1):
>
> print i,
>
>
>
>but I just get the numeric values of the string. Can anyone help?
>
>
>
>Also, does anyone know of a PDA that would run python?
>
>
>
>TIA
From alan.gauld at freenet.co.uk Mon Jun 19 00:15:35 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sun, 18 Jun 2006 23:15:35 +0100
Subject: [Tutor] I Give Up.
References: <7a8d5a0c0606121409r450073eav6f276b3d77f478f@mail.gmail.com><18f27cbe0606121440v6630fd08u98d2dd1293cb69e9@mail.gmail.com><449469A3.5060101@daviesinc.com><1150581363.27979.247.camel@www.venix.com><44949244.7060602@daviesinc.com>
<20060618194636.GA22079@cutter.rexx.com>
Message-ID: <001c01c69324$b90a6610$0301a8c0@XPpro>
> reference docs, they do not replace tutorial books like "Learning
> Python" or "Learn to Program Using Python" (by Alan Gauld, who
Thanks for the plug, but I'd be first to admit my tutor is way too
basic to go near the ConfigParser modules etc. I had actually
hoped that Mertz' "Text Processing in Python" would cover that
kind of stuff but instead it goes off into the 3rd party mx modules
after
giving only the briefest of examples of using ConfigParser...
> thanks to Fred Drake.
In the few emails I've exchanged with Fred, mainly about links
to my tutors and the various translations, he has been most helpful.
I'll add my thanks to the list. :-)
Alan G
From alan.gauld at freenet.co.uk Mon Jun 19 00:18:29 2006
From: alan.gauld at freenet.co.uk (Alan Gauld)
Date: Sun, 18 Jun 2006 23:18:29 +0100
Subject: [Tutor] Beginner question(s)
References: <20060618105838.0DB326318@mem01.ecsis.net>
Message-ID: <002801c69325$20e48cc0$0301a8c0@XPpro>
> message = raw_input("Enter your message:")
> for i in range(len(message)-1,-1, -1):
> print i,
>
> but I just get the numeric values of the string. Can anyone help?
As an alternative approach consider converting to a list and
using the reverse method...
> Also, does anyone know of a PDA that would run python?
There was a project called pippy, but I haven't heard anything of it
recently so I don't know if its still around or if it runs on modern
PDAs - I think it was PalmOS anyhow...
There was rumours of a Pocket Windows version too but
I've never really been interested in that one...
Alan G.
From ismaelgf at adinet.com.uy Mon Jun 19 00:34:10 2006
From: ismaelgf at adinet.com.uy (Ismael Garrido)
Date: Sun, 18 Jun 2006 19:34:10 -0300
Subject: [Tutor] Beginner question(s)
In-Reply-To: <002801c69325$20e48cc0$0301a8c0@XPpro>
References: <20060618105838.0DB326318@mem01.ecsis.net>
<002801c69325$20e48cc0$0301a8c0@XPpro>
Message-ID: <4495D4E2.6060303@adinet.com.uy>
Alan Gauld wrote:
>> Also, does anyone know of a PDA that would run python?
>>
>
> There was a project called pippy, but I haven't heard anything of it
> recently so I don't know if its still around or if it runs on modern
> PDAs - I think it was PalmOS anyhow...
>
>
Pippy is quite dead. No development done recently. It supposedly runs
fine, but runs only Python 1.5.
If you want it, it's at:
http://sourceforge.net/projects/pippy
Ismael
From simplebob at gmail.com Mon Jun 19 00:39:03 2006
From: simplebob at gmail.com (Daniel McQuay)
Date: Sun, 18 Jun 2006 18:39:03 -0400
Subject: [Tutor] Beginner Question
In-Reply-To:
References:
Message-ID: <6d87ecf40606181539r30ee95dcl4ce3d1b13635cfba@mail.gmail.com>
On 6/18/06, Josh F wrote:
>
> re. Beginner Question
>
> I'm still in the fairly early stages of learning Python, but I have an
> intermediate level of HTML, CSS, and VB6 knowledge along with the
> fundamentals of C and C++ and a very little bit of PERL..
>
> But enough about me...Here's the solution.
>
> message = raw_input("Enter your message:")
> print message[-1::-1]
just another noob here.
but wouldn't his way work like this:
>>>message = "foobar"
>>>for i in range(len(message)-1,-1,-1):
... print message[i],
...
r a b o o f
i guess there's lots of ways to do it.
that's my 2 cents.
Slicing a string takes three arguments, all of which are optional: The first
> character to be sliced, the last character to be sliced, and tio slice
> every
> nth character.
>
> In Python strings, -1 refers to the last character in the string and thus
> becomes the first argument.
>
> You don't specify the second argument because you're printing the string
> from end to beginning.
>
> Finallly, the -1 in the 3rd argument indicates that you want the string to
> be printed in reverse order (i.e. iterate backwards by one character).
>
>
>
>
>
>
>
> >Message: 1
> >Date: Sun, 18 Jun 2006 05:58:38 -0500
> >From: "Bill Tatum"
> >Subject: [Tutor] Beginner question(s)
> >To:
> >Message-ID: <20060618105838.0DB326318 at mem01.ecsis.net>
> >Content-Type: text/plain; charset="us-ascii"
> >
> >Hi,
> >
> >
> >
> >I'm working through Python Programming for the Absolute Beginner. One of
> >the challenges at the end of chapter 4 is to get a message from the user
> >and
> >then print it out backwards. I have.
> >
> >
> >
> >message = raw_input("Enter your message:")
> >
> >count = len(message)
> >
> >print count
> >
> >
> >
> >which gives me the number of characters in the message. I tried to use a
> >for loop:
> >
> >
> >
> >for i in range(len(message)-1,-1, -1):
> >
> > print i,
> >
> >
> >
> >but I just get the numeric values of the string. Can anyone help?
> >
> >
> >
> >Also, does anyone know of a PDA that would run python?
> >
> >
> >
> >TIA
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
--
Daniel McQuay
simplebob at gmail.com
boxster.homelinux.org
H: 814.825.0847
M: 814-341-6233
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060618/6d6486a1/attachment.htm
From john at fouhy.net Mon Jun 19 01:02:41 2006
From: john at fouhy.net (John Fouhy)
Date: Mon, 19 Jun 2006 11:02:41 +1200
Subject: [Tutor] Beginner question(s)
In-Reply-To: <20060618105838.0DB326318@mem01.ecsis.net>
References: <20060618105838.0DB326318@mem01.ecsis.net>
Message-ID: <5e58f2e40606181602g69a4d714ub59d5ac20de031b6@mail.gmail.com>
> Also, does anyone know of a PDA that would run python?
Some of the new Nokias run python: http://www.forum.nokia.com/python
--
John.
From python at venix.com Mon Jun 19 14:40:19 2006
From: python at venix.com (Python)
Date: Mon, 19 Jun 2006 08:40:19 -0400
Subject: [Tutor] Writing to a remote file
In-Reply-To:
References:
<1150475085.27979.136.camel@www.venix.com>
Message-ID: <1150720819.27979.299.camel@www.venix.com>
On Sun, 2006-06-18 at 20:11 +0100, kieran flanagan wrote:
> Hi
>
> Thanks for the help. I took a quick scan through the logging module
> and I can't see any mention of writing to a remote file ? Could you
> please direct me to the part you mentioned ?.
I had 3 suggestions: use the remote computer as a file server, use the
remote server as a syslog server, write your own logging server on the
remote computer.
1. If the remote system is a file server, the logging module does not
know it is writing to a remote computer. The remote computer is simply
mounted into your local file system. You'd use linux commands something
like:
mkdir logfiles
mount -t smbfs //remote/logs ./logfiles
That assumes the remote computer is running samba. The Python code
would be something like:
import logging, logging.handlers
logger = logging.getLogger('')
logger.addHandler(logging.handlers.FileHandler('logfiles/myapp.log'))
(all this is untested, but, hopefully, close to being correct)
2. You eliminate the remote syslog option below.
3. Write your own logging server to run on the remote computer. Have
your local program use the remote logging server. The example code is
here:
http://docs.python.org/lib/network-logging.html
> I went through some of the examples and the one related to remote
> logging is via the console (tcp port). I cannot see any information
> given regarding remote logging.
> Just to give some more info on what I am doing. I have a large script
> that is running and outputting messages to a logfile I am storing. I
> want these messages to be output to a remote file instead which can be
> viewed on a browser to provide realtime data as the script processes.
> So this logfile is not handled by syslog.
>
> This is being done on a Linux machine.
>
> Thanks for the help
> Kieran
>
>
>
>
> On 6/16/06, Lloyd Kvam wrote:
> On Fri, 2006-06-16 at 14:47 +0100, kieran flanagan wrote:
> > Hi
> >
> > I want to run a script on one machine and log output
> messages to a
> > remote file located on another machine. Is there any easy
> method of
> > doing this ?.
>
> http://docs.python.org/lib/module-logging.html
>
> If the remote machine is a file server, you can use the
> logging module
> to write to a file on the remote machine
>
> Also the logging module can be used to easily log to a syslog
> handler.
> If this remote file is a "normal" log file managed by a syslog
> process
> then you should find the python part pretty easy. The syslog
> process
> still needs to be configured to accept your logging messages,
> but that
> should not be too difficult.
>
> Scanning the logging module docs, it looks like you can use it
> to write
> your own process to run on the remote machine to handle
> "logging
> messages". Then use the logging module on the local machine
> to send
> "logging messages" to the remote machine.
>
>
> > Thanks
> > Kieran
> >
> > --
> > "Behind every great man, there is a great woman. Behind that
> woman is
> > Mr.T."
> > _______________________________________________
> > Tutor maillist - Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> --
> Lloyd Kvam
> Venix Corp.
> 1 Court Street, Suite 378
> Lebanon, NH 03766-1358
>
> voice: 603-653-8139
> fax: 320-210-3409
>
>
>
>
> --
> "Behind every great man, there is a great woman. Behind that woman is
> Mr.T."
--
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358
voice: 603-653-8139
fax: 320-210-3409
--
Lloyd Kvam
Venix Corp
From frank.hoffsummer at gmail.com Mon Jun 19 15:38:43 2006
From: frank.hoffsummer at gmail.com (frank h.)
Date: Mon, 19 Jun 2006 15:38:43 +0200
Subject: [Tutor] local day names in ascii
Message-ID: <60fae7c30606190638i27460a25qed35630a83617c67@mail.gmail.com>
Hello List,
i am trying to convert local Swedish daynames to ASCII
"M?ndag" should become "Mandag"
"L?rdag" should become "Lordag"
"S?ndag" should become "Sondag"
here is my session
import locale
locale.setlocale(locale.LC_ALL, 'sv_Se')
datetime.date(2006, 06, 19).strftime("%A")
'M\xc3\xa5ndag'
datetime.date(2006, 06,
19).strftime("%A").decode('utf8').encode('ascii','ignore')
'Mndag'
Somehow, the Swedish character "?" gets dropped in the conversion to ascii.
how can I accomplish the conversion '?' --> 'a' etc.? should I use a
dictionary?
thanks for any insight
-frank
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060619/6a38f2b2/attachment.html
From andre.roberge at gmail.com Mon Jun 19 15:50:17 2006
From: andre.roberge at gmail.com (Andre Roberge)
Date: Mon, 19 Jun 2006 10:50:17 -0300
Subject: [Tutor] local day names in ascii
In-Reply-To: <60fae7c30606190638i27460a25qed35630a83617c67@mail.gmail.com>
References: <60fae7c30606190638i27460a25qed35630a83617c67@mail.gmail.com>
Message-ID: <7528bcdd0606190650y7f4a0d01n9592c905f029553a@mail.gmail.com>
May I suggest you look at this
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/251871
including the comments. (The last comment in particular looks intriguing...)
Andr?
On 6/19/06, frank h. wrote:
> Hello List,
> i am trying to convert local Swedish daynames to ASCII
>
> "M?ndag" should become "Mandag"
> "L?rdag" should become "Lordag"
> "S?ndag" should become "Sondag"
>
> here is my session
>
> import locale
> locale.setlocale(locale.LC_ALL, 'sv_Se')
> datetime.date(2006, 06, 19).strftime("%A")
> 'M\xc3\xa5ndag'
> datetime.date(2006, 06,
> 19).strftime("%A").decode('utf8').encode('ascii','ignore')
> 'Mndag'
>
> Somehow, the Swedish character "?" gets dropped in the conversion to ascii.
> how can I accomplish the conversion '?' --> 'a' etc.? should I use a
> dictionary?
> thanks for any insight
> -frank
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
From andre.roberge at gmail.com Mon Jun 19 16:55:49 2006
From: andre.roberge at gmail.com (Andre Roberge)
Date: Mon, 19 Jun 2006 11:55:49 -0300
Subject: [Tutor] Fwd: local day names in ascii
In-Reply-To: <60fae7c30606190706k24d6cdebq711b9b1340130f7a@mail.gmail.com>
References: <60fae7c30606190638i27460a25qed35630a83617c67@mail.gmail.com>
<7528bcdd0606190650y7f4a0d01n9592c905f029553a@mail.gmail.com>
<60fae7c30606190706k24d6cdebq711b9b1340130f7a@mail.gmail.com>
Message-ID: <7528bcdd0606190755x4c949cc6x65096e50c04ff5e9@mail.gmail.com>
Message forwarded to the list for information.
Andr?
---------- Forwarded message ----------
From: frank h.
Date: Jun 19, 2006 11:06 AM
Subject: Re: [Tutor] local day names in ascii
To: Andre Roberge
Andr?,
thank you so much for this spot-on pointer. the last comment indeed nails it.
excellent!!
-frank
On 6/19/06, Andre Roberge < andre.roberge at gmail.com> wrote:
> May I suggest you look at this
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/251871
> including the comments. (The last comment in particular looks intriguing...)
>
> Andr?
>
> On 6/19/06, frank h. < frank.hoffsummer at gmail.com> wrote:
> > Hello List,
> > i am trying to convert local Swedish daynames to ASCII
> >
> > "M?ndag" should become "Mandag"
> > "L?rdag" should become "Lordag"
> > "S?ndag" should become "Sondag"
> >
> > here is my session
> >
> > import locale
> > locale.setlocale(locale.LC_ALL, 'sv_Se')
> > datetime.date(2006, 06, 19).strftime("%A")
> > 'M\xc3\xa5ndag'
> > datetime.date(2006, 06,
> > 19).strftime("%A").decode('utf8').encode('ascii','ignore')
> > 'Mndag'
> >
> > Somehow, the Swedish character "?" gets dropped in the conversion to ascii.
> > how can I accomplish the conversion '?' --> 'a' etc.? should I use a
> > dictionary?
> > thanks for any insight
> > -frank
> >
> >
> > _______________________________________________
> > Tutor maillist - Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> >
> >
>
From josipl2000 at yahoo.com Mon Jun 19 16:39:11 2006
From: josipl2000 at yahoo.com (josip)
Date: Mon, 19 Jun 2006 07:39:11 -0700 (PDT)
Subject: [Tutor] projects for beginners
Message-ID: <20060619143911.50179.qmail@web60818.mail.yahoo.com>
Hi!
I have read learning python and mede some smaller examples.
Now I want to make smoe project, I'm thinking about text editor.
Can someone give me pointers like (where and how to start, etc.)?
Or maybe another project suitable for beginners.
---------------------------------
Sneak preview the all-new Yahoo.com. It's not radically different. Just radically better.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060619/0f73248f/attachment.html
From anushbadii at gmail.com Mon Jun 19 17:52:45 2006
From: anushbadii at gmail.com (anush badii)
Date: Mon, 19 Jun 2006 08:52:45 -0700
Subject: [Tutor] local day names in ascii
In-Reply-To: <60fae7c30606190638i27460a25qed35630a83617c67@mail.gmail.com>
References: <60fae7c30606190638i27460a25qed35630a83617c67@mail.gmail.com>
Message-ID:
Why don't you use the extended ASCII characters where Swedish characters are
included.
On 6/19/06, frank h. wrote:
>
> Hello List,
> i am trying to convert local Swedish daynames to ASCII
>
> "M?ndag" should become "Mandag"
> "L?rdag" should become "Lordag"
> "S?ndag" should become "Sondag"
>
> here is my session
>
> import locale
> locale.setlocale(locale.LC_ALL, 'sv_Se')
> datetime.date(2006, 06, 19).strftime("%A")
> 'M\xc3\xa5ndag'
> datetime.date(2006, 06,
> 19).strftime("%A").decode('utf8').encode('ascii','ignore')
> 'Mndag'
>
> Somehow, the Swedish character "?" gets dropped in the conversion to
> ascii.
> how can I accomplish the conversion '?' --> 'a' etc.? should I use a
> dictionary?
> thanks for any insight
>
> -frank
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060619/de4149a2/attachment.htm
From mhansen at cso.atmel.com Mon Jun 19 18:34:30 2006
From: mhansen at cso.atmel.com (Mike Hansen)
Date: Mon, 19 Jun 2006 10:34:30 -0600
Subject: [Tutor] projects for beginners
In-Reply-To: <20060619143911.50179.qmail@web60818.mail.yahoo.com>
Message-ID: <005801c693be$3d2fcd10$28645f0a@mikehansen>
_____
From: tutor-bounces at python.org [mailto:tutor-bounces at python.org] On Behalf
Of josip
Sent: Monday, June 19, 2006 8:39 AM
To: tutor at python.org
Subject: [Tutor] projects for beginners
Hi!
I have read learning python and mede some smaller examples.
Now I want to make smoe project, I'm thinking about text editor.
Can someone give me pointers like (where and how to start, etc.)?
Or maybe another project suitable for beginners.
http://pyfaq.infogami.com/tutor-im-learning-python-what-should-i-program
Has a couple of ideas for projects.
Mike