Re: Old newbie needs help.

2014-12-23 Thread Ian Kelly
On Sat, Dec 20, 2014 at 9:34 AM, John Culleton j...@wexfordpress.com
wrote:

 This week I wrote my first Python program, a script callable from
Scribus, a DTP program. It ran! Now I want to spread my wings a little. How
do I call a C language executable subprogram from Python and pass
information back and forth?

When you say subprogram, do you mean that you want to start and
communicate with a whole new process, or do you merely want to invoke some
dynamically loaded entry point within the same process? For the former, use
the subprocess module. For the latter, use the ctypes module (or consider
using Cython instead of pure Python if Scribus will support it).
-- 
https://mail.python.org/mailman/listinfo/python-list


Old newbie needs help.

2014-12-20 Thread John Culleton
This week I wrote my first Python program, a script callable from Scribus, a 
DTP program. It ran! Now I want to spread my wings a little. How do I call a C 
language executable subprogram from Python and pass information back and forth? 

I am of the old school, meaning that object oriented programming is only 
slightly 
less obscure to me than Sanscrit or Navaho. So be gentle.

Python 2.7.5 on Slackware 14.1


John Culleton.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Old newbie needs help.

2014-12-20 Thread Larry Martell
On Sat, Dec 20, 2014 at 11:34 AM, John Culleton j...@wexfordpress.com wrote:
 This week I wrote my first Python program, a script callable from Scribus, a 
 DTP program. It ran! Now I want to spread my wings a little. How do I call a 
 C language executable subprogram from Python and pass information back and 
 forth?

 I am of the old school, meaning that object oriented programming is only 
 slightly
 less obscure to me than Sanscrit or Navaho. So be gentle.

 Python 2.7.5 on Slackware 14.1

Look at the subprocess module:

https://docs.python.org/2/library/subprocess.html
-- 
https://mail.python.org/mailman/listinfo/python-list


newbie needs help with cookielib

2011-05-04 Thread Sells, Fred
I'm using Python 2.4 and 2.7 for different apps.  I'm happy with a
solution for either one.

I've got to talk to a url that uses a session cookie.  I only need to
set this when I'm developing/debugging so I don't need a robust
production solution and I'm somewhat confused by the docs on cookielib.
I can use urllib2 without cookielib just fine, but need the cookie to
add some security.

I'm normally using Firefox 4.0 to login to the server and get the
cookie.  After that I need some way to set the same cookie in my python
script.  I can do this by editing my code, since I only need it while
defeloping from my test W7 box.


I was hoping to find something like

...set_cookie('mycookiename', 'myvalue', 'mydomain.org')

I've googled this most of the morning and found everything but what I
need, or I just don't understand the basic concept.  Any pointers would
be greatly appreciated.  One of my false starts looks like this. But I
get a 

...
  File C:\alltools\python26\lib\urllib2.py, line 518, in
http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 500: Access Deinied

def test1():
cj = cookielib.MozillaCookieJar()
cj.load('C:/Users/myname/Desktop/cookies.txt')
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
r = opener.open(http://daffyduck.mydomain.org/wsgi/myapp.wsgi;)   
print r.read() 
return

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


Re: Newbie needs help

2009-07-08 Thread Aahz
In article mailman.2781.1246979580.8015.python-l...@python.org,
Pablo Torres N. tn.pa...@gmail.com wrote:

Give this one a try too: http://www.mikeash.com/getting_answers.html
It doesn't talk down to you...as much :P

Nice!  I'll try remembering that one.
-- 
Aahz (a...@pythoncraft.com)   * http://www.pythoncraft.com/

as long as we like the same operating system, things are cool. --piranha
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie needs help

2009-07-07 Thread Simon Forman
On Mon, Jul 6, 2009 at 7:00 PM, nacim_br...@agilent.com wrote:
 Dear Python gurus,

 If I'd like to set dielectric constant for the certain material, is it 
 possible to do such in Python environment? If yes, how to do or what syntax 
 can be used?

 Also, I'd like to get a simulation result, like voltage, is it possible to 
 get this value in Python environment?

 Please let me know,
 nacim


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


The answers to your first and third questions are, yes and yes. :]
 (Generally speaking if something can be done by a computer it can be
done with python.)

As for your second question check out the magnitude package:

http://pypi.python.org/pypi/magnitude/   and
http://juanreyero.com/magnitude/

(That second link also has links to three other packages that deal
with units of measurement.)

Ii has units for the SI measurements, including volts and coulombs, so
you should be able to accomplish your goals with it.

The tricky thing is, as far as I can tell from the wikipedia entry
(http://en.wikipedia.org/wiki/Relative_static_permittivity),
dielectric constant seems to be a dimensionless number, i.e. C/C...
 I could be totally daft though.

HTH,
~Simon
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Newbie needs help

2009-07-07 Thread nacim_bravo
Hello Gurus,

Thank you for trying to help to my initial and not well written questions.  I 
will compile more detailed information and ask again.  Btw, I am giving a 
glimpse to: How To Ask Questions The Smart Way.

nacim


-Original Message-
From: Simon Forman [mailto:sajmik...@gmail.com] 
Sent: Tuesday, July 07, 2009 7:19 AM
To: BRAVO,NACIM (A-Sonoma,ex1)
Cc: python-list@python.org
Subject: Re: Newbie needs help

On Mon, Jul 6, 2009 at 7:00 PM, nacim_br...@agilent.com wrote:
 Dear Python gurus,

 If I'd like to set dielectric constant for the certain material, is it 
 possible to do such in Python environment? If yes, how to do or what syntax 
 can be used?

 Also, I'd like to get a simulation result, like voltage, is it possible to 
 get this value in Python environment?

 Please let me know,
 nacim


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


The answers to your first and third questions are, yes and yes. :]
 (Generally speaking if something can be done by a computer it can be
done with python.)

As for your second question check out the magnitude package:

http://pypi.python.org/pypi/magnitude/   and
http://juanreyero.com/magnitude/

(That second link also has links to three other packages that deal
with units of measurement.)

Ii has units for the SI measurements, including volts and coulombs, so
you should be able to accomplish your goals with it.

