Re: reading one byte from stdin

2008-07-16 Thread Diez B. Roggisch

Mark McDuff schrieb:

I'm trying to read one byte from stdin, without the newline.

If I try something like:
 >>> import os, sys
 >>> os.read(sys.stdin.fileno(),1)

I can input a character, but then I have to press enter, which leaves a 
newline character in the stdin buffer and requires two keypresses.  Is 
there any way to read only one keypress in a simple manner (i.e. no 
curses)?


Depending on your OS, yes. Under *nix, you need to set the terminal to 
RAW-mode.


This recipe claims to be OS-agnostinc:

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

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


Re: Redirecting stdout to another script

2008-07-16 Thread Diez B. Roggisch

Richard Simões schrieb:

Hopefully, this explanation will sufficiently clear despite the lack
of code.

I wrote a python script that takes data via stdin, does stuff with the
data, and outputs the result to stdout. A friend wrote a perl script
that opens a pipe to my script, feeds it data, and then accepts the
result. The problem here is that the python script's outputting the
result to stdout via print statements isn't doing what we expected: my
friend's perl script isn't getting the result back via the pipe.

Is there is simple solution for this problem? Whose script needs to be
modified?


That of your friend, if he is the one invoking you. Because the invoking 
script is the one responsible for connecting the pipes properly.



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


Re: Is re.findall guaranteed to be "in order?"

2008-07-16 Thread Fredrik Lundh

Joshua Kugler wrote:


Experimenting has shown me that re.findall() will return a list with the
matches in the order it found them.


"in the order it found them" doesn't really say much, does it? ;-)

"findall" and "finditer" both scans the string from left to right, and 
will return matches in that order.


(the documentation is a bit vague, so if you have the time, please add a 
request for clarification to the bug tracker)




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


Re: About wmi

2008-07-16 Thread Tim Golden

patrol wrote:

http://timgolden.me.uk/wmi-project/wmi.py


It cannot work either.


Oh well. It was only a quick fix! I'll try
to get some kind of non-ASCII edition of Windows
to test against. As I understand it, the situation
is that some WMI exception (ie coming from the
underlying WMI/COM subsystem) results in an error
message which contains non-ASCII characters.

Just so I'm not chasing red herrings, could you
paste the output from the following code, please?


import wmi # use the version linked above

c = wmi.WMI ("non-existent computer")

#
# Should give a traceback here for the DCOM
# error, not a UnicodeDecodeError.
#


Thanks

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


Re: Python internals

2008-07-16 Thread Ben Finney
Peter Anderson <[EMAIL PROTECTED]> writes:

> If Python doesn't do it like C and the others then what mechanism does
> it use

You've already been pointed to it, but here it is again:
http://effbot.org/zone/python-objects.htm>

-- 
 \ “I may disagree with what you say, but I will defend to the |
  `\death your right to mis-attribute this quote to Voltaire.” |
_o__) —Avram Grumer, rec.arts.sf.written, May 2000 |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list

Re: Is this correct behavior for default parameters?

2008-07-16 Thread Fredrik Lundh

Bruce Pearson wrote:

The first call to test has the file_list empty but on the second call to 
test the file_list is no longer empty but contains the values appended 
in the first call.


Is this correct behavior? I'm using python 2.5


yes:

http://docs.python.org/ref/function.html

"Default parameter values are evaluated when the function
definition is executed." (in bold, even)

it's also explained in the tutorial (section 4.7.1) and in the FAQ.

(it's always a good idea to double-check the documentation or google a 
little before convincing yourself that you may have found a bug in a 
commonly used part of a system that's over 15 years old and has been 
used by hundred of thousands of programmers).




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


Re: Is there any library that can extract titles from PDFs?

2008-07-16 Thread Fredrik Lundh

ZelluX wrote:


I want to write a script which will rename PDFs according to their
titles. I want to know if there is any library that can extract
titles(the first line of the PDF) from PDFs.


Mathieu Fenniak's PyPdf should be able to do this:

http://pybrary.net/pyPdf/

(but note that "the first line of the PDF" may not be the first thing 
that's rendered on the page, so don't expect such an approach to work 
for all files)




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


Re: bad recursion, still works

2008-07-16 Thread iu2
On Jul 16, 2:21 am, Michael Torrie <[EMAIL PROTECTED]> wrote:
> iu2 wrote:
> > I still don't understand: In each recursive call to flatten, acc
> > should be bound to a new [], shouldn't it? Why does the binding happen
> > only on the first call to flatten?
>
> Nope.  In each new call it's (re)bound to the same original list, which
> you've added to as your function continues--it's mutable.  Default
> variables that are bound to mutable objects are one of the big caveats
> that is mentioned in the FAQ.

Thanks guys, it's clear now
--
http://mail.python.org/mailman/listinfo/python-list


Re: Logging to different addressees

2008-07-16 Thread McA
Hi Vinay,

thank you for being so patient.

On 16 Jul., 01:21, Vinay Sajip <[EMAIL PROTECTED]> wrote:
> On Jul 15, 5:17 pm, McA <[EMAIL PROTECTED]> wrote:
>
> > > If you added the admin sink handler to the root logger, you're done.
>
> > Isn't that the first thing above? What do you mean?
>
> I gave you a choice - to add the handler to the admin_logger OR the
> root logger. So I am saying here that if you added to the root logger
> (and not common_logger, assuming they're different), then there's
> nothing more to do...

Reading the rest of your mail let me understand what you meant.

>
> # simple.py
> import logging
>
> admin_logger = logging.getLogger("") # The root logger
> addressee_logger = logging.getLogger("addressee")
>
> admin_sink = logging.FileHandler("admin.log", "w")
> addressee_sink = logging.FileHandler("addressee.log", "w")
>
> admin_logger.addHandler(admin_sink)
> addressee_logger.addHandler(addressee_sink)
>
> admin_logger.setLevel(logging.DEBUG)
>
> admin_logger.debug("This message appears in admin sink only.")
> addressee_logger.debug("This message appears in both admin sink and
> addressee sink."
>

Thank you for that snippet. That means, that the root-logger does
inherit
EVERY message (if it fits to the level and isn't filtered) and the
inheritage chain is build by the chosen logger names, e.g.
messages to logging.getLogger('tree.leave') would also show up in
logging.getLogger('tree') automatically?

If this is true, how can I avoid this "bubbling up" if I would like
to?
(You see, that's a new question, but I want to take the chance to get
the answers from you personally ;-)

Hope not to bother.

Best regards
Andreas Mock

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


Re: snippet to update local (bazaar, mercurial, svn) versioned source

2008-07-16 Thread Alia Khouri
On Jul 16, 8:34 am, Alia Khouri <[EMAIL PROTECTED]> wrote:
> Here's a very simple snippet I use to automatically keep my versioned
> sources fresh.. Posted here in case it may be of use to anybody...
>
> 
> #!/usr/local/bin/python
> import os, sys
>
> src = '/Users/ak/Code/src'
>
> # utility functions
> join, isdir, listdir = os.path.join, os.path.isdir
> def run(cmd):
>     print cmd
>     os.system(cmd)
>
> ops = {
>     '.bzr': ['bzr pull', 'bzr update'],
>     '.hg': ['hg pull', 'hg update'],
>     '.svn': ['svn update']
>
> }
>
> for folder in os.listdir(src):
>     target = os.path.join(src,folder)
>     if os.path.isdir(target):
>         internal = os.listdir(target)
>         for f in internal:
>             if f in ops:
>                 print
>                 os.chdir(target)
>                 cmds = ops[f]
>                 print
>                 print target, '-->',
>                 for cmd in cmds:
>                     run(cmd)
>
> 

My bad, here's the one that actually (-:



#!/usr/local/bin/python
import os, sys

src = '/Users/sa/Code/src'

# utility functions
join, isdir = os.path.join, os.path.isdir
def run(cmd):
print cmd
os.system(cmd)

ops = {
'.bzr': ['bzr pull', 'bzr update'],
'.hg': ['hg pull', 'hg update'],
'.svn': ['svn update']
}

for folder in os.listdir(src):
target = join(src,folder)
if isdir(target):
internal = os.listdir(target)
for f in internal:
if f in ops:
print
# print f, target
os.chdir(target)
cmds = ops[f]
print
print target, '-->',
for cmd in cmds:
run(cmd)



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


How can i use a variable without define it ?

2008-07-16 Thread zhw
How can i use a variable without define it ?

I have thought about the __import__ function,  but the docs says "the
__import__() function does not set the local variable named eggs"。

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


Re: Amazon: "Practical Django Projects" by James Bennett (June 2008)

2008-07-16 Thread Stefan Scholl
Dave U. Random <[EMAIL PROTECTED]> wrote:
> http://snipr.com/PracticalDjango

June 2008 is a bit too early. Django isn't ready.


-- 
Web (en): http://www.no-spoon.de/ -*- Web (de): http://www.frell.de/
--
http://mail.python.org/mailman/listinfo/python-list


Re: iterator clone

2008-07-16 Thread Yosifov Pavel
On 16 июл, 11:32, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Tue, 15 Jul 2008 19:54:30 -0700, Yosifov Pavel wrote:
> > Kay, can you show example of such generator? ReIter, for example, work
> > with usual generators.
>
> > But for "big" iterator, I think is no any good solutions. IMHO we can
> > discern 2 types of iterators: re-startable (based on internal Python
> > objects) and not re-startable (with an external state, side-
> > effects)...
>
> Has nothing to do with internal vs. external.
> Examples: ``itertools.count(1)``, ``itertools.cycle(iterable)``, or
>
> def fib():
> a, b = 0, 1
> while True:
> yield a
> a, b = b, a + b
>
> Ciao,
> Marc 'BlackJack' Rintsch

Yes. So, I'm disconcerted: what Python "means" about iterators. Why
iterator's are not clonable in default?.. ``itertools.count(it) ``
"suppose" ``it`` will be restarted after count? So ``count(it)``
"suppose" ``it`` is restarable and therefore clonable (why not?!).
Generator is only function, so can be restarted/cloned. Generator
keeps "position" and can't be iterated again. But this position can be
reseted (main rule: if generator function has not side-effects/
external state, see below)!

Iterator, I think, is more general method (for naturally serial
access). For example, you can read values from some device (RS323 or
other) and represent it in program like iterator. In this case,
``__iter__()`` make some preparation, ``next()`` read next value from
RS232. In this case, iterator can't be restarted and really cloned. It
has external state (state of device) and can't to return it at start.
But when series of values are generated (are born) in the program: no
problem to have the feature of clone/restart iterator.

And is very interesting to research Icon iterators. Is possible to
create something in Python such theirs, for non-deterministic solving
purpose... :-)

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

Re: How can i use a variable without define it ?

2008-07-16 Thread Ben Finney
zhw <[EMAIL PROTECTED]> writes:

> How can i use a variable without define it ?

What do you mean by "use"? That's so vague I can think of many
possible interpretations.

What do you mean by "variable"? That term carries a lot of baggage
that doesn't apply in Python.

Can you give a small, complete example that demonstrates the issue
you're trying to solve?

-- 
 \  “The face of a child can say it all, especially the mouth part |
  `\of the face.” —Jack Handey |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list

Re: reading one byte from stdin

2008-07-16 Thread Fredrik Lundh

Mark McDuff wrote:


I'm trying to read one byte from stdin, without the newline.

If I try something like:
 >>> import os, sys
 >>> os.read(sys.stdin.fileno(),1)

I can input a character, but then I have to press enter, which leaves a 
newline character in the stdin buffer and requires two keypresses.  Is 
there any way to read only one keypress in a simple manner (i.e. no 
curses)?


in addition to the cookbook article Diez posted, there's also a FAQ 
entry about this:


http://effbot.org/pyfaq/how-do-i-get-a-single-keypress-at-a-time.htm



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


RE: isPrime works but UnBoundLocalError when mapping on list

2008-07-16 Thread Andreas Tawn
Terry Reedy wrote:
>Wrong.
Thank you.

>For loop variables continue after the loop exits.  This is 
>intentional.
I never knew that and I can't find reference to it in the docs. Can you
help me with the reasons for it?

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


Re: Amazon: "Practical Django Projects" by James Bennett (June 2008)

2008-07-16 Thread Fredrik Lundh

Stefan Scholl wrote:


Django isn't ready.


That's a remarkably ignorant statement.



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


