Re: UnicodeDecodeError, how to elegantly deal with this?

2008-08-05 Thread Jorgen Bodde
Hi Edwin,

Filemask is obvious as it is assigned in the python code itself. It is
%file%. The idea is that the file clicked is substituted for the
%file% by the replace action. The file that needs to be substituted
is a simple file on disk.

Here is a dump of the file and it's characters. I do understand that
it is not in the range of ASCII but how can I make it so that it will
work?

E:\Series\Series\American Dad\American Dad - S03E15 - Stanny Slickers II, 
The Legend of OllieÂŽs Gold.avi

E (69): (58)\ (92)S (83)e (101)r (114)i (105)e (101)s (115)\ (92)S
(83)e (101)r (114)i (105)e (101)s (115)\ (92)A (65)m (109)e (101)r
(114)i (105)c (99)a (97)n (110)  (32)D (68)a (97)d (100)\ (92)A (65)m
(109)e (101)r (114)i (105)c (99)a (97)n (110)  (32)D (68)a (97)d (100)
 (32)- (45)  (32)S (83)0 (48)3 (51)E (69)1 (49)5 (53)  (32)- (45)
(32)S (83)t (116)a (97)n (110)n (110)y (121)  (32)S (83)l (108)i
(105)c (99)k (107)e (101)r (114)s (115)  (32)I (73)I (73), (44)  (32)T
(84)h (104)e (101)  (32)L (76)e (101)g (103)e (101)n (110)d (100)
(32)o (111)f (102)  (32)O (79)l (108)l (108)i (105)e (101)Â (194)Ž
(180)s (115)  (32)G (71)o (111)l (108)d (100). (46)a (97)v (118)i
(105)Traceback (most recent call last):

  File D:\backup\important\src\airs\gui\AirsFrame.py, line 575, in
_onWebRequest

webdispatch.execute(cmd, id, args)

  File D:\backup\important\src\airs\webserver\webdispatch.py, line
167, in execute

_cmd_dispatcher[cmd](cb, args)

  File D:\backup\important\src\airs\webserver\webdispatch.py, line
122, in playFile

therep = arg.replace(filemask, thefile)

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position
93: ordinal not in range(128)



I assume it is about this part:

 OllieÂŽs Gold.avi

But what can I do to decode that properly?

With regards,
- Jorgen