The tricky thing is, as far as I can tell from the wikipedia entry
(http://en.wikipedia.org/wiki/Relative_static_permittivity),
dielectric constant seems to be a dimensionless number, i.e. C/C...
 I could be totally daft though.

HTH,
~Simon


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


Re: Newbie needs help

2009-07-07 Thread Pablo Torres N.
On Tue, Jul 7, 2009 at 10:02, nacim_br...@agilent.com wrote:
 Hello Gurus,

 Thank you for trying to help to my initial and not well written questions.  I 
 will compile more detailed information and ask again.  Btw, I am giving a 
 glimpse to: How To Ask Questions The Smart Way.

 nacim

Give this one a try too: http://www.mikeash.com/getting_answers.html
It doesn't talk down to you...as much :P


-- 
Pablo Torres N.
-- 
http://mail.python.org/mailman/listinfo/python-list


Newbie needs help

2009-07-06 Thread nacim_bravo
Dear Python gurus,

If I'd like to set dielectric constant for the certain material, is it possible 
to do such in Python environment? If yes, how to do or what syntax can be used?

Also, I'd like to get a simulation result, like voltage, is it possible to get 
this value in Python environment? 

Please let me know, 
nacim


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


Re: Newbie needs help

2009-07-06 Thread Rhodri James

On Tue, 07 Jul 2009 00:00:39 +0100, nacim_br...@agilent.com wrote:


Dear Python gurus,

If I'd like to set dielectric constant for the certain material, is it  
possible to do such in Python environment? If yes, how to do or what  
syntax can be used?


Also, I'd like to get a simulation result, like voltage, is it possible  
to get this value in Python environment?


Quite possibly, however you're going to have to give us a *lot* more
information before the answers you get will be worth anything at all.
How is the certain material represented?  What simulator are you
using?  Which Python environment?  Which Python version for that matter?

We may appear to be mind-readers, but we usually need a bit more
than this to work on.

--
Rhodri James *-* Wildebeest Herder to the Masses
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie needs help

2009-07-06 Thread Steven D'Aprano
On Mon, 06 Jul 2009 17:00:39 -0600, nacim_bravo wrote:

 Dear Python gurus,
 
 If I'd like to set dielectric constant for the certain material, is it
 possible to do such in Python environment? If yes, how to do or what
 syntax can be used?

certain_material.dielectric_constant = 1.234


 Also, I'd like to get a simulation result, like voltage, is it possible
 to get this value in Python environment?

Yes.



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


Re: Newbie needs help

2009-07-06 Thread Gary Herron

nacim_br...@agilent.com wrote:

Dear Python gurus,

If I'd like to set dielectric constant for the certain material, is it possible 
to do such in Python environment? If yes, how to do or what syntax can be used?

Also, I'd like to get a simulation result, like voltage, is it possible to get this value in Python environment? 

Please let me know, 
nacim
  

This would be a good place for you to start:
 http://www.catb.org/~esr/faqs/smart-questions.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie needs help

2008-08-27 Thread Marco Bizzarri
On Tue, Aug 26, 2008 at 8:33 PM, frankrentef [EMAIL PROTECTED] wrote:


 Would the second file need something akin to...

 loginout.admin (ie,url,adminlogin)

Yes. Since you're importing the whole module.



-- 
Marco Bizzarri
http://iliveinpisa.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie needs help

2008-08-27 Thread frankrentef
Help, I'm missing / still not grasping something

My loginout file contains the following...

from cPAMIE import PAMIE

#Imports - used to setup / control finding files
import time
import os
import sys

url = 'http://test2/'


adminlogin = 'Gorillia'
adminpassword = 'Gorillia1$'


#Admin Login Def Function

def adminlogin(ie,url):
ie.navigate (url + 'isweb/admin/default.aspx')
time.sleep(2)
ie.textBoxSet ('AdminLogin1:txtUsername','adminlogin')
time.sleep(2)
ie.textBoxSet ('AdminLogin1:inputPassword','adminpassword')
time.sleep(2)
ie.buttonClick ('AdminLogin1:btnLogin')
time.sleep(2)


My main Python file contains...

from cPAMIE import PAMIE

import time
import os
import sys
import loginout
from log import log

ie=PAMIE()
ie=Visible =1
t=time

ie=PAMIE ()

#++
+

adminlogin (ie, url, adminlogin)
if ie.findText ('Site Status: Active'):
log ('PASSED -- ADMIN Module - ADMIN Login  Admin Tab Navigation
Successful')
else:
log ('WARNING -- ADMIN Module Login  Admin Tab Navigation
FAILED')
time.sleep(2)


All that happens is an I.E. session comes up with the url
about:blank in the address.

What am I doing incorrectly.


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


Newbie needs help

2008-08-26 Thread frankrentef
Greetings all,

I'm wanting to maintain what values in one file and call them in
another.  The purpose being to keep a single location where url's,
login's and passwords can be maintained, then called as needed from
another file.

In file #1 I have...

import time
import os
import sys

url = 'http://zoo/'

adminlogin = 'Zebra'
adminpassword = 'Zebra12$'


-

In file #2 I have the following...

from cPAMIE import PAMIE

#Imports - used to setup / control finding files
import time
import os
import sys
import loginout#name of the file retaining all url/login info
from log import log

#Create New Pamie Object
ie=PAMIE()
ie=Visible =1
t=time

adminlogin (ie,url)
if ie.findText ('Site Status: Active'):
log ('PASSED -- ADMIN Module - ADMIN Login  Admin Tab Navigation
Successful')
else:
log ('WARNING -- ADMIN Module Login  Admin Tab Navigation
FAILED')
time.sleep(2)



What am I doing incorrectly to not have file two log in when
executed.  All files are in the same directory.   Keep it simple...
I'm new at this.

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


Re: Newbie needs help

2008-08-26 Thread Eric Wertman
Is the loginout file named loginout.py ?  It needs to be for the
import to work.  If the import works, you have to refer to those
variables within the right namespace,  ie :   loginout.url,
loginout.adminlogin,  etc.



On Tue, Aug 26, 2008 at 12:46 PM, frankrentef [EMAIL PROTECTED] wrote:
 Greetings all,

 I'm wanting to maintain what values in one file and call them in
 another.  The purpose being to keep a single location where url's,
 login's and passwords can be maintained, then called as needed from
 another file.

 In file #1 I have...

 import time
 import os
 import sys

 url = 'http://zoo/'

 adminlogin = 'Zebra'
 adminpassword = 'Zebra12$'


 -

 In file #2 I have the following...

 from cPAMIE import PAMIE

 #Imports - used to setup / control finding files
 import time
 import os
 import sys
 import loginout#name of the file retaining all url/login info
 from log import log

 #Create New Pamie Object
 ie=PAMIE()
 ie=Visible =1
 t=time

 adminlogin (ie,url)
 if ie.findText ('Site Status: Active'):
log ('PASSED -- ADMIN Module - ADMIN Login  Admin Tab Navigation
 Successful')
 else:
log ('WARNING -- ADMIN Module Login  Admin Tab Navigation
 FAILED')
 time.sleep(2)



 What am I doing incorrectly to not have file two log in when
 executed.  All files are in the same directory.   Keep it simple...
 I'm new at this.

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

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


Re: Newbie needs help

2008-08-26 Thread frankrentef
On Aug 26, 11:46 am, frankrentef [EMAIL PROTECTED] wrote:
 Greetings all,

 I'm wanting to maintain what values in one file and call them in
 another.  The purpose being to keep a single location where url's,
 login's and passwords can be maintained, then called as needed from
 another file.

 In file #1 I have...

 import time
 import os
 import sys

 url = 'http://zoo/'

 adminlogin = 'Zebra'
 adminpassword = 'Zebra12$'

 -

 In file #2 I have the following...

 from cPAMIE import PAMIE

 #Imports - used to setup / control finding files
 import time
 import os
 import sys
 import loginout    #name of the file retaining all url/login info
 from log import log

 #Create New Pamie Object
 ie=PAMIE()
 ie=Visible =1
 t=time

 adminlogin (ie,url)
 if ie.findText ('Site Status: Active'):
     log ('PASSED -- ADMIN Module - ADMIN Login  Admin Tab Navigation
 Successful')
 else:
     log ('WARNING -- ADMIN Module Login  Admin Tab Navigation
 FAILED')
 time.sleep(2)

 What am I doing incorrectly to not have file two log in when
 executed.  All files are in the same directory.   Keep it simple...
 I'm new at this.

 THNX

Yes, the first file is named loginout.py

Would the second file need something akin to...

loginout.admin (ie,url,adminlogin)

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


Newbie needs help with his blood pressure...

2008-08-21 Thread Luis Speciale

Hi u all :

I'm trying to build mod_python in Leopard 10.5.4 with a cvs version from

http://svn.apache.org/repos/asf/quetzalcoatl/mod_python/trunk

I have

$ python
Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53)
[GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin

Then when I try

./configure --with-apxs=/usr/sbin/apxs 
--with-python=/usr/local/bin/python ARCHFLAGS='-arch ppc'


I get this

checking for gcc... gcc
checking for C compiler default output file name... a.out
checking whether the C compiler works... yes
checking whether we are cross compiling... no
checking for suffix of executables...
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether gcc accepts -g... yes
checking for gcc option to accept ANSI C... none needed
checking for ar... ar
checking for a BSD-compatible install... /usr/bin/install -c
checking whether make sets $(MAKE)... yes
checking for main in -lm... yes
checking for an ANSI C-conforming const... yes
checking your blood pressure... a bit high, but we can proceed
configure: checking whether apxs is available...
checking Apache version... 2.2.8
checking for Apache libexec directory... /usr/libexec/apache2
checking for Apache include directory... -I/usr/include/apache2
checking for --with-python... /usr/local/bin/python
checking Python version... 2.5
checking for --with-python-src... no
checking for --with-mutex-dir... no
Using MUTEX_DIR /tmp
checking for --with-max-locks... no
Using 8 MAX_LOCKS.
checking for --with-flex... no
checking for flex... /usr/bin/flex
found /usr/bin/flex, we'll use this. Use --with-flex to specify another.
checking flex version... 2.5.33. Good
configure: creating ./config.status
config.status: creating Makefile
config.status: creating src/Makefile
config.status: creating Doc/Makefile
config.status: creating src/include/mod_python.h
config.status: creating test/Makefile
config.status: creating test/testconf.py
config.status: creating dist/setup.py
config.status: creating dist/Makefile

Seems to be OK for my blood pressure, but

make

brings this

/usr/sbin/apxs -I/Users/speciale/Desktop/dossier sans titre 
3/src/include 
-I/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5 
-DNDEBUG -Wc,'-arch ppc7400' -Wc,'-arch ppc64' -Wc,'-arch i386' 
-Wc,'-arch x86_64' -c mod_python.c _apachemodule.c requestobject.c 
tableobject.c util.c serverobject.c connobject.c filterobject.c hlist.c 
hlistobject.c finfoobject.c -arch ppc7400 -arch ppc64 -arch i386 -arch 
x86_64 -Wl,-F/Library/Frameworks -framework Python -u _PyMac_Error  -ldl

Usage: apxs -g [-S var=val] -n modname
   apxs -q [-S var=val] query ...
   apxs -c [-S var=val] [-o dsofile] [-D name[=value]]
   [-I incdir] [-L libdir] [-l libname] [-Wc,flags]
   [-Wl,flags] [-p] files ...
   apxs -i [-S var=val] [-a] [-A] [-n modname] dsofile ...
   apxs -e [-S var=val] [-a] [-A] [-n modname] dsofile ...
make[1]: *** [mod_python.so] Error 1
make: *** [do_dso] Error 2

I'm dead ?

Thanks Doctors !-)

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


Newbie needs help with... his blood pressure ;-)

2008-08-21 Thread Luis Speciale

Hi

I'm trying to build mod_pyton on Leopard 10.5.4 on a Mac G5 with this 
cvs version

http://svn.apache.org/repos/asf/quetzalcoatl/mod_python/trunk

with this Python

python
Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53)
[GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin

So i did
./configure --with-apxs=/usr/sbin/apxs 
--with-python=/usr/local/bin/python ARCHFLAGS='-arch ppc'


and I get

checking for gcc... gcc
checking for C compiler default output file name... a.out
checking whether the C compiler works... yes
checking whether we are cross compiling... no
checking for suffix of executables...
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether gcc accepts -g... yes
checking for gcc option to accept ANSI C... none needed
checking for ar... ar
checking for a BSD-compatible install... /usr/bin/install -c
checking whether make sets $(MAKE)... yes
checking for main in -lm... yes
checking for an ANSI C-conforming const... yes
checking your blood pressure... a bit high, but we can proceed
configure: checking whether apxs is available...
checking Apache version... 2.2.8
checking for Apache libexec directory... /usr/libexec/apache2
checking for Apache include directory... -I/usr/include/apache2
checking for --with-python... /usr/local/bin/python
checking Python version... 2.5
checking for --with-python-src... no
checking for --with-mutex-dir... no
Using MUTEX_DIR /tmp
checking for --with-max-locks... no
Using 8 MAX_LOCKS.
checking for --with-flex... no
checking for flex... /usr/bin/flex
found /usr/bin/flex, we'll use this. Use --with-flex to specify another.
checking flex version... 2.5.33. Good
configure: creating ./config.status
config.status: creating Makefile
config.status: creating src/Makefile
config.status: creating Doc/Makefile
config.status: creating src/include/mod_python.h
config.status: creating test/Makefile
config.status: creating test/testconf.py
config.status: creating dist/setup.py
config.status: creating dist/Makefile

Seems good for my blood, but

make

gives this

Compiling for DSO.

/usr/sbin/apxs -I/Users/speciale/Desktop/dossier sans titre 
3/src/include 
-I/Library/Frameworks/Python.framework/Versions/2.5/include/python2.5 
-DNDEBUG -Wc,'-arch ppc7400' -Wc,'-arch ppc64' -Wc,'-arch i386' 
-Wc,'-arch x86_64' -c mod_python.c _apachemodule.c requestobject.c 
tableobject.c util.c serverobject.c connobject.c filterobject.c hlist.c 
hlistobject.c finfoobject.c -arch ppc7400 -arch ppc64 -arch i386 -arch 
x86_64 -Wl,-F/Library/Frameworks -framework Python -u _PyMac_Error  -ldl

Usage: apxs -g [-S var=val] -n modname
   apxs -q [-S var=val] query ...
   apxs -c [-S var=val] [-o dsofile] [-D name[=value]]
   [-I incdir] [-L libdir] [-l libname] [-Wc,flags]
   [-Wl,flags] [-p] files ...
   apxs -i [-S var=val] [-a] [-A] [-n modname] dsofile ...
   apxs -e [-S var=val] [-a] [-A] [-n modname] dsofile ...
make[1]: *** [mod_python.so] Error 1
make: *** [do_dso] Error 2

Am I already dead ?

Thanks Doctors ;-)

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


Re: Newbie needs help with... his blood pressure ;-)

2008-08-21 Thread Luis Speciale
Oups. Bad beginning. Sorry for the double post. Thunderbird has mental 
problems


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


Re: Newbie needs help with... his blood pressure ;-)

2008-08-21 Thread Paul Boddie
On 21 Aug, 14:57, Luis Speciale [EMAIL PROTECTED] wrote:

 /usr/sbin/apxs -I/Users/speciale/Desktop/dossier sans titre 3/src/include

[...]

I imagine that if this is really the command run by the Makefile, apxs
might get upset by the unquoted path which contains spaces. Either the
Makefile needs editing to quote the directory or you might want to
rename dossier sans titre 3 to something without spaces... and
perhaps with a more informative name, too. ;-)

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


Re: Newbie - needs help

2007-04-04 Thread Goldfish
Nothing beats http://diveintopython.org/toc/index.html for getting
into the basics of Python. This guy's writing is great!

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


Re: Newbie - needs help

2007-04-04 Thread brzrkr0
On Apr 3, 4:28 pm, 7stud [EMAIL PROTECTED] wrote:
 Learning Python can be purchased at amazon.com.  Or, not as good:
 Beginning Python: From Novice to Professional.  If you get the
 second one, you'll need Python in a Nutshell: A Desktop Quick
 Reference to fill in all the gaps.

If you already have experience with other programming languages, I
think you might find that Learning Python is a bit too beginner-
oriented.  Dive into Python is probably a better choice for a first
reading, IMO.

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


Re: Newbie - needs help

2007-04-04 Thread Larry Bates
Anbeyon wrote:
 Hi
 
 I have not yet programmed in Python but am experienced in a number o
 other languages.
 
 I'd like to start to use Python to develop cross platform applications
 but havin kust started to investigate tols, libraries etc  I feel a
 little overwhelmed.
 
 I'm hoping someone might be able to point me in the right direction.
 
 What I'd like to achieve is the abilty to develop applications for
 both Windows and Linux (Desktop and embedded).  I'd also like to be
 able to develop applications that make use of TCP/IP and things like
 'Widget' libraries.
 
 In an ideal would like to be able to pull together Python apps with
 GUI front ends  in a nice IDE with a debugger.
 
 Does such a toolset exisit ?
 
 Perhaps some people can sully me some links ?
 
 Thanks in advance.
 
 Anbeyon
 
If you are on Windows take a look at PyScripter:

http://mmm-experts.com/Products.aspx?ProductId=4

I would also recommend a copy of Python Cookbook
which has LOTS of example code you can look at and
use.

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


Newbie - needs help

2007-04-03 Thread Anbeyon
Hi

I have not yet programmed in Python but am experienced in a number o
other languages.

I'd like to start to use Python to develop cross platform applications
but havin kust started to investigate tols, libraries etc  I feel a
little overwhelmed.

I'm hoping someone might be able to point me in the right direction.

What I'd like to achieve is the abilty to develop applications for
both Windows and Linux (Desktop and embedded).  I'd also like to be
able to develop applications that make use of TCP/IP and things like
'Widget' libraries.

In an ideal would like to be able to pull together Python apps with
GUI front ends  in a nice IDE with a debugger.

Does such a toolset exisit ?

Perhaps some people can sully me some links ?

Thanks in advance.

Anbeyon

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


Re: Newbie - needs help

2007-04-03 Thread kyosohma
On Apr 3, 3:42 pm, Anbeyon [EMAIL PROTECTED] wrote:
 Hi

 I have not yet programmed in Python but am experienced in a number o
 other languages.

 I'd like to start to use Python to develop cross platform applications
 but havin kust started to investigate tols, libraries etc  I feel a
 little overwhelmed.

 I'm hoping someone might be able to point me in the right direction.

 What I'd like to achieve is the abilty to develop applications for
 both Windows and Linux (Desktop and embedded).  I'd also like to be
 able to develop applications that make use of TCP/IP and things like
 'Widget' libraries.

 In an ideal would like to be able to pull together Python apps with
 GUI front ends  in a nice IDE with a debugger.

 Does such a toolset exisit ?

 Perhaps some people can sully me some links ?

 Thanks in advance.

 Anbeyon

There's lot of Python tools available for you.

ActiveState has ActivePython (free) - 
http://www.activestate.com/products/activepython/
Eclipse has a plugin to use for Python - http://www.easyeclipse.org/site/home/

If you use wxPython you can use:
Boa Constructor - http://boa-constructor.sourceforge.net/
Stani's Python Editor - http://pythonide.blogspot.com/
Dabo - http://dabodev.com/

For others, check this:
http://wiki.python.org/moin/IntegratedDevelopmentEnvironments

Most are free, but some have different licenses. Read up on them.

I still use IDLE for most of my work. Currently I am playing with
XRCed. I did find PythonWin, ActiveState's and Eclipse's to be handy
too though.

Mike

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


Re: Newbie - needs help

2007-04-03 Thread 7stud
On Apr 3, 2:42 pm, Anbeyon [EMAIL PROTECTED] wrote:
 Hi

 I have not yet programmed in Python but am experienced in a number o
 other languages.

 I'd like to start to use Python to develop cross platform applications
 but havin kust started to investigate tols, libraries etc  I feel a
 little overwhelmed.

 I'm hoping someone might be able to point me in the right direction.


Learning Python can be purchased at amazon.com.  Or, not as good:
Beginning Python: From Novice to Professional.  If you get the
second one, you'll need Python in a Nutshell: A Desktop Quick
Reference to fill in all the gaps.

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


newbie needs help building Python 2.5 for Fedora Core 6

2007-02-24 Thread bobmon
Hello, and please be gentle...

I'm trying to build Python 2.5 on my Fedora Core 6 installation.  I
think I've resolved most of my problems, but make test reports an
error for test_socket.py, shown below.

I suppose my FC6 installation is missing something, but I have no idea
what.  Any ideas, directions, pointers would be most appreciated.



==
 ERROR: testSockName (__main__.GeneralModuleTests)
 
--
 Traceback (most recent call last):
   File ./Lib/test/test_socket.py, line 456, in testSockName
 my_ip_addr = socket.gethostbyname(socket.gethostname())
 gaierror: (-2, 'Name or service not known')

 
--
 Ran 66 tests in 35.478s

 FAILED (errors=1)
 Traceback (most recent call last):
   File ./Lib/test/test_socket.py, line 962, in module
 test_main()
   File ./Lib/test/test_socket.py, line 958, in test_main
 test_support.run_unittest(*tests)
   File /home/Installer/Python/Python-2.5/Lib/test/test_support.py,
line 441, in run_uni
 ttest
 run_suite(suite, testclass)
   File /home/Installer/Python/Python-2.5/Lib/test/test_support.py,
line 426, in run_sui
 te
 raise TestFailed(err)
 test.test_support.TestFailed: Traceback (most recent call last):
   File ./Lib/test/test_socket.py, line 456, in testSockName
 my_ip_addr = socket.gethostbyname(socket.gethostname())
 gaierror: (-2, 'Name or service not known')

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


Re: newbie needs help building Python 2.5 for Fedora Core 6

2007-02-24 Thread Tony Nelson
In article [EMAIL PROTECTED],
 bobmon [EMAIL PROTECTED] wrote:

 Hello, and please be gentle...
 
 I'm trying to build Python 2.5 on my Fedora Core 6 installation.  I
 think I've resolved most of my problems, but make test reports an
 error for test_socket.py, shown below.
 
 I suppose my FC6 installation is missing something, but I have no idea
 what.  Any ideas, directions, pointers would be most appreciated.
 
 
 
 ==
  ERROR: testSockName (__main__.GeneralModuleTests)
  
 --
  Traceback (most recent call last):
File ./Lib/test/test_socket.py, line 456, in testSockName
  my_ip_addr = socket.gethostbyname(socket.gethostname())
  gaierror: (-2, 'Name or service not known')
 
  
 --
  Ran 66 tests in 35.478s
 
  FAILED (errors=1)
  Traceback (most recent call last):
File ./Lib/test/test_socket.py, line 962, in module
  test_main()
File ./Lib/test/test_socket.py, line 958, in test_main
  test_support.run_unittest(*tests)
File /home/Installer/Python/Python-2.5/Lib/test/test_support.py,
 line 441, in run_uni
  ttest
  run_suite(suite, testclass)
File /home/Installer/Python/Python-2.5/Lib/test/test_support.py,
 line 426, in run_sui
  te
  raise TestFailed(err)
  test.test_support.TestFailed: Traceback (most recent call last):
File ./Lib/test/test_socket.py, line 456, in testSockName
  my_ip_addr = socket.gethostbyname(socket.gethostname())
  gaierror: (-2, 'Name or service not known')

OK, so this fails:

my_ip_addr = socket.gethostbyname(socket.gethostname())

Try it from the python command line.  This is what happens when I try it 
on FC6 w/ Python 2.5 (retyped, tho):

 import socket
 socket.gethostname()
'localhost.localdomain'
 socket.gethostbyname(_)
'127.0.0.1'


TonyN.:'[EMAIL PROTECTED]
  '  http://www.georgeanelson.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie needs help building Python 2.5 for Fedora Core 6

2007-02-24 Thread bobmon
WOW.  I'm gobsmacked...

On Feb 24, 6:13 pm, Tony Nelson
[EMAIL PROTECTED] wrote:

 Try it from the python command line.  This is what happens when I try it


Okay, that was interesting...

Apparently there's a subtlety of /etc/hosts that affects this!
Originally it had this line:
127.0.0.1localhostlocalhost.localdomainfoobar
and I get this result for my machine (foobar.foodomain.com):

 import socket
 socket.gethostname()
'foobar.foodomain.com'
 socket.gethostbyname(_)
Traceback (most recent call last):
  File stdin, line 1, in module
socket.gaierror: (-2, 'Name or service not known')


 socket.gethostbyname('localhost')
'127.0.0.1'
 socket.gethostbyname('localhost.localdomain')
'127.0.0.1'


Whe I change /etc/hosts to this:
127.0.0.1foobarfoobar.foodomain.net
localhost.localdomain   localhost
Python is happy and I get;

 import socket
 socket.gethostname()
'foobar.foodomain.net'
 socket.gethostbyname(_)
'127.0.0.1'



So, problem fixed although I have no real understanding of what was
wrong or what's right now.
Only that gethostbyname() seems to be really sensitive to the format
of the /etc/hosts file.

Thank you, Tony Nelson.
-Bob Montante, -bob,mon.

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


Newbie needs Help

2006-08-16 Thread len
Hi all

I am writing a python program that inserts records into a database on
XP using mxODBC.

I need to write a section of code which will create the following SQL
command as an example;

INSERT INTO statecode (state, name) VALUES ('IL', 'Illinois')

This statement will be built up using the following code;

import mx.ODBC
import mx.ODBC.Windows
def insertFromDict(table, dict):
Take dictionary object dict and produce sql for
inserting it into the named table
sql = 'INSERT INTO ' + table
sql += ' ('
sql += ', '.join(dict)
sql += ') VALUES ('
sql += ', '.join(map(dictValuePad, dict)) # ??? this code does
NOT format correctly
sql += ')'
return sql

def dictValuePad(key):# ??? this code
does Not format correctly
return ' + str(key) + '

db = mx.ODBC.Windows.DriverConnect('dsn=UICPS Test')
c = db.cursor()
insert_dict = {'state':'IL', 'name':'Illinois'}
sql = insertFromDict(statecode, insert_dict)
print sql
c.execute(sql)

I copied this code off of ASP and I sure it worked for his particular
circumstance but I need to format up the VALUE clause just a bit
different.

I will be working from a dictionary which will be continualy update in
another part of the program and this code is working.

Len Sumnler

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


Re: Newbie needs Help

2006-08-16 Thread John Machin
len wrote:
 Hi all

 I am writing a python program that inserts records into a database on
 XP using mxODBC.

 I need to write a section of code which will create the following SQL
 command as an example;

 INSERT INTO statecode (state, name) VALUES ('IL', 'Illinois')

 This statement will be built up using the following code;

 import mx.ODBC
 import mx.ODBC.Windows
 def insertFromDict(table, dict):
 Take dictionary object dict and produce sql for
 inserting it into the named table
 sql = 'INSERT INTO ' + table
 sql += ' ('
 sql += ', '.join(dict)
 sql += ') VALUES ('
 sql += ', '.join(map(dictValuePad, dict)) # ??? this code does
 NOT format correctly
 sql += ')'
 return sql

 def dictValuePad(key):# ??? this code
 does Not format correctly
 return ' + str(key) + '

 db = mx.ODBC.Windows.DriverConnect('dsn=UICPS Test')
 c = db.cursor()
 insert_dict = {'state':'IL', 'name':'Illinois'}
 sql = insertFromDict(statecode, insert_dict)
 print sql
 c.execute(sql)


The code below will do what you say that you want to do -- so long as
all your columns are strings (varchar or whatever in SQL terms).
Otherwise IMHO you would be much better off doing it this way:
sql = insert into policy (type, premium) values(?, ?)
data = ('building', 123.45)
cursor.execute(sql, data)
for two reasons:
(1) let the ODBC kit worry about formatting dates, strings with
embedded single quotes, etc
(2) it can be more efficient; the sql is constant and needs to be
parsed only once
(3) [bonus extra reason] the way you are doing it is vulnerable to
what's called an SQL injection attack; although you have no doubt
eyeballed all the data, doing it that way is a bad habit to get into.

You should be able to modify the supplied code very easily to produce
the sql variety with ? in it.

HTH,
John

C:\junktype sqlinsdict.py
def sqlquote(astring):
return ' + astring.replace(', '') + '

def insertFromDict(table, adict):
Take dictionary object dict and produce sql for
inserting it into the named table.
Sample input:
insert_dict = {'state':'IL', 'name':'Illinois'}
sql = insertFromDict(statecode, insert_dict)
Required output:
INSERT INTO statecode (state, name) VALUES ('IL', 'Illinois')


t = [
'INSERT INTO ',
table,
' (',
', '.join(adict.keys()),
') VALUES (',
', '.join(sqlquote(x) for x in adict.values()),
')',
]
return ''.join(t)

if __name__ == __main__:
tests = [
('IL', 'Illinois'),
('OH', O'Hara),
]
cols = ['state', 'name']
for test in tests:
the_dict = dict(zip(cols, test))
print the_dict
print insertFromDict('statecode', the_dict)

C:\junksqlinsdict.py
{'state': 'IL', 'name': 'Illinois'}
INSERT INTO statecode (state, name) VALUES ('IL', 'Illinois')
{'state': 'OH', 'name': O'Hara}
INSERT INTO statecode (state, name) VALUES ('OH', 'O''Hara')

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


Re: Newbie needs Help

2006-08-16 Thread johnzenger
Also, it may be easier to use string interpolation, as in:

return INSERT INTO statecode (state, name) VALUES ('%(state)s',
'%(name)s') % insert_dict

...after all necessary escaping, of course.

John Machin wrote:
 len wrote:
  Hi all
 
  I am writing a python program that inserts records into a database on
  XP using mxODBC.
 
  I need to write a section of code which will create the following SQL
  command as an example;
 
  INSERT INTO statecode (state, name) VALUES ('IL', 'Illinois')
 
  This statement will be built up using the following code;
 
  import mx.ODBC
  import mx.ODBC.Windows
  def insertFromDict(table, dict):
  Take dictionary object dict and produce sql for
  inserting it into the named table
  sql = 'INSERT INTO ' + table
  sql += ' ('
  sql += ', '.join(dict)
  sql += ') VALUES ('
  sql += ', '.join(map(dictValuePad, dict)) # ??? this code does
  NOT format correctly
  sql += ')'
  return sql
 
  def dictValuePad(key):# ??? this code
  does Not format correctly
  return ' + str(key) + '
 
  db = mx.ODBC.Windows.DriverConnect('dsn=UICPS Test')
  c = db.cursor()
  insert_dict = {'state':'IL', 'name':'Illinois'}
  sql = insertFromDict(statecode, insert_dict)
  print sql
  c.execute(sql)
 

 The code below will do what you say that you want to do -- so long as
 all your columns are strings (varchar or whatever in SQL terms).
 Otherwise IMHO you would be much better off doing it this way:
 sql = insert into policy (type, premium) values(?, ?)
 data = ('building', 123.45)
 cursor.execute(sql, data)
 for two reasons:
 (1) let the ODBC kit worry about formatting dates, strings with
 embedded single quotes, etc
 (2) it can be more efficient; the sql is constant and needs to be
 parsed only once
 (3) [bonus extra reason] the way you are doing it is vulnerable to
 what's called an SQL injection attack; although you have no doubt
 eyeballed all the data, doing it that way is a bad habit to get into.

 You should be able to modify the supplied code very easily to produce
 the sql variety with ? in it.

 HTH,
 John

 C:\junktype sqlinsdict.py
 def sqlquote(astring):
 return ' + astring.replace(', '') + '

 def insertFromDict(table, adict):
 Take dictionary object dict and produce sql for
 inserting it into the named table.
 Sample input:
 insert_dict = {'state':'IL', 'name':'Illinois'}
 sql = insertFromDict(statecode, insert_dict)
 Required output:
 INSERT INTO statecode (state, name) VALUES ('IL', 'Illinois')
 

 t = [
 'INSERT INTO ',
 table,
 ' (',
 ', '.join(adict.keys()),
 ') VALUES (',
 ', '.join(sqlquote(x) for x in adict.values()),
 ')',
 ]
 return ''.join(t)

 if __name__ == __main__:
 tests = [
 ('IL', 'Illinois'),
 ('OH', O'Hara),
 ]
 cols = ['state', 'name']
 for test in tests:
 the_dict = dict(zip(cols, test))
 print the_dict
 print insertFromDict('statecode', the_dict)

 C:\junksqlinsdict.py
 {'state': 'IL', 'name': 'Illinois'}
 INSERT INTO statecode (state, name) VALUES ('IL', 'Illinois')
 {'state': 'OH', 'name': O'Hara}
 INSERT INTO statecode (state, name) VALUES ('OH', 'O''Hara')

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


Re: Newbie needs Help

2006-08-16 Thread John Machin

[EMAIL PROTECTED] wrote:
 Also, it may be easier to use string interpolation, as in:

 return INSERT INTO statecode (state, name) VALUES ('%(state)s',
 '%(name)s') % insert_dict

 ...after all necessary escaping, of course.


Excuse me!? statecode needs to come from the first argument. Likewise
the words state and name are *variables*. The OP has a gazillion
other tables to process -- are you suggesting he should type in a
gazillion different hard-coded return statements when he's already on
the right track and just needs a bit of help with dict.keys() and
dict.values()?

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


Re: Newbie needs Help

2006-08-16 Thread Steve Holden
len wrote:
 Hi all
 
 I am writing a python program that inserts records into a database on
 XP using mxODBC.
 
 I need to write a section of code which will create the following SQL
 command as an example;
 
 INSERT INTO statecode (state, name) VALUES ('IL', 'Illinois')
 
 This statement will be built up using the following code;
 
 import mx.ODBC
 import mx.ODBC.Windows
 def insertFromDict(table, dict):
 Take dictionary object dict and produce sql for
 inserting it into the named table
 sql = 'INSERT INTO ' + table
 sql += ' ('
 sql += ', '.join(dict)
 sql += ') VALUES ('
 sql += ', '.join(map(dictValuePad, dict)) # ??? this code does
 NOT format correctly
 sql += ')'
 return sql
 
 def dictValuePad(key):# ??? this code
 does Not format correctly
 return ' + str(key) + '
 
 db = mx.ODBC.Windows.DriverConnect('dsn=UICPS Test')
 c = db.cursor()
 insert_dict = {'state':'IL', 'name':'Illinois'}
 sql = insertFromDict(statecode, insert_dict)
 print sql
 c.execute(sql)
 
 I copied this code off of ASP and I sure it worked for his particular
 circumstance but I need to format up the VALUE clause just a bit
 different.
 
ASP code frequently makes the mistake of bulding SQL statements that 
way. I suspect this is because the ASP ADO model makes it difficult to 
produce paramtereized queries. In Python, however, the position is very 
different, and you should always try to separate the data from the 
fieldnames.

 I will be working from a dictionary which will be continualy update in
 another part of the program and this code is working.
 
Well, assuming you would rather be free of SQL inhection errors you 
would be much better advised to do something like this:

   def insertFromDict(table, d):  vector
  ...   Return SQL statement and data vector for insertion into table.
  ...   fields = d.keys()
  ...   sql = 'INSERT INTO %s (%s) VALUES(%s)' % (
  ... table, ,
  ... .join(fields),
  ... , .join(? for f in fields))
  ...   return sql, d.values()
  ...
   sql, data = insertFromDict(statecode,
  ... {state: IL, name: Illinois})
   sql
'INSERT INTO statecode (state, name) VALUES(?, ?)'
   data
['IL', 'Illinois']
  

Then you make the insertion into the database using

c.execute(sql, data)

The other principal advantage of this technique is that you don't need 
to discriminate between numeric and string fields, since they are both 
handled the same way. You also get better efficiency if you run with the 
same fields many times, as the DBMS will  (if it's sufficiently 
advanced) use the already-prepared version of the statement rather than 
recompiling it repeatedly.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Newbie needs Help

2006-08-16 Thread Steve Holden
Steve Holden wrote:
[...]
 
def insertFromDict(table, d):  vector
  
Please ignore the Cygwin mousedroppings ...

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: Newbie needs Help

2006-08-16 Thread John Machin

Dennis Lee Bieber wrote:
 c.execute(insert into %s (%s) values (%s)
   % (statecode,
   , .join(data.keys() ),
   , .join([%s] * len(data.keys() ) ) ),
   data.values() )
 # NOTE: only works if data.keys() and data.values() are
 # in the same order.


It is guaranteed, provided you don't mutate the dictionary between
times. In any case, it's a bit hard to imagine under what circumstances
there would be different traversal orders to obtain keys and values :-)

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


Re: Newbie..Needs Help

2006-07-30 Thread Anthra Norell
Graham,

Would it help to use another web site? Not as long as the program works on this 
site. If it doesn't it may help to change sites, but
a new reader would have to be crafted. Towards this my code may look 
intimidating. It isn't really a good example for a demo,
because it looks scary. As I said, I experimentally stretched the envelope.
  The trick is to develop incrementally, one step at a time, look at the 
result of each stage, recognize what needs to be done
next and add missing definitions or add a subsequent translation step. In this 
manner a complex system can be built. SE is
particualry accommodating in this respect. You can test an Editor object in 
seconds on the IDLE command line, e.g.:

   s = 'Total: $1,234.55  (-6.7)'

   print SE.SE ('$=USD  ,=\' .=, := )=%)') (s)
  TotalUSD 1'234,55  (-6,7%)

It also helps to read  SE-DOC.HTM which explains a host of basic techniques.

Glad to help

Frederic

- Original Message -
From: Graham Feeley [EMAIL PROTECTED]
Newsgroups: comp.lang.python
To: python-list@python.org
Sent: Sunday, July 30, 2006 5:55 AM
Subject: Re: Newbie..Needs Help


 Well Well Well, Anthra you are a clever person, Are
 nt you
 I nearly fell over when i read your post.
 Would it help if we used another web site to gather data
 As you stated the tables are not all that well structured.
 well I will give thisone  a go first and if there is anything I can do for
 you just ask and I will try my best.
 I really appreciate what you have done.
 Of course I will try to follow your code to see if any will fall on
 meLOL
 Regards
 Graham

 Anthra Norell [EMAIL PROTECTED] wrote in message
 news:[EMAIL PROTECTED]
 
  - Original Message -
  From: Graham Feeley [EMAIL PROTECTED]
  Newsgroups: comp.lang.python
  To: python-list@python.org
  Sent: Friday, July 28, 2006 5:11 PM
  Subject: Re: Newbie..Needs Help
 
 
  Thanks Nick for the reply
  Of course my first post was a general posting to see if someone would be
  able to help
  here is the website which holds the data I require
  http://www.aapracingandsports.com.au/racing/raceresultsonly.asp?storydate=27/07/2006meetings=bdgo
 
  The fields required are as follows
   NSW Tab
  #  Win  Place
   2$4.60   $2.40
   5$2.70
   1$1.30
   Quin$23.00
   Tri  $120.70
  Field names are
  Date   ( not important )
  Track= Bendigo
  RaceNoon web page
  Res1st...2
  Res2nd..5
  Res3rd..1
  Div1..$4.60
  DivPlc...$2.40
  Div2..$2.70
  Div3..$1.30
  DivQuin.$23.00
  DivTrif...$120.70
  As you can see there are a total of 6 meetings involved and I would need
  to
  put in this parameter ( =bdgo) or (=gosf) these are the meeting tracks
 
  Hope this more enlightening
  Regards
  graham
 
 
  Graham,
 
  Only a few days ago I gave someone a push who had a very similar problem.
  I handed him code ready to run. I am doing it again for
  you.
   The site you use is much harder to interpret than the other one was
  and so I took the opportunity to experimentally stretch
  the envelope of a new brain child of mine: a stream editor called SE. It
  is new and so I also take the opportunity to demo it.
   One correspondent in the previous exchange was Paul McGuire, the
  author of 'pyparse'. He made a good case for using 'pyparse'
  in situations like yours. Unlike a stream editor, a parser reads structure
  in addition to data and can relate the data to its
  context.
   Anlayzing the tables I noticed that they are poorly structured: The
  first column contains both data and ids. Some records are
  shorter than others, so column ids have to be guessed and hard coded.
  Missing data sometimes is a dash, sometimes nothing. The
  inconsistencies seem to be consistent, though, down the eight tables of
  the page. So they can be formalized with some confidence
  that they are systematic. If Paul could spend some time on this, I'd be
  much interested to see how he would handle the relative
  disorder.
   Another thought: The time one invests in developing a program should
  not exceed the time it can save overall (not talking
  about recreational programming). Web pages justify an extra measure of
  caution, because they may change any time and when they do
  they impose an unscheduled priority every time the reader stops working
  and requires a revision.
 
  So, here is your program. I write it so you can copy the whole thing to a
  file. Next copy SE from the Cheese Shop. Unzip it and put
  both SE.PY and SEL.PY where your Python progams are. Then 'execfile' the
  code in an IDLE window, call 'display_horse_race_data
  ('Bendigo', '27/07/2006') and see what happens. You'll have to wait ten
  seconds or so.
 
  Regards
 
  Frederic

Re: Newbie..Needs Help

2006-07-29 Thread Anthra Norell

- Original Message -
From: Graham Feeley [EMAIL PROTECTED]
Newsgroups: comp.lang.python
To: python-list@python.org
Sent: Friday, July 28, 2006 5:11 PM
Subject: Re: Newbie..Needs Help


 Thanks Nick for the reply
 Of course my first post was a general posting to see if someone would be
 able to help
 here is the website which holds the data I require
 http://www.aapracingandsports.com.au/racing/raceresultsonly.asp?storydate=27/07/2006meetings=bdgo

 The fields required are as follows
  NSW Tab
 #  Win  Place
  2$4.60   $2.40
  5$2.70
  1$1.30
  Quin$23.00
  Tri  $120.70
 Field names are
 Date   ( not important )
 Track= Bendigo
 RaceNoon web page
 Res1st...2
 Res2nd..5
 Res3rd..1
 Div1..$4.60
 DivPlc...$2.40
 Div2..$2.70
 Div3..$1.30
 DivQuin.$23.00
 DivTrif...$120.70
 As you can see there are a total of 6 meetings involved and I would need to
 put in this parameter ( =bdgo) or (=gosf) these are the meeting tracks

 Hope this more enlightening
 Regards
 graham


Graham,

Only a few days ago I gave someone a push who had a very similar problem. I 
handed him code ready to run. I am doing it again for
you.
  The site you use is much harder to interpret than the other one was and 
so I took the opportunity to experimentally stretch
the envelope of a new brain child of mine: a stream editor called SE. It is new 
and so I also take the opportunity to demo it.
  One correspondent in the previous exchange was Paul McGuire, the author 
of 'pyparse'. He made a good case for using 'pyparse'
in situations like yours. Unlike a stream editor, a parser reads structure in 
addition to data and can relate the data to its
context.
  Anlayzing the tables I noticed that they are poorly structured: The first 
column contains both data and ids. Some records are
shorter than others, so column ids have to be guessed and hard coded. Missing 
data sometimes is a dash, sometimes nothing. The
inconsistencies seem to be consistent, though, down the eight tables of the 
page. So they can be formalized with some confidence
that they are systematic. If Paul could spend some time on this, I'd be much 
interested to see how he would handle the relative
disorder.
  Another thought: The time one invests in developing a program should not 
exceed the time it can save overall (not talking
about recreational programming). Web pages justify an extra measure of caution, 
because they may change any time and when they do
they impose an unscheduled priority every time the reader stops working and 
requires a revision.

So, here is your program. I write it so you can copy the whole thing to a file. 
Next copy SE from the Cheese Shop. Unzip it and put
both SE.PY and SEL.PY where your Python progams are. Then 'execfile' the code 
in an IDLE window, call 'display_horse_race_data
('Bendigo', '27/07/2006') and see what happens. You'll have to wait ten seconds 
or so.

Regards

Frederic

##

TRACKS = { 'New Zealand' : '',
   'Bendigo' : 'bdgo',
   'Gosford' : 'gosf',
   'Northam' : 'nthm',
   'Port Augusta': 'pta',
   'Townsville'  : 'town',
 }


# This function does it all once all functions are loaded. If nothing shows, the
# page has not data.

def display_horse_race_data (track, date, clip_summary = 100):

   
  tracks: e.g. 'Bendigo' or 'bdgo'
  date: e.g. '27/07/2006'
  clip_summary: each table has a long summary header.
the argument says hjow much of it to show.
   

   if track [0].isupper ():
  if TRACKS.has_key (track):
 track = TRACKS [track]
  else:
 print 'No such track %s' % track
 return
   open ()
   header, records = get_horse_race_data (track, date)
   show_records (header, records, clip_summary)



##


import SE, urllib

_is_open = 0

def open ():

   global _is_open

   if not _is_open:   # Skip repeat calls

  global Data_Filter, Null_Data_Marker, Tag_Stripper, Space_Deflator, 
CSV_Maker

  # Making the following Editors is a step-by-step process, adding one 
element at a time and
  # looking at what it does and what should be done next.
  # Get pertinent data segments
  header= ' ~(?i)Today\'s Results - .+?div 
style=padding-top:5px;~==*END*OF*HEADER* '
  race_summary  = ' ~(?i)Race [1-9].*?/fontbr~== '
  data_segment  = ' ~(?i)table border=0 width=100% cellpadding=0 
cellspacing=0(.|\n)*?/table~==*END*OF*SEGMENT* '
  Data_Filter = SE.SE (' EAT ' + header + race_summary + data_segment)

  # Some data items are empty. Fill them with a dash.
  mark_null_data = ' ~(?i)\s*nbsp;\s*/td

Re: Newbie..Needs Help

2006-07-29 Thread Graham Feeley
Well Well Well, Anthra you are a clever person, Are
nt you
I nearly fell over when i read your post.
Would it help if we used another web site to gather data
As you stated the tables are not all that well structured.
well I will give thisone  a go first and if there is anything I can do for 
you just ask and I will try my best.
I really appreciate what you have done.
Of course I will try to follow your code to see if any will fall on 
meLOL
Regards
Graham

Anthra Norell [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]

 - Original Message -
 From: Graham Feeley [EMAIL PROTECTED]
 Newsgroups: comp.lang.python
 To: python-list@python.org
 Sent: Friday, July 28, 2006 5:11 PM
 Subject: Re: Newbie..Needs Help


 Thanks Nick for the reply
 Of course my first post was a general posting to see if someone would be
 able to help
 here is the website which holds the data I require
 http://www.aapracingandsports.com.au/racing/raceresultsonly.asp?storydate=27/07/2006meetings=bdgo

 The fields required are as follows
  NSW Tab
 #  Win  Place
  2$4.60   $2.40
  5$2.70
  1$1.30
  Quin$23.00
  Tri  $120.70
 Field names are
 Date   ( not important )
 Track= Bendigo
 RaceNoon web page
 Res1st...2
 Res2nd..5
 Res3rd..1
 Div1..$4.60
 DivPlc...$2.40
 Div2..$2.70
 Div3..$1.30
 DivQuin.$23.00
 DivTrif...$120.70
 As you can see there are a total of 6 meetings involved and I would need 
 to
 put in this parameter ( =bdgo) or (=gosf) these are the meeting tracks

 Hope this more enlightening
 Regards
 graham


 Graham,

 Only a few days ago I gave someone a push who had a very similar problem. 
 I handed him code ready to run. I am doing it again for
 you.
  The site you use is much harder to interpret than the other one was 
 and so I took the opportunity to experimentally stretch
 the envelope of a new brain child of mine: a stream editor called SE. It 
 is new and so I also take the opportunity to demo it.
  One correspondent in the previous exchange was Paul McGuire, the 
 author of 'pyparse'. He made a good case for using 'pyparse'
 in situations like yours. Unlike a stream editor, a parser reads structure 
 in addition to data and can relate the data to its
 context.
  Anlayzing the tables I noticed that they are poorly structured: The 
 first column contains both data and ids. Some records are
 shorter than others, so column ids have to be guessed and hard coded. 
 Missing data sometimes is a dash, sometimes nothing. The
 inconsistencies seem to be consistent, though, down the eight tables of 
 the page. So they can be formalized with some confidence
 that they are systematic. If Paul could spend some time on this, I'd be 
 much interested to see how he would handle the relative
 disorder.
  Another thought: The time one invests in developing a program should 
 not exceed the time it can save overall (not talking
 about recreational programming). Web pages justify an extra measure of 
 caution, because they may change any time and when they do
 they impose an unscheduled priority every time the reader stops working 
 and requires a revision.

 So, here is your program. I write it so you can copy the whole thing to a 
 file. Next copy SE from the Cheese Shop. Unzip it and put
 both SE.PY and SEL.PY where your Python progams are. Then 'execfile' the 
 code in an IDLE window, call 'display_horse_race_data
 ('Bendigo', '27/07/2006') and see what happens. You'll have to wait ten 
 seconds or so.

 Regards

 Frederic

 ##

 TRACKS = { 'New Zealand' : '',
   'Bendigo' : 'bdgo',
   'Gosford' : 'gosf',
   'Northam' : 'nthm',
   'Port Augusta': 'pta',
   'Townsville'  : 'town',
 }


 # This function does it all once all functions are loaded. If nothing 
 shows, the
 # page has not data.

 def display_horse_race_data (track, date, clip_summary = 100):

   
  tracks: e.g. 'Bendigo' or 'bdgo'
  date: e.g. '27/07/2006'
  clip_summary: each table has a long summary header.
the argument says hjow much of it to show.
   

   if track [0].isupper ():
  if TRACKS.has_key (track):
 track = TRACKS [track]
  else:
 print 'No such track %s' % track
 return
   open ()
   header, records = get_horse_race_data (track, date)
   show_records (header, records, clip_summary)



 ##


 import SE, urllib

 _is_open = 0

 def open ():

   global _is_open

   if not _is_open:   # Skip repeat calls

  global Data_Filter, Null_Data_Marker, Tag_Stripper, Space_Deflator, 
 CSV_Maker

  # Making the following Editors is a step-by-step process

Newbie..Needs Help

2006-07-28 Thread Graham Feeley
Hi this is a plea for some help.
I am enjoying a script that was written for me and its purpose is to collect 
data from a web site and puts it into a access database table.
It works fine, however it is a sports info table but now I need to collect 
the results of those races.

I simply can't keep up putting the results in manually.
I dont care if it is a access table or a text file ( whichever is easiest)
there are only 12 fields to extract
The person who wrote the script is not available as he is engrossed in 
another project which is talking all his time.
I hope someone has a little time on his hands willing to help me
Regards
Graham
 


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


Re: Newbie..Needs Help

2006-07-28 Thread Nick Vatamaniuc
Your description is too general. The way to 'collect the results'
depends largely in what format the results are. If they are in an html
table you will have to parse the html data if they are in a simple
plaintext you might use a different method, and if the site renders the
numbers to images and adds some noise and font effects to them, then
you can abandon the idea altogether unless you have a good background
in OCR.

But let's assume that you data is embedded an html sourse. Even so you,
it would largely depend on the specific syntax used. Sometimes you
could  just use regular expressions, other times a full HTML parser
will be needed. Then you could have the issue of 'how to get to the
right page' and/or 'how to uniquely identify and match each of the
previously parsed rows of data to the new set of rows of data that also
have the results added to them?'

Perhaps if you post the website plus a clear and exact description of
what you want to accomplish and what has already been accomplished you
might find someone to help.

-Nick V.





Graham Feeley wrote:
 Hi this is a plea for some help.
 I am enjoying a script that was written for me and its purpose is to collect
 data from a web site and puts it into a access database table.
 It works fine, however it is a sports info table but now I need to collect
 the results of those races.

 I simply can't keep up putting the results in manually.
 I dont care if it is a access table or a text file ( whichever is easiest)
 there are only 12 fields to extract
 The person who wrote the script is not available as he is engrossed in
 another project which is talking all his time.
 I hope someone has a little time on his hands willing to help me
 Regards
 Graham

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


Re: Newbie..Needs Help

2006-07-28 Thread Graham Feeley
Thanks Nick for the reply
Of course my first post was a general posting to see if someone would be 
able to help
here is the website which holds the data I require
http://www.aapracingandsports.com.au/racing/raceresultsonly.asp?storydate=27/07/2006meetings=bdgo

The fields required are as follows
 NSW Tab
#  Win  Place
 2$4.60   $2.40
 5$2.70
 1$1.30
 Quin$23.00
 Tri  $120.70
Field names are
Date   ( not important )
Track= Bendigo
RaceNoon web page
Res1st...2
Res2nd..5
Res3rd..1
Div1..$4.60
DivPlc...$2.40
Div2..$2.70
Div3..$1.30
DivQuin.$23.00
DivTrif...$120.70
As you can see there are a total of 6 meetings involved and I would need to 
put in this parameter ( =bdgo) or (=gosf) these are the meeting tracks

Hope this more enlightening
Regards
graham

Graham Feeley [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 Hi this is a plea for some help.
 I am enjoying a script that was written for me and its purpose is to 
 collect data from a web site and puts it into a access database table.
 It works fine, however it is a sports info table but now I need to collect 
 the results of those races.

 I simply can't keep up putting the results in manually.
 I dont care if it is a access table or a text file ( whichever is easiest)
 there are only 12 fields to extract
 The person who wrote the script is not available as he is engrossed in 
 another project which is talking all his time.
 I hope someone has a little time on his hands willing to help me
 Regards
 Graham


 


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


Re: Newbie..Needs Help

2006-07-28 Thread Nick Vatamaniuc
Graham,

I won't write the program for you since I have my own program to work
on but here is an idea how to do it.
1) Need to have a function to download the page -- use the urllib
module. Like this:
import urllib
page=urllib.urlopen(URL_GOES_HERE).read()

2) Go to the page with your browser and view the source of the html.
You will need to find specific html patterns that you can use to
identify the boundaries between each race first. A good one would be
the actual title 'Race 1 results:', then you have 'Race 2 results:' and
so on until 'Race 8 results:'. From this you need to derive a regular
expression in Python (here is documenation
http://docs.python.org/lib/module-re.html) to express all those
boundaries as one pattern it is: 'Race [0-9]+ results:'. In other words
the word 'Race' then space then a digit repeated one or more times then
another space and 'results:'. So you can do:
races_pattern=re.comple(r'Race [0-9]+ results:') # - this is your
pattern
chunks=races_pattern.split(page) #- split the page into chunks based
on the pattern
you will have 9 chunks if you have 8 races. The first one will be all
the stuff before the title (i.e. the start of the page), throw it away:
chunks=chunks[1:]

3) Now go back to the html source and look inside each race at the
table with the results, find a pattern for  a good boundary between
table rows. Again use the regular expressions like before to split each
table away from other junk, then each table into rows (use tr)

4) Look again at the source, and split each row into data cells (use
td).

5) Then for each of the split cell chunks remove the html tag data with

chunk=re.sub('.*?', '', chunk)

6) Now all you should have is pure data stored in strings in  each of
the data cell chunks  in each of the  table row in each of the table.