Re: How can i use a variable without define it ?

2008-07-16 Thread zhw
On 7月16日, 下午4时47分, Ben Finney <[EMAIL PROTECTED]>
wrote:
> zhw <[EMAIL PROTECTED]> writes:
> > How can i use a variable without define it ?
>
> What do you mean by "use"? That's so vague I can think of many
> possible interpretations.
>
> What do you mean by "variable"? That term carries a lot of baggage
> that doesn't apply in Python.
>
> Can you give a small, complete example that demonstrates the issue
> you're trying to solve?
>
> --
>  \  “The face of a child can say it all, especially the mouth part |
>   `\of the face.” ―Jack Handey |
> _o__)  |
> Ben Finney

Thank you! Sorry for my poor english!

Here is a example that I want to complete:
>>> import sys, new
>>> context={"name":"david", "sex":"male"}
>>> sys.modules["foo"] = new.module("foo")
>>> import foo
>>> for attr in context:
setattr(foo, attr, context[attr])

>>> def bar():
# here is a error
# import * only allowed at module level
from foo import *
print name, sex
>>> bar()


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

Re: Testing for connection to a website

2008-07-16 Thread Fredrik Lundh

Alexnb wrote:


e = ''


try: 
...

except HTTPError, e:
print e.code
except URLError, e:
print e.reason

if e == '':

print "good to go"


footnote: here's a better way to test if an exception was raised or not:

try:
...
except HTTPError, e:
print e.code
except URLError, e:
print e.reason
else:
print "good to go"



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


Re: isPrime works but UnBoundLocalError when mapping on list

2008-07-16 Thread Fredrik Lundh

Andreas Tawn wrote:


I never knew that and I can't find reference to it in the docs.


the for-in loop does ordinary assignments in the current scope:

http://docs.python.org/ref/for.html

"Each item in turn is assigned to the target list using the
standard rules for assignments, and then the suite is executed."

somewhat simplified, "for vars in expression: code" is equivalent to 
inlining:


_ = iter(expression)
while 1:
try:
vars = _.next()
except StopIteration:
break
else:
body

where "_" is an internal variable.



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


Re: How can i use a variable without define it ?

2008-07-16 Thread Ben Finney
zhw <[EMAIL PROTECTED]> writes:

> Here is a example that I want to complete:
> >>> import sys, new
> >>> context={"name":"david", "sex":"male"}

Here you have a set of values addressible by name.

> >>> sys.modules["foo"] = new.module("foo")

Why do you believe you need to create a module object?

> >>> import foo
> >>> for attr in context:
>   setattr(foo, attr, context[attr])

This doesn't appear to get you anything that isn't already available
with the 'context' mapping.

> >>> def bar():
> # here is a error
> # import * only allowed at module level
>   from foo import *
> print name, sex

You can simply do:

>>> context = {'name': "david", 'sex': "male"}
>>> def bar():
... print context['name'], context['sex']
...
>>> bar()
david male

Or, more flexible and more explicit:

>>> foo = {'name': "david", 'sex': "male"}
>>> def bar(context):
... print context['name'], context['sex']
...
>>> bar(foo)
david male

What problem are you trying to solve?

-- 
 \  “The best mind-altering drug is truth.” —Jane Wagner, via Lily |
  `\Tomlin |
_o__)  |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list

Re: How can i use a variable without define it ?

2008-07-16 Thread zhw
On 7月16日, 下午5时35分, Ben Finney <[EMAIL PROTECTED]>
wrote:
> zhw <[EMAIL PROTECTED]> writes:
> > Here is a example that I want to complete:
> > >>> import sys, new
> > >>> context={"name":"david", "sex":"male"}
>
> Here you have a set of values addressible by name.
>
> > >>> sys.modules["foo"] = new.module("foo")
>
> Why do you believe you need to create a module object?
>
> > >>> import foo
> > >>> for attr in context:
> >setattr(foo, attr, context[attr])
>
> This doesn't appear to get you anything that isn't already available
> with the 'context' mapping.
>
> > >>> def bar():
> > # here is a error
> > # import * only allowed at module level
> >from foo import *
> > print name, sex
>
> You can simply do:
>
> >>> context = {'name': "david", 'sex': "male"}
> >>> def bar():
> ... print context['name'], context['sex']
> ...
> >>> bar()
> david male
>
> Or, more flexible and more explicit:
>
> >>> foo = {'name': "david", 'sex': "male"}
> >>> def bar(context):
> ... print context['name'], context['sex']
> ...
> >>> bar(foo)
> david male
>
> What problem are you trying to solve?

I an sorry, I can't tell you.

If you can't give a solution, just ignore it!

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

Re: new itertools functions in Python 2.6

2008-07-16 Thread Mark Dickinson
On Jul 16, 7:20 am, Mensanator <[EMAIL PROTECTED]> wrote:
> > > ##  Combinations with replacement
> > > ##  -
> > > ##  aaa aab aac aad aae abb abc abd abe acc acd ace
> > > ##  add ade aee bbb bbc bbd bbe bcc bcd bce bdd bde
> > > ##  bee ccc ccd cce cdd cde cee ddd dde dee eee
> > > ##
> > > ##  actual words: 35    (m+n-1)!/(n!(m-1)!) words: 35

>>> for x in combinations(range(7), 4):
... x = [-1] + list(x) + [7]
... print ''.join(c*(x[i+1]-x[i]-1) for i, c in
enumerate('abcde'))
...
eee
dee
dde
ddd
cee
cde
cdd
cce
ccd
ccc
bee
bde
bdd
bce
bcd
bcc
bbe
bbd
bbc
bbb
aee
ade
add
ace
acd
acc
abe
abd
abc
abb
aae
aad
aac
aab
aaa


Generalization left as an exercise for the reader.

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


Re: Using McMillan Installer, PyInstall or py2exe cross-platform?

2008-07-16 Thread Paul Boddie
On 15 Jul, 23:00, Hartmut Goebel <[EMAIL PROTECTED]> wrote:
>
> I started working on cross-pyinstall today.

Let us know how you get on! In theory, one should be able to build
Python (and derived works) using the mingw32 libraries and a suitable
cross-compiler on platforms other than Windows, but I've never
bothered to do so myself.

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


Re: How can i use a variable without define it ?

2008-07-16 Thread Cristina Yenyxe González García
Hello.

2008/7/16 zhw <[EMAIL PROTECTED]>:
> On 7月16日, 下午5时35分, Ben Finney <[EMAIL PROTECTED]>
> wrote:
>> zhw <[EMAIL PROTECTED]> writes:
>> > Here is a example that I want to complete:
>> > >>> import sys, new
>> > >>> context={"name":"david", "sex":"male"}
>>
>> Here you have a set of values addressible by name.
>>
>> > >>> sys.modules["foo"] = new.module("foo")
>>
>> Why do you believe you need to create a module object?
>>
>> > >>> import foo
>> > >>> for attr in context:
>> >setattr(foo, attr, context[attr])
>>

Forgetting these considerations (I agree with Ben, though), your error
is trying to use an 'import *' inside a function. You should take it
outside the function, and try to run it again.

>>
>> > >>> def bar():
>> > # here is a error
>> > # import * only allowed at module level
>> >from foo import *
>> > print name, sex
>>

There are different import statements you can use in Python. I
recommend you to take a look at the tutorial to learn about the
differences between them: http://docs.python.org/tut/node8.html

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

Re: Modify a string's value

2008-07-16 Thread s0suk3
On Jul 15, 11:55 pm, Ben Finney <[EMAIL PROTECTED]>
wrote:
> [EMAIL PROTECTED] writes:
> > I just came across this unusual situation where I'd like to modify a
> > string passed to a function
>
> Again: Why? The normal way to do this is to create a new string and
> return that.
>


Yes, usually, but that won't work in this case (look at my previous
post around the 'cin >> line' line). This is what I came up with:

class StreamLineBuffer:
def __init__(self):
self.buf = ""

def __rrshift__(self, stream):
self.buf = stream.readline()

def __str__(self):
return self.buf

cin = sys.stdin
buf = StreamLineBuffer()

cin >> buf
line = str(buf)

Works like a charm :)

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


RE: Logging in __del__()

2008-07-16 Thread Robert Rawlins
Hi Vinay,

> Python uses reference counting with a cycle detector, but the
> detector's behaviour is different if there are finalizers  (__del__) -
> see
>
> http://www.python.org/doc/ext/refcounts.html
>

Thank you for the link, that certainly explains a great deal. 

So, am I right to assume that python will still handle its garbage disposal
if I implement __del__(), it just handles circular references in a slightly
different way, but to the same effect. Right?

Cheers,

Robert

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


Re: How can i use a variable without define it ?

2008-07-16 Thread Chris
On Jul 16, 11:06 am, zhw <[EMAIL PROTECTED]> wrote:
> On 7月16日, 下午4时47分, Ben Finney <[EMAIL PROTECTED]>
> wrote:
>
>
>
> > zhw <[EMAIL PROTECTED]> writes:
> > > How can i use a variable without define it ?
>
> > What do you mean by "use"? That's so vague I can think of many
> > possible interpretations.
>
> > What do you mean by "variable"? That term carries a lot of baggage
> > that doesn't apply in Python.
>
> > Can you give a small, complete example that demonstrates the issue
> > you're trying to solve?
>
> > --
> >  \  "The face of a child can say it all, especially the mouth part |
> >   `\of the face." --Jack Handey |
> > _o__)  |
> > Ben Finney
>
> Thank you! Sorry for my poor english!
>
> Here is a example that I want to complete:>>> import sys, new
> >>> context={"name":"david", "sex":"male"}
> >>> sys.modules["foo"] = new.module("foo")
> >>> import foo
> >>> for attr in context:
>
> setattr(foo, attr, context[attr])
>
> >>> def bar():
>
> # here is a error
> # import * only allowed at module level
> from foo import *
> print name, sex
>
> >>> bar()
>
>

def bar():
from foo import name, sex
print name, sex

You will need to know beforehand what attributes you want to import
into the function.
--
http://mail.python.org/mailman/listinfo/python-list

Re: isPrime works but UnBoundLocalError when mapping on list

2008-07-16 Thread Tim Golden

Andreas Tawn wrote:

Terry Reedy wrote:

Wrong.

Thank you.

For loop variables continue after the loop exits.  This is 
intentional.
I never knew that and I can't find reference to it in the docs. 


Interesting starting point. It never occurred to me
that they might not. (So I didn't look for anything
in the docs when they did :) ).

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


Get current class namespace.

2008-07-16 Thread Robert Rawlins
Guys,

 

What's the simplest way to access a classes namespace from within itself. I
want to use it in a custom __repr__() method so it prints the current
namespace for the class like package.module.class.

 

Suggestions? I'm sure there is a simple enough method built in to help me
here, I've just not seen it before.

 

Cheers,

 

Robert

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

Re: Get current class namespace.

2008-07-16 Thread Fredrik Lundh

Robert Rawlins wrote:

What’s the simplest way to access a classes namespace from within 
itself. I want to use it in a custom __repr__() method so it prints the 
current namespace for the class like package.module.class.


Name or namespace?  You can access the class name from an instance via 
the __class__ attribute:


>>> class foo:
... def __repr__(self):
... return "<%s instance at %x>" % (
... self.__class__.__name__, id(self)
... )
...
>>> foo()


The module the class was defined in is also available:

>>> class foo:
... def __repr__(self):
... return "<%s.%s instance at %x>" % (
... self.__class__.__module__, self.__class__.__name__,
... id(self)
... )
...
>>> foo()
<__main__.foo instance at c9fbc0>

To get the namespace (that is, the collection of (name, value)
pairs that make up the class' contents), use vars(self.__class__)
(or vars(self), if you want the full instance).



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


Re: bad recursion, still works

2008-07-16 Thread Jeff
On Jul 15, 7:21 pm, Michael Torrie <[EMAIL PROTECTED]> wrote:
> iu2 wrote:
> > I still don't understand: In each recursive call to flatten, acc
> > should be bound to a new [], shouldn't it? Why does the binding happen
> > only on the first call to flatten?
>
> Nope.  In each new call it's (re)bound to the same original list, which
> you've added to as your function continues--it's mutable.  Default
> variables that are bound to mutable objects are one of the big caveats
> that is mentioned in the FAQ.

Is this avoidable by using a call to list() in the definition instead?
--
http://mail.python.org/mailman/listinfo/python-list


Re: bad recursion, still works

2008-07-16 Thread oj
On Jul 16, 1:09 pm, Jeff <[EMAIL PROTECTED]> wrote:
> On Jul 15, 7:21 pm, Michael Torrie <[EMAIL PROTECTED]> wrote:
>
> > iu2 wrote:
> > > I still don't understand: In each recursive call to flatten, acc
> > > should be bound to a new [], shouldn't it? Why does the binding happen
> > > only on the first call to flatten?
>
> > Nope.  In each new call it's (re)bound to the same original list, which
> > you've added to as your function continues--it's mutable.  Default
> > variables that are bound to mutable objects are one of the big caveats
> > that is mentioned in the FAQ.
>
> Is this avoidable by using a call to list() in the definition instead?

No.

Probably what you'd want to do, is something like this:

def func(arg1, arg2=None):
if arg2 is None:
arg2 = list()

...

So you create a list at runtime if arg2 has its default value.
--
http://mail.python.org/mailman/listinfo/python-list


Re: How can i use a variable without define it ?

2008-07-16 Thread Ben Finney
zhw <[EMAIL PROTECTED]> writes:

> On 7月16日, 下午5时35分, Ben Finney <[EMAIL PROTECTED]>
> wrote:
> > What problem are you trying to solve?
> 
> I an sorry, I can't tell you.

Perhaps I'm not being clear: What *programming* problem are you trying
to solve?

I ask because it seems you are focussed to much on some specific
method, when it is very likely that your problem is better solved
using different methods.

> If you can't give a solution, just ignore it!

I *did* give a solution. If that doesn't work for you, please tell us
more about the problem so we can provide better solutions.

-- 
 \  “Say what you will about the Ten Commandments, you must always |
  `\ come back to the pleasant fact that there are only ten of |