On Mon, Aug 4, 2008 at 8:46 PM,  [EMAIL PROTECTED] wrote:
 if you can print out values  of 'filemask', and 'thefile' variables, when it 
 crashes, I can help.

 thx. Edwin

 -Original Message-
 From: [EMAIL PROTECTED]
 [mailto:[EMAIL PROTECTED]
 On Behalf Of Jorgen Bodde
 Sent: Monday, August 04, 2008 2:24 PM
 To: python-list@python.org
 Subject: UnicodeDecodeError, how to elegantly deal with this?


 Hi All,

 I am relatively new to python unicode pains and I would like to have
 some advice. I have this snippet of code:

 def playFile(cmd, args):
argstr = list()
for arg in appcfg.options[appcfg.CFG_PLAYER_ARGS].split():
thefile = args[file]
filemask = u%file%
therep = arg.replace(filemask, thefile)   # error here
argstr.append(therep)
argstr.insert(0, appcfg.options[appcfg.CFG_PLAYER_PATH])

try:
subprocess.Popen( argstr )
except OSError:
cmd.html = h1Can't play file/h1/br + args[file]
return

cmd.redirect = _getBaseURL(series?cmd_get_series=%i % args[id])
cmd.html = 

 ---

 It crashes on this:

 20:03:49:   File
 D:\backup\important\src\airs\webserver\webdispatch.py, line 117, in
 playFile therep = arg.replace(filemask, thefile)

 20:03:49: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in
 position 93: ordinal not in range(128)

 20:03:49: Unhandled Error: type 'exceptions.UnicodeDecodeError':
 'ascii' codec can't decode byte 0xc2 in position 93: ordinal not in
 range(128)

 It chokes on a ` character in a file name. I read this file from disk,
 and I would like to play it. However in the replace action it cannot
 translate this character. How can I transparently deal with this issue
 because in my eyes it is simply replacing a string with a string, and
 I do not want to be bothered with unicode problems. I am not sure in
 which encoding it is in, but I am not experienced enough to see how I
 can solve this

 Can anybody guide me to an elegant solution?

 Thanks in advance!
 - Jorgen
 --
 http://mail.python.org/mailman/listinfo/python-list



 The information contained in this message and any attachment may be
 proprietary, confidential, and privileged or subject to the work
 product doctrine and thus protected from disclosure.  If the reader
 of this message is not the intended recipient, or an employee or
 agent responsible for delivering this message to 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 me
 immediately by replying to this message and deleting it and all
 copies and backups thereof.  Thank you.


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

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


Re: UnicodeDecodeError, how to elegantly deal with this?

2008-08-05 Thread Jorgen Bodde
Hi John,

 If you don't want to be bothered with unicode problems:
 (1) Don't create a unicode problem when one doesn't exist.
 (2) Don't bother other people with *your* unicode problems.

Well I guess you misunderstood what I meant. I meant I am a simple
developer, getting a string from the file system that happens to be in
some kind of encoding. It is totally a mystery to me why it crashes on
that so that is what I meant with not wanted to be bothered with it,
because I don't see any obvious reason why, not that I am too lazy to
deal with it, it simply seems strange to me.

 In this case, less is more; remove the u prefix in the line
filemask = u%file%

Ok thanks. I thought making it unicode because it is a search string
that is used in a UTF-8 encoded replacement, would solve it,

 Long Path:
 Ignorance is not bliss. Lose the attitude. Unicode is your friend, not
 an instrument of Satan. Read this:
http://www.amk.ca/python/howto/unicode

I never said that I have an attitude towards unicode, I simply
misunderstood it's inner workings. Thanks for the link I will look at
it.

ps. sorry for the direct mail, I can't get used to one mailinglist
always replying to the list, and the other replying to the user by
default ;-)

With regards,
- Jorgen

On Tue, Aug 5, 2008 at 11:00 AM, John Machin [EMAIL PROTECTED] wrote:
 On Aug 5, 4:23 am, Jorgen Bodde [EMAIL PROTECTED] wrote:
 Hi All,

 I am relatively new to python unicode pains and I would like to have
 some advice. I have this snippet of code:

 thefile = args[file]
 filemask = u%file%
 therep = arg.replace(filemask, thefile)   # error here


 It crashes on this:

 20:03:49:   File
 D:\backup\important\src\airs\webserver\webdispatch.py, line 117, in
 playFile therep = arg.replace(filemask, thefile)

 20:03:49: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in
 position 93: ordinal not in range(128)

 20:03:49: Unhandled Error: type 'exceptions.UnicodeDecodeError':
 'ascii' codec can't decode byte 0xc2 in position 93: ordinal not in
 range(128)

 It chokes on a ` character in a file name. I read this file from disk,
 and I would like to play it. However in the replace action it cannot
 translate this character. How can I transparently deal with this issue
 because in my eyes it is simply replacing a string with a string, and
 I do not want to be bothered with unicode problems. I am not sure in
 which encoding it is in, but I am not experienced enough to see how I
 can solve this

 If you don't want to be bothered with unicode problems:
 (1) Don't create a unicode problem when one doesn't exist.
 (2) Don't bother other people with *your* unicode problems.


 Can anybody guide me to an elegant solution?


 Short path:
 In this case, less is more; remove the u prefix in the line
filemask = u%file%

 Long Path:
 Ignorance is not bliss. Lose the attitude. Unicode is your friend, not
 an instrument of Satan. Read this:
http://www.amk.ca/python/howto/unicode

 By the way, how one's filesystem encodes file names can be a good
 thing to know; in your case it appears to be UTF-8.

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

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


UnicodeDecodeError, how to elegantly deal with this?

2008-08-04 Thread Jorgen Bodde
Hi All,

I am relatively new to python unicode pains and I would like to have
some advice. I have this snippet of code:

def playFile(cmd, args):
argstr = list()
for arg in appcfg.options[appcfg.CFG_PLAYER_ARGS].split():
thefile = args[file]
filemask = u%file%
therep = arg.replace(filemask, thefile)   # error here
argstr.append(therep)
argstr.insert(0, appcfg.options[appcfg.CFG_PLAYER_PATH])

try:
subprocess.Popen( argstr )
except OSError:
cmd.html = h1Can't play file/h1/br + args[file]
return

cmd.redirect = _getBaseURL(series?cmd_get_series=%i % args[id])
cmd.html = 

---

It crashes on this:

20:03:49:   File
D:\backup\important\src\airs\webserver\webdispatch.py, line 117, in
playFile therep = arg.replace(filemask, thefile)

20:03:49: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in
position 93: ordinal not in range(128)

20:03:49: Unhandled Error: type 'exceptions.UnicodeDecodeError':
'ascii' codec can't decode byte 0xc2 in position 93: ordinal not in
range(128)

It chokes on a ` character in a file name. I read this file from disk,
and I would like to play it. However in the replace action it cannot
translate this character. How can I transparently deal with this issue
because in my eyes it is simply replacing a string with a string, and
I do not want to be bothered with unicode problems. I am not sure in
which encoding it is in, but I am not experienced enough to see how I
can solve this

Can anybody guide me to an elegant solution?

Thanks in advance!
- Jorgen
--
http://mail.python.org/mailman/listinfo/python-list


Re: Very weird bug!

2008-07-08 Thread Jorgen Bodde
Maybe the interpreter remembered the values of some objects you used?
If you type in the interpreter, the objects you create have a lifetime
as long as the interpreter is active, which means it can get a state
behaviour that otherwise is not present if you start a new interpreter
instance. To be safe you should always try it with a script and run it
from the commandline to get the same 'state' everytime your script
runs.

- Jorgen


On Mon, Jul 7, 2008 at 7:36 PM, ssecorp [EMAIL PROTECTED] wrote:
 i know, idid try it again and it works as expected. but how the h***
 did it not work that one time?
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: Send output to printer

2008-06-25 Thread Jorgen Bodde
Hi,

It depends on how your printer can be accessed. Is there a driver for
it? The most simple way might be using ShellExecute (under windows)
but I found  no way to supress the print dialog.

Another way is using win32com module and instantiate an IE automation
object, which you feed a HTML page and issue a print. Be careful about
printing too fast allow it 4-5 seconds to process or successive print
jobs will fail.

Here is a snippet of code to get you on your way;

from win32com import client
ie = client.Dispatch(InternetExplorer.Application)
ie.Navigate(fn)  # fn = filename (to temp file) to print
time.sleep(2)
ie.ExecWB(6, 2)
time.sleep(2)
ie.Quit()
ie = None

For successive prints it is better to instantiate one IE object per
multiple print jobs, but once done, release it and set it up again.

- Jorgen






On Wed, Jun 25, 2008 at 6:54 AM, ajak_yahoo [EMAIL PROTECTED] wrote:
 Need some help from you all,

 I already manage to write a program to print a packaging label.

 The output on screen is as below,


 Part Number   :  PWEEAA
 Quantity :  100 pcs
 Lot Number :  10A2008
 Customer:  ABC Pte. Ltd.


 My questions is how can I send this output to my Panasonic KX-P1121 dot
 matric printer,
 Is it a module that i can used, previously i wrote my program using foxpro
 2.6, i have no experience in python.


 Regards,
 Ajak
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Print HTML from Python

2008-05-21 Thread Jorgen Bodde
Hi All,

I am at a loss. This is slightly OT because it concerns Windows and
HTML printing. I would like to print a HTML document from Python, but
not showing the printing dialog. After numerous searches and trials I
came to the conclusion that ShellExecute with the print command and
a HTML document simply always shows a print dialog, so that road is a
dead end (or unless someone can show me a snippet that does work).

I used win32com and I am able to print through he internet explorer
interface which seems to work, but quite unreliably. When I execute
the scipt too fast, nothing is printed at all. The method isBusy that
IE exposes through COM always returns False so there is no way to wait
reliably on the progress of the printer.

So basically my question is, does someone know a python lib or way to
print HTML to the default printer (I can get the printer name so even
that is not really needed) without showing the print dialog?

With regards,
- Jorgen
--
http://mail.python.org/mailman/listinfo/python-list


comtypes question

2008-03-17 Thread Jorgen Bodde
Hi All,

I am trying to automate a 3rd party application, and all I have to
work on is the type library and some documentation. I hope a Python /
COM guru can answer this or put me on the right path because I don't
know why it does not work.

First I imported the typelib with comtypes like;

 from comtypes.client import GetModule
 GetModule(C:\\Program Files\\Seagull\\BarTender\\8.0\\bartend.exe)

Which blurbs out a lot of text:

# Generating comtypes.gen._D58562C1_E51B_11CF_8941_00A024A9083F_0_8_1
# Generating comtypes.gen.BarTender
module 'comtypes.gen.BarTender' from
'C:\Python24\lib\site-packages\comtypes\gen\_D58562C1_E51B_11CF_8941_00A024A9083F_0_8_1.pyc'

Which seems to be ok. Now, I need to call a function on the
Application object on which I need a Messages instance. The
Application object gets created properly:

 import comtypes.gen.Bartender as bt
 app = comtypes.client.CreateObject(bt.Application)

Which gives me the application (the bt.Application points to a wrapper
class containing the CLSID of the COM class to be instantiated).

Now I browse the typelibrary and I see there is a CoClass called
Messages. I need one of those to pass as an argument, and since
Messages is listed as a CoClass similar to Application, I assume it
can also be instantiated. But when I try this I get an error:

 msgs = cc.CreateObject('{2B52174E-AAA4-443D-945F-568F60610F55}')
Traceback (most recent call last):
  File interactive input, line 1, in ?
  File C:\Python24\Lib\site-packages\comtypes\client\__init__.py,
line 198, in CreateObject
obj = comtypes.CoCreateInstance(clsid, clsctx=clsctx, interface=interface)
  File C:\Python24\Lib\site-packages\comtypes\__init__.py, line 931,
in CoCreateInstance
_ole32.CoCreateInstance(byref(clsid), punkouter, clsctx,
byref(iid), byref(p))
  File source/callproc.c, line 757, in GetResult
WindowsError: [Errno -2147221164] Class not registered

Both Application and Messages are listed as CoClass inside the
typelibrary. Does anybody know  why it gives me this error and what I
am doing wrong? I have a COM Delphi background, and it would be
similar to:

msgs := CoMessages.Create;
... if the TLB is imported properly.

Here is the details of the Application CoClass:

[
  uuid(B9425246-4131-11D2-BE48-004005A04EDF)
]
coclass Application {
[default] interface IBtApplication;
dispinterface DBtApplication;
};

And here is one from the Messages CoClass (as you can see the GUID matches):

[
  uuid(2B52174E-AAA4-443D-945F-568F60610F55)
]
coclass Messages {
[default] interface IBtMessages;
dispinterface DBtMessages;
};

Regards,
- Jorgen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: comtypes question

2008-03-17 Thread Jorgen Bodde
Hi Thomas,

Thank you a lot for going through great lenghts to help me. I am
relatively new to COM and to python, so using those two together is
sometimes watching water burn and be totally amazed by it ;-)

It's greatly aprpeciated that you installed the app and even checked
out the typelib to see what might go wrong. I will investigate furter
and look at your working example to see what I was missing in my code.

I will also subscribe to the comtypes-users mailinglist for future questions.

ps. For background info about Bartender, it is a label application and
it can be automated by COM. By sending an XML script to it, I can set
the variables for that label and issue a print command.

With kind regards,
- Jorgen

On Mon, Mar 17, 2008 at 12:58 PM, Thomas Heller [EMAIL PROTECTED] wrote:
 Jorgen Bodde schrieb:


  Hi All,
  
   I am trying to automate a 3rd party application, and all I have to
   work on is the type library and some documentation. I hope a Python /
   COM guru can answer this or put me on the right path because I don't
   know why it does not work.
  
   First I imported the typelib with comtypes like;
  
   from comtypes.client import GetModule
   GetModule(C:\\Program Files\\Seagull\\BarTender\\8.0\\bartend.exe)
  
   Which blurbs out a lot of text:
  
   # Generating comtypes.gen._D58562C1_E51B_11CF_8941_00A024A9083F_0_8_1
   # Generating comtypes.gen.BarTender
   module 'comtypes.gen.BarTender' from
   
 'C:\Python24\lib\site-packages\comtypes\gen\_D58562C1_E51B_11CF_8941_00A024A9083F_0_8_1.pyc'
  
   Which seems to be ok. Now, I need to call a function on the
   Application object on which I need a Messages instance. The
   Application object gets created properly:
  
   import comtypes.gen.Bartender as bt
   app = comtypes.client.CreateObject(bt.Application)
  
   Which gives me the application (the bt.Application points to a wrapper
   class containing the CLSID of the COM class to be instantiated).
  
   Now I browse the typelibrary and I see there is a CoClass called
   Messages. I need one of those to pass as an argument, and since
   Messages is listed as a CoClass similar to Application, I assume it
   can also be instantiated. But when I try this I get an error:
  
   msgs = cc.CreateObject('{2B52174E-AAA4-443D-945F-568F60610F55}')

  [...]


   WindowsError: [Errno -2147221164] Class not registered
  
   Both Application and Messages are listed as CoClass inside the
   typelibrary. Does anybody know  why it gives me this error and what I
   am doing wrong?

  Not all coclasses can be created from scratch with CreateObject.  Sometimes
  they are created by calls to methods on some other object.
  I downloaded the bartender trial, and looking into the typelib it seems that,
  for example, the 'XMLScript' method on the IBtApplication interface returns
  Messages instances:
 COMMETHOD([dispid(17), helpstring(u'Runs xml scripts')], HRESULT, 
 'XMLScript',
   ( ['in'], BSTR, 'XMLScript' ),
   ( ['in'], BtXMLSourceType, 'SourceType' ),
   ( ['out'], POINTER(POINTER(Messages)), 'Messages' ),
  
   ( ['retval', 'out'], POINTER(BSTR), 'retval' )),

  Here is an interactive session:

  Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] 
 on win32
  Type help, copyright, credits or license for more information.
   from comtypes.gen import BarTender
   from comtypes.client import CreateObject
   app = CreateObject(BarTender.Application)
   print app
  POINTER(IBtApplication) ptr=0x277074 at 11f0a30
   app.XMLScript(foo, 0)
  (POINTER(IBtMessages) ptr=0x27b354 at 125bb70, u'')
   msg, retval = app.XMLScript(foo, 0)
   print msg
  POINTER(IBtMessages) ptr=0x275a54 at 125bc10
   msg[0]

 Traceback (most recent call last):
   File stdin, line 1, in module
   File comtypes\__init__.py, line 308, in __getitem__
 result = self.Item(index)
  _ctypes.COMError: (-2147220992, None, (u'The item at position 0 was not 
 found.', u'bartend', None, 0, None))
   msg[1]
  POINTER(IBtMessage) ptr=0x276ffc at 125bc60
   m = msg[1]
   print m
  POINTER(IBtMessage) ptr=0x276ffc at 125bcb0
   m.Number
  3908
   m.Message
  uAn error occurred during XML script processing:\r\n\r\nInvalid at the top 
 level of the document.\r\nLine 1, Column 1:
  'foo'
   ^Z

  Not that the above makes much sense, but I hope it will get you started.

  Thomas

  BTW:  The 'official' comtypes mailing list is at
  https://lists.sourceforge.net/lists/listinfo/comtypes-users.  Requires that 
 you subscribe before you can
  post, but you could disable mail delivery and use via gmane: 
 gmane.comp.python.comtypes.user

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

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


Re: Small problem executing python script as shortcut

2008-02-08 Thread Jorgen Bodde
Hi Larry,

Sorry for accidentally mailing you personally. I fixed the problem, it
was a problem with the search path, and once that was fixed it works
fine!

thanks again,
- Jorgen

On Feb 8, 2008 9:26 AM, Jorgen Bodde [EMAIL PROTECTED] wrote:
 Hi Larry,

  Sure there is.  Just put double quotes around the entire Target and Start in
  entries in the shortcut.

 That is exacty the problem. The shortcut (if dropped on the start menu
 even by hand or by Inno Installer) already has those quotes. Still, it
 is mpossible to launch a python script that way so it seems.

  Example:
  Target:C:\Program Files\WebSafe\WStools\WSsend.exe
  Start in:  C:\Program Files\WebSafe\WStools\

 As I already explained, the windows shortcut is already formatted like that

  1) Download Inno Installer and wrap your distribution into a proper 
  installation
  (setup.exe) program.  It takes care of all this for you.

 it's actually the same with inno setup. A python script like
 c:\Program Files\app\app.py won't start. Could you please verify this
 for me? Simply make a subdir in Program Files and put a python script
 in there. Then drag and drop this script as a shortcut on the start
 menu. Then try to execute it. This does not seem to work

  2) Take a look at py2exe to bundle your entire application up so that you 
  don't
  need python on the machine at all.

 Like explained, I would like to offer both. Source based install and
 exe based, so people who are into python can view the code, and
 contribute if needed. I always like it when I get the choice to modify
 the app when there are small issues with it that I can easly resolve.

 thanks for your reply!
 - Jorgen


 
  Hope info helps.
 
  -Larry
  --
  http://mail.python.org/mailman/listinfo/python-list
 

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


Small problem executing python script as shortcut

2008-02-07 Thread Jorgen Bodde
Hi all,

This is slightly OT but it drives me nuts. Whenever I create a
shortcut in the start menu (in Windows) of a python script, it will
only execute it when the path where the script resides in contains no
spaces. For example;

d:\src\app\app.py

If I drag that to the Start Menu it can be executed fine.

Whenever I distribute my app and the path will become:

c:\program files\app\app.py

Windows will make spaces itself inside the shortcut so I guess it
realizes that it needs to execute the full string but probably
somewhere when resolving the app to execute the script with, the
double quotes get lost and the python interpreter (I use ActiveState
as my Python bundle) will only see c:\program as the first part and
doesn't pick up the latter.

I know I can write a batch script that runs the python script, but
since it is a wxPython app, I want to launch a *.pyw to suppress the
dos box. However as it seems now there is no way to create a shortcut
under windows to launch a python script when the directory contains
spaces in the name.

Does anyone know a solution? I would like to distribute my app both
with py2exe (no problems there) but also as source only version so
people can adjust the code if they wish.

Regards,
- Jorgen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: where do my python files go in linux?

2008-01-16 Thread Jorgen Bodde
Hi All,

Sorry for the late reply back, I had a busy weekend ... it seems there
is no clear way to do it and maybe that is why I was / am so confused.

Eventually I searched for *.py files, and like I said most apps seem
to install in /usr/share/{app} I believe that location is for data
only that is shared between users. But for simplicity's sake I put my
whole python application in there. It saves me setting a lot of paths
differently.

I made a symbolic link in /usr/bin that points to /usr/share/{app}/{app}.py

This all seems to work fine. When I am getting more experienced with
Debian / Ubuntu and linux overall, I will re-evaluate this and see if
I can improve it.

Thanks all for your answer,
- Jorgen

On Jan 14, 2008 4:30 PM, Nick Craig-Wood [EMAIL PROTECTED] wrote:
 Paul Boddie [EMAIL PROTECTED] wrote:
   On 14 Jan, 08:47, A.T.Hofkamp [EMAIL PROTECTED] wrote:
  
   Rather than re-inventing the wheel, please have a look at distutils:
   http://docs.python.org/lib/module-distutils.html
  
   It does most if not all of the things you want to do.
   If you want something more advanced, read about eggs.
 
   Although distutils does some of the work needed by the inquirer, it
   falls far short of what is needed to make a Debian package - that's
   why you have the new Debian Python policy and why the authors
   specifically refer to both distutils and setuptools in that document.

 It would be nice to have an equivalent to dh-make-perl which takes a
 CPAN module and makes a .deb directly.

   http://packages.debian.org/stable/devel/dh-make-perl

 What I usually do is

 python setup.py bdist_rpm

 Then use alien to convert the resulting .rpm into a .deb

 I don't think these create particularly policy compliant .debs but
 they are good enough for local usage.

   Meanwhile, even stdeb [1] doesn't appear to completely automate the
   production of Debian packages using distutils.

 Looks interesting though!

   [1] http://stdeb.python-hosting.com/

 --
 Nick Craig-Wood [EMAIL PROTECTED] -- http://www.craig-wood.com/nick
 --

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

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


where do my python files go in linux?

2008-01-12 Thread Jorgen Bodde
Hi All,

I am trying to make a debian package. I am following the tutorial by
Horst Jens 
(http://showmedo.com/videos/video?name=linuxJensMakingDebfromSeriesID=37)
and it is very informative. However one thing my app has and his
doesn't, is multiple python files which need to be executed. For
example

{dir}/app
app.py

app.py calls a lot of modules in {dir}/app. Horst says the python file
goes in /usr/bin/app.py which is ok with me, but I have multiple
python files, and I decided to use an app.sh script to call my python
files. In the /usr/bin I do not see subdirs so I assume that is not
really desirable.

Question 1. Where do I put the bulk of python scripts in a normal
linux environment?
Question 2. Should I use *.pyc rather then *.py files to speed up
executing as the user cannot write to /usr/bin or any other dir in the
system and everytime my app runs it will recompile it

Thanks for any advice or maybe a good tutorial how to set up files in
a linux environment

With regards,
- Jorgen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: where do my python files go in linux?

2008-01-12 Thread Jorgen Bodde
Hi Jeroen,

Thanks for the advice.

 Personally I'd be loathe to put app.py in /usr/bin. This directory is normally
 reserved for OS-specific binaries. For personal/system-extended stuff I'd use
 /usr/local/bin or whatever your system mandates. (But hey, that's the typical
 mentality difference between the BSD and Linux world it seems, so do with it
 what you want.)

I thought about that too. I just wonder why /usr/local/bin is always
empty and every .deb I install from a source (if it's from Ubuntu or
not) installs files in /usr/bin .. So I looked further and noticed
that most python files do reside in /usr/share/{appname}

 Normally you'd split up the bulk of the code into a module which gets
 installed into site-packages and a piece of stand-alone front-end code which
 imports the module and executes whatever you need to do and gets installed
 into a typical PATH directory.

I would agree but it is not a site package I am trying to distribute,
but a wxPython application. I would not think my app belongs in the
python site packages dir.

Thanks a lot for the input!

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


Re: Web update library in python?

2007-11-21 Thread Jorgen Bodde
Thanks everybody,

You gave me plenty of information to go on and look for something that
might give me a sound and solid solution to my problem!
I will look into bzr I've heard good things about it, and maybe I can
use it in my app!

Regards,
- Jorgen

On Nov 21, 2007 9:05 AM, A.T.Hofkamp [EMAIL PROTECTED] wrote:
 On 2007-11-20, Diez B. Roggisch [EMAIL PROTECTED] wrote:
  Jorgen Bodde wrote:
 
  Hi, A.T.Hofkamp (sorry for not knowing your first name ;-),

 Well Jorgen, it is at the bottom of each post (usually)... ;-)

  SCM sounds like a term I can google for, if the tool needed is very
  easy to install, maybe even accompany with my application to run as a
  service for the updating, it is worth a try to find something that can
  handle the synchronizing of distributed repositories.
 
  Talking a bit more about it and hearing various solutions gave me more
  insight in how it might be solved. Thanks everybody for your input!
 
  SCM mean source code management - like SVN or CVS.
 
  Diez

 Diez is right, except my choice of the phrase 'SCM' was not exactly right. SCM
 is a general term for two kinds of activities, namely version control (VC) and
 configuration control.
 VC is what everybody does with SVN, CVS, darcs, bzr, git, mercurial, etc in 
 the
 context of software development (hence these tools are known as version 
 control
 systems (VCS)).

 You may want to add 'distributed' to your search term.


 Configuration management is much less often done. It is about controlling
 deployment of some system or software. Imagine you are managing a few
 (hundreds) of web sites. They all use LAMP, but exactly what Apache, Py-Mod,
 Linux, hardware, is different each time. This of course also holds for the
 various initialization and configuration files.
 Keeping track of this data over time is called configuration management.
 (and if you think this is complicated, consider what Boeing is doing for all
 its air-planes... :) ).


  SVN isn't distributed, but AFAIK darcs is.
 

 As Diez already guessed, SVN and CVS are organized around a central 
 repository,
 darcs, bzr, git, and mercurial do not need a central repository (although they
 often can handle one if the project wants it).

 The nice thing is that at least bzr and mercurial are written in Python!!


 What I found very enlightening was to find the web-site of these tools, and
 then read the docs about their strong and weak points w.r.t. their 
 competitors.
 Of course each of these is biased, but if you read them all, it kind of
 balances out :)
 Also, they all explain what their world model is, you should check whether 
 that
 matches with your problem.

 Good luck with your search,
 Albert


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

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


Web update library in python?

2007-11-20 Thread Jorgen Bodde
Hi all,

I want to provide my users the ability to download a repository from
the web, and after that check for updates. I thought of a mechanism
that could do that, but since there is patch and diff readily
available I wondered if there is a python solution that allows me to
download a file, and let the patch be applied locally. In the patch
there are binaries and sources I am not sure if patch can handle them
both though.

So here are the situations;

Downloading
1. User enters URL and local path where to store
2. Updated downloads the file
3. Either creates a new repository or patches an existing one

Check for updates
1. A web check is done if there is a newer version
2. File is downloaded, patch is applied

Plain zip file extraction is possible, but I will miss out on files
that might be deleted in future versions, but not yet on the client
side. Also local changes might need to be preserved although it is not
a show stopper if it doesn't.

I want to have a solution that is very easy for the user, so point and
click kind of work. Is there a tool / library around that can provide
me a base for this problem?

Thanks in advance!
- Jorgen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Web update library in python?

2007-11-20 Thread Jorgen Bodde
Hi All,

Thanks for the input. Concering 'egg' it's not a web update for python
per-ce but it should be written in python to easily interface with
(wx)Python. As I believe it 'egg' is only a dependency downloader and
installer for python scripts right?

As for subversion, this is not possible as I want to provide people
wihtout the ability to have a subversion server but only a plain web
site, to download a file that can upgrade a local work copy. Requiring
either SVN locally or server side is not really user friendly ..

Thanks for your input!
- Jorgen

On Nov 20, 2007 10:48 AM, Diez B. Roggisch [EMAIL PROTECTED] wrote:
 Jorgen Bodde wrote:

  Hi all,
 
  I want to provide my users the ability to download a repository from
  the web, and after that check for updates. I thought of a mechanism
  that could do that, but since there is patch and diff readily
  available I wondered if there is a python solution that allows me to
  download a file, and let the patch be applied locally. In the patch
  there are binaries and sources I am not sure if patch can handle them
  both though.
 
  So here are the situations;
 
  Downloading
  1. User enters URL and local path where to store
  2. Updated downloads the file
  3. Either creates a new repository or patches an existing one
 
  Check for updates
  1. A web check is done if there is a newer version
  2. File is downloaded, patch is applied
 
  Plain zip file extraction is possible, but I will miss out on files
  that might be deleted in future versions, but not yet on the client
  side. Also local changes might need to be preserved although it is not
  a show stopper if it doesn't.
 
  I want to have a solution that is very easy for the user, so point and
  click kind of work. Is there a tool / library around that can provide
  me a base for this problem?

 Subversion. With it's python-libs of course.

 Diez
 --

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

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


Re: Web update library in python?

2007-11-20 Thread Jorgen Bodde
Hi A.T.Hofkamp,

Using svn still requires the people wanting to offer updates to have a
svn server installed, or use one of the svn services available and
that is simply too limiting.

I will explain a bit more where I will use this for. I am writing a
tool that takes a repository (e.g. a bunch of files with some XML to
tie it together) and generate something else based upon the user's
input configuration.

The 'repositories' can be created by anyone who likes to share their
code templates, and let the end user configure this template and
create a customized code base of it, on which they can code their
entire app. My tool supports incremental configuration which means if
there are updates to this repository, the user simply has to click
configure/generate again and merge the changes into their working
copy.

To provide others with a web update functionality from inside my tool,
all they should have to do is put a file online, containing a snapshot
(or delta snapshot files) of the repository that can be used. So all
they do is either click UPDATE or DOWNLOAD if the repository is
not yet present. For the maintainer of the repository it should be as
simple as making a snapshot of their directory and out comes a ZIP
file that can be put online for others to update from.

SVN is wonderful in resolving issues, but it requires everyone to
either use a service like berlios / sourceforge or be fortunate that
they have a SVN server set up somewhere. What I want, looks like a
plain down to earth update mechanism which is a bit more standardized
and it would be nice if there was already something like this called
PyWebUpdate, or PyUpdater.

For my tool it's key that the learning and usage curve is not very
steep. I can imagine on a web site you are simply instructed to enter
an url like http://www.somesite.com/repository/framework; inside my
tool, press DOWNLOAD / UPDATE and it will install it for you.

I guess where you can compare it with, is what Eclipse uses to update
or install their plugins ... This is not exactly re-inventing the
wheel as the majority of the users cannot use SVN (because they have
no place to store their repositories).
I really thought about SVN but I would not like end-users to be
bothered with maintaining or installing SVN or a SVN server, and have
intermediate .svn local files inside every directory ;-)

I hope this is a bit more clear,
With regards,
- Jorgen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Web update library in python?

2007-11-20 Thread Jorgen Bodde
Hi Diez ,

I fail to see that. If I am the one that can only put new archive
files on my server by FTP or HTTP upload or whatever, and I update
the file which contains the information about what updates are present
on my site as last, there is no data corruption or loss of data.

There are two roles:

Repository maintainer:
-
- Developer of the 'repository' creates a snapshot
- This archive is uploaded on his private site
- A file that accompanies the archive containing the list of updates
is sent last

Repository updater:
-
- Downloads the accompanying file
- If the accompanying file is valid (I agree upon uploading this small
file can be downloaded, but since it is a small text file I would not
consider this a huge risk)
- Downloads the archive that was put there earlier

It might not be a 100% secure methodology, but I won't claim I get
thousands of hits per hour to begin with, I am lucky if someone is
willing to try my tool to begin with ;-)

If all fails I can temporarily rename the directory on the server
side, upload the files, and rename it back so that no corrupted files
are downloaded. But even it the small 'dictionary' file is corrupted,
the install process can abort and the user is asked to try again
later.

But I guess I am defending my way of solving the issue while the main
question was if there was anything remotely similar to what I would
need, besides using SVN that is ;-)

Thank you for your input!
- Jorgen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Web update library in python?

2007-11-20 Thread Jorgen Bodde
I must add, the way I was originally attempting to solve this is
issuing delta files per upgrade cycle so that only changes are placed
in a new ZIP file. The delta zip file will always be a new file on the
site / ftp location. I do understand that if you are re-using the same
archive file all the time, people might download the file at the same
time I am uploading a new version.

So the bottleneck indeed is with the small accompanying file the
updater should download to see if there are changes needed to
download. If that file is updated while it's downloaded, it should
somehow be detected.

thanks for pointing that out..

Regards,
- Jorgen

On Nov 20, 2007 12:41 PM, Jorgen Bodde [EMAIL PROTECTED] wrote:
 Hi Diez ,

 I fail to see that. If I am the one that can only put new archive
 files on my server by FTP or HTTP upload or whatever, and I update
 the file which contains the information about what updates are present
 on my site as last, there is no data corruption or loss of data.

 There are two roles:

 Repository maintainer:
 -
 - Developer of the 'repository' creates a snapshot
 - This archive is uploaded on his private site
 - A file that accompanies the archive containing the list of updates
 is sent last

 Repository updater:
 -
 - Downloads the accompanying file
 - If the accompanying file is valid (I agree upon uploading this small
 file can be downloaded, but since it is a small text file I would not
 consider this a huge risk)
 - Downloads the archive that was put there earlier

 It might not be a 100% secure methodology, but I won't claim I get
 thousands of hits per hour to begin with, I am lucky if someone is
 willing to try my tool to begin with ;-)

 If all fails I can temporarily rename the directory on the server
 side, upload the files, and rename it back so that no corrupted files
 are downloaded. But even it the small 'dictionary' file is corrupted,
 the install process can abort and the user is asked to try again
 later.

 But I guess I am defending my way of solving the issue while the main
 question was if there was anything remotely similar to what I would
 need, besides using SVN that is ;-)

 Thank you for your input!
 - Jorgen

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


Re: Web update library in python?

2007-11-20 Thread Jorgen Bodde
Hi Paul,

Like I said, I do not want to limit my end users into installing
something in Apache or some other solution in order to get my tool
working. On the end user side (which also are the people who are
creating the repositories for others) there must be no burden
whatsoever. Your thoughts are interesting though, I will have to look
into that.

Hi, A.T.Hofkamp (sorry for not knowing your first name ;-),

SCM sounds like a term I can google for, if the tool needed is very
easy to install, maybe even accompany with my application to run as a
service for the updating, it is worth a try to find something that can
handle the synchronizing of distributed repositories.

Talking a bit more about it and hearing various solutions gave me more
insight in how it might be solved. Thanks everybody for your input!
- Jorgen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: toprettyxml messes up with whitespaces

2007-10-09 Thread Jorgen Bodde
Dear list,

Thanks for the suggestions and clarification. After playing with XML
for a while I noticed whitespaces can indeed be more important then I
thought. I did came to the following conclusions;

1. Removing whitespaces was done by my code, not by the
xml.dom.minidom so I regret the fact I said that it removed
whitespaces automatically
2. toprettyxml() should however be smarter with outputting the XML. If
it adds whitespaces in the sake of formatting, it should check how
many of the whitespaces are already there. Consecutive read / modify /
write actions should not cause an explosive growth of whitespaces.
When I use toprettyxml() I am obviously not interested in whitespaces
in front of the text in the nodes, or else I would have outputted it
differently.

Thanks all for the feedback,
- Jorgen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: toprettyxml messes up with whitespaces

2007-10-03 Thread Jorgen Bodde
Hi there,

Thank you for confirming this, I did manage a work around. When
reading back the XML file, I strip it off it's whitespaces before I
parse it. Then when writing it back no excessive whitespaces are
appended. My best guess is that toprettyxml is not intelligently
handling whitespaces that are already there, and bluntly appends more
whitespaces to it, making it grow exponentially.

This is the snippet;

f = open(filename, rt)
for line in f:
s = line.strip(' \t\n')
if s:
xmlstr += s + ' ' # space needed for spanning text nodes

And then I simply use parseString instead of parse. But honestly, I
think it is a bug, because the XML standard also says that whitespaces
before normal text should be ignored, and I do not see it back as text
when I read the node, so why preserve it and mess up the formatting in
the end?

Regards,
- Jorgen




On 10/2/07, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 On Oct 2, 11:43 am, Jorgen Bodde [EMAIL PROTECTED] wrote:
  Hi all,
 
  I parse an XML file, replace a node with a new one (like updating
  cache) and write it back. Every write, new spaces are added. For
  example, first read - update - write cycle;
 
  var name=APPNAME status=undefined
   My First App
  /var
 
  Second cycle:
 
  var name=APPNAME status=undefined
   My First App
  /var
 
  Third cycle:
 
  var name=APPNAME status=undefined
 My First App
  /var
 
  And this goes on. The node is one that is not touched in the XML, it
  is simply written back after reading. I have the same with void spaces
  in between the nodes, I managed to compensate that by stripping the
  lines.
 
  I would like to use toprettyxml to make it user editable and viewable.
  But this is really weird. How can I circumvent this behaviour?
 
  regards,
  - Jorgen

 I had similar problems and ended up switching to the lxml package to
 solve the issue. I think you can do it with ElementTree too. Maybe
 somebody with more experience with the xml / minidom modules will show
 up soon.

 Mike

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

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


Re: toprettyxml messes up with whitespaces

2007-10-03 Thread Jorgen Bodde
Hi Paul,

 This seems like a reasonable explanation without having looked at the
 source code myself.

It's by thorough investigation ;-)

 Which part of the standard is this? Here's the XML 1.0 specification's
 section on whitespace:

 http://www.w3.org/TR/2006/REC-xml-20060816/#sec-white-space

Well 2.10 if I quote:

quote
Such white space is typically not intended for inclusion in the
delivered version of the document. On the other hand, significant
white space that should be preserved in the delivered version is
common, for example in poetry and source code.
/quote

I interpret significant whitespaces as the ones between the words,
if whitespaces occur at the beginning of a line due to an indent like

value
 This is indented text
/value

We can assume that the spaces in front of it are not significant
whitespaces. Because when I read the text node in python and it is not
included, I see no reason why it should be preserved. And if it is
preserved in the xml DOM, toprettyxml should first investigate how
many whitespaces are already there before adding more to indent the
text.

Also this happens. First the nodes are properly shown:

value
a ... /a
/value
value
a ... /a
/value

When writing back this sometimes happen (mind the blank lines):

value
a ... /a
/value

value
a ... /a
/value

And the next time, the spaces between the nodes is expanded again:

value
a ... /a
/value


value
a ... /a
/value

(etc) .. so when reading, modifying, writing XML files, the empty
blank lines will grow exponentially.

 It seems to me that applications (and the libraries which serve them)
 can choose what to do unless xml:space is set to preserve. It does
 seem odd that the toprettyxml method chooses to respect existing
 whitespace whilst also disrupting it by adding more, however.

I would think (simplistic I'm sure) that if spaces are that important,
you can always use a CDATA tag which should treat the text inside as
raw data without any formatting and whitespace changes.

Should I file this as a bug to be solved? I have my workaround now,
but I read online that more people seem to have ran into this.

Regards,
- Jorgen
-- 
http://mail.python.org/mailman/listinfo/python-list


toprettyxml messes up with whitespaces

2007-10-02 Thread Jorgen Bodde
Hi all,

I parse an XML file, replace a node with a new one (like updating
cache) and write it back. Every write, new spaces are added. For
example, first read - update - write cycle;

var name=APPNAME status=undefined
 My First App   
/var

Second cycle:

var name=APPNAME status=undefined
 My First App   

/var

Third cycle:

var name=APPNAME status=undefined
   My First App 

/var


And this goes on. The node is one that is not touched in the XML, it
is simply written back after reading. I have the same with void spaces
in between the nodes, I managed to compensate that by stripping the
lines.

I would like to use toprettyxml to make it user editable and viewable.
But this is really weird. How can I circumvent this behaviour?

regards,
- Jorgen
-- 
http://mail.python.org/mailman/listinfo/python-list


How to determine the bool between the strings and ints?

2007-09-07 Thread Jorgen Bodde
Hi All,

I have a dictionary with settings. The settinfgs can be strings, ints
or bools. I would like to write this list dynamically to disk in a big
for loop, unfortunately the bools need to be written as 0 or 1 to the
config with WriteInt, the integers also with WriteInt and the strings
with a simple Write.

The list is something like;

options[A] = True
options[B] = 1
options[C] = Hello

I wanted to use isinstance to determine if it is a bool or an int or a
string. However I am confused trying it out in the interactive editor;

 a = False
 if isinstance(a, bool):
... print OK
... 
OK
 if isinstance(a, int):
... print OK
... 
OK


I don't get it. is the bool derived from 'int' in some way? What is
the best way to check if the config I want to write is an int or a
bool ?

Regards,
- Jorgen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to determine the bool between the strings and ints?

2007-09-07 Thread Jorgen Bodde
Awesome! Thanks you!

As for why caring if they are bools or not, I write True and False to
the properties, the internal mechanism works like this so I need to
make that distinction.

Thanks again guys,
- Jorgen

ps. Sorry TheFlyingDutch for mailing you personally, I keep forgetting
this mailinglist does not default back to the user list when replying
;-)
-- 
http://mail.python.org/mailman/listinfo/python-list


moving files in a seperate thread (and/or with progress?)

2007-08-15 Thread Jorgen Bodde
Hi all,

I want to make a small batch copy tool that scans for certain files,
and copies them to a specified directory. Since the files are huge
(AVI / DIVX) typical 300 to 700 Mb, I want to provide the user with
some feedback during the file copy.

Here is my dillemma; When I use shutil.move(..,..) I have to wait
until it's done, there is no feedback, so the GUI basically hangs.
However, shutil.move can be fast because it intelligently renames the
file when it is on the same medium, but slow when it moves to a
different one.
When I use my own implementation of a move mechanism that provides
feedback, I lose that intelligence, and I might slow down the copy
process unneccessarily.

When I move files, feedback is handy to have, but not neccesary so I
thought I can also call shutil.move from a seperate thread so the main
GUI stays responsive. What are my options in aborting a move by
killing the thread or are there other (3rdparty) modules I might use
to get better move or copy performances?

Just opening the file, performing a block copy myself seems like it
will slow down the transfer, but up until now I found no way to move
or copy with progress or abilities to abort the file transfer..

Any ideas?

Regards,
- Jorgen
-- 
http://mail.python.org/mailman/listinfo/python-list


Using python for dynamic behavior from C++

2007-08-15 Thread Jorgen Bodde
Hi all,

I am looking into using Python to introduce dynamic behavior in my
C++, e.g. something like a simulation where objects can interact with
eachother. I know Python can be called from C++, but is it possible to
call a binary compiled Python file / array from C++ ? The reason I ask
is that if my objects call a script every tick to do something, I
would not like to let the python interpreter recompile the same code
over and over again.

Any pointers to how I can do that?

Regards,
- Jorgen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Too many 'self' in python.That's a big flaw in this language.

2007-06-27 Thread Jorgen Bodde
I had the same feeling when I started, coming from a C++ background, I
forgot about self a lot, creating local copies of what should be an
assign to a class instance, or methods that could not be found because
I forgot 'self' .

Now I am 'kinda' used to it, as every language has some draw backs
(you can't please all). But, what about something in between like only
using the dot (.) for a shorter notation?

self.some_var = True

Could become:

.some_var = True

Which basically shows about the same thing, but you leave 'self' out
of the syntax. Ofcourse it should not be allowed to break a line
between the dot and the keywords, else Python would never know what to
do;

my_class()
.my_var = True

Should not be parsed the same as;

my_class().my_var = True

Just a suggestion. I am pretty happy with self, but I could settle for
a shorter version if possible.

- Jorgen


On 6/27/07, Roy Smith [EMAIL PROTECTED] wrote:
 Marc 'BlackJack' Rintsch [EMAIL PROTECTED] wrote:
  Use a shorter name than `self` or an editor with auto completion.

 Of the two, I'd strongly vote for the auto completion (assuming you feel
 the need to solve this problem at all).  The name self is so ingrained
 in most Python programmers minds, that it's almost a keyword.  Changing it
 to this or s or me will just make your program a little harder for
 other people to understand.

 Changing it to this would be particularly perverse since it's not even
 any less typing.  In fact, on a standard keyboard, it's harder to type
 since it involves moving off the home row more :-)
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: Adding a DB regs to a wx listbox

2007-06-12 Thread Jorgen Bodde
self.list_box_1_copy.Append( your_item )

In the wxWidgets help:

http://www.wxwidgets.org/manuals/2.8.0/wx_wxcontrolwithitems.html#wxcontrolwithitems

And in the wxPython help:

http://www.wxpython.org/docs/api/wx.ItemContainer-class.html

Regards,
- Jorgen

On 6/12/07, Marcpp [EMAIL PROTECTED] wrote:
 Hi, I need add to a listbox a list of items extracted from a database.
 This is that I've do:

 class tasques(wx.Frame):
 def __init__(self, *args, **kwds):
 
 self.list_box_1_copy = wx.ListBox(self, -1, choices=[],
 style=wx.LB_SINGLE|wx.LB_ALWAYS_SB)
 ...

 How I add the list to choices?

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

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


function in a function accessing vars

2007-06-06 Thread Jorgen Bodde
Hi all,

I wanted to solve a small problem, and I have a function that is
typically meant only as a function belonging inside another function.
From the inner function I want to access a variable from the outer
function like;

def A():
  some_var = 1
  def B():
some_var += 1

  B()


But this does not work, the function B does not recognize the
some_var. In my mind I thought the scope would propagate to the new
function and the vars would still be accessible.

How can I go about this?

With regards
- Jorgen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: function in a function accessing vars

2007-06-06 Thread Jorgen Bodde
Hi Diez,

Thanks, I thought it worked similar to C++ where a higher compound
could access a lower section. But as it is not straight forward, I
think it is better to embed the functionality inside a class, and make
it a member variable .. now why didn't I think of that ;-)

Thanks,
- Jorgen

On 6/6/07, Diez B. Roggisch [EMAIL PROTECTED] wrote:
 Jorgen Bodde wrote:

  Hi all,
 
  I wanted to solve a small problem, and I have a function that is
  typically meant only as a function belonging inside another function.
 From the inner function I want to access a variable from the outer
  function like;
 
  def A():
some_var = 1
def B():
  some_var += 1
 
B()
 
 
  But this does not work, the function B does not recognize the
  some_var. In my mind I thought the scope would propagate to the new
  function and the vars would still be accessible.
 
  How can I go about this?

 The problem here is the way python determines which variables are local to a
 function - by inspecting left sides.

 I'm not sure if there are any fancy inspection/stackframe/cells-hacks to
 accomplish what you want. But the easiest solution seems to be a
 (admittedly not too beautiful)

 def A():
some_var = [1]
def B(v):
v[0] += 1

B(some_var)


 Or you should consider making A a callable class and thus an instance, and
 some_var an instance variable. Always remember: a closure is a poor
 persons object, and an object is a poor mans closure

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

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


Re: [Fwd: Re: managed lists?]

2007-05-24 Thread Jorgen Bodde
@ Larry,

As much as I like to follow the idiom that Python has, I do not see
the usefulness of making an add function that checks the interface
that other objects might need. Besides the fact it is a bit overhead
and not to mention performance draining, in an application that I
develop myself, without plugin architecture (not yet) etc, it is a bit
much to do that.

I agree with the writing C in Python, it is all I know, because that
is the language I started with. This is my first big project and most
certainly when evaluating this when it is finished I will come to the
conclusion it was all for nothing ;-)

I will change to extend() and maybe drop the type safety, but I do
wish to keep the list functionality as I find it more logical to write

song.categories.append()

Then creating a method in song called AddCategory() and kind of
duplicating the list functionality there.

Thank you for the guide lines and the nice comments! They are really helpful.

@ Bruno,

 list. The right solution IMHO is to *not* expose these lists as part of
 the interface - after all, the fact that tabs and tunes are stored in
 lists is an implementation detail -, and to add the necessary API to the
 Song object - ie : Song.add_tune, Song.add_tab, Song.iter_tunes,
 Song.iter_tabs, etc. Then you just have to add some assert statements in
 the add_XXX methods so you'll be warned at the right time when some part

This is how I did it before, I created Song.AddTab, Song.DeleteTab,
then there was a category class which also needed adding, deleting,
clearing, and soon my whole Song object was filled with relational
methods which were basically a copy of the list, with a check on the
presence of the class in the list.

Then I realized, a managed list with self-check capability solves this
because I do not like to duplicate code, but now that I think of it,
the type check might be a bit too much. Like said, the list solution
you described and the solution I use, are basically the same, I
encapsulated a list [] in a class, with some extra methods to warn the
'owner' of the list that something is changed.

 Oh, yes, while we're at it, and in case you don't know yet: the Python
 idiom for implementation attributes (including methods - remember,
 everything is an object) is to prefix them with a single underscore.

Ok, but why is that? I do know semi-private symbols can be realised
using two underscores, and if I wish to hide a list / index / etc so
it cannot accidentally changed, would I not use double underscores?

Thanks for your extensive help!
- Jorgen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Fwd: Re: managed lists?]

2007-05-22 Thread Jorgen Bodde
Hi,

Thanks. I agree that it is only 'me' that is the one doing it wrong.
But consider this scenario:

- Somewhere in my app I add a wrong type to an open regular list
- The app continues like it should
- After a (long) while I need to perform some search on the list, or whatever
- Exception occurs

It makes it hard to test this way. For example I can do something to
that list and not know about it much later .. If it blows up in my
face, I can fix it, but when that error hinders people who are using
my application, it is much worse.

With a somewhat managed list (forget about the types then, it was only
meant for my own satisfaction I guess), the access violation always
occurs on adding elements, which is always the path that a user
creates something 'new'. And if something new gets not added
correctly, I know where to look..

Anyway, I was looking for such a list class but i do understand that
most of the resposobility is for the programmer anyways and people
interacting with it. I did however need this solution so that I can
also add a better support for my database objects, add generic find
routines to that list class etc. So I basically added the interface
methods needed to let it be treated like a general list, like the
iterator, get method and what else. I was surprised it was so easy to
be done.

Python is cool when it comes to the interface specification v.s.
class specification it opens a lot of doors to paradigms otherwise
hard to implement, and I like the fact that every object can be
adapted to mimic another object needed by an internal routine in
Python, very-very dynamic indeed.

But being a strong typed C++ guy once, it takes some getting used to ;-)

Regards,
- Jorgen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [Fwd: Re: managed lists?]

2007-05-22 Thread Jorgen Bodde
Hi Gabriel,

Yep that basically covered my implementation as well. It was rather
trivial to make it, and even for a python newbie it was simple which
says enough about the language itself. ;-)

Although I understand the opinions that you should not care about
types, I do believe putting a constraint on the list by either class
type or interface spec, is no bad thing. The interface specification
is hard to realise as this list now functions as some kind of template
class (hence the parameter that specifies which type is allowed).

I also added callback arguments that are called opon when there are
items added to the list, deleted or when it is cleared so that the
main object gets notified when another object changes it.

Here is my implementation (I bet it can be done better, but I am only
playing with python since about 3 months now):

--

class ObjListException(Exception):
pass

class ObjListIterator(object):
def __init__(self, objlist):
self.__objlist = objlist
self.__idx = 0

#---
def __iter__(self):
return self

#---
def next(self):
result = None
if self.__idx = len(self.__objlist):
raise StopIteration()
else:
result = self.__objlist[self.__idx]
self.__idx += 1
return result

#===

 ObjList - A managed somewhat strong typed list for Python.
Expects {object}._id to be a property 

class ObjList(object):
def __init__(self, class_name, add_callback = None,
 remove_callback = None, clear_callback = None):
self.__list = []
self.__cname = class_name
self.__add_cb = add_callback
self.__remove_cb = remove_callback
self.__clear_cb = clear_callback

#---
def __iter__(self):
return ObjListIterator(self.unmanaged_list())

#---
def __getitem__( self, key):
if key  len(self.__list) and key = 0:
return self.__list[key]
return None

#---
def clear(self):
self.__list = []

#---
def append(self, obj):
if isinstance(obj, self.__cname):
if obj not in self.__list:
self.__list.append(obj)
if self.__add_cb:
self.__add_cb(self, obj)
else:
  raise ObjListException()

#---
def remove(self, obj):
if obj in self.__list:
self.__list.remove(obj)
if self.__remove_cb:
self.__remove_cb(self, obj)

#---
def count(self):
return len(self.__list)

#---
def unmanaged_list(self):
return self.__list[:]

#---
def find_id(self, id):
for i in self.__list:
if i._id == id:
return i
return None

#---
def has_item(self, obj):
if obj in self.__list:
return True
return False

#---
def append_many(self, lst):
for l in lst:
self.append(l)

Regards,
- Jorgen
-- 
http://mail.python.org/mailman/listinfo/python-list


managed lists?

2007-05-21 Thread Jorgen Bodde
Hi all,

I have been slowly progressing with my application written in
wxPython. I love the freedom, speed and lack of the compiling run. I
still have to get used to the lack of (strong) types, and it sometimes
frustates me to no end that a wrongly given argument explodes
somewhere deep inside my application without giving any clue why it
blew up in the first place..

Right now i have a list in a class that I export as a member variable
to the outside world, it is a standard list (e.g. [] ) but I wish to
have a stronger type checking when adding objects, that only some
objects are allowed and others are not. It was quite easy to create
it, but I wonder if there is already a standard solution for lists
that carry only objects of a single type?

I solved it now, by using isinstance() and giving the class name as
argument to the list (thank god that everything in Python is an object
;-) ) where I check against when adding, but re-inventing the wheel is
silly ofcourse

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


Re: Python and GUI

2007-05-21 Thread Jorgen Bodde
Well wxPython offers all of the above. They use XRC which is a XML
file which can be loaded inside the GUI, that auto-creates the
components + layout for you. It also supports creating the gui
programatically, which might be very handy when your layout is
undetermined or changes when users select options etc.

I use wxPython because I am used to wxWidgets C++ and it is very good
under python (I am a python newbie and the integration in python is
fine). I use wxGlade to auto generate the GUI from inside the GUI
designer, works great as well

As for tkinter, PyQt or PyGTK, I do not have much experience with
them. You don't change a winning formula ;-)

- Jorgen


On 5/21/07, Michael L Torrie [EMAIL PROTECTED] wrote:
 On Mon, 2007-05-21 at 18:23 +0200, Petr Muller wrote:
  There's PyQt thingy, imho very good and easy to learn/use, but still
  powerful. I've used it for a small gui-oriented project with almost no
  problems and it worked like a charm. However, sometimes I had troubles
  finding useful documentation for it.
  I've also tried to play with PyGTK, it's quite nice and easy (and you
  have the advantage of Glade), but I don't like GTK way of creating GUI.
  I haven't used Tkinter a lot, only looked at it. And I didn't like it much.

 How does GTK's way of creating the GUI (I presume you're not talking
 look and feel) differ from Qt's?  From what I can see (having developed
 large apps in both GTKmm and Qt (C++), they both function the same.  In
 other words you create the widget first, then parent it in a container
 and add callbacks. Whereas wxPython's approach is somewhat different.

 It appears that most wxPython apps setup the GUI programmatically,
 whereas Most Qt and Gtk apps tend to use XML-based gui-building
 factories.  In this latter case, Glade's method is quite different from
 Qt's.

 
  I would really suggest PyQt. (with a big IMHO :)
 
  Petr

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

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


Re: [Fwd: Re: managed lists?]

2007-05-21 Thread Jorgen Bodde
Hi Bruno,

Thanks for your answer.

Well what I am after is a list of relations to some class type. And in
that list I do not wish to have accidentally put ints, strings, only
one type of object, or interface. Now I can make the list interface
safe, but it is only meant for relational purposes only. So to
illustrate:

Song  Tab
Song --- Tuning

I want a tabs collection only consisting of Tab objects. They are
very specific so mimicing a tab interface is not something that will
be done anytime soon.

I'm a traditional C++ programmer, and maybe I go through some
transitional phase I don't know but exposing my list as read /
(over)write property to the outside world being the rest of my
object model, is just asking for problems. So this strong typed list
will ensure me at add time the exception occurs, rather then
somewhere in my applciation who knows much later that something blows
up because the object from that list is retrieved and something
unpredictable goes wrong. Is that so weird to do? As I said earlier I
am a python newbie, I love the language, but the fact it can blow up
at unpredictable times, gives me shivers.

 Everything in Python is an object. Including integers. And there's no
 'char' type in Python.

The array type by the way says in the API that it can be constructed
with a simple type like a char as in a c type, an int as in a i
type etc..

See here:

http://www.python.org/doc/1.5.2p2/lib/module-array.html

So what I understand it's purpose is creating a buffer of some kind of
a fixed type to maybe communicate with other DLL's or objects that
require such a thing.

As I said, I might be going through a transitional phase, but exposing
my relation list as simply a list class where all kinds of objects can
be dumped in, seems too much for me at this point ;-)

Thanks,
- Jorgen
-- 
http://mail.python.org/mailman/listinfo/python-list


Real globals inside a module

2007-05-13 Thread Jorgen Bodde
Hi All,

I am wrestling with some architecture inside my app. Let's say I have
a tunings collection, which contains e.g. 23 types of guitar tunings.
In my song object I want to restore a relation between one of the
tuning objects inside the tunings module.

I already figured out I need somethign like a global collection inside
the tunings module,. but how global is it? When I am inside my app
object, and import the tunings module, can I access the same global
class as when I am inside my songs module and load the tunings module?

So for some pseudo code:

--- songs.py

import tunings

class Song(object):
  def __init__(self, tuning_id):
# create relation with tuning object
self._tuning = tunings.GetTuningById(tuning_id)

-- app.py

import tunings

# get list of tunings

for t in tunings._tuningCollection:
  print 'Tuning:', t._name



So basically I want to access the same global list in both modules,
but not re-create the list in every module since it should be restored
by the database layer once.

Is this as simple as defining a global variable in the module tunings
which is available on both imports, or should I do it different, and
then my next question ofcourse is, how ? :-)

Thanks for any advice, I do not want to make a global manager object
that I need to pass around all the time, that would be silly..

Regards,
- Jorgen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Real globals inside a module

2007-05-13 Thread Jorgen Bodde
great! Thanks it makes perfect sense, but before attempting some code
rewrite I just wanted to be sure ;-)

Regards,
- Jorgen

On 5/13/07, Christoph Haas [EMAIL PROTECTED] wrote:
 On Sun, May 13, 2007 at 11:41:12AM +0200, Jorgen Bodde wrote:
  I am wrestling with some architecture inside my app. Let's say I have
  a tunings collection, which contains e.g. 23 types of guitar tunings.
  In my song object I want to restore a relation between one of the
  tuning objects inside the tunings module.
 
  I already figured out I need somethign like a global collection inside
  the tunings module,. but how global is it? When I am inside my app
  object, and import the tunings module, can I access the same global
  class as when I am inside my songs module and load the tunings module?

 You are on the right way. If you import the same module a second time in
 another place of your application you get access to the exact same data.
 That is called a singleton. I often use such a singleton for global
 configuration data.

  So basically I want to access the same global list in both modules,
  but not re-create the list in every module since it should be restored
  by the database layer once.

 Import your global module and just run the initalisation once. That
 should do it.

  Thanks for any advice, I do not want to make a global manager object
  that I need to pass around all the time, that would be silly..

 Indeed. That would suck.

  Christoph

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

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


Re: preferred windows text editor?

2007-05-10 Thread Jorgen Bodde
I prefer PsPad.

If you like Notepad++, PSPad might be a better choice. More intuitive.
I've used Notepad++ for a while, I really disliked the fact that every
new install my settings XML file would get overwritten, and what does
that guy have with Comic sans MS? Every default style is hard coded
into the app, to that strange oddly looking style for comments etc.

Anyway, I do not want to get too personal. PsPad is very nice, I also
use more python-like editors like SPE and UliPad.

- Jorgen

On 10 May 2007 00:57:52 -0700, Ant [EMAIL PROTECTED] wrote:
 On May 9, 11:21 pm, BartlebyScrivener [EMAIL PROTECTED] wrote:
 ...
  I too vote for VIM. I use it on both Windows XP and Debian Etch. I
  can't find anything it doesn't do.

 I also use Vim (well, GVim).

 The only thing I find missing is an integrated console for running
 code snippets/entire scripts. The runscript plugin is OK, but lacks
 interactive use. I have been thinking about some way of interacting
 with a Python shell using sockets to send snippets directly to the
 shell from Vim, but haven't had time to get very far.

 What method of executing code snippets in a Python shell do other Vim
 users use? Other than just copy/paste?

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

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


Re: changing a var by reference of a list

2007-05-09 Thread Jorgen Bodde
Hi Bruno,

Unfortunately SQLAlchemy will be too involved at this point I will
have to rewrite a lot of code to remove my current DB solution and use
that. Howerver I've learned from my mistake and the next project will
use it, as it seems to be a nice way of mapping objects to databases..

I'v solved it by just sending back the record set from sqlite3 because
I noticed sometimes a 1:1 mapping cannot be done from column value to
variable anyway..

Thanks everyone,
- Jorgen
-- 
http://mail.python.org/mailman/listinfo/python-list


changing a var by reference of a list

2007-05-08 Thread Jorgen Bodde
Hi,

I am trying to simplify my code, and want to automate the assigning of
variables I get back from a set. I was thinking of putting the
variables I want changed in a list:

L = [self._varA, self._varB ]

self._varA is a variable I want to change when I pass L to a function.
I know doing this;

L[0] = 12

Will replace the entry self._varA with 12, but is there a way to
indirectly change the value of self._varA, through the list, something
like a by-reference in C++ or a pointer-pointer?

With regards,
- Jorgen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: changing a var by reference of a list

2007-05-08 Thread Jorgen Bodde
Ok thanks,

I will try this approach. The idea was that I could give a list to the
SQL execute command, so that the results coming back would
automatically be assigned to variables.

With regards,
- Jorgen

On 5/8/07, Diez B. Roggisch [EMAIL PROTECTED] wrote:
 Jorgen Bodde wrote:

  Hi,
 
  I am trying to simplify my code, and want to automate the assigning of
  variables I get back from a set. I was thinking of putting the
  variables I want changed in a list:
 
  L = [self._varA, self._varB ]
 
  self._varA is a variable I want to change when I pass L to a function.
  I know doing this;
 
  L[0] = 12
 
  Will replace the entry self._varA with 12, but is there a way to
  indirectly change the value of self._varA, through the list, something
  like a by-reference in C++ or a pointer-pointer?

 No, there isn't.

 But you could do

 L = ['_varA']

 for v in L:
 setattr(self, v, value)

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

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


Relative import problem

2007-04-19 Thread Jorgen Bodde
Hi all,

I want to structure my app so that I have two dirs like;

obj/{object files}

gui/{gui files}

Here comes the catch. From the GUI dir, I would like to access the obj
submodule path. I need to go one dir back.. I read there was something
like from .. import x in python 2.5 so that I could access my obj dir
from a lower level, but I have problems getting this to work.

Example;

In the main dir I have;

main.py:

import gui

gui.gui.startme()


In the obj dir I have;

obj/obj.py
-

def start():
print 'Started OBJ'
-

In the GUI dir I have

gui/gui.py
-
from .. import obj

def start():
obj.obj.start()
-

This does not work. It gives me;

D:\personal\src\GuitarPortfolio\tmppython start.py
Traceback (most recent call last):
  File start.py, line 4, in module
gui.gui.start()
AttributeError: 'module' object has no attribute 'gui'

Am I shooting myself in the foot by trying to structure? Or are there
better more elegant ways?

Regards,
- Jorgen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OverflowError: mktime argument out of range ???

2007-04-17 Thread Jorgen Bodde
Thanks again,

I will explain what happened. I am a python newbie. The time and
datetime modules are confusing at the beginning, but after diving into
them I started to understand the structure. So what I did was using
the time module for date storage, but I came to understand that time
is actually more used for file dates and times. That would explain the
epoch and 1970 boundaries as there are not much files before the
pre-PC era to keep timestamps for.

Basically it would have been clearer if the time module would have
been called 'filetime' as datetime kind of supercedes the time by
removing all boundaries and still presenting all methods to the user.

Onca again, it was confusing for someone starting with python, but I
think I got it now. I cannot claim it was not documented, I was more
surprised that there was a boundary and decided to ask before reading
the python docs, sorry 

With regards,
- Jorgen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Import From SubFolder

2007-04-17 Thread Jorgen Bodde
From what I know, if you place a __init__.py file in the folder that
will become your subfolder, you can make it a module subfolder.

Like;

d:\src\app\submodule\__init__.py   (can be empty file)

Then in d:\src\app\main.py simply do;

import submodule

# use your new module like

submodule.somefunction()

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


Re: PYTHON and GUIS and LOGIC... What First? (NEWBIE)

2007-04-17 Thread Jorgen Bodde
Hi,

Basically your data model needs to be defined. It depends on your
'problem area'. It is usually good practice to keep your datamodel
free of GUI elements, so that it can be easily reused. The GUI in the
other hand can know everything about the public interface of the data
model.

I've recently started to use pyDispatcher / wx.lib.pubsub to send
messages from the object model to the GUI, notifying about additions /
updates so that the individual elements such as the list control
showing the items, or other views are updated without you having to
make sure any little data change has to be synced with the GUI. The
data syncs the GUI through an abstract interface. Python is a really
good language for this ..

Regards,
- Jorgen
-- 
http://mail.python.org/mailman/listinfo/python-list


OverflowError: mktime argument out of range ???

2007-04-15 Thread Jorgen Bodde
Hi  List

I am working on an app to store guitar songs I am practicing, and for
the fun of it I want to store the date of songs when they were
originally made. So far so good..

However, my taste of music is Rag Time Blues and that os OLD, very
OLD music. So it happened I entered a song from the date  28 dec
1928.

It appears time.mktime cannot handle these 'extremities' ? I get an
overflow error. is there by any chance a solution to this? I do know
modern languages support at least 1900 as date (and now that I come to
think of it, songs from J.S. Bach are excluded from entering as well)
..

This is what I try:

 time.mktime((1928, 12,28, 0, 0, 0,  0, 0, 0))
Traceback (most recent call last):
  File interactive input, line 1, in module
OverflowError: mktime argument out of range

The only solution I can think of is making a custom time class that
handles all years, dates and months, but that is plain silly. I want
to be able to use the long date formatting etc, and that would mean
rewriting that part as well.

Any help is appreciated!
- Jorgen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: OverflowError: mktime argument out of range ???

2007-04-15 Thread Jorgen Bodde
Ok thanks, I missed out on datetime where the methods I need are also present.

I'll be refactoring my data a bit, thanks again!
- Jorgen

On 4/15/07, Diez B. Roggisch [EMAIL PROTECTED] wrote:
 Jorgen Bodde schrieb:
  Hi  List
 
  I am working on an app to store guitar songs I am practicing, and for
  the fun of it I want to store the date of songs when they were
  originally made. So far so good..
 
  However, my taste of music is Rag Time Blues and that os OLD, very
  OLD music. So it happened I entered a song from the date  28 dec
  1928.
 
  It appears time.mktime cannot handle these 'extremities' ? I get an
  overflow error. is there by any chance a solution to this? I do know
  modern languages support at least 1900 as date (and now that I come to
  think of it, songs from J.S. Bach are excluded from entering as well)
  ..
 
  This is what I try:
 
  time.mktime((1928, 12,28, 0, 0, 0,  0, 0, 0))
  Traceback (most recent call last):
   File interactive input, line 1, in module
  OverflowError: mktime argument out of range
 
  The only solution I can think of is making a custom time class that
  handles all years, dates and months, but that is plain silly. I want
  to be able to use the long date formatting etc, and that would mean
  rewriting that part as well.

 import datetime
 datetime.date(1928, 12, 28)

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

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


Re: sqlite3 question

2007-04-13 Thread Jorgen Bodde
Thanks,

This is how I did it in the end as well. Yes i use the connection
object, abbreviated as 'c' for ease of typing.

In my real app the connection is kept inside a singleton object and I
use the DB like

result = GuitarDB().connection.execute('select * from song where id =
1').fetchone()
if result:
  print 'Found a song'
else:
  print 'Found nothing'

I know there will always be a cursor object back from
connection.execute, so for ease of use and sparing a temp var, I put
the .fetchone() behind the connection.execute()

Thanks everyone for their help!
- Jorgen

On 4/12/07, Carsten Haese [EMAIL PROTECTED] wrote:
 On Thu, 2007-04-12 at 13:43 +0200, Marc 'BlackJack' Rintsch wrote:
  In [EMAIL PROTECTED], Jorgen Bodde
  wrote:
 
   r = c.execute('select * from song where id = 1')
   for s in r:
   ... print s
   ...
   (1, u'Spikedrivers Blues', u'Mississippi John Hurt')
  
   That works. But when I can't restore the row by e.g. an ID that does
   not exist, I cannot see any method in 'r' (which is a SQLite.Cursor)
   that can tell me if I have rows. As explained in the help, r.rowcount
   does not give a valid result because it can't determine how many rows
   are restored in advance.
 
  This should not work because `r` should not be a `Cursor` object.  The
  `execute()`-Method returns an integer with the number of affected rows.

 It does work if 'c' is a connection object with a poorly chosen name.
 According to
 http://docs.python.org/lib/sqlite3-Connection-Objects.html , sqlite3
 connection objects have a non-standard execute method that creates a
 cursor, executes a query on that cursor, and returns that cursor.

 Anyway, if you expect a query to return at most one row, such as when
 you're filtering on the table's primary key, this is how I would do it:

 cur.execute(select * from song where id = ?, (wanted_id,) )
 song_row = cur.fetchone()
 if song_row:
# Do something with song_row
 else:
# Song not found

 HTH,

 Carsten.


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



On 4/12/07, Carsten Haese [EMAIL PROTECTED] wrote:
 On Thu, 2007-04-12 at 13:43 +0200, Marc 'BlackJack' Rintsch wrote:
  In [EMAIL PROTECTED], Jorgen Bodde
  wrote:
 
   r = c.execute('select * from song where id = 1')
   for s in r:
   ... print s
   ...
   (1, u'Spikedrivers Blues', u'Mississippi John Hurt')
  
   That works. But when I can't restore the row by e.g. an ID that does
   not exist, I cannot see any method in 'r' (which is a SQLite.Cursor)
   that can tell me if I have rows. As explained in the help, r.rowcount
   does not give a valid result because it can't determine how many rows
   are restored in advance.
 
  This should not work because `r` should not be a `Cursor` object.  The
  `execute()`-Method returns an integer with the number of affected rows.

 It does work if 'c' is a connection object with a poorly chosen name.
 According to
 http://docs.python.org/lib/sqlite3-Connection-Objects.html , sqlite3
 connection objects have a non-standard execute method that creates a
 cursor, executes a query on that cursor, and returns that cursor.

 Anyway, if you expect a query to return at most one row, such as when
 you're filtering on the table's primary key, this is how I would do it:

 cur.execute(select * from song where id = ?, (wanted_id,) )
 song_row = cur.fetchone()
 if song_row:
# Do something with song_row
 else:
# Song not found

 HTH,

 Carsten.


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

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


sqlite3 question

2007-04-12 Thread Jorgen Bodde
Hi all,

I am using sqlite3 in python, and I wonder if there is a way to know
if there are valid rows returned or not. For example I have a table
song with one entry in it. The ID of that entry is 1, so when I do;

 r = c.execute('select * from song where id = 1')
 for s in r:
... print s
... 
(1, u'Spikedrivers Blues', u'Mississippi John Hurt')

That works. But when I can't restore the row by e.g. an ID that does
not exist, I cannot see any method in 'r' (which is a SQLite.Cursor)
that can tell me if I have rows. As explained in the help, r.rowcount
does not give a valid result because it can't determine how many rows
are restored in advance.

All I can think of is a 'crappy' construction where I use the iterator
to see if there was something in there, but surely, there must be a
better way to know?

 r = c.execute('select * from song where id = 2')
 notfound = True
 for s in r:
... notfound = False
... print s
 if notfound:
... print 'No rows'

I am pretty new with Python, maybe there are some properties of an
iterator / sqlite3 I am not aware of that can tell me how many rows
are there?

With regards,
- Jorgen
-- 
http://mail.python.org/mailman/listinfo/python-list


Calling private base methods

2007-04-12 Thread Jorgen Bodde
Hi All,

Now that I am really diving into Python, I encounter a lot of things
that us newbies find difficult to get right. I thought I understood
how super() worked, but with 'private' members it does not seem to
work. For example;

 class A(object):
... def __baseMethod(self):
... print 'Test'

Deriving from A, and doing;

 class D(A):
... def someMethod(self):
... super(A, self).__baseMethod()
... print 'test3'

Will not work;

 p = D()
 p.someMethod()
Traceback (most recent call last):
 File interactive input, line 1, in module
 File interactive input, line 3, in someMethod
AttributeError: 'super' object has no attribute '_D__baseMethod'

Is it possible to call a private base method? I come from a C++
background, and I liked this construction as my base class has helper
methods so that I do not have to  duplicate code.

When I do;

 class E(object):
... def someMethod(self):
... print 'Hello'
...
 class F(E):
... def otherMethod(self):
... super(F, self).someMethod()
... print 'There'
...
 p = F()
 p.otherMethod()
Hello
There


This seems to work.

Thanks in advance,
- Jorgen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does not my wx.html.HtmlWindow work?

2007-04-11 Thread Jorgen Bodde
Hi,

Coming from the wx community, I do know that the wx.HtmlWindow is NOT
meant to load full blown web pages with. It has no concept of
javascript, CSS, and other complex DOM properties.

If you really want to display complex web pages in a window, look at
wxMozilla or the wxIE binding.

So the reason it freaks out might be related to the fact the page is
too complex, or that the simplistic engine cannot cope with html tags
out in the wild.

Regards,
- Jorgen

On 4/8/07, Carsten Haese [EMAIL PROTECTED] wrote:
 On 7 Apr 2007 20:38:25 -0700, [EMAIL PROTECTED] wrote
  Below are my source code:
  [snip
  html.LoadPage(
  http://www.pythonthreads.com/articles/python/incorporating-into-
  wxpython-part-1.html)
  [snip]

 Have you tried loading a simpler page, something like http://www.google.com?

 -Carsten

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

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


PyDispatcher question

2007-04-05 Thread Jorgen Bodde
Hi all,

Hopefully someone can help me. I am fairly new to Python, and I am
looking into PyDispatcher. I am familiar with the C++ sigslot variant,
and I wonder how similar PyDispatches is. I run in to the following
'problem' (pseudo code, untested here)

import pydispatch.dispatcher

class A:
  def __init__(self):
dispatcher.connect(self.someSignal, signal = 1)

  def someSignal(self):
print 'Hello world'

obj = A()

# send a trial signal

dispatcher.send(signal = 1)
 Hello world

# now for the catch, how to clean up?
# if I do:
obj = None  # clean up

dispatcher.send(signal = 1)
 Hello world

The object still extists... Which is logical, the method is still
bound to the signal, and the object itself is not yet deleted. Is
there an elegant way to delete the object and let the signal unbind
itself? Or do I need to do this in the destructor of the object? AFAIK
there is no real destructor in Python?

Do I need to do it differently? Or is there a better signal mechanism to use?

Any help is appreciated!
- Jorgen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PyDispatcher question

2007-04-05 Thread Jorgen Bodde
Hi Mike,

Thanks for the explanation! The Python shell really threw me off here.
I thought it would work exactly the same as in the interpreter itself.
:-)

Even assigning None to the object exibits the same behaviour as del
does. COOL!

This is what I did sofar:

from pydispatch import dispatcher

class X(object):
  def __init__(self):
dispatcher.connect(self.someSignal, signal = 1)
  def someSignal(self):
print 'Hello world'

a = X()
dispatcher.send(1)

a = None

dispatcher.send(1)

print '--'

b = X()
c = X()
dispatcher.send(1)

With as output;

C:\Documents and Settings\Jorg\Desktoppython New1.py
Hello world
--
Hello world
Hello world

Nice! Thanks a lot for the info!

- Jorgen


On 4/5/07, Mike C. Fletcher [EMAIL PROTECTED] wrote:
 Jorgen Bodde wrote:
  Hi all,
 
  Hopefully someone can help me. I am fairly new to Python, and I am
  looking into PyDispatcher. I am familiar with the C++ sigslot variant,
  and I wonder how similar PyDispatches is. I run in to the following
  'problem' (pseudo code, untested here)
 
 Here's some real code...

 from pydispatch import dispatcher
 import gc

 class X(object):
 def __init__( self ):
 dispatcher.connect( self.someSignal, signal=1 )
 def someSignal( self ):
 print 'hello world'

 obj = X()
 dispatcher.send( signal= 1 )

 del obj
 #gc.collect()

 dispatcher.send( signal= 1 )

 This will print out only one hello world on my Python 2.5 Gentoo
 machine (it should work the same on any recent Python).  Basically your
 python shell will tend to keep around an extra copy of the X instance
 until you get rid of it explicitly, and that's what keeps the object
 live and receiving signals if you try the code in the shell.
 PyDispatcher is designed so that, by default, when the object goes away
 the registration is removed.  It uses the weakref module to do this,
 rather than __del__ methods, to avoid garbage cycles, btw.

 HTH,
 Mike

 --
 
   Mike C. Fletcher
   Designer, VR Plumber, Coder
   http://www.vrplumber.com
   http://blog.vrplumber.com


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