7) Then save to text file and import into your database.

Anyway that's the general idea, there are other ways to do it, but
that's my approach. I wrote a couple of screen scrapping applications
like this before  in Python and I used this method and it worked well
enough.

Good luck,
Nick V.




Graham Feeley wrote:
 Thanks Nick for the reply
 Of course my first post was a general posting to see if someone would be
 able to help
 here is the website which holds the data I require
 http://www.aapracingandsports.com.au/racing/raceresultsonly.asp?storydate=27/07/2006meetings=bdgo

 The fields required are as follows
  NSW Tab
 #  Win  Place
  2$4.60   $2.40
  5$2.70
  1$1.30
  Quin$23.00
  Tri  $120.70
 Field names are
 Date   ( not important )
 Track= Bendigo
 RaceNoon web page
 Res1st...2
 Res2nd..5
 Res3rd..1
 Div1..$4.60
 DivPlc...$2.40
 Div2..$2.70
 Div3..$1.30
 DivQuin.$23.00
 DivTrif...$120.70
 As you can see there are a total of 6 meetings involved and I would need to
 put in this parameter ( =bdgo) or (=gosf) these are the meeting tracks

 Hope this more enlightening
 Regards
 graham

 Graham Feeley [EMAIL PROTECTED] wrote in message
 news:[EMAIL PROTECTED]
  Hi this is a plea for some help.
  I am enjoying a script that was written for me and its purpose is to
  collect data from a web site and puts it into a access database table.
  It works fine, however it is a sports info table but now I need to collect
  the results of those races.
 
  I simply can't keep up putting the results in manually.
  I dont care if it is a access table or a text file ( whichever is easiest)
  there are only 12 fields to extract
  The person who wrote the script is not available as he is engrossed in
  another project which is talking all his time.
  I hope someone has a little time on his hands willing to help me
  Regards
  Graham
 
 
 

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