_o__) them.” —Henry L. Mencken |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list

RE: isPrime works but UnBoundLocalError when mapping on list

2008-07-16 Thread Andreas Tawn
 
> Andreas Tawn wrote:
> > Terry Reedy wrote:
> >> Wrong.
> > Thank you.
> > 
> >> For loop variables continue after the loop exits.  This is 
> >> intentional.
> > I never knew that and I can't find reference to it in the docs. 
> 
> Interesting starting point. It never occurred to me
> that they might not. (So I didn't look for anything
> in the docs when they did :) ).
> 
> TJG

I don't have experience of too many other languages, but in C++ (and I
guess C)...

for (int i=0; i<10; ++i)
{
doStuff(i);
}

doStuff(i); // Error

int i;

for (i=0; i<10;++i)
{
doStuff(i);
}

doStuff(i); // No error

That's the behaviour I was expecting.

Is the Python behaviour just a happy side effect of the target list
assignment or specific design decision?

Cheers,

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


Re: About wmi

2008-07-16 Thread patrol
On 7月16日, 下午3时29分, Tim Golden <[EMAIL PROTECTED]> wrote:
> patrol wrote:
> >>http://timgolden.me.uk/wmi-project/wmi.py
>
> > It cannot work either.
>
> Oh well. It was only a quick fix! I'll try
> to get some kind of non-ASCII edition of Windows
> to test against. As I understand it, the situation
> is that some WMI exception (ie coming from the
> underlying WMI/COM subsystem) results in an error
> message which contains non-ASCII characters.
>
> Just so I'm not chasing red herrings, could you
> paste the output from the following code, please?
>
> 
> import wmi # use the version linked above
>
> c = wmi.WMI ("non-existent computer")
>
> #
> # Should give a traceback here for the DCOM
> # error, not a UnicodeDecodeError.
> #
> 
>
> Thanks
>
> TJG
The errors are in the following:

Traceback (most recent call last):
  File "D:\My Documents\code\python\wmi\test.py", line 5, in 
c = wmi.WMI ("non-existent computer")
  File "C:\Python25\lib\wmi.py", line 1199, in connect
handle_com_error (error_info)
  File "C:\Python25\lib\wmi.py", line 184, in handle_com_error
exception_string = [u"%s - %s" % (hex (hresult_code),
hresult_name)]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position
4: ordinal not in range(128)

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

Re: Python internals

2008-07-16 Thread Scott David Daniels

Peter Anderson wrote:
Thanks everyone!  Just a quick correction - "as the original poster is" 
is a bit of a jump that does not reflect my original question. I DO 
understand how C and other programming languages handle variables 
internally (the bits of actual memory reserved, etc. etc.) and that's 
why I asked the question in the first place.


If Python doesn't do it like C and the others then what mechanism does 
it use - it's the sort of issue that helps me understand how the 
language is interacting with the underlying operating system/hardware.


The easiest way to think of this is that Python uses mostly dictionaries
dictionaries for namespaces, and a few places it uses other techniques
if there are over-riding considerations that make the dictionaries
impractical in particular cases.  Python performance would be crippled
if their dictionary implementation(s) slowed down, much as C performance
would suffer is access to RAM slowed down.

--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why is this blowing the stack, thought it was tail-recursive...

2008-07-16 Thread Lie
On Jul 13, 8:44 pm, Fuzzyman <[EMAIL PROTECTED]> wrote:
> On Jul 13, 7:56 am, Steven D'Aprano <[EMAIL PROTECTED]
>
>
>
> cybersource.com.au> wrote:
> > On Sat, 12 Jul 2008 19:25:18 -0400, Terry Reedy wrote:
> > > ssecorp wrote:
> > >> def fib(n):
> > >>     def fibt(a, b, n):
> > >>         if n <= 1:
> > >>             return b
> > >>         else:
> > >>             return fibt(b, a + b, n - 1)
> > >>     if n == 0:
> > >>         return 0
> > >>     else:
> > >>         return fibt(0, 1, n);
>
> > >> and can memoization speed up this even more? tesintg with memoization
> > >> doesnt really say anything because it is so fast it is instant anyway.
>
> > > Except for the fact that a+b gets slower as a and b get bigger, this
> > > would already be linear time in n.  Memoization (here by means of a
> > > linear list) only helps if the list is preserved and one makes repeated
> > > requests for various fib values.
>
> > > I am just curious what input you tried that blew the stack?  It had to
> > > be pretty large.
>
> > No, not really. Try it for yourself: on my system, I get RuntimeError:
> > maximum recursion depth exceeded with fib(999).
>
> > fib(999) is a large number, with 208 digits, but not that large:
>
> > 268638100244853593861467272021429239676166093189869523401
> > 231759976179817002478816893383696544833565641918278561614
> > 433563129766736422103503246348504103776803673341511728991
> > 69723197082763985615764450078474174626L
>
> > --
> > Steven
>
> The default CPython recursion limit is 1000 - so hitting it with an
> input of 999 is not that surprising...
>
> You can set a higher limit with sys.setrecursionlimit(...)

Though that would be a kludge, not a fix. Using iteration or generator
expression is better.

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


Re: Need Python Programmer (preferentially in Los Angeles)

2008-07-16 Thread Scott David Daniels

robnhood00 wrote:

I need a python programmer that can integrate graphics into an
existing python application.  The application is a basic application
and the job should be pretty easy for an experienced Python
programmer.  Los Angeles programmer is preferred but this can
obviously be done from anywhere.
Please contact me at [EMAIL PROTECTED] is you can help me.
Thank you.


I get worried when I hear people tell me that a job they don't know
how to do "should be pretty easy," but at least it is better than
"should only take a week."  What I'd rather hear is, "seems like it
is a simple job."

Beware of customers who know something will take little effort
without being able to characterize that effort.

--Scott David Daniels
[EMAIL PROTECTED]

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


Re: isPrime works but UnBoundLocalError when mapping on list

2008-07-16 Thread Fredrik Lundh

Andreas Tawn wrote:


I don't have experience of too many other languages, but in C++ (and I
guess C)...


That's invalid C (you cannot declare variables in the "for" statement 
itself, at least not in C89).  And back in the old days, some C++ 
compilers did in fact leak declarations from "for" loops, and others 
didn't...



Is the Python behaviour just a happy side effect of the target list
assignment or specific design decision?


I'd say it all follows from the fact that Python doesn't have variable 
declarations; if you want to stick to the principle that variables can 
introduced simply by assigning to them, you cannot introduce new blocks 
nilly-willy.  So none of the basic structural elements do that; 
variables introduced inside an "if" statement or a "for-in" statement 
are no different from variables introduced outside them.  And intro-
ducing a new block only for the loop variables would be confusing and 
rather impractical, given how fundamental looping over sequences and 
iterables are in Python.


(the discussions about loop variables in list comprehensions and 
generator expressions are a bit different; they're expressions, not 
statements, and shouldn't really do assignments as a side effect, any 
more than function calls should leak parameter names into the calling 
scope...)




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


Re: bad recursion, still works

2008-07-16 Thread Fredrik Lundh

Jeff wrote:


Is this avoidable by using a call to list() in the definition instead?


No.  Default values are *always* evaluated when, and only when, the 
"def" statement is executed; see:


http://docs.python.org/ref/function.html

Also note that "def" is an executable statement in Python, and that 
default arguments are evaluated in the "def" statement's environment. 
If you execute "def" multiple times, it'll create a new function object 
(with freshly calculated default values) each time.


:::

The workaround is, as others have mentioned, to use a placeholder value 
instead of modifying the default value.  None is a common value:


def myfunc(value=None):
if value is None:
value = default()
# go on an modify value

If you need to handle arbitrary objects (including None), you can use a 
sentinel object:


sentinel = object()

def myfunc(value=sentinel):
if value is sentinel:
value = default()

(in older code, written before "object" was introduced, you sometimes 
see things like "sentinel = ['placeholder']" used to create a non-false 
object with a unique identity; [] creates a new list every time it is 
evaluated.)


:::

Finally, it should be noted that more advanced Python code often uses 
this mechanism to its advantage; for example, if you create a bunch of 
UI buttons in a loop, you might try something like:


 for i in range(10):
 def callback():
 print "clicked button", i
 UI.Button("button %s" % i, callback)

only to find that all callbacks print the same value (most likely 9, in 
this case).  The reason for this is that Python's nested scopes bind to 
variables, not object values, so all callback instances will see the 
current (=last) value of the "i" variable.  To fix this, use explicit 
binding:


 for i in range(10):
 def callback(i=i):
 print "clicked button", i
 UI.Button("button %s" % i, callback)

The "i=i" part binds a local variable "i" to the *current* value of the 
outer variable "i".


Two other uses are local caches/memoization; e.g.

def calculate(a, b, c, memo={}):
try:
value = memo[a, b, c] # return already calculated value
except KeyError:
value = do calculation on a, b, c
memo[a, b, c] = value # update the memo dictionary
return value

(this is especially nice for certain kinds of recursive algorithms)

and, for highly optimized code, local rebinding of global names:

def this_one_must_be_fast(x, sin=math.sin, cos=math.cos):
...

Hope this helps more than it confuses.



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


Re: How to figure out if the platform is 32bit or 64bit?

2008-07-16 Thread Ken Hartling
Thanks .. but I want to find out if the system is "running on 64bit" even
when the interpreter is a
32-bit build executable ("what python was built on").
platform.architecture() and platform() in general seems to only be looking
at the build executable and what it was built for on windows (sorry, I don't
have a unix box available at the moment).  platform.architecture() returns
32bit when on a windows 64bit box.

Another recommendation was:
import sys
hex(sys.maxint)
x = sys.maxint
n = 1
while x:
n += 1
x >>= 1

print n

Unfortunately this too appears to be looking at the build executable ... on
Windows 64 it returns '32'.

Thanks for the suggestions, hopefully we'll come up with a winner.

Ken


On Tue, Jul 15, 2008 at 1:39 PM, Benjamin Kaplan <[EMAIL PROTECTED]>
wrote:

>
>
> On Tue, Jul 15, 2008 at 4:10 PM, <[EMAIL PROTECTED]> wrote:
>
>> I need to know if I'm running on 32bit or 64bit ... so far I haven't
>> come up with how to get this info via python. sys.platform returns
>> what python was built on ... but not what the current system is.
>>
>> I thought platform.uname() or just platform.processor() would have
>> done it, but python returns an empty string on windows. Any ideas?
>>
>> Thanks, Ken
>> --
>
>
> platform.architecture() should have it.
>
>
--
http://mail.python.org/mailman/listinfo/python-list