Re: Newbie..Needs Help

2006-07-28 Thread Nick Vatamaniuc
What do you mean?
The html table is right there (at least in Firefox it is...). I'll
paste it in too. Just need to isolate with some simple regexes and
extract the text...
Nick V.

---
table border=0 width=100% cellpadding=0 cellspacing=0
tr class=normbold
Td width=13% class=tdblue#
/td

Td align=right width=13% 
class=tdblueWinnbsp;
/td
Td align=right width=16% 
class=tdbluePlacenbsp;
/td
Td align=right width=13% 
class=tdblueWinnbsp;
/td
Td align=right 
class=tdbluePlacenbsp;

/tdTd align=right width=13% 
class=tdblueWinnbsp;
/td
Td align=right width=16% 
class=tdbluePlacenbsp;
/td
/tr
  ! MORE tr.../tr ROWS IN HERE 
!
/table
-

Dennis Lee Bieber wrote:
 On Sat, 29 Jul 2006 01:11:41 +1000, Graham Feeley
 [EMAIL PROTECTED] declaimed the following in
 comp.lang.python:

 http://www.aapracingandsports.com.au/racing/raceresultsonly.asp?storydate=27/07/2006meetings=bdgo
 
   Ugh... Javascript and CSS...

   Getting down to the actual race tables is the pain... Once down to
 the tables it may not be that difficult...

 --
   WulfraedDennis Lee Bieber   KD6MOG
   [EMAIL PROTECTED]   [EMAIL PROTECTED]
   HTTP://wlfraed.home.netcom.com/
   (Bestiaria Support Staff:   [EMAIL PROTECTED])
   HTTP://www.bestiaria.com/

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


Re: Newbie needs help extracting data from XML

2005-12-29 Thread Alan Kennedy
[Rodney]
 Im a Python newbie and am trying to get the data out of a series of XML 
 files.

As Paul McGuire already noted, it's unusual to extract information from 
a SOAP message this way: it is more usual to use a SOAP toolkit to do 
the job for you.

But, assuming that you know what you're doing, and that you're doing it 
for good reasons, here's a snippet that uses xpath to do what you want.

#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
document = \
?xml version=1.0 encoding=utf-8?
soap:Envelope
   xmlns:soap=http://schemas.xmlsoap.org/soap/envelope/;
   xmlns:soapenc=http://schemas.xmlsoap.org/soap/encoding/;
   xmlns:tns=http://www.ExchangeNetwork.net/schema/v1.0/node.wsdl;
   xmlns:types=http://www.ExchangeNetwork.net/schema/v1.0/node.wsdl;
   xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance;
   xmlns:xsd=http://www.w3.org/2001/XMLSchema;
   soap:Header
 wsu:Timestamp
   xmlns:wsu=http://schemas.xmlsoap.org/ws/2002/07/utility;
   wsu:Created2005-12-28T05:59:38Z/wsu:Created
   wsu:Expires2005-12-28T06:04:38Z/wsu:Expires
 /wsu:Timestamp
   /soap:Header
   soap:Body
 soap:encodingStyle=http://schemas.xmlsoap.org/soap/encoding/;
 q1:NodePingResponse
   xmlns:q1=http://www.ExchangeNetwork.net/schema/v1.0/node.xsd;
   return xsi:type=xsd:stringReady/return
 /q1:NodePingResponse
   /soap:Body