Securing mobile Python code

2008-07-16 Thread Mads Kristensen

Hi guys and girls.

I am currently developing an execution environment for mobile Python 
code. To that end I have developed a system called Scavenger based on 
Stackless Python. The biggest problem when working with mobile code is 
of course security - especially when working with a language such as 
Python that has no security modes. I have therefore used a 
validation/blacklisting approach towards code security, i.e., before the 
mobile code is executed it is validated and if it uses illegal 
operations it is rejected (apart from that I have also monkey-patched 
some functionality so that my own versions of built-in functions are 
invoked). Using such a blacklist approach is of course problematic 
because one has to know about every possible way to circumvent the 
system to be sure of its validity... This is where you come in: To test 
the security of my system I have placed a Scavenger host on the Internet 
that will perform any Python code you throw at it. I would like to 
invite anybody with an interest in Python and security to participate in 
this "Hack-Attack" on my Scavenger host :-)


For more information see: http://www.daimi.au.dk/~madsk/?cat=15

Thanks for your time!

Best regards,
Mads Kristensen
--
http://mail.python.org/mailman/listinfo/python-list


python's YENC.DECODE -> weird output

2008-07-16 Thread John Savage
I save posts from a midi music newsgroup, some are encoded with
yenc encoding. This gave me an opportunity to try out the decoders 
in Python. The UU decoder works okay, but my YENC effort gives
results unexpected:

import yenc, sys

fd1=open(sys.argv[1],'r') 
#yenc.encode(sys.argv[1],"outfile.yenc",bytes=0)
yenc.decode(sys.argv[1],"outfile.mid",bytes=0,crc_in='')

I confirmed that yenc.decode exactly reverses yenc.encode, BUT the
encoding itself seems to differ from the USENET standard. That is,
when I decode USENET files the result isn't a valid music file. 
(I did try both with and w/o the headers.)

Maybe it uses a different character set? I can't quite put my
finger on what might be happening. What I can say is that the
yenc coding from the newsgroup article, when viewed with Linux
'more', displays roughly 10% of its characters as a question mark,
whereas when I give Python's yenc.encode a binary music file and
view its output using 'more', it displays about 90% of the output
as a question mark.

Any ideas?
-- 
John Savage(my news address is not valid for email)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Logging to different addressees

2008-07-16 Thread Vinay Sajip
On Jul 16, 8:55 am, McA <[EMAIL PROTECTED]> wrote:
> Thank you for that snippet. That means, that the root-logger does
> inherit
> EVERY message (if it fits to the level and isn't filtered) and the
> inheritage chain is build by the chosen logger names, e.g.
> messages tologging.getLogger('tree.leave') would also show up 
> inlogging.getLogger('tree') automatically?

Yes.

> If this is true, how can I avoid this "bubbling up" if I would like
> to?
> (You see, that's a new question, but I want to take the chance to get
> the answers from you personally ;-)
>
> Hope not to bother.
>

Use the propagate flag, which is mentioned in the documentation. In
fact, please make sure you've reviewed all the documentation before
posting, as the documentation is intended to answer the more
straightforward and common questions which come up.

Best regards,

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


Re: How to figure out if the platform is 32bit or 64bit?

2008-07-16 Thread Fredrik Lundh

Ken Hartling wrote:

> Thanks .. but I want to find out if the system is "running on 64bit"
> even when the interpreter is a 32-bit build executable ("what python
> was built on").  platform.architecture() and platform() in general
> seems to only be looking at the build executable

You can pass in an arbitrary binary to architecture(), so I guess you 
could use this on some suitable thing under "/bin" on a Unix box.  This 
doesn't work on Windows, though.


In this message,

http://mail.python.org/pipermail/python-list/2005-June/326158.html

Thomas Heller suggests using ctypes to call the Windows API directly; so 
something like this could work:


>>> import ctypes, sys
>>> i = ctypes.c_int()
>>> kernel32 = ctypes.windll.kernel32
>>> process = kernel32.GetCurrentProcess()
>>> kernel32.IsWow64Process(process, ctypes.byref(i))
1
>>> is64bit = (i.value != 0)
>>> is64bit
False

(IsWow64Process returns a non-zero value if it manages to check the 
status, and sets the variable to a non-zero value if the process is 
running under WOW64.  I only have 32-bit boxes here, so it's only 
partially tested).


And yes, looks like official support for this might appear in 2.6:

http://mail.python.org/pipermail/python-dev/2008-May/079022.html

(in that thread, Mark Hammond suggests "'64 bit' in sys.version" as a 
workaround, but warns for false negatives).




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


Playing stereo wav files in Python

2008-07-16 Thread AM
-Hello all,

I am trying to play stereo wavefiles in python with no success. I can
play mono wavefiles, using either pygames mixer library, python's
winsound library or wxPython's wx.Sound library, but i cannot get
stereo wavefiles to play in any of these.  Normally i wouldn't care
and covert the files to mono, but the phase difference between the two
ears in important for this application. Does anyone know of a way that
i have missed? I am using a LynxONE soundcard if that is important.

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


Re: How to figure out if the platform is 32bit or 64bit?

2008-07-16 Thread Tim Golden

Fredrik Lundh wrote:

Ken Hartling wrote:

 > Thanks .. but I want to find out if the system is "running on 64bit"
 > even when the interpreter is a 32-bit build executable ("what python
 > was built on").  platform.architecture() and platform() in general
 > seems to only be looking at the build executable

You can pass in an arbitrary binary to architecture(), so I guess you 
could use this on some suitable thing under "/bin" on a Unix box.  This 
doesn't work on Windows, though.


In this message,

http://mail.python.org/pipermail/python-list/2005-June/326158.html

Thomas Heller suggests using ctypes to call the Windows API directly; so 
something like this could work:


 >>> import ctypes, sys
 >>> i = ctypes.c_int()
 >>> kernel32 = ctypes.windll.kernel32
 >>> process = kernel32.GetCurrentProcess()
 >>> kernel32.IsWow64Process(process, ctypes.byref(i))
1
 >>> is64bit = (i.value != 0)
 >>> is64bit
False


This is included in the latest pywin32-211 as well:


import win32process
print win32process.IsWow64Process ()



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


Re: How to figure out if the platform is 32bit or 64bit?

2008-07-16 Thread Fredrik Lundh

Tim Golden wrote:


This is included in the latest pywin32-211 as well:


import win32process
print win32process.IsWow64Process ()



on the other hand, "ctypes" is only an import away if you have a current 
Python...




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


Regular expression

2008-07-16 Thread Beema shafreen
Hi all,

How do I write a regular expression for this kind of sequences

>gi|158028609|gb|ABW08583.1| CG8385-PF, isoform F [Drosophila melanogaster]
MGNVFANLFKGLFGKKEMRILMVGLDAAGKTTILYKLKLGEIVTTIPTIGFNVETVE

thanks

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

Re: Regular expression

2008-07-16 Thread Fredrik Lundh

Beema shafreen wrote:


How do I write a regular expression for this kind of sequences

 >gi|158028609|gb|ABW08583.1| CG8385-PF, isoform F [Drosophila melanogaster]
MGNVFANLFKGLFGKKEMRILMVGLDAAGKTTILYKLKLGEIVTTIPTIGFNVETVE


line.split("|") ?

it's a bit hard to come up with a working RE with only a single sample; 
what are the constraints for the different fields?  is the last part 
free form text or something else, etc.


have you googled for existing implementations of the format you're using?



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


Best Python packages?

2008-07-16 Thread Ben Sizer
Although the standard library in Python is great, there are
undoubtedly some great packages available from 3rd parties, and I've
encountered a few almost by accident. However, I don't know how a user
would become aware of many of these. http://pypi.python.org/pypi/
presumably lists most of the decent ones, but there's a lot there and
little indication as to quality or popularity - great if you know
exactly what you need, but not so great for just browsing. I'd love to
have some way of finding out what hidden gems are out there in the
Python world which could make my development a lot easier. Any
suggestions?

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


Re: Logging to different addressees

2008-07-16 Thread McA
On 16 Jul., 15:38, Vinay Sajip <[EMAIL PROTECTED]> wrote:
> On Jul 16, 8:55 am, McA <[EMAIL PROTECTED]> wrote:
>
> > messages tologging.getLogger('tree.leave') would also show up 
> > inlogging.getLogger('tree') automatically?
>
> Yes.

Ok.

>
> > Hope not to bother.
>
> Use the propagate flag, which is mentioned in the documentation.

That's the right hint.


> In fact, please make sure you've reviewed all the documentation before
> posting, as the documentation is intended to answer the more
> straightforward and common questions which come up.

I did it and I'll do it again. :-)
You know, sometimes a piece of text/documentation starts to
become information for the reader when he exactly hits the
problem.

Anyway, thank you for your help and for that module.

> Best regards,
>
> Vinay Sajip

Best regards
Andreas Mock

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


Re: Best Python packages?

2008-07-16 Thread Fredrik Lundh

Ben Sizer wrote:


make my development a lot easier.


Knowing what kind of development you do might help, of course.  Some 
libraries are excellent in some contexts and suck badly in others...


Looking at things that larger projects and distributions use can also be 
a good idea.  For example, if you're doing scientific stuff, go directly 
to enthought.com.  If you're doing web stuff, look at the libraries big 
Django applications use.  Etc.




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


Re: About wmi

2008-07-16 Thread Tim Golden
patrol wrote:
> The errors are in the following:
> 
> Traceback (most recent call last):
>   File "D:\My Documents\code\python\wmi\test.py", line 5, in 
> c = wmi.WMI ("non-existent computer")
>   File "C:\Python25\lib\wmi.py", line 1199, in connect
> handle_com_error (error_info)
>   File "C:\Python25\lib\wmi.py", line 184, in handle_com_error
> exception_string = [u"%s - %s" % (hex (hresult_code),
> hresult_name)]
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position
> 4: ordinal not in range(128)

OK, I'm trying to set up a Virtual PC so I can install
a non-English XP. But would you mind running the
following code for me, please, so I can get a handle
on what's coming back:


import pythoncom
import win32com.client

try:
  win32com.client.GetObject ("winmgmts://blahblah")
except pythoncom.com_error, info:
  for i in info:
print repr (i)



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


Re: Logging in __del__()

2008-07-16 Thread Marc 'BlackJack' Rintsch
On Wed, 16 Jul 2008 12:38:50 +0100, Robert Rawlins wrote:

> So, am I right to assume that python will still handle its garbage disposal
> if I implement __del__(), it just handles circular references in a slightly
> different way, but to the same effect. Right?

No.  Circular references in objects with a `__del__()` implementation are
not collected!  Why are you using `__del__()` anyway?  Are you aware of
the promises that are *not* made!  It's not guaranteed when the method
is called nor if it is called at all!

Ciao,
Marc 'BlackJack' Rintsch
--
http://mail.python.org/mailman/listinfo/python-list


Angle brackets in command-line arguments?

2008-07-16 Thread Keith Hughitt
Hi all,

I am using someone else's script which expects input in the form of:

 ./script.py  arg2

I was wondering if the angle-brackets here have a special meaning? It
seems like
they specify an input and output stream to use in place of the
console. I could not
find anything in the python manual or Python in a Nut-shell though.

Anyone know?


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


Custom 'Float' class. Am I right here?

2008-07-16 Thread Prashant Saxena
import sys

class Float(float):
"""
Custom float datatype with addtional attributes.
"""

def __new__(self,
value=0.0, #default value
name='', # string
range=(0.0, 1.0) # tuple
)

try:
self.name = name
self.range = range
self.pos = (1, 1)
return float.__new__(self, value)
except:
print ('Invalid value : Float = %s %s' % (str(value), 
sys.exc_info()[:2]))


def setpos(self, value):
self.pos = value
def getpos(self):
return self.pos*2.0
p = property(getpos, setpos)

myFloat = Float(0.23)
print myFloat.pos

I am trying to create a custom 'float' datatype by subtyping default 'float'. 
There are few things I would like to know here:

1. How to make 'name' & 'range' only readable attributes.
2. The property 'p' is not working as it has to. What's wrong here?
3. I would be heavily instancing this class, and I won't be creating any new 
attribute on instance. Is there any way to optimize? __slots__?

Thanks



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

Re: Angle brackets in command-line arguments?

2008-07-16 Thread Marc 'BlackJack' Rintsch
On Wed, 16 Jul 2008 07:53:56 -0700, Keith Hughitt wrote:

> I am using someone else's script which expects input in the form of:
> 
>  ./script.py  arg2
> 
> I was wondering if the angle-brackets here have a special meaning? It
> seems like they specify an input and output stream to use in place of the
> console. I could not find anything in the python manual or Python in a
> Nut-shell though.
> 
> Anyone know?

That's not Python's business but the command shell's.  Those characters
are used for redirecting input and ouput from/to files in shells, so it
should be covered in the documentation of the shell you are using. 
Including ways to protect the characters, so they reach the called program
in arguments.

Ciao,
Marc 'BlackJack' Rintsch
--
http://mail.python.org/mailman/listinfo/python-list


Re: Angle brackets in command-line arguments?

2008-07-16 Thread Fredrik Lundh

Keith Hughitt wrote:


I am using someone else's script which expects input in the form of:

 ./script.py  arg2


 is a common notation for "replace with argument value", so it 
could be that they're just expecting you to type:


./script.py arg1 arg2

Alternatively, they meant

./script.py arg2

in which case arg1 and arg2 are filenames.  This is most commonly used 
with tools that process textfiles in some way.  In the latter case, you 
can try the script simply by running:


 ./script.py

and then typing the input to the terminal (use control-D on Unix or 
control-Z on Windows to terminate).


Do the instructions use more meaningful names than "arg1" and "arg2"?



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


Re: Angle brackets in command-line arguments?

2008-07-16 Thread Gary Herron

Keith Hughitt wrote:

Hi all,

I am using someone else's script which expects input in the form of:

 ./script.py  arg2

I was wondering if the angle-brackets here have a special meaning? It
seems like
they specify an input and output stream to use in place of the
console. I could not
find anything in the python manual or Python in a Nut-shell though.

Anyone know?


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



In most Unix/Linux and related OS shells,  the angled brackets *do* 
specify input and output streams as you surmise.  However, they are 
*not* seen by the script  as command line arguments.  (And they are 
*not* brackets, and do not need to be matched. )


For any command,
 cmd < file
redirects the contents of file to cmd's standard input, which in Python 
is accessed by reading from sys.stdin (use input or raw_input or 
sys.stdin.read...)


Also for any command,
 cmd > file
redirects the output of cmd to the named file.  In Python this can be 
accessed using print, sys.stdout.write, ...


Anything written to sys.stderr will not be caught by the ">" 
redirection, ans so will probably end up on the screen instead of in file.


Also various shells will provide similar functionality using a variety 
of similar syntaxes:  <<, >>, >&, and |, and so on.


Gary Herron


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


poplib 100% cpu usage

2008-07-16 Thread Oli Schacher

Hi all

I wrote a multithreaded script that  polls mails from several pop/imap 
accounts. To fetch the messages I'm using the getmail classes ( 
http://pyropus.ca/software/getmail/ ) , those classes use the poplib for 
the real pop transaction.


When I run my script for a few hours cpu usage goes up to 100%, 
sometimes even 104% according to 'top' :-) This made our test machine 
freeze once. First I thought I maybe didn't stop my threads correctly 
after polling an account but I attached a remote debugger and it showed 
that threads are stopped ok and that the cpu gets eaten in poplib in the 
function "_getline" which states in the description:


---snip---
 # Internal: return one line from the server, stripping CRLF.
# This is where all the CPU time of this module is consumed.
# Raise error_proto('-ERR EOF') if the connection is closed.

def _getline(self):
---snip---


So for testing purposes I changed this function and added:
time.sleep(0.0001)
(googling about similar problems with cpu usage yields this time.sleep() 
trick)


It now looks ok, cpu usage is at about 30% with a few spikes to 80-90%.

Of course I don't feel cozy about changing a standard library as the 
changes will be overwritten by python upgrades.


Did someone else from the list hit a similar problem and maybe has a 
better solution?



Thanks for your hints.

Best regards,
Oli Schacher
--
http://mail.python.org/mailman/listinfo/python-list


Re: Angle brackets in command-line arguments?

2008-07-16 Thread Keith Hughitt
On Jul 16, 11:16 am, Gary Herron <[EMAIL PROTECTED]> wrote:
> Keith Hughitt wrote:
> > Hi all,
>
> > I am using someone else's script which expects input in the form of:
>
> >      ./script.py  arg2
>
> > I was wondering if the angle-brackets here have a special meaning? It
> > seems like
> > they specify an input and output stream to use in place of the
> > console. I could not
> > find anything in the python manual or Python in a Nut-shell though.
>
> > Anyone know?
>
> > Thanks,
> > Keith
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> In most Unix/Linux and related OS shells,  the angled brackets *do*
> specify input and output streams as you surmise.  However, they are
> *not* seen by the script  as command line arguments.  (And they are
> *not* brackets, and do not need to be matched. )
>
> For any command,
>   cmd < file
> redirects the contents of file to cmd's standard input, which in Python
> is accessed by reading from sys.stdin (use input or raw_input or
> sys.stdin.read...)
>
> Also for any command,
>   cmd > file
> redirects the output of cmd to the named file.  In Python this can be
> accessed using print, sys.stdout.write, ...
>
> Anything written to sys.stderr will not be caught by the ">"
> redirection, ans so will probably end up on the screen instead of in file.
>
>  Also various shells will provide similar functionality using a variety
> of similar syntaxes:  <<, >>, >&, and |, and so on.
>
> Gary Herron

Thanks all for the quick response. I should have known it was shell-
related. I haven't ever had to use this
kind of redirection before, mostly just the single-bracket version to
feed the contents of a file into some
command.

The reason it was causing me concern in the first place was that I was
trying to execute a python script
from Apache Ant, and it was failing. It turned out that when I escaped
the angle brackets in Ant, they were
there-after treated as normal command-line arguments, so when the
script was then executed, it just had
some additional values in sys.argv.

I ended up getting around the issue by creating a small bash-script
which simply wraps input in angle brackets
and then executes the python script itself. That way I didn't have to
escape anything in in Ant, and things
worked well.

Thanks everyone for taking the time to explain things to me. I really
appreciate the help :)

Take care,
Keith
--
http://mail.python.org/mailman/listinfo/python-list


Re: MySQL Insert

2008-07-16 Thread maestroQC
Thanks to all for your time and patience with this!
The insert is working fine based on the suggestions in this thread.

I now have another problem that should be resolved with a regular
expression to remove currency formatting before inserting into the db.
--
http://mail.python.org/mailman/listinfo/python-list


Setting Message Importance using SMTP Mail

2008-07-16 Thread Whyatt
Hi all,

I'm trying to create a message using SMTP Mail through Python with a
message Importance of either 0 (Low) or 2 (High).

If I do outer.Add_header('Importance', '0') it is ignored.

If I do uter.Replace_header('Importance', '0') I get the error below.
Traceback (most recent call last):
  File "#", line 840, in 
outer.Replace_header('Importance', '0')
AttributeError: MIMEMultipart instance has no attribute
'Replace_header'

Can anyone provide any clues on the correct way of updating the Msg
Importance header?

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


Re: About wmi

2008-07-16 Thread patrol
On 7月16日, 下午10时39分, Tim Golden <[EMAIL PROTECTED]> wrote:
> patrol wrote:
> > The errors are in the following:
>
> > Traceback (most recent call last):
> >   File "D:\My Documents\code\python\wmi\test.py", line 5, in 
> > c = wmi.WMI ("non-existent computer")
> >   File "C:\Python25\lib\wmi.py", line 1199, in connect
> > handle_com_error (error_info)
> >   File "C:\Python25\lib\wmi.py", line 184, in handle_com_error
> > exception_string = [u"%s - %s" % (hex (hresult_code),
> > hresult_name)]
> > UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position
> > 4: ordinal not in range(128)
>
> OK, I'm trying to set up a Virtual PC so I can install
> a non-English XP. But would you mind running the
> following code for me, please, so I can get a handle
> on what's coming back:
>
> 
> import pythoncom
> import win32com.client
>
> try:
>   win32com.client.GetObject ("winmgmts://blahblah")
> except pythoncom.com_error, info:
>   for i in info:
> print repr (i)
>
> 
>
> Thanks
> TJG

-2147023174
'RPC \xb7\xfe\xce\xf1\xc6\xf7\xb2\xbb\xbf\xc9\xd3\xc3\xa1\xa3'
None
None

--
import pythoncom
import win32com.client


try:
  win32com.client.GetObject ("winmgmts://blahblah")
except pythoncom.com_error, info:
  for i in info:
print i

-2147023174
RPC 服务器不可用。
None
None
-
>>> a="RPC 服务器不可用。"
>>> a
'RPC \xb7\xfe\xce\xf1\xc6\xf7\xb2\xbb\xbf\xc9\xd3\xc3\xa1\xa3'
>>>
-
Patrol
--
http://mail.python.org/mailman/listinfo/python-list

Re: About wmi

2008-07-16 Thread Tim Golden
patrol wrote:
> -2147023174
> 'RPC \xb7\xfe\xce\xf1\xc6\xf7\xb2\xbb\xbf\xc9\xd3\xc3\xa1\xa3'
> None
> None
> 
> --
> import pythoncom
> import win32com.client
> 
> 
> try:
>   win32com.client.GetObject ("winmgmts://blahblah")
> except pythoncom.com_error, info:
>   for i in info:
> print i
> 
> -2147023174
> RPC 服务器不可用。
> None
> None
> -
 a="RPC 服务器不可用。"
 a
> 'RPC \xb7\xfe\xce\xf1\xc6\xf7\xb2\xbb\xbf\xc9\xd3\xc3\xa1\xa3'
> -
> Patrol

Brilliant. Thanks, Patrol. So the error message comes back
encoded. Can you confirm what your console encoding is,
please? The following script should confirm:


import os, sys

print sys.stdout.encoding
os.system ("chcp")



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

Is there any interest in working on an application?

2008-07-16 Thread Ron Longo
Hello,

I have an python application which I've been developing for several years (off 
and on, mostly off for lack of time) which I'm considering putting up to open 
source if I can find other developers interested in contributing.

The application is a web publisher/information outliner.  (See an example of a 
beta here:  http://members.cox.net/ronpro/welcome.html where I test my ability 
to generate an interactive tree for the data in an outline.)

The application is 100% Python.  The gui is written using Tkinter and Tix -- 
I'm definitely open to other libraries for the GUI.  The app supports unicode 
in the outlines.  There's a spell-checker plugin (complements of the pyenchant 
project).  The application is written on top of an application framework and 
plugin framework both of which I developed myself.  Much of the application is 
actually plugins so it's very modular.  For screen shots of the app so far see: 
http://members.cox.net/ronpro/scrnCap1.JPG and 
http://members.cox.net/ronpro/scrnCap2.JPG

The development would probably be done through SourceForge.

I'm in the process of documenting the current design in UML class diagrams 
using the free version of Visual Paradigm (if another tool is suggested we 
could switch).

My motive:  I'm a research scientist.  My prefered method to record, review, 
edit and organize my notes is within an outline (rather than a flat notebook 
format used by most researchers).  The ability to consider new ideas can be as 
easy as moving items around in the outline.  I've used many commercial programs 
in the past but all have had some limitation or another.  Most don't support 
unicode (I need unicode characters to record mathematical and logical 
formulae).  Those that do produce html don't produce the side-by-side view of 
an interactive tree (able to expand or collapse nodes) beside the actual 
on-screen notes.  The interactive tree is a necessity for me with over 2000 
entries in my largest outline and growing fast.

Design Philosophy:  I've attempted to keep to the following design philosophy 
(prioritized by order).
- User Experience -- everything should be easy for the user.
- OO, Maximize modularity, minimize cross dependence.
  (e.g. The Application framework, plugin framework and word processor know 
nothing about the problem domain and nothing about the other modules in the 
application).
- KISS, I prefer simple straightforward code over speedy "tricks".  If it's 
hard to read or understand I'll probably hate it.
- Minimize 3rd party modules in the core application.  I know 3rd party libs 
can make it easier to develop and this would seem to violate KISS.  However, 
with User Experience being higher priority, the less there is for a user to 
install the easier.  Best case, the user installs Python and s/he's ready to 
go.  I don't mind requiring 3rd party libs for most plugins.  My take on this 
is here:
   - If it's part of the core distribution (the core application or a plugin 