/soap:Envelope


import xml.dom.minidom
import xml.xpath

#dom_tree = xml.dom.minidom.parse('my_xml_file.xml')
dom_tree = xml.dom.minidom.parseString(document)
return_node = xml.xpath.Evaluate('//return', dom_tree)[0]
print Return status is: '%s' % return_node.childNodes[0].nodeValue
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

You have to install PyXML to get xpath support: http://pyxml.sf.net

There are other ways to do it, e.g. using ElementTree, but I'll leave it 
to others to suggest the best way to do that.

HTH,

-- 
alan kennedy
--
email alan:  http://xhaus.com/contact/alan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie needs help extracting data from XML

2005-12-29 Thread Fredrik Lundh
Alan Kennedy wrote

 There are other ways to do it, e.g. using ElementTree, but I'll leave it
 to others to suggest the best way to do that.

using ElementTree with SOAP is discussed here:

http://effbot.org/zone/elementsoap-1.htm

/F



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


Re: Newbie needs help extracting data from XML

2005-12-29 Thread Rodney
Thanks for the help

This was a SOAP Webservice message.  I used httplib instead of SOAPpy or ZSI 
because SOAPpy cann't do arrays of complex type and ZSI was confusing.

Thanks again



Rodney [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 Hi,

 Im a Python newbie and am trying to get the data out of a series of XML 
 files.  So for example the xml is:

 ?xml version=1.0 encoding=utf-8?soap:Envelope 
 xmlns:soap=http://schemas.xmlsoap.org/soap/envelope/; 
 xmlns:soapenc=http://schemas.xmlsoap.org/soap/encoding/; 
 xmlns:tns=http://www.ExchangeNetwork.net/schema/v1.0/node.wsdl; 
 xmlns:types=http://www.ExchangeNetwork.net/schema/v1.0/node.wsdl; 
 xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance; 
 xmlns:xsd=http://www.w3.org/2001/XMLSchema;soap:Headerwsu:Timestamp 
 xmlns:wsu=http://schemas.xmlsoap.org/ws/2002/07/utility;wsu:Created2005-12-28T05:59:38Z/wsu:Createdwsu:Expires2005-12-28T06:04:38Z/wsu:Expires/wsu:Timestamp/soap:Headersoap:Body
  
 soap:encodingStyle=http://schemas.xmlsoap.org/soap/encoding/;q1:NodePingResponse
  
 xmlns:q1=http://www.ExchangeNetwork.net/schema/v1.0/node.xsd;return 
 xsi:type=xsd:stringReady/return/q1:NodePingResponse/soap:Body/soap:Envelope


 and I want to get the value from the element return which currently has 
 a value of Ready.

 Other XML files I want to work with may have several elements I want to 
 pull data from.  This seem relatively easy but I have been reading and 
 cruising google for hours and none of the examples make any sense.

 I appreciate any code writing help with this.


 


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


Newbie needs help extracting data from XML

2005-12-28 Thread Rodney
Hi,

Im a Python newbie and am trying to get the data out of a series of XML 
files.  So for example the xml is:

?xml version=1.0 encoding=utf-8?soap:Envelope 
xmlns:soap=http://schemas.xmlsoap.org/soap/envelope/; 
xmlns:soapenc=http://schemas.xmlsoap.org/soap/encoding/; 
xmlns:tns=http://www.ExchangeNetwork.net/schema/v1.0/node.wsdl; 
xmlns:types=http://www.ExchangeNetwork.net/schema/v1.0/node.wsdl; 
xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance; 
xmlns:xsd=http://www.w3.org/2001/XMLSchema;soap:Headerwsu:Timestamp 
xmlns:wsu=http://schemas.xmlsoap.org/ws/2002/07/utility;wsu:Created2005-12-28T05:59:38Z/wsu:Createdwsu:Expires2005-12-28T06:04:38Z/wsu:Expires/wsu:Timestamp/soap:Headersoap:Body
 
soap:encodingStyle=http://schemas.xmlsoap.org/soap/encoding/;q1:NodePingResponse
 
xmlns:q1=http://www.ExchangeNetwork.net/schema/v1.0/node.xsd;return 
xsi:type=xsd:stringReady/return/q1:NodePingResponse/soap:Body/soap:Envelope


and I want to get the value from the element return which currently has a 
value of Ready.

Other XML files I want to work with may have several elements I want to pull 
data from.  This seem relatively easy but I have been reading and cruising 
google for hours and none of the examples make any sense.

I appreciate any code writing help with this.



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


Re: Newbie needs help extracting data from XML

2005-12-28 Thread Paul McGuire
Rodney [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]
 Hi,

 Im a Python newbie and am trying to get the data out of a series of XML
 files.  So for example the xml is:

 ?xml version=1.0 encoding=utf-8?soap:Envelope
 xmlns:soap=http://schemas.xmlsoap.org/soap/envelope/;
 xmlns:soapenc=http://schemas.xmlsoap.org/soap/encoding/;
 xmlns:tns=http://www.ExchangeNetwork.net/schema/v1.0/node.wsdl;
 xmlns:types=http://www.ExchangeNetwork.net/schema/v1.0/node.wsdl;
 xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance;
 xmlns:xsd=http://www.w3.org/2001/XMLSchema;soap:Headerwsu:Timestamp

xmlns:wsu=http://schemas.xmlsoap.org/ws/2002/07/utility;wsu:Created2005-
12-28T05:59:38Z/wsu:Createdwsu:Expires2005-12-28T06:04:38Z/wsu:Expires
/wsu:Timestamp/soap:Headersoap:Body

soap:encodingStyle=http://schemas.xmlsoap.org/soap/encoding/;q1:NodePingR
esponse
 xmlns:q1=http://www.ExchangeNetwork.net/schema/v1.0/node.xsd;return

xsi:type=xsd:stringReady/return/q1:NodePingResponse/soap:Body/soap
:Envelope


 and I want to get the value from the element return which currently has
a
 value of Ready.

 Other XML files I want to work with may have several elements I want to
pull
 data from.  This seem relatively easy but I have been reading and cruising
 google for hours and none of the examples make any sense.

 I appreciate any code writing help with this.


This is data in a set of files?  It looks like the SOAP reply from a Web
Service described in the WSDL found at
http://www.ExchangeNetwork.net/schema/v1.0/node.wsdl, specifically the
NodePingResponse which is the return value from the web operation NodePing.
You might best generate the proper Python parsing classes using SOAPpy,
using the WSDL source.

You can also use Python's XML modules for loading the XML into a DOM tree,
or use Fredrik Lundh's ElementTree utility module.

-- Paul


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


Re: Python newbie needs help

2005-12-15 Thread Kent Johnson
Ron Hudson wrote:
 I am trying to create something like a MUD, It will eventually evolve  
 to a multi player
 MUD over the network game, but for now it's just a platform for  
 authoring and playing
 text adventures that works like a single user MUD.

You might Google python text adventure game if you want to build on others' 
work instead 
of starting from scratch.

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


Newbie needs help with regex strings

2005-12-14 Thread Catalina Scott A Contr AFCA/EVEO
I have a file with lines in the following format.

pie=apple,quantity=1,cooked=yes,ingredients='sugar and cinnamon'
Pie=peach,quantity=2,ingredients='peaches,powdered sugar'
Pie=cherry,quantity=3,cooked=no,price=5,ingredients='cherries and sugar'

I would like to pull out some of the values and write them to a csv
file.

For line in filea
pie = regex
quantity = regex
cooked = regex
ingredients = regex
fileb.write (quantity,pie,cooked,ingredients)

How can I retreive the values and assign them to a name?

Thank you
Scott
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie needs help with regex strings

2005-12-14 Thread Paul McGuire
This isn't a regex solution, but uses pyparsing instead.  Pyparsing
helps you construct recursive-descent parsers, and maintains a code
structure that is easy to compose, read, understand, maintain, and
remember what you did 6-months after you wrote it in the first place.

Download pyparsing at http://pyparsing.sourceforge.net.

-- Paul


data = pie=apple,quantity=1,cooked=yes,ingredients='sugar and
cinnamon'
Pie=peach,quantity=2,ingredients='peaches,powdered sugar'
Pie=cherry,quantity=3,cooked=no,price=5,ingredients='cherries and
sugar'

from pyparsing import CaselessLiteral, Literal, Word, alphas, nums,
oneOf, quotedString, \
Group, Dict, delimitedList, removeQuotes

# define basic elements for parsing
pieName = Word(alphas)
qty = Word(nums)
yesNo = oneOf(yes no,caseless=True)
EQUALS = Literal(=).suppress()

# define separate pie attributes
pieEntry = CaselessLiteral(pie) + EQUALS + pieName
qtyEntry = CaselessLiteral(quantity) + EQUALS + qty
cookedEntry  = CaselessLiteral(cooked) + EQUALS + yesNo
ingredientsEntry = CaselessLiteral(ingredients) + EQUALS +
quotedString.setParseAction(removeQuotes)
priceEntry   = CaselessLiteral(price) + EQUALS + qty

# define overall list of alternative attributes
pieAttribute = pieEntry | qtyEntry | cookedEntry | ingredientsEntry |
priceEntry

# define each line as a list of attributes (comma delimiter is the
default), grouping results by attribute
pieDataFormat = delimitedList( Group(pieAttribute) )

# parse each line in the input string, and create a dict of the results
for line in data.split(\n):
pieData = pieDataFormat.parseString(line)
pieDict = dict( pieData.asList() )
print pieDict

''' prints out:
{'cooked': 'yes', 'ingredients': 'sugar and cinnamon', 'pie': 'apple',
'quantity': '1'}
{'ingredients': 'peaches,powdered sugar', 'pie': 'peach', 'quantity':
'2'}
{'cooked': 'no', 'price': '5', 'ingredients': 'cherries and sugar',
'pie': 'cherry', 'quantity': '3'}
'''

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


Re: Newbie needs help with regex strings

2005-12-14 Thread Fredrik Lundh
Scott wrote:

 I have a file with lines in the following format.

 pie=apple,quantity=1,cooked=yes,ingredients='sugar and cinnamon'
 Pie=peach,quantity=2,ingredients='peaches,powdered sugar'
 Pie=cherry,quantity=3,cooked=no,price=5,ingredients='cherries and sugar'

 I would like to pull out some of the values and write them to a csv
 file.

 For line in filea
 pie = regex
 quantity = regex
 cooked = regex
 ingredients = regex
 fileb.write (quantity,pie,cooked,ingredients)

 How can I retreive the values and assign them to a name?

here's a relatively straightforward re solution that gives you a dictionary
with the values for each line.

import re

for line in open(infile.txt):
d = {}
for k, v1, v2 in re.findall((\w+)=(?:(\w+)|'([^']*)'), line):
d[k.lower()] = v1 or v2
print d

(the pattern looks for alphanumeric characters (k) followed by an equal
sign followed by either a number of alphanumeric characters (v1), or text
inside single quotes (v2).  either v1 or v2 will be set)

getting from dictionary to file is left as an exercise to the reader.

/F



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


Re: Newbie needs help with regex strings

2005-12-14 Thread Christopher Subich
Paul McGuire wrote:
 This isn't a regex solution, but uses pyparsing instead.  Pyparsing
 helps you construct recursive-descent parsers, and maintains a code
 structure that is easy to compose, read, understand, maintain, and
 remember what you did 6-months after you wrote it in the first place.
 
 Download pyparsing at http://pyparsing.sourceforge.net.


For the example listed, pyparsing is even overkill; the OP should 
probably use the csv module.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie needs help with regex strings

2005-12-14 Thread Dennis Benzinger
Catalina Scott A Contr AFCA/EVEO schrieb:
 I have a file with lines in the following format.
 
 pie=apple,quantity=1,cooked=yes,ingredients='sugar and cinnamon'
 Pie=peach,quantity=2,ingredients='peaches,powdered sugar'
 Pie=cherry,quantity=3,cooked=no,price=5,ingredients='cherries and sugar'
 
 I would like to pull out some of the values and write them to a csv
 file.
 
 For line in filea
   pie = regex
   quantity = regex
   cooked = regex
   ingredients = regex
   fileb.write (quantity,pie,cooked,ingredients)
 
 How can I retreive the values and assign them to a name?
 
 Thank you
 Scott

Try this:

import re
import StringIO

filea_string = pie=apple,quantity=1,cooked=yes,ingredients='sugar and 
cinnamon'
pie=peach,quantity=2,ingredients='peaches,powdered sugar'
pie=cherry,quantity=3,cooked=no,price=5,ingredients='cherries and sugar'


FIELDS = (pie, quantity, cooked, ingredients, price)

field_regexes = {}

for field in FIELDS:
 field_regexes[field] = re.compile(%s=([^,\n]*) % field)