that's part of the main distribution), do everything possible to avoid 3rd 
party libs.
   - For plugins distributed separately from the application installer, the 
plugin must check for the required libs upon loading and exit gracefully if the 
lib is not present (at most display a dialog stating that the required lib is 
not installed.)
- If at all possible, provide unit test with each module (including plugins)

Future Direction:
- Some of the features in the menus and on the toolbars are not yet implemented.
   (e.g. find, search/replace, bulletized and numbered lists, tables)
- The content of any tree entry is displayed in the content pane to the right 
of the outline.  Right now the only supported content is formatted text in a 
word processor (actually a glorified Text widget).  The Text widget is part of 
the core app.  I want this widget to be turned into a plugin so that other 
kinds of content are possible with other content editor plugins.  The main app 
would then select and display the appropriate content editor for a given kind 
of data.
- Currently, cutting and pasting is possible, however cutting and pasing 
formatted text is only possible within the application.  Want to support 
cutting and pasing stylized text with the system clipboard and other 
applications (word, star office, etc.)
- Import export other formats (importers and exporters are already plugins).  
We just need to write more of them.
- Support multiple views of a single outline so we can view different parts of 
the outline simultaneously.
- Support cutting and pasting, dragging and dropping across different outlines.
- Customizable appearance for HTML output.
- Anything else the development group or users can think of.


If you're interested in more information or trying out this app (note that it's 
very immature and probably only worthy of being called an alpa) please don't 
hesitate to contact me.

Thanks for reading,
Ron--
http://mail.python.org/mailman/listinfo/python-list

Re: Regular expression

2008-07-16 Thread bearophileHUGS
On Jul 16, 4:14 pm, Fredrik Lundh <[EMAIL PROTECTED]> wrote:
> Beema shafreen wrote:
> > How do I write a regular expression for this kind of sequences
>
> >  >gi|158028609|gb|ABW08583.1| CG8385-PF, isoform F [Drosophila melanogaster]
> > MGNVFANLFKGLFGKKEMRILMVGLDAAGKTTILYKLKLGEIVTTIPTIGFNVETVE
>
> line.split("|") ?
>
> it's a bit hard to come up with a working RE with only a single sample;
> what are the constraints for the different fields?  is the last part
> free form text or something else, etc.
>
> have you googled for existing implementations of the format you're using?

That'a a fasta file, so for the header line this is enough:
[part.strip() for part in line.split("|")]
But better is to use the biopython libs that already perform all such
things better.

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


Re: About wmi

2008-07-16 Thread Tim Golden
Assuming that the error comes back in the sys.stdout encoding, the following 
version *should* work ok. I still haven't got a non-English set up to test it 
on, but it certainly does return a Unicode error message.

http://timgolden.me.uk/wmi-project/wmi.py

The usual test case, if you wouldn't mind:


import wmi

wmi.WMI ("non-existent computer")



should give a (language-specific) error message, not an UnicodeDecodeError

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


Eclipse, Pydev, question

2008-07-16 Thread Ken Starks

I have a small project for further development
in eclipse, using the pyDev plug-in.

I am working on foo.py and bar.pyc is also
in the directory.

bar.py is not in the directory; it is someone
else's (confidential) file, and I don't get
the python source.

Can I run bar.pyc from eclipse ?
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to match whole word

2008-07-16 Thread Peng Yu
On Jul 15, 10:29 pm, Gary Herron <[EMAIL PROTECTED]> wrote:
> Peng Yu wrote:
> > Hi,
>
> > The following code snippet is from /usr/bin/rpl. I would like the it
> > to match a word, for example, "abc" in ":abc:". But the current one
> > would not match "abc" in ":abc:". I tried to modify it myself. Would
> > you please let me know what is the corrected way to do it?
>
> > Thanks,
> > Peng
>
> >if opts.whole_words:
> >regex = re.compile(r"(?:(?<=\s)|^)" + re.escape(old_str) + 
> > r"(?=\s|
> > $)",
> >   opts.ignore_case and re.I or 
> > 0)
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> The regular expression "\w+" will match (what might be your definition
> of) a word, and in particular will match abc in :abc:.   Regular
> expressions have lots of other special \-sequences that might be worth
> your while to read about:  http://docs.python.org/lib/re-syntax.html
>
> Gary Herron

I didn't read the docs and tried the following code.

regex = re.compile(r"\A" + re.escape(old_str) + r"\Z",
opts.ignore_case and re.I or 0)

But I'm not sure why it is not working.

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


Framework recommendations for web service?

2008-07-16 Thread Phillip B Oldham
We're looking at the next phase of development for our webapp, and the
main focus will be to move the core from the app to a web service so
other systems can use the data we've gathered (we're thinking along
the lines of the XML API of Highrise from 37Signals).

Its possible that we'll extend the service to allow access via vanilla
XML, JSON, and YAML at some point, however we've decided to use
Facebook's Thrift for connectivity initially to support as many techs
as possible and also because our web interface for the app is written
in PHP.

As we're extracting the core we'll be translating it to Python to make
use of the wealth of well-structured libraries and hopefully make the
project shorter. However, we've hit a snag in choosing a framework
around which to rebuild the service.

It seems the more popular frameworks (django, turbogears) are all
focused on providing web content. Since our core will be using thrift
to communicate, we don't need templating, feeds, admin pages (django),
or ajax (turbogears).

What we *do* need is a lightweight, simple framework that will allow
us to create a RESTful interface and throw code together fast. We'll
probably go with SQLObject (unless we can extract the ORM from django
- lazy evaluation would be very useful), and we're just looking for
something fast and light to sit between that and the thrift interfaces
we'll create.

So, can anyone suggest a lightweight python framework which just does
the essentials?
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to match whole word

2008-07-16 Thread Fredrik Lundh

Peng Yu wrote:


I didn't read the docs and tried the following code.

regex = re.compile(r"\A" + re.escape(old_str) + r"\Z",
opts.ignore_case and re.I or 0)

But I'm not sure why it is not working.


as the documentation says, \A and \Z matches at the beginning/end of a 
*string*, not a word.




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


Re: About wmi

2008-07-16 Thread patrol
On 7月16日, 下午11时59分, Tim Golden <[EMAIL PROTECTED]> wrote:
> patrol wrote:
> > -2147023174
> > 'RPC \xb7\xfe\xce\xf1\xc6\xf7\xb2\xbb\xbf\xc9\xd3\xc3\xa1\xa3'
> > None
> > None
>
> > --
> > import pythoncom
> > import win32com.client
>
> > try:
> >   win32com.client.GetObject ("winmgmts://blahblah")
> > except pythoncom.com_error, info:
> >   for i in info:
> > print i
>
> > -2147023174
> > RPC 服务器不可用。
> > None
> > None
> > -
>  a="RPC 服务器不可用。"
>  a
> > 'RPC \xb7\xfe\xce\xf1\xc6\xf7\xb2\xbb\xbf\xc9\xd3\xc3\xa1\xa3'
> > -
> > Patrol
>
> Brilliant. Thanks, Patrol. So the error message comes back
> encoded. Can you confirm what your console encoding is,
> please? The following script should confirm:
>
> 
> import os, sys
>
> print sys.stdout.encoding
> os.system ("chcp")
>
> 
>
> TJG- 隐藏被引用文字 -
>
> - 显示引用的文字 -

>>> import os,sys
>>> print sys.stdout.encoding
cp936
>>> os.system("chcp")
活动的代码页: 936
0
>>> sys.getdefaultencoding()
'ascii'
--
http://mail.python.org/mailman/listinfo/python-list

Re: About wmi

2008-07-16 Thread patrol
On 7月17日, 上午12时16分, Tim Golden <[EMAIL PROTECTED]> wrote:
> Assuming that the error comes back in the sys.stdout encoding, the following 
> version *should* work ok. I still haven't got a non-English set up to test it 
> on, but it certainly does return a Unicode error message.
>
> http://timgolden.me.uk/wmi-project/wmi.py
>
> The usual test case, if you wouldn't mind:
>
> 
> import wmi
>
> wmi.WMI ("non-existent computer")
>
> 
>
> should give a (language-specific) error message, not an UnicodeDecodeError
>
> TJG
--
>>> import wmi
>>> wmi.WMI('non-existent computer')
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python25\lib\wmi.py", line 1199, in connect
handle_com_error (error_info)
  File "C:\Python25\lib\wmi.py", line 184, in handle_com_error
exception_string = [u"%s - %s" % (hex (hresult_code),
hresult_name)]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position
4: ordinal
not in range(128)
--
yup,error_info contains the Chinese encoded string. All of the Simple
Chinese Windows use the CP936.Every Chinese word utilizes two
bytes.Maybe you can fix this bug by modifying  handle_com_error.

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

Re: Best Python packages?

2008-07-16 Thread Dennis Cote

Ben Sizer wrote:

I'd love to have some way of finding out what hidden gems are out
there in the Python world 


If they were easy to find, they wouldn't be "hidden gems". :-)

Dennis Cote


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


Re: How to figure out if the platform is 32bit or 64bit?

2008-07-16 Thread norseman


> > I need to know if I'm running on 32bit or 64bit ... so far I haven't
> > come up with how to get this info via python. sys.platform returns
> > what python was built on ... but not what the current system is.
> >
> > I thought platform.uname() or just platform.processor() would have
> > done it, but python returns an empty string on windows. Any ideas?
> >
> > Thanks, Ken

===
From what I'm reading I think the answer lies in being able to see 
Microsoft's OS 'About' statement.  One of the Python guru's should be 
able to supply the code.  On Linux you should be able to uname -m and 
get a pretty good idea. See man uname.


something like:
#contents of t.py
#---
import os
zstatflg= os.system("uname -m")
#---  EOF ---
then:
python t.py
i686

(I'm running a stock Python 2.5.2)

If the Python itself was compiled 32 bit and installed on a 64 bit 
machine that runs 32 bit code (like most all do during transition times) 
then all attempts with Python to check itself will return 32 bit 
responses. Using math and/or 'kibitz' (cheater text) will be useless.


Hope this helps;

Steve
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: how can i save my command prompt screen?

2008-07-16 Thread norseman



Ty hensons wrote:
> how can i save my command prompt screen?

==

That by itself leaves lots of questions.  Taken literally to be the 
"box" then:


In Microsoft use the "Print Screen" followed by mspaint and Edit/paste
  (Or SHIFT-PrintScreen if whole screen showed up, I forget which it is.
One does just the box that is hot while the other gets all)

In Unix use  xwd.   See  man xwd and xwud. Also  man convert

with box open and text you want for show'n'tell visible
xwd>screen_1.xwd
(click in box of choice)

to view results:
xwudWith Python running something in one box and a simple script in another 
you can create lots of pics for the documentation. If you invert the 
colors the pics will have black letters on a white background and save 
tons of ink.



Steve
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: how can i save my command prompt screen?

2008-07-16 Thread Mike Driscoll
On Jul 16, 12:28 pm, norseman <[EMAIL PROTECTED]> wrote:
> Ty hensons wrote:
>
>  > how can i save my command prompt screen?
>
> ==
>
> That by itself leaves lots of questions.  Taken literally to be the
> "box" then:
>
> In Microsoft use the "Print Screen" followed by mspaint and Edit/paste
>    (Or SHIFT-PrintScreen if whole screen showed up, I forget which it is.
>      One does just the box that is hot while the other gets all)
>


In Windows you can right-click, choose "Mark" and then select the
text. Hit  to copy it to the clipboard. Then you can paste it
into any text editor you like.


> Steve
> [EMAIL PROTECTED]


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


For_loops hurt my brain.

2008-07-16 Thread bsagert
This script uses a simple for loop to zip some files. However I am
repeating code that cries out for a nested loop. My two lists of
files_to_be_zipped (spare and seekfacts) are of uneven length so I
can't seem to decipher the "for_logic". I would appreciate any help.
Thanks, Bill

import zipfile
import os

zips = [
'c:/spare.zip',
'c:/seekfacts.zip'
]
spare = [
'c:/spare/huge.fm3',
'c:/spare/huge.wk3'
]
seekfacts = [
'c:/seekfacts/bookmark.html',
'c:/seekfacts/index.htm',
'c:/seekfacts/seek.css',
'c:/seekfacts/seek.js'
]

zFile = zipfile.ZipFile(zips[0], 'w')
for files in spare:
zFile.write(files, os.path.basename(files), zipfile.ZIP_DEFLATED)
zFile.close()

zFile = zipfile.ZipFile(zips[1], 'w')
for files in seekfacts:
zFile.write(files, os.path.basename(files), zipfile.ZIP_DEFLATED)
zFile.close()

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


Re: About wmi

2008-07-16 Thread Tim Golden
patrol wrote:
 import wmi
 wmi.WMI('non-existent computer')
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "C:\Python25\lib\wmi.py", line 1199, in connect
> handle_com_error (error_info)
>   File "C:\Python25\lib\wmi.py", line 184, in handle_com_error
> exception_string = [u"%s - %s" % (hex (hresult_code),
> hresult_name)]
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position
> 4: ordinal
> not in range(128)
> --
> yup,error_info contains the Chinese encoded string. All of the Simple
> Chinese Windows use the CP936.Every Chinese word utilizes two
> bytes.Maybe you can fix this bug by modifying  handle_com_error.


Well, that's what I've done in that latest version.
Only I naively assumed
that I could use sys.stdout.encoding to determine
the encoding. I'll have to try harder.

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


Is there any component-oriented (non-MVC) web framework available for Python?

2008-07-16 Thread Alis
Hi

Is there any component-oriented (non-MVC) web framework available for
Python?

That is something like Apache Wicket, Tapestry or JSF, but I need it
to be in Python.

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


Uploading an image using PUT

2008-07-16 Thread noelob
Hi All,

Let me start by saying that's I'm relatively new to Python, so please
be gentle!

I need to up upload a file to a Tomcat web app using httplib. The web
app requires the following:
Files need to be split into 100kb (102400b) and each file segment
loaded using the PUT request. It is also a requirement that the
following headers be sent:

For simplicity I've used an image (jpg) smaller than 100kb, so it
doesn't need to be chunked

headers = {
"Accept": "text/xml",
"Authorization": "testAuthHeader",
"Content-Length": 50172,
"Content-Range": "bytes 0-50172/50172",
"Content-Type": "image/jpeg",
"If-Match": "1",
"User-Agent":  "(en-IE; Grinder)",
}

I make the following connection:

conn = httplib.HTTPConnection(url)
conn.request(method, uriStr, body, additionalHeaders)

where:
method = PUT
uriStr is the web app specific URI
body is the raw data (bytes) from the jpg image
additionalHeaders are the headers above

For some reason I keep getting a Status 400 error from the web server.
Is it possible to PUT (or POST?) data in this fashion using httplib?

Many thanks for your help
Noelob
--
http://mail.python.org/mailman/listinfo/python-list


Re: For_loops hurt my brain.

2008-07-16 Thread Dan
On Jul 16, 1:42 pm, [EMAIL PROTECTED] wrote:
> This script uses a simple for loop to zip some files. However I am
> repeating code that cries out for a nested loop. My two lists of
> files_to_be_zipped (spare and seekfacts) are of uneven length so I
> can't seem to decipher the "for_logic". I would appreciate any help.
> Thanks, Bill
>
> import zipfile
> import os
>
> zips = [
> 'c:/spare.zip',
> 'c:/seekfacts.zip'
> ]
> spare = [
> 'c:/spare/huge.fm3',
> 'c:/spare/huge.wk3'
> ]
> seekfacts = [
> 'c:/seekfacts/bookmark.html',
> 'c:/seekfacts/index.htm',
> 'c:/seekfacts/seek.css',
> 'c:/seekfacts/seek.js'
> ]
>
> zFile = zipfile.ZipFile(zips[0], 'w')
> for files in spare:
> zFile.write(files, os.path.basename(files), zipfile.ZIP_DEFLATED)
> zFile.close()
>
> zFile = zipfile.ZipFile(zips[1], 'w')
> for files in seekfacts:
> zFile.write(files, os.path.basename(files), zipfile.ZIP_DEFLATED)
> zFile.close()

I would do something like this:
# UNTESTED

import zipfile
import os

zip_dict = { 'spare' : ['c:/spare.zip', 'c:/seekfacts.zip'],
 'seekfacts' : [
'c:/seekfacts/bookmark.html',
'c:/seekfacts/index.htm',
'c:/seekfacts/seek.css',
'c:/seekfacts/seek.js'
] }

for key,value in zip_dict.items():
zFile = zipfile.ZipFile("c:/%s.zip" % key, 'w')
for fname in value:
zFile.write(fname, os.path.basename(files),
zipfile.ZIP_DEFLATED)
zFile.close()

# End untested code.

This implicitly maps thing with the key foo to the zip file c:/
foo.zip, but if you want to be more general, I would suggest thinking
about making a class.

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


Re: Converting from local -> UTC

2008-07-16 Thread Keith Hughitt
Thanks Gabriel!

That helps clear things up for me. The above method works very well. I
only have one remaining question:
How can I pass a datetime object to MySQL?'

So far, what I've been doing is building the query as a string, for
example:

query = "INSERT INTO image VALUES(%d, %d, %s, '%s')" % (id, meas,
date, 'jpg')
cursor.execute(query)

This works fine for regular datetime objects, which are passed as
strings similar
to: "2003-10-01 00:00:00." When incorporating a timezone, however, the
resulting string
is of the form "2003-10-01 00:00:00+00:00." Unfortunately, MySQL does
not recognize
the offset.

I know you said you don't use MySQL, but how would you do something
execute a similar query
on the database you normally interface with?


Thanks,
Keith


On Jul 15, 12:04 am, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Mon, 14 Jul 2008 12:06:30 -0300,KeithHughitt  
> <[EMAIL PROTECTED]> escribió:
>
>
>
> > On Jul 12, 12:52 am, "Gabriel Genellina" <[EMAIL PROTECTED]>
> > wrote:
> >> En Fri, 11 Jul 2008 15:42:37 -0300,KeithHughitt  
> >> <[EMAIL PROTECTED]> escribió:
>
> >> > I am having a little trouble figuring out how to convert a python
> >> > datetime to UTC. I have a UTC date (e.g. 2008-07-11 00:00:00). I would
> >> > like to create a UTC date so that when I send it to MySQL (which
> >> > treats all dates at local dates by default), it will already have
> >> > incorporated the proper UTC offset. I've tried looking through the
> >> > docshttp://python.active-venture.com/lib/datetime-datetime.html), but
> >> > have not had any luck.
>
> >> You have to use a "timezone aware" datetime object. If all you want is  
> >> to  
> >> store an UTC date, the tzinfo demo classes that you can find in the  
> >> Python  
> >> docs at  may be enough.
>
> > Thanks for advice Gabriel. I downloaded the tzinfo demo class, saved
> > it as
> > UTC.py and imported it. I'm still not exactly sure how to use it
> > though. It looks like
> > the file already creates an instance of the UTC tzinfo class (line 20:
> > "utc = UTC()"),
> > however, when I try to test it out in the interpreter, it cannot be
> > found. I'm new
> > to python, and there is probably something obvious I'm missing, but do
> > you have any ideas?
>
> The import statement in Python doesn't behave the same way as similar  
> statements in other languages - and it may be confusing you. I'll try to  
> explain it using this example.
> You have:
> - a *file* UTC.py, containing the source code for the *module* UTC. It  
> contains:
> - a *class* definition (UTC) and
> - an *instance* of that class, utc.
>
> --- begin UTC.py ---If you pass a "timezone aware" datetime object as a SQL 
> parameter
> class UTC(tzinfo):
>    ...
> utc = UTC()
> ...
> --- end UTC.py ---
>
> > Here is what I'm attempting:
>
> >  output begin =
>
> > Python 2.5.2 (r252:60911, Apr 21 2008, 11:12:42)
> > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
> > Type "help", "copyright", "credits" or "license" for more information.
>  import datetime, UTC
>
> Here you have imported the *module* UTC. That is, the name UTC now refers  
> to a newly created module just loaded from the UTC.py file.
>
>  t = datetime.datetime(2008, 7, 14, 00, 00, 00, UTC())
> > Traceback (most recent call last):
> >   File "", line 1, in 
> > TypeError: 'module' object is not callable
>
> The error comes from UTC(): UTC is a module, UTC() is attempting to "call"  
> it, and since modules are not callable objects, we get a TypeError.
>
>  utc
> > Traceback (most recent call last):
> >   File "", line 1, in 
> > NameError: name 'utc' is not defined
>
> The *only* name we have imported so far is UTC - the module. Lowercase utc  
> isn't defined.
>
>  utc = UTC()
> > Traceback (most recent call last):
> >   File "", line 1, in 
> > TypeError: 'module' object is not callable
>
> Same as above...
>
> Ok, how to solve it? We know that UTC refers to the *module* with the same  
> name. To get the *class* inside that module, use UTC.UTC - try again in  
> the interpreter. To create a new instance of that class, you can use  
> UTC.UTC(). To obtain the instance already created in the UTC module, use  
> UTC.utc
>
> **OR**
>
> Import those names explicitely:
>
> py> from UTC import UTC
>
> In this case the name UTC refers to the *class* inside the module.
> In this particular example it may be confusing - both have the same name.  
> Another example from the standard library: the poplib module contains a  
> POP3 class, so after executing this line:
>
> py> from poplib import POP3
>
> the name POP3 refers to that class. The poplib module itself isn't  
> directly available.
> Back to the UTC module, you could use:
>
> py> from UTC import utc
>
> and now utc refers to the *instance* already created inside the module.  
> This last form may be the most convenient in your case:
>
> py> import datetime
> py> from UTC import utc
> py> pri

Re: Is there any component-oriented (non-MVC) web framework available for Python?

2008-07-16 Thread Phillip B Oldham
On Jul 16, 6:48 pm, Alis <[EMAIL PROTECTED]> wrote:
> Hi
>
> Is there any component-oriented (non-MVC) web framework available for
> Python?
>
> That is something like Apache Wicket, Tapestry or JSF, but I need it
> to be in Python.
>
> Regards,
> Ali

Have you looked at kamaelia?

http://kamaelia.sourceforge.net/
--
http://mail.python.org/mailman/listinfo/python-list


Re: bad recursion, still works

2008-07-16 Thread Peter Pearson
On Wed, 16 Jul 2008 15:20:23 +0200, Fredrik Lundh wrote:
[snip]
> Hope this helps more than it confuses.

Absolutely.  It is wonderfully enlightening.  Many thanks.

-- 
To email me, substitute nowhere->spamcop, invalid->net.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Testing for connection to a website

2008-07-16 Thread Alexnb



Fredrik Lundh wrote:
> 
> Alexnb wrote:
> 
>> e = ''
> 
>> try: 
>> ...
>> except HTTPError, e:
>> print e.code
>> except URLError, e:
>> print e.reason
>> 
>> if e == '':
>> print "good to go"
> 
> footnote: here's a better way to test if an exception was raised or not:
> 
>  try:
>  ...
>  except HTTPError, e:
>  print e.code
>  except URLError, e:
>  print e.reason
>  else:
>  print "good to go"
> 
> 
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
> 
> 

Thanks! can't believe I didn't think of that. 

-- 
View this message in context: 
http://www.nabble.com/Testing-for-connection-to-a-website-tp18473382p18493785.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Is re.findall guaranteed to be "in order?"

2008-07-16 Thread Joshua Kugler
Fredrik Lundh wrote:

> Joshua Kugler wrote:
> 
>> Experimenting has shown me that re.findall() will return a list with the
>> matches in the order it found them.
> 
> "in the order it found them" doesn't really say much, does it? ;-)
> 
> "findall" and "finditer" both scans the string from left to right, and
> will return matches in that order.
> 
> (the documentation is a bit vague, so if you have the time, please add a
> request for clarification to the bug tracker)

Done.

http://bugs.python.org/issue3384

j


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


py2exe issues with pictures and icons

2008-07-16 Thread Alexnb

Hello

I am sure most of you are familiar with py2exe. I am having a bit of a
problem. See the program has a few pictures involved and the .ico it uses
for the windows. However, the pictures are stored in the same directory as
the source, something like: C:\Docs and settings\me\My docs\python\program.
When I run the program for the interpreter, just as a .py, everything works
just as it should. However, when I compile the main source as an .exe, and
say let a friend try the program. It fails because it is missing the .ico.
The catch, is I don't want to have it have to installed, at least at this
point, I want it to be able to just run. So how can I make it just run from
any computer with the files not being in the immediate directory. If that is
not possible, how can I put them in the immediate directory and still make
it work. Because that directory may change a lot so the path will change. 

Just a few questions. I hope someone out there can help me out!
-- 
View this message in context: 
http://www.nabble.com/py2exe-issues-with-pictures-and-icons-tp18493908p18493908.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Framework recommendations for web service?

2008-07-16 Thread Joshua Kugler
Phillip B Oldham wrote:
> So, can anyone suggest a lightweight python framework which just does
> the essentials?

web.py is pretty slim (not to be confused with web2py).

Pylons isn't very large, depending on what you call "essential."

j

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


Re: Framework recommendations for web service?

2008-07-16 Thread Ivan Ven Osdel
>What we *do* need is a lightweight, simple framework that will allow
>us to create a RESTful interface and throw code together fast. We'll
>probably go with SQLObject (unless we can extract the ORM from django
>- lazy evaluation would be very useful), and we're just looking for
>something fast and light to sit between that and the thrift interfaces
>we'll create.
>
>So, can anyone suggest a lightweight python framework which just does
>the essentials?

Have you looked at CherryPy? It's very simple to get up and running and can be 
changed to go through Apache if you need it to be fast. 

I don't think RESTful interfaces are built in but I know people have 
succesfully built RESTful apps on top of CherryPy. Also plans for REST in 
CherryPy 3 look promising. Here is a post I ran across from one of the 
contributers.

"Hey there,

CherryPy 3 is currently under brainstorming before being first draft. There 
some feature we do want such as the ability to change the URL dispatching at 
will depending on what is required for a given application.

One dispatching rule I do want is the one based on HTTP verbs. So it might take 
a few months to get there but eventually it will be a built-in :)