for line in StringIO.StringIO(filea_string):

 field_values = {}

 for field in FIELDS:
 match_object = field_regexes[field].search(line)

 if match_object is not None:
 field_values[field] = match_object.group(1)

 print field_values
 #fileb.write (quantity,pie,cooked,ingredients)



Bye,
Dennis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie needs help with regex strings

2005-12-14 Thread Dennis Benzinger
Christopher Subich schrieb:
 Paul McGuire wrote:
 
 [...]
 For the example listed, pyparsing is even overkill; the OP should 
 probably use the csv module.

But the OP wants to parse lines with key=value pairs, not simply lines
with comma separated values. Using the csv module will just separate the 
key=value pairs and you would still have to take them apart.

Bye,
Dennis
-- 
http://mail.python.org/mailman/listinfo/python-list


Python newbie needs help

2005-12-14 Thread Ron Hudson
First let me apologize if this post offends, I am a real newbie to  
Python having only used it for about
2 days. If this is the wrong place to post newbie questions, please  
be polite.

I have the O'Reily Learning Python book and I am reading it.

Here's what I am working on..

I am trying to create something like a MUD, It will eventually evolve  
to a multi player
MUD over the network game, but for now it's just a platform for  
authoring and playing
text adventures that works like a single user MUD.

I am using a dictionary to hold the world.

I have a .py file with some def scripts(?) in it. right now it only  
has scripts to
save and load the world dictionary.

I am using Import to read it after I start an interactive python.  
What I need
right now is I seem to have some sort of scoping problems with the  
world dictionary.

I can read it and write it and worldcr lists it out. but my def  
look(at): script
it seems it doesn't see the the world dictionary.

  import lets
  world = lets.loadworld()
  world
{'wizarddescription':'A short guy wearing a robe and a pointy hat'}
  lets.look('wizard')
  file stdin line ?
  file lets.py line 14 in look
 print world[at+'description']
nameError:world
  at = 'wizard'
  print world[at+'description']
A short guy wearing a robe and a pointy hat
 

Is there a way to make 'world' global? can I do it in lets.py?

Am I going about this all wrong?

Thanks.

P.S.  Is there a way to tell python to save my whole environment  
and to reload my whole environment

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


Re: Newbie needs help with regex strings

2005-12-14 Thread Gerard Flanagan
Fredrik Lundh wrote:

 Scott wrote:

  I have a file with lines in the following format.
 
  pie=apple,quantity=1,cooked=yes,ingredients='sugar and cinnamon'
  Pie=peach,quantity=2,ingredients='peaches,powdered sugar'
  Pie=cherry,quantity=3,cooked=no,price=5,ingredients='cherries and sugar'
 
  I would like to pull out some of the values and write them to a csv
  file.

 here's a relatively straightforward re solution that gives you a dictionary
 with the values for each line.

 import re

 for line in open(infile.txt):
 d = {}
 for k, v1, v2 in re.findall((\w+)=(?:(\w+)|'([^']*)'), line):
 d[k.lower()] = v1 or v2
 print d


How about replacing

d={}

with

d = {'pie': ',', 'quantity': ',', 'cooked': ',', 'price':
',','ingredients': '', 'eol': '\n'}

to get the appropriate commas for missing fields?

Gerard

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


Re: Newbie needs help with regex strings

2005-12-14 Thread Michael Spencer
Dennis Benzinger wrote:
 Christopher Subich schrieb:
 Paul McGuire wrote:

 [...]
 For the example listed, pyparsing is even overkill; the OP should 
 probably use the csv module.
 
 But the OP wants to parse lines with key=value pairs, not simply lines
 with comma separated values. Using the csv module will just separate the 
 key=value pairs and you would still have to take them apart.
 
 Bye,
 Dennis
that, and csv.reader has another problem with this task:

   csv.reader([Pie=peach,quantity=2,ingredients='peaches,powdered sugar'], 
quotechar = ').next()
  ['Pie=peach', 'quantity=2', ingredients='peaches, powdered sugar']

i.e., it doesn't allow separators within fields unless either the *whole* field 
is quoted:

   csv.reader([Pie=peach,quantity=2,'ingredients=peaches,powdered sugar'], 
quotechar = ').next()
  ['Pie=peach', 'quantity=2', 'ingredients=peaches,powdered sugar']
  

or the separator is escaped:

   csv.reader([Pie=peach,quantity=2,ingredients='peaches\,powdered 
sugar'], 
quotechar = ', escapechar = \\).next()
  ['Pie=peach', 'quantity=2', ingredients='peaches,powdered sugar']
  


Michael

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


Re: Python newbie needs help

2005-12-14 Thread Dennis Benzinger
Ron Hudson schrieb:
 [...]
 I have a .py file with some def scripts(?) in it. 

def is the begining of a function definition.

 [...]
 I am using Import to read it after I start an interactive python.  
 What I need
 right now is I seem to have some sort of scoping problems with the  
 world dictionary.
 
 I can read it and write it and worldcr lists it out. but my def  
 look(at): script
 it seems it doesn't see the the world dictionary.
 
   import lets
   world = lets.loadworld()
   world
 {'wizarddescription':'A short guy wearing a robe and a pointy hat'}
   lets.look('wizard')
  file stdin line ?
  file lets.py line 14 in look
 print world[at+'description']
 nameError:world
   at = 'wizard'
   print world[at+'description']
 A short guy wearing a robe and a pointy hat
  
 
 Is there a way to make 'world' global? can I do it in lets.py?
 
 Am I going about this all wrong?
 [...]

The easiest solution for you would be a world variable in your lets 
module. Then at the interactive prompt you could refer to it with 
lets.world. So the loadworld function in lets.py would look like this:

def loadworld():
 # Your loading code
 global world
 world = ...


Bye,
Dennis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie needs help with regex strings

2005-12-14 Thread Michael Spencer
Catalina Scott A Contr AFCA/EVEO wrote:
 I have a file with lines in the following format.
 
 pie=apple,quantity=1,cooked=yes,ingredients='sugar and cinnamon'
 Pie=peach,quantity=2,ingredients='peaches,powdered sugar'
 Pie=cherry,quantity=3,cooked=no,price=5,ingredients='cherries and sugar'
 
 I would like to pull out some of the values and write them to a csv
 file.
 
 For line in filea
   pie = regex
   quantity = regex
   cooked = regex
   ingredients = regex
   fileb.write (quantity,pie,cooked,ingredients)
 
 How can I retreive the values and assign them to a name?
 
 Thank you
 Scott

Here's a trick to parse this source, exploiting the fact that its syntax mimics 
python's keyword arguments.  All that's needed is a way to quote the bare names:

   class lazynames(dict):
  ... def __getitem__(self, key):
  ... if key in self:
  ... return dict.__getitem__(self, key)
  ... return %s % key # if name not found, return it as a str constant
  ...
   d = lazynames(dict=dict, __builtins__ = None)


   source = \
  ... pie=apple,quantity=1,cooked=yes,ingredients='sugar and cinnamon'
  ... Pie=peach,quantity=2,ingredients='peaches,powdered sugar'
  ... Pie=cherry,quantity=3,cooked=no,price=5,ingredients='cherries and sugar'
  ... 
  
   [eval(dict(%s) % line, d) for line in source.splitlines()]
  [{'cooked': 'yes', 'ingredients': 'sugar and cinnamon', 'pie': 'apple', 
'quantity': 1}, {'ingredients': 'peaches,powdered sugar', 'Pie': 'peach', 
'quantity': 2}, {'cooked': 'no', 'price': 5, 'ingredients': 'cherries and 
sugar', 'Pie': 'cherry', 'quantity': 3}]
  

Michael

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


Re: Newbie needs help. Setting PYTHONDOCS to read HTML.

2005-10-11 Thread Brett Hoerner
That's because the Python docs come zipped up within a folder, for
example:

python_docs.tar.bz2 has a folder inside it called Python-Docs-2.4.2.

You need to have C:\Python24\Python-Docs-2.4.2\ as the value if thats
where that folder is, or wherever you unzipped it.  I, personally, just
took all the directories out of Python-Docs-2.4.2 and put them in
C:\Python24\Doc and then added C:\Python24\Doc as the value for
PYTHONDOCS.

Hope that made sense.

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


Re: Newbie needs help. Setting PYTHONDOCS to read HTML.

2005-10-11 Thread moondusterone
Yes it did.  And it worked!  Thank you!


moondusterone


Brett Hoerner [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 That's because the Python docs come zipped up within a folder, for
 example:

 python_docs.tar.bz2 has a folder inside it called Python-Docs-2.4.2.

 You need to have C:\Python24\Python-Docs-2.4.2\ as the value if thats
 where that folder is, or wherever you unzipped it.  I, personally, just
 took all the directories out of Python-Docs-2.4.2 and put them in
 C:\Python24\Doc and then added C:\Python24\Doc as the value for
 PYTHONDOCS.

 Hope that made sense.
 


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


Newbie needs help. Setting PYTHONDOCS to read HTML.

2005-10-10 Thread moondusterone
I have installed Python 2.4.2 from Python.org. I type help() and I get 
basic help.  In help, I type keywords and I get an error saying, Sorry, 
topic and keyword documentation is not available because the Python HTML 
documentation  files could not be found. If you have installed them, please 
set the envirenment variable PYTHONDOCS to indicate their location.  I have 
downloaded them and they are in the same folder with Pythons other files. 
I'm using XP.  I can open the HTML file manually and it opens ok.  Can I use 
Python regardless?  Thanks! 


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


Re: Newbie needs help. Setting PYTHONDOCS to read HTML.

2005-10-10 Thread Ivan Shevanski
You can still use it, but you can't use the help. I don't know but this has always been better than the help for me! =D-- -Ivan
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Newbie needs help. Setting PYTHONDOCS to read HTML.

2005-10-10 Thread Brett Hoerner
You can use Python regardless of the docs... of course.  Not sure what
you mean there.

As far as setting an Environment Variable, though:

(1) Right-Click My Computer, go to Properties

(2) Go to the Advanced tab

(3) Click Environment Variables (bottom middle-ish)

(4) Under User Variables click New,

(5)
Variable name: PYTHONDOCS
Variable value: C:\Python24

Of course, the value needs to be the correct folder that you said you
dropped the HTML docs into.

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


Re: Newbie needs help. Setting PYTHONDOCS to read HTML.

2005-10-10 Thread moondusterone
Brett, I did that and now when I enter keywords I get a list of words. 
And it says that I can enter any of the words to get more help.  I enter 
class and I get could not read docs from C:/Python24/ref/if.html.


Brett Hoerner [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 You can use Python regardless of the docs... of course.  Not sure what
 you mean there.

 As far as setting an Environment Variable, though:

 (1) Right-Click My Computer, go to Properties

 (2) Go to the Advanced tab

 (3) Click Environment Variables (bottom middle-ish)

 (4) Under User Variables click New,

 (5)
 Variable name: PYTHONDOCS
 Variable value: C:\Python24

 Of course, the value needs to be the correct folder that you said you
 dropped the HTML docs into.
 


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


Re: Confused newbie needs help with __init__() takes exactly 11 arguments (1 given)

2005-08-19 Thread [EMAIL PROTECTED]
it looks like your problem is in this line:
reviews = [Review(*[field.strip() for field in row]) for row in reader]

ouch! split that up a bit so we can understand what the heck you are
trying to do here. Also, it appears the whole thing is in these [ ] ?
why?

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


Re: Confused newbie needs help with __init__() takes exactly 11 arguments (1 given)

2005-08-19 Thread [EMAIL PROTECTED]
d'oh I'm an idiot... you are making a 'list' object.

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


Confused newbie needs help with __init__() takes exactly 11 arguments (1 given)

2005-08-18 Thread googleboy
I've written a little script to parse a csv file then use seach/replace
over a template to create a file for each line in the file.  It pikes
out when I call the function that parses the csv (read_revs).  If I
have inadvertantly left an extra comma or two in the comma field, it
gives an error that says:

Traceback (most recent call last):
  File
C:\dev\python\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py,
line 310, in RunScript
exec codeObject in __main__.__dict__
  File d:\dev\python\projects\books\revgen3.py, line 177, in ?
gen_html()
  File d:\dev\python\projects\books\revgen3.py, line 92, in gen_html
revlist =
read_revs(r'D:\library\work\websites\gobooks\cgi\reviews.csv')
  File d:\dev\python\projects\books\revgen3.py, line 38, in read_revs
reviews = [Review(*[field.strip() for field in row]) for row in
reader]
TypeError: __init__() takes exactly 11 arguments (13 given)

Which I understand totally, because I can see the two extra fields in
the csv.  Problem is, if I correct that problem it gives me confusing
output that is identical except for the final line which says:

TypeError: __init__() takes exactly 11 arguments (1 given)

I don't get how it goes from 13 arguments to 1!  I now have 10 fields
and can understand that it is passing self as the 11th argument.

Particularly confusing to me was that when I translated this from a
windows box running Python 2.4 to an OpenBSD box running python 2.3, it
just worked on the unix box.

Find below an the code and an example of the csv file in question.

TIA

googleboy




-
param1,param2,param3,param4,param5,param6,param7,param8,param9,comments
data1,data2,data3,data4,data5,data6,data7,data8,data9,Comments on the
item reviewed go here. Sometime, but not all the time, there might be
extra commas in this text.
data1,data2,data3,data4,data5,data6,data7,data8,data9,Comments on the
item reviewed go here.



--

import string, os, re, sys, operator, csv

class Review(object):
def __init__(self, param1, param2, param3, param4, param5, param6,
param7, param8, param9, comments):
params = locals()
del params['self']
self.__dict__.update(params)
def __repr__(self):
all_items = self.__dict__.items()
return '%s,%s,%s,%s,%s,%s,%s,%s,%s,%s' % (self.param1,
self.param2, self.param3, self.param4, self.param5, self.param6,
self.param7, self.param8, self.param9, self.comments)


def read_revs(filename):
csv_file = open(filename, rb)
reader = csv.reader(csv_file)
reviews = [Review(*[field.strip() for field in row]) for row in
reader]
csv_file.close()
return reviews


def gen_revs():

revlist = read_revs(r'd:\dev\python\projects\books\reviews.csv')
revheader = revlist[0]
all_reviews = revlist[1:]

template = open(r'd:\dev\python\projects\books\template.txt', 'r')
sTemplate = template.read()

for review in all_reviews:
param1 = getattr(review, 'param1')
param2 = getattr(review, 'param2')
param3 = getattr(review, 'param3')
param4 = getattr(review, 'param4')
param5 = getattr(review, 'param5')
param6 = getattr(review, 'param6')
param7 = getattr(review, 'param7')
param9 = getattr(review, 'param8')
param9 = getattr(review, 'param9')
comments = getattr(review, 'comments')

output = template % (param1, param2, param3, param4, param5,
param6, param7, param8, param9, comments)

f=open(rd:\dev\python\projects\books\%s.html % param1, 'w')
f.write(output)
f.close()

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


Re: Confused newbie needs help with __init__() takes exactly 11 arguments (1 given)

2005-08-18 Thread [EMAIL PROTECTED]
That's great, but it seems like a lot of work just to read in
everything. Take a look at the sample that I did with the
interpreter...

First, X is a simulated input line...
---
x = 
param1,param2,param3,param4,param5,param6,param7,param8,param9,comments
blah , blah, test
---
Ok, so just like your first example, with commas in the comments.
Next, let's parse that into the variables and seperate on the commas...
without using the CSV module..
---
param1, param2, param3, param4, param5, param6, param7, param8, param9,
comments = x.split(',',9)
---
Simply, this splits on the commas, up to 9 times. So, no need to fix
your input text. Now, the output...
---
f.write(param1 +   + param2 +   + param3 +   + param4 +   +
param5 +   + param6 +   + param7 +   + param8 +   + param9 + 
 + \ comments + \ + \n)
---
Writes the file, no commas except in the comments, and the comments are
enclosed in quote marks. Also, the line ends in a CR+LF (depending on
O/S).

Is that something similar to what you were looking for? It doesnt look
like your file is properly formatted for CSV, hence I suggest not using
the CSV module. If you want to make your file CSV compatible, it should
have quotation marks around the comments, as they could include commas.

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


Confused newbie needs help with __init__() takes exactly 11 arguments (1 given)

2005-08-18 Thread googleboy
Mostly I posted to try to find out more about the arguments being
passed to __init__,  and why they'd be 13 one second and 1 the next.

I also was hoping to get a little more background on what is happening
under the hood of the csv function I've plagiarised.  I haev read the
online python doco on it, but I am not really entirely sure in my own
head how it is breaking down that csv entry.

I am actually quite familiar with handling strings and lists in python,
though less so with dictionaries.

I did like your trick with telling splut to stop after 9 times.  I
hadn't seen that before.

Thanks for the response.

:-)

Googleboy

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


Re: Confused newbie needs help with __init__() takes exactly 11 arguments (1 given)

2005-08-18 Thread John Machin
googleboy wrote:
 I've written a little script to parse a csv file then use seach/replace
 over a template to create a file for each line in the file.  It pikes
 out when I call the function that parses the csv (read_revs).  If I
 have inadvertantly left an extra comma or two in the comma field, it
 gives an error that says:
 
 Traceback (most recent call last):
   File
 C:\dev\python\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py,
 line 310, in RunScript
 exec codeObject in __main__.__dict__
   File d:\dev\python\projects\books\revgen3.py, line 177, in ?
 gen_html()
   File d:\dev\python\projects\books\revgen3.py, line 92, in gen_html
 revlist =
 read_revs(r'D:\library\work\websites\gobooks\cgi\reviews.csv')
   File d:\dev\python\projects\books\revgen3.py, line 38, in read_revs
 reviews = [Review(*[field.strip() for field in row]) for row in
 reader]
 TypeError: __init__() takes exactly 11 arguments (13 given)
 
 Which I understand totally, because I can see the two extra fields in
 the csv.  Problem is, if I correct that problem it gives me confusing
 output that is identical except for the final line which says:

How do you correct that problem?

 
 TypeError: __init__() takes exactly 11 arguments (1 given)
 
 I don't get how it goes from 13 arguments to 1!  I now have 10 fields
 and can understand that it is passing self as the 11th argument.
 
 Particularly confusing to me was that when I translated this from a
 windows box running Python 2.4 to an OpenBSD box running python 2.3, it
 just worked on the unix box.
 
 Find below an the code and an example of the csv file in question.
 
 TIA
 
 googleboy
 
 
 
 
 -
 param1,param2,param3,param4,param5,param6,param7,param8,param9,comments
 data1,data2,data3,data4,data5,data6,data7,data8,data9,Comments on the
 item reviewed go here. Sometime, but not all the time, there might be
 extra commas in this text.
 data1,data2,data3,data4,data5,data6,data7,data8,data9,Comments on the
 item reviewed go here.
 
 
 
 --
 
 import string, os, re, sys, operator, csv
 
 class Review(object):
 def __init__(self, param1, param2, param3, param4, param5, param6,
 param7, param8, param9, comments):
 params = locals()
 del params['self']
 self.__dict__.update(params)
 def __repr__(self):
 all_items = self.__dict__.items()
 return '%s,%s,%s,%s,%s,%s,%s,%s,%s,%s' % (self.param1,
 self.param2, self.param3, self.param4, self.param5, self.param6,
 self.param7, self.param8, self.param9, self.comments)
 
 
 def read_revs(filename):
 csv_file = open(filename, rb)
 reader = csv.reader(csv_file)
 reviews = [Review(*[field.strip() for field in row]) for row in
 reader]

   so that you can see what you are actually getting as the 1 
argument instead of guessing, try some diagnostics:

reviews = []
for row in reader:
args = [field.strip() for field in row]
print row, repr(row)
print args, repr(args)
reviews.append(Review(*args))

 csv_file.close()
 return reviews
 
 
 def gen_revs():
 
 revlist = read_revs(r'd:\dev\python\projects\books\reviews.csv')
 revheader = revlist[0]
 all_reviews = revlist[1:]
 
 template = open(r'd:\dev\python\projects\books\template.txt', 'r')
 sTemplate = template.read()
 
 for review in all_reviews:
 param1 = getattr(review, 'param1')
 param2 = getattr(review, 'param2')
 param3 = getattr(review, 'param3')
 param4 = getattr(review, 'param4')
 param5 = getattr(review, 'param5')
 param6 = getattr(review, 'param6')
 param7 = getattr(review, 'param7')
 param9 = getattr(review, 'param8')
 param9 = getattr(review, 'param9')
 comments = getattr(review, 'comments')
 
 output = template % (param1, param2, param3, param4, param5,
 param6, param7, param8, param9, comments)
 
 f=open(rd:\dev\python\projects\books\%s.html % param1, 'w')
 f.write(output)
 f.close()
 
-- 
http://mail.python.org/mailman/listinfo/python-list


FW: python oldie, SWIG newbie needs help

2005-08-16 Thread Sells, Fred


-Original Message-
From: Sells, Fred 
Sent: Tuesday, August 16, 2005 5:09 PM
To: python-list@python.org
Subject: python oldie, SWIG newbie needs help 


I've been trying all day to get a simple SWIG generated interface to a
simple (but ugly) piece of c++ code provided to us by the gov't.  I've tried
google, and every variation on the examples I can think of.  I'm really
under the gun to get this working and would appreciate someone showing me
the error of my ways.  We're running python 2.3 redhat 9 and gcc

although the code is c++, it does not use classes and the only function I
need to access is RugCacl.

My typical error messages are shown below and the files attached.  I've
tried SWIG with and without --shadow.  If my last line of the .i file is
%include rug520.cpp, I don't get an error on import, but the RugCalc
function is undefined.

$ python rug520.py
Traceback (most recent call last):
  File rug520.py, line 5, in ?
import _rug520
ImportError: /home/frsells/dll/_rug520.so: undefined symbol: RugCalc


part of the c++ code is below; the whole file was bigger than the mail
handler would accept.

#include rug520.h
#include stdio.h
#include stdlib.h
#include string.h
#include ctype.h
#define LINUX

char masItemVal[108][5];

void LoadValue( char * sMdsRecord, int location, int length, char *
masItemValue ) 
{  
   for ( int i=0; ilength; i++ ) masItemValue[i] = sMdsRecord[location+i];
   masItemValue[length] = '\0';
}

int LoadRange() 

.
#ifdef LINUX
int RugCalc( char * sMdsRecord, char * sRehabType, char * sModel, int
iQuarterlyFlag, 
 double nCmiArray[], char * sRugHier, char *
sRugMax, int * iRugHier,
 int * iRugMax, double * nCmiValueHier, double *
nCmiValueMax, 
 int * iAdlSum, int * iCpsCode, char * sRugsVersion,
char * sDllVersion, 
 int * iError )
#else

extern C __declspec(dllexport) int __stdcall 
RugCalc( char * sMdsRecord, char * sRehabType, char * sModel, int
iQuarterlyFlag, 
 double nCmiArray[], char * sRugHier, char *
sRugMax, int * iRugHier,
 int * iRugMax, double * nCmiValueHier, double *
nCmiValueMax, 
 int * iAdlSum, int * iCpsCode, char * sRugsVersion,
char * sDllVersion, 
 int * iError )
#endif

---
The information contained in this message may be privileged and / or
confidential and protected from disclosure. If the reader of this message is
not the intended recipient, you are hereby notified that any dissemination,
distribution or copying of this communication is strictly prohibited. If you
have received this communication in error, please notify the sender
immediately by replying to this message and deleting the material from any
computer.
---


build.sh
Description: Binary data


rug520.h
Description: Binary data


rug520.i
Description: Binary data
-- 
http://mail.python.org/mailman/listinfo/python-list

Newbie needs help with canvas.create_image !

2005-02-12 Thread Antti Isomursu
Ok, this is my problem:
With code below I get a red box with given width and height. When I
use that create_image, nothing happens. I only see that same red box.
Why is that?
The loop.bmp is working fine when I use show() method.

win = Toplevel() 

canvas = Canvas(win, width=100, height=100, background='red')
canvas.pack()

im = Image.open(loop.bmp)
photo = ImageTk.PhotoImage(im)
 
canvas.create_image(8, 8, anchor=nw, image=photo)
   
(Interestingly loop.bmp appears to the red box if I try to pack that
canvas.create_image ( canvas.create_image.pack()) and ofcourse I also
get an error message that It can't be done. But anyway the picture
appears ...weird)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie needs help with canvas.create_image !

2005-02-12 Thread Fredrik Lundh
Antti Isomursu wrote:

 With code below I get a red box with given width and height. When I
 use that create_image, nothing happens. I only see that same red box.
 Why is that?
 The loop.bmp is working fine when I use show() method.

win = Toplevel()

canvas = Canvas(win, width=100, height=100, background='red')
canvas.pack()

im = Image.open(loop.bmp)
photo = ImageTk.PhotoImage(im)

canvas.create_image(8, 8, anchor=nw, image=photo)

the problem might be that the PhotoImage is garbage collected before being
displayed.  see the note on the bottom of this page for details:

http://effbot.org/zone/tkinter-photoimage.htm

/F 



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


Re: Newbie needs help with canvas.create_image !

2005-02-12 Thread Arthur
On Sat, 12 Feb 2005 18:24:11 +0100, Fredrik Lundh
[EMAIL PROTECTED] wrote:

Antti Isomursu wrote:

 With code below I get a red box with given width and height. When I
 use that create_image, nothing happens. I only see that same red box.
 Why is that?
 The loop.bmp is working fine when I use show() method.

win = Toplevel()

canvas = Canvas(win, width=100, height=100, background='red')
canvas.pack()

im = Image.open(loop.bmp)
photo = ImageTk.PhotoImage(im)

canvas.create_image(8, 8, anchor=nw, image=photo)

the problem might be that the PhotoImage is garbage collected before being
displayed.  see the note on the bottom of this page for details:

http://effbot.org/zone/tkinter-photoimage.htm

/F 

I had run into this for the first time recently as well.

and found this tutor thread helped.

http://starship.python.net/pipermail/python-de/2002q4/002834.html

Declaring im as global is one way to go (there I said it). In fact,
IMO, probably the clearest (though not the prettiest) way to go under
under the circumstances.  

I don't think anyone is particularly defending the circumstances. I
have heard the circumstances described as a bug, and the various
solutions  are perhaps better thought of as work-arounds.

Art




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