- Sylvain"


-- 
Ivan Ven Osdel
Senior Software Engineer
http://datasyncsuite.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Framework recommendations for web service?

2008-07-16 Thread Ivan Ven Osdel
>I don't think RESTful interfaces are built in but I know people have 
>succesfully built RESTful apps on top of CherryPy. Also plans >for REST in 
>CherryPy 3 look promising. Here is a post I ran across from one of the 
>contributers.

>"Hey there,

>CherryPy 3 is currently under brainstorming before being first draft. There 
>some feature we do want such as the ability to change >the URL dispatching at 
>will depending on what is required for a given application.
>
>One dispatching rule I do want is the one based on HTTP verbs. So it might 
>take a few months to get there but eventually it will be >a built-in :)
>
>- Sylvain"

My apologies, it appears that post was from 2006!

-- 
Ivan Ven Osdel
Senior Software Engineer
http://datasyncsuite.com
--
http://mail.python.org/mailman/listinfo/python-list


New to Python - Accessing Lotus Notes

2008-07-16 Thread KDawg44
Hi,

We have a Lotus Notes Database that tracks time spent on projects.
What I would like to do is develop a Time Tracker in Python that
communicates with the server.  This would pull projects in and allow a
use to start a timer as he/she works on a given project.  The user
would then be able to commit this back to the database (thus,
preventing them from having to go to the calendar view and pick the
project and enter the hours).

As another potential feature, I would like the user to be able to
create projects in the app and track time and then when a project
exists in the database, it would retroactively add those hours (users
cannot create their own projects and sometimes managers take some time
to actually get a project in the system).  Lasty, the user could run a
report by date to get their hours on each project.

Anyway, long story short, how can I communicate with Lotus Notes to
accomplish these tasks?  Lotus Notes 7.

Thank you for your help.  I am very new to Python and am hoping to
learn a lot from this project so I can incorporate Python into my
daily tasks.  Also, forgive my rant as I figured out some of my specs
as I typed this.

Thanks again.

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


Re: About wmi

2008-07-16 Thread Tim Golden
patrol wrote:
> On 7月17日, 上午12时16分, Tim Golden <[EMAIL PROTECTED]> wrote:
>> Assuming that the error comes back in the sys.stdout encoding, the following 
>> version *should* work ok. I still haven't got a non-English set up to test 
>> it on, but it certainly does return a Unicode error message.
>>
>> http://timgolden.me.uk/wmi-project/wmi.py
>>
>> The usual test case, if you wouldn't mind:
>>
>> 
>> import wmi
>>
>> wmi.WMI ("non-existent computer")
>>
>> 
>>
>> should give a (language-specific) error message, not an UnicodeDecodeError
>>
>> TJG
> --
 import wmi
 wmi.WMI('non-existent computer')
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "C:\Python25\lib\wmi.py", line 1199, in connect
> handle_com_error (error_info)
>   File "C:\Python25\lib\wmi.py", line 184, in handle_com_error
> exception_string = [u"%s - %s" % (hex (hresult_code),
> hresult_name)]
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xb7 in position
> 4: ordinal
> not in range(128)
> --
> yup,error_info contains the Chinese encoded string. All of the Simple
> Chinese Windows use the CP936.Every Chinese word utilizes two
> bytes.Maybe you can fix this bug by modifying  handle_com_error.

Can you confirm that that last bit of
code was run with the version of wmi.py
currently at:

http://timgolden.me.uk/wmi-project/wmi.py

That version should already be decoding the
string correctly.

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

Re: py2exe issues with pictures and icons

2008-07-16 Thread Mike Driscoll
On Jul 16, 1:37 pm, Alexnb <[EMAIL PROTECTED]> wrote:
> Hello
>
> I am sure most of you are familiar with py2exe. I am having a bit of a
> problem. See the program has a few pictures involved and the .ico it uses
> for the windows. However, the pictures are stored in the same directory as
> the source, something like: C:\Docs and settings\me\My docs\python\program.
> When I run the program for the interpreter, just as a .py, everything works
> just as it should. However, when I compile the main source as an .exe, and
> say let a friend try the program. It fails because it is missing the .ico.
> The catch, is I don't want to have it have to installed, at least at this
> point, I want it to be able to just run. So how can I make it just run from
> any computer with the files not being in the immediate directory. If that is
> not possible, how can I put them in the immediate directory and still make
> it work. Because that directory may change a lot so the path will change.
>
> Just a few questions. I hope someone out there can help me out!
> --
> View this message in 
> context:http://www.nabble.com/py2exe-issues-with-pictures-and-icons-tp1849390...
> Sent from the Python - python-list mailing list archive at Nabble.com.


Put the part of the code that needs the ico file(s) into a try/except
block. You could also try reading the py2exe wiki and tutorials. This
one looks like it has relevant data:

http://www.py2exe.org/index.cgi/CustomIcons

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


Re: New to Python - Accessing Lotus Notes

2008-07-16 Thread Mike Driscoll
On Jul 16, 2:11 pm, KDawg44 <[EMAIL PROTECTED]> wrote:
> Hi,
>
> We have a Lotus Notes Database that tracks time spent on projects.
> What I would like to do is develop a Time Tracker in Python that
> communicates with the server.  This would pull projects in and allow a
> use to start a timer as he/she works on a given project.  The user
> would then be able to commit this back to the database (thus,
> preventing them from having to go to the calendar view and pick the
> project and enter the hours).
>
> As another potential feature, I would like the user to be able to
> create projects in the app and track time and then when a project
> exists in the database, it would retroactively add those hours (users
> cannot create their own projects and sometimes managers take some time
> to actually get a project in the system).  Lasty, the user could run a
> report by date to get their hours on each project.
>
> Anyway, long story short, how can I communicate with Lotus Notes to
> accomplish these tasks?  Lotus Notes 7.
>
> Thank you for your help.  I am very new to Python and am hoping to
> learn a lot from this project so I can incorporate Python into my
> daily tasks.  Also, forgive my rant as I figured out some of my specs
> as I typed this.
>
> Thanks again.
>
> Kevin

Use Google...it is very cool. Here are some links I found:

http://mail.python.org/pipermail/python-list/2005-May/323756.html
http://www.velocityreviews.com/forums/t350942-python-and-lotus-notes.html

HTH

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


Re: py2exe issues with pictures and icons

2008-07-16 Thread Alexnb



Mike Driscoll wrote:
> 
> On Jul 16, 1:37 pm, Alexnb <[EMAIL PROTECTED]> wrote:
>> Hello
>>
>> I am sure most of you are familiar with py2exe. I am having a bit of a
>> problem. See the program has a few pictures involved and the .ico it uses
>> for the windows. However, the pictures are stored in the same directory
>> as
>> the source, something like: C:\Docs and settings\me\My
>> docs\python\program.
>> When I run the program for the interpreter, just as a .py, everything
>> works
>> just as it should. However, when I compile the main source as an .exe,
>> and
>> say let a friend try the program. It fails because it is missing the
>> .ico.
>> The catch, is I don't want to have it have to installed, at least at this
>> point, I want it to be able to just run. So how can I make it just run
>> from
>> any computer with the files not being in the immediate directory. If that
>> is
>> not possible, how can I put them in the immediate directory and still
>> make
>> it work. Because that directory may change a lot so the path will change.
>>
>> Just a few questions. I hope someone out there can help me out!
>> --
>> View this message in
>> context:http://www.nabble.com/py2exe-issues-with-pictures-and-icons-tp1849390...
>> Sent from the Python - python-list mailing list archive at Nabble.com.
> 
> 
> Put the part of the code that needs the ico file(s) into a try/except
> block. You could also try reading the py2exe wiki and tutorials. This
> one looks like it has relevant data:
> 
> http://www.py2exe.org/index.cgi/CustomIcons
> 
> Mike
> --
> http://mail.python.org/mailman/listinfo/python-list
> 
> 

Well, that may solve the icon problem. But what about getting pictures in
there?

-- 
View this message in context: 
http://www.nabble.com/py2exe-issues-with-pictures-and-icons-tp18493908p18495626.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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

Re: py2exe issues with pictures and icons

2008-07-16 Thread Alexnb



Alexnb wrote:
> 
> 
> 
> Mike Driscoll wrote:
>> 
>> On Jul 16, 1:37 pm, Alexnb <[EMAIL PROTECTED]> wrote:
>>> Hello
>>>
>>> I am sure most of you are familiar with py2exe. I am having a bit of a
>>> problem. See the program has a few pictures involved and the .ico it
>>> uses
>>> for the windows. However, the pictures are stored in the same directory
>>> as
>>> the source, something like: C:\Docs and settings\me\My
>>> docs\python\program.
>>> When I run the program for the interpreter, just as a .py, everything
>>> works
>>> just as it should. However, when I compile the main source as an .exe,
>>> and
>>> say let a friend try the program. It fails because it is missing the
>>> .ico.
>>> The catch, is I don't want to have it have to installed, at least at
>>> this
>>> point, I want it to be able to just run. So how can I make it just run
>>> from
>>> any computer with the files not being in the immediate directory. If
>>> that is
>>> not possible, how can I put them in the immediate directory and still
>>> make
>>> it work. Because that directory may change a lot so the path will
>>> change.
>>>
>>> Just a few questions. I hope someone out there can help me out!
>>> --
>>> View this message in
>>> context:http://www.nabble.com/py2exe-issues-with-pictures-and-icons-tp1849390...
>>> Sent from the Python - python-list mailing list archive at Nabble.com.
>> 
>> 
>> Put the part of the code that needs the ico file(s) into a try/except
>> block. You could also try reading the py2exe wiki and tutorials. This
>> one looks like it has relevant data:
>> 
>> http://www.py2exe.org/index.cgi/CustomIcons
>> 
>> Mike
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>> 
>> 
> 
> Well, that may solve the icon problem. But what about getting pictures in
> there?
> 
> 

Okay, the icon fix didn't really fix it, what it did was make the .exe have
the icon as the little picture for the shortcut, but it isn't really a
shortcut. Whatever. But, I went and ran it on another computer and this was
the error log it created right off the bat.

Traceback (most recent call last):
  File "The GUI.py", line 696, in 
  File "Tkinter.pyc", line 1515, in wm_iconbitmap
_tkinter.TclError: bitmap "C:\Documents and Settings\Alex\My
Documents\PYTHON\DictionaryApp\Windows.ico" not defined

-- 
View this message in context: 
http://www.nabble.com/py2exe-issues-with-pictures-and-icons-tp18493908p18495836.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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

  1   2   >