Re: Using ElementTree to tidy up an XML string to my liking

2006-02-23 Thread Simon Dahlbacka
..I hope that you are aware that xml is *case sensitive*

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


Re: ls files --> list packer

2006-02-23 Thread I V

kpp9c wrote:
> Namely i have organized a bunch of folders that have soundfiles in them
> and would like Python to slurp up all the .aif/.aiff (or .wav whatever)
> files in a given set of directories. My friend hacked up this is perl:
>
> $files = `ls /snd/Public/*.aiff`;

You could use posix.popen to duplicate the perl hack:

files = posix.popen('ls /snd/Public/*.aiff').read().strip()

> @snd_filelist = split('\n',$files);

snd_filelist = files.split('\n')

> I would like something similar, that works with python that is more
> elegant and maybe even more robust.

Lucklily, python lets you avoid this kind of horrible hack. Try
os.listdir:

snd_filelist = [f for f in os.listdir('/snd/Public/') if
f.endswith('.aiff')]

I think it's more elegant, and it's certainly more robust.

> but i am failing miserably and my perl friends mock me.

Now you get to mock your perl friends!

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


Re: ls files --> list packer

2006-02-23 Thread kpp9c
and one example of a slightly fancier version would be a variation that
looks recursively into subdirectories and makes separate lists for each
subdirectory encountered.

so if i had a directory called "~/snd/"

and in "~/snd/" i had:

"~/snd/one/"
"~/snd/two/"
"~/snd/three/"

each with soundfiles in it.

I could get those packed in three separate lists named after the
directory or some such thing

This would be so awesome because my carefully organizing your
directory, you would be carefully
organizing your data, change your dir structure or add/delete some
files and you would get a new structure in your script... prolly would
work with scripting your iTunes music folder too...

gosh ... sorry ... just thinking out-loud here and getting kind of
giddy! reaching for the python book ...

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


Re: 'rar' is not recognized as an internal or external command��������

2006-02-23 Thread cn.popeye
 os.chdir() ?
thank you!

-- 

"Dennis Lee Bieber" <[EMAIL PROTECTED]> 
news:[EMAIL PROTECTED]
> On Fri, 24 Feb 2006 11:36:08 +0800, "Ê÷Éϲä»Ò" <[EMAIL PROTECTED]>
> declaimed the following in comp.lang.python:
>
> > thank everyone!!!
> >
> I'd had to run to work so couldn't test, but... notice this:
>
>
> C:\Documents and Settings\Dennis Lee Bieber>python
> ActivePython 2.3.5 Build 236 (ActiveState Corp.) based on
> Python 2.3.5 (#62, Feb  9 2005, 16:17:08) [MSC v.1200 32 bit (Intel)] on
> win32
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import os
> >>> os.system("dir /w")
>  Volume in drive C is System
>  Volume Serial Number is 0487-A514
>
>  Directory of C:\Documents and Settings\Dennis Lee Bieber
>
> [.][..]   [.eclipse]
> [.gps] [.mysqlcc] [.netbeans]
> [.refactorit]  [.refactorit_please_delete_me]
> [Application Data]
> [Desktop]  Eudora.lnk [Favorites]
> [Start Menu]   [workspace]
>1 File(s)820 bytes
>   13 Dir(s)  22,481,092,608 bytes free
> 0
> >>> os.system("cd e:\\userdata")
> 0
> >>> os.system("dir /w")
>  Volume in drive C is System
>  Volume Serial Number is 0487-A514
>
>  Directory of C:\Documents and Settings\Dennis Lee Bieber
>
> [.][..]   [.eclipse]
> [.gps] [.mysqlcc] [.netbeans]
> [.refactorit]  [.refactorit_please_delete_me]
> [Application Data]
> [Desktop]  Eudora.lnk [Favorites]
> [Start Menu]   [workspace]
>1 File(s)820 bytes
>   13 Dir(s)  22,481,092,608 bytes free
> 0
> >>> os.chdir("e:\\userdata")
> >>> os.system("dir /w")
>  Volume in drive E is Data
>  Volume Serial Number is 2626-D991
>
>  Directory of e:\userdata
>
> [.] [..][Dennis Lee Bieber]
> DummyQuicken.IDX
> DummyQuicken.QDFDummyQuicken.QELDummyQuicken.QPH[Root]
>4 File(s)316,184 bytes
>4 Dir(s)  307,433,058,304 bytes free
> 0
> >>>
>
> Notice how using os.system() to do a "cd" doesn't "stick"... But if
> you used os.chdir() instead, THAT setting carries over to subsequent
> os.system() calls.
>
> -- 
>  > == <
>  >   [EMAIL PROTECTED]  | Wulfraed  Dennis Lee Bieber  KD6MOG <
>  >  [EMAIL PROTECTED] |   Bestiaria Support Staff   <
>  > == <
>  >   Home Page: <
>  >Overflow Page: <


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

ls files --> list packer

2006-02-23 Thread kpp9c
I would like to use the power of Python to build some list structures
for me.

Namely i have organized a bunch of folders that have soundfiles in them
and would like Python to slurp up all the .aif/.aiff (or .wav whatever)
files in a given set of directories. My friend hacked up this is perl:

$files = `ls /snd/Public/*.aiff`;

@snd_filelist = split('\n',$files);

$i = 0;
while ($file = @snd_filelist[$i]) {
   print "file $i = @snd_filelist[$i]\n";
   $i++;
}


The only catch with the above code (besides its hideousness hee hee) is
if you have a directory w/i the structure, but in general it works and
with this i can just put gobs of files into separate dirs pack them
into a list and then send them to my script that scrambles them and
plays them.

I would like something similar, that works with python that is more
elegant and maybe even more robust.

but i am failing miserably and my perl friends mock me.

cheers,
kp8

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


Re: time.sleep(1) sometimes runs for 200 seconds under windows

2006-02-23 Thread Paul Rubin
Dennis Lee Bieber <[EMAIL PROTECTED]> writes:
>   Any chance they all tend to have slow clocks, and are getting bitten
> by a semi-random NTP time update; my machine tends to run the NTP update
> at 7-day intervals (including time of day), counting from the last
> successful synchronization.

This is a good possibility, that the clock is jumping ahead rather
than that 200 seconds of actual real time is going during the
time.sleep call.

What happens if you replace the time.time call with something that
reads the current time from an SNTP server (or equivalent) through a
socket?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: CSV module and UNICODE

2006-02-23 Thread Rudy Schockaert
Thanks a lot Skip. Sure that this will help.

Learned two things: how to do it and to look at the docs for 2.5 also.

These samples are not in the 2.4.2 reference guide.

RudyOn 2/24/06, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
Rudy> I'm having problems writing unicode to a csv file.Rudy> I use the following code:...Have you tried the example UnicodeReader and UnicodeWriter classes in themodule documentation:
http://www.python.org/dev/doc/devel/lib/node631.htmlWhile the csv module is 8-bit clean it knows nothing about Unicode, so yourUnicode data has to be encoded before it hits the csv module code.  Your
code is expecting the Unicode to go through the csv module and be encoded toutf-8 downstream in the by the eventual file object.If there are people reading this who would like to tackle something forPython 
2.5, I am sure a patch that Unicodifies the csv module would bewelcome.Skip-- It is not economical to go to bed early to save the candles if the result is twins. - Chinese Proverb 

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

Re: PyAtom, a Python module for creating Atom syndication feeds

2006-02-23 Thread Steve R. Hastings
I have edited PyAtom, and now it should be in better conformance with the
PEP 8 guidelines.  It is available from the same place as before:

http://www.blarg.net/~steveha/pyatom.tar.gz

-- 
Steve R. Hastings"Vita est"
[EMAIL PROTECTED]http://www.blarg.net/~steveha

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


Re: time.sleep(1) sometimes runs for 200 seconds under windows

2006-02-23 Thread Grant Edwards
On 2006-02-23, Paul Probert <[EMAIL PROTECTED]> wrote:

>>In similar situation I would start to blame the hardware for the 
>>problem, so below a kind of checklist to go through:
>
>   Thanks for the reply. I should have mentioned, this happens to just 
> about every machine in our collection of about 20 machines. Each is of a 
> different age, and the hardware is completely diverse. Each has either 
> of NT4, win2k, or XP installed. They all belong to our domain

Time to dowload a linux CD then, eh?

-- 
Grant Edwards   grante Yow!  I am KING BOMBA of
  at   Sicily!...I will marry
   visi.comLUCILLE BALL next Friday!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 'rar' is not recognized as an internal or external command��������

2006-02-23 Thread ���ϲ��
thank everyone!!!

the code:

import os
import time
source = [r'e:\temp\code',r'e:\temp\domains']
target_dir = r'e:\temp\bak'
target = target_dir+time.strftime('%Y%m%d%H%M%S')+'.rar'
rar_cmd = "D:\\Progra~1\\WinRAR\\rar.exe a -idcdp %s %s" % (target,'
'.join(source))
print rar_cmd
if os.system(rar_cmd) == 0:
   print 'Successful backup to',target
else:
   print 'Backup Failed!'

thanks again!


-- 
Ê÷Éϲä»Ò
"Ê÷Éϲä»Ò" <[EMAIL PROTECTED]> дÈëÓʼþ
news:[EMAIL PROTECTED]
>
> 'rar' is not recognized as an internal or external command,
> operable program or batch file.
>
>
> import os
> import time
> source = [r'e:\temp\code',r'e:\temp\domains']
> target_dir = r'e:\temp\bak'
> target = target_dir+time.strftime('%Y%m%d%H%M%S')+'.rar'
> rar_cmd = "rar a -idcdp %s %s" % (target,' '.join(source))
> print rar_cmd
> if os.system(r'cd D:\Program Files\WinRAR') == 0:
>   if os.system(rar_cmd) == 0:
> print 'Successful backup to',target
>   else:
> print 'Backup Failed!'
> else:
>   print 'FAILED!!!'
>
> 'rar' is not recognized as an internal or external command,
> operable program or batch file.
>
> rar a -idcdp e:\temp\bak20060222191139.rar e:\temp\code e:\temp\domains
> Backup Failed!
>
>
> but.
>
> D:\>cd D:\Program Files\WinRAR
>
> D:\Program Files\WinRAR>rar a -idcdp e:\temp\bak20060222191139.rar
> e:\temp\code
> e:\temp\domains
>
> Creating archive e:\temp\bak20060222191139.rar
>
> Addinge:\temp\Code\Code\.classpath
OK
> Addinge:\temp\Code\Code\.project
OK
> Addinge:\temp\Code\Code\common\Code.class
OK
> Addinge:\temp\Code\Code\common\Code.java
OK
> Addinge:\temp\Code\Code\common
OK
> Addinge:\temp\Code\Code
OK
> Addinge:\temp\Code
OK
> Addinge:\temp\domains\examples.jar
OK
> Addinge:\temp\domains\medrec.jar
OK
> Addinge:\temp\domains\wls.jar
OK
> Addinge:\temp\domains\wlw.jar
OK
> Addinge:\temp\domains
OK
>
> D:\Program Files\WinRAR>
>
>
>
> why?
>
>
>
>
> -- 
> Ê÷Éϲä»Ò
>
>


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

Re: regular expresson for Unix and Dos Lineendings wanted

2006-02-23 Thread John Zenger
How about r"\s+[\n\r]+|\s+$"  ?

Franz Steinhaeusler wrote:
> Hello, I need a regularexpression, which trims trailing whitespaces.
> 
> While with unix line endings, it works; 
> but not with Window (Dos) CRLF's:
> 
> 
import re
retrailingwhitespace = re.compile('(?<=\S)[ \t]+$', re.MULTILINE)
> 
> 
> 1) Windows
> 
r="erewr\r\nafjdskl "
newtext, n = retrailingwhitespace.subn('', r)
n
> 
> 1
> 
newtext
> 
> 'erewr\r\nafjdskl'
> 
> 2) Unix
> 
r="erewr\nafjdskl "
newtext, n = retrailingwhitespace.subn('', r)
n
> 
> 2
> 
newtext
> 
> 'erewr\nafjdskl'
> 
> 
> Who can help me (regular expression, which works for both cases).
> 
> Thank you in advance!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python stdout and Win 2003

2006-02-23 Thread Philippe Martin
PS: I forgot to mention that some of the "print"s are made from wxPython
timer events.

Philippe


Philippe Martin wrote:

> Hi,
> 
> I have a program at a customer's site that seems to have random problem
> which eventually come down to not being able to read/write from serial
> ports.
> 
> I trapped all the exceptions I could think of and all of them look like
> this:
> ***
> (ACCESS CONTROL)Fri, 24 Feb 2006 02:07:18 + : Traceback (most recent
> call last):
>   File "C
> \Python24\lib\site-packages\SC\readers\SC_IDTech_MiniSmart_RS232.py", line
> 308, in Is_Card_Inserted
> print 'CARD NOT INSERTED'
> IOError: [Errno 9] Bad file descriptor
> ***
> 
> To me that means the print failed ... that stdout was not available
> anymore.
> 
> Am I correct?  what could cause this.
> 
> 
> Many thanks.
> 
> Philippe

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


Re: Python vs. Lisp -- please explain

2006-02-23 Thread Peter Mayne
Torsten Bronger wrote:
> 
 Another example: is Java the bytecode, which is compiled from
 Java the language, interpreted or not? Even when the HotSpot JIT
 cuts in?
>>> It is partly interpreted and partly compiled.  That's why it's
>>> faster than Python.
>> But Python is partly interpreted and partly compiled too
> 
> It's byte-compiled for a VM, that's not the same, and you know it.

Do you mean that Python is byte-compiled for a VM, and not Java, or 
vice-versa?

> I agree that the distinction between interpreted and compiled
> languages is not as clear as between positiv and negative numbers,
> however, neither anybody has claimed that so far, nor it is
> necessary.  It must be *practical*, i.e. a useful rule of thumb for
> decision making.  If you really know all implications (pros and
> cons) of interpreted languages, it's are very useful rule in my
> opinion.

So what kind of practical decisions are you trying to make? What kind of 
implications are useful to you?

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


Re: Pickling/unpickling Cookie.SimpleCookie fails with protocol=2

2006-02-23 Thread Paul Rubin
"Erwin S. Andreasen" <[EMAIL PROTECTED]> writes:
> Pickling a Cookie.SimpleCookie (or SmartCookie) when using protocol=2
> seems to do something very strange. Protocol 0/1 work fine:

Don't use SmartCookies because of the security issue.  See the docs.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: CSV module and UNICODE

2006-02-23 Thread skip

Rudy> I'm having problems writing unicode to a csv file.
Rudy> I use the following code:
...

Have you tried the example UnicodeReader and UnicodeWriter classes in the
module documentation:

http://www.python.org/dev/doc/devel/lib/node631.html

While the csv module is 8-bit clean it knows nothing about Unicode, so your
Unicode data has to be encoded before it hits the csv module code.  Your
code is expecting the Unicode to go through the csv module and be encoded to
utf-8 downstream in the by the eventual file object.

If there are people reading this who would like to tackle something for
Python 2.5, I am sure a patch that Unicodifies the csv module would be
welcome.

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


Python stdout and Win 2003

2006-02-23 Thread Philippe Martin
Hi,

I have a program at a customer's site that seems to have random problem
which eventually come down to not being able to read/write from serial
ports.

I trapped all the exceptions I could think of and all of them look like
this:
***
(ACCESS CONTROL)Fri, 24 Feb 2006 02:07:18 + : Traceback (most recent
call last):
  File "C
\Python24\lib\site-packages\SC\readers\SC_IDTech_MiniSmart_RS232.py", line
308, in Is_Card_Inserted
print 'CARD NOT INSERTED'
IOError: [Errno 9] Bad file descriptor
***

To me that means the print failed ... that stdout was not available anymore.

Am I correct?  what could cause this.


Many thanks.

Philippe







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


Pickling/unpickling Cookie.SimpleCookie fails with protocol=2

2006-02-23 Thread Erwin S. Andreasen

Pickling a Cookie.SimpleCookie (or SmartCookie) when using protocol=2
seems to do something very strange. Protocol 0/1 work fine:

$ python2.4
Python 2.4.2 (#2, Nov 20 2005, 17:04:48) 
[GCC 4.0.3 2005 (prerelease) (Debian 4.0.2-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

>>> import cPickle, Cookie
>>> cPickle.loads(cPickle.dumps(Cookie.SimpleCookie('hi=there')))


Protocol 2 however:

>>> pickle.loads(pickle.dumps(Cookie.Cookie('hi=there'),2))
>

>>>pickle.loads(pickle.dumps(Cookie.Cookie('hi=there'),2))['hi'].__dict__

{'coded_value':
'"ccopy_reg\\012_reconstructor\\012p1\\012(cCookie\\012Morsel\\012p2\\012c__builtin__\\012dict\\012p3\\012(dp4\\012S\'comment\'\\012p5\\012S\'\'\\012sS\'domain\'\\012p6\\012S\'\'\\012sS\'version\'\\012p7\\012S\'\'\\012sS\'secure\'\\012p8\\012S\'\'\\012sS\'path\'\\012p9\\012S\'\'\\012sS\'expires\'\\012p10\\012S\'\'\\012sS\'max-age\'\\012p11\\012S\'\'\\012stRp12\\012(dp13\\012S\'coded_value\'\\012p14\\012S\'there\'\\012p15\\012sS\'value\'\\012p16\\012g15\\012sS\'key\'\\012p17\\012S\'hi\'\\012p18\\012sb."',
'value': , 'key': 'hi'}


I can't really say what goes wrong here, but it looks like a bug to me
-- comments? I guess I'll have to go to protocol 0 for this, or not
serialize the cookie but re-parse it on the other side (this pickle
gets passed down a UNIX socket together with the file descriptor of a
request, in a load balancing system).



-- 
===
<[EMAIL PROTECTED]>   London, E14
http://www.andreasen.org/> <*>   
===

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


Re: A C-like if statement

2006-02-23 Thread Terry Hancock
On Fri, 24 Feb 2006 09:14:53 +1100
"Steven D'Aprano" <[EMAIL PROTECTED]> wrote:
> There are *reasons* why Python discourages functions with
> side-effects. Side-effects make your code hard to test and
> harder to debug.

You of course meant "expressions with side-effects".  Python
is pretty good at making functions with side-effects. At
least it is if you want them. ;-)

-- 
Terry Hancock ([EMAIL PROTECTED])
Anansi Spaceworks http://www.AnansiSpaceworks.com

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


Re: pyserial

2006-02-23 Thread Petr Jakes
Few notes from the Python beginner :) HTH.
I do not understand what do you mean by the expression: " I can
read data without try and try again." Can you be more specific
please. I do not understand what do you exactly mean. AFIK the pyserial
is waiting while the data occur on the serial port (so called blocking
read) so it is not necessary to do some "polling" (checking the serial
port periodically) .

Following snippets of code is running in infinitive loop, but it is not
necessary too be worried about processor utilization because the
readline waits for the data on the serial port and the code continues
to run when data occurs or when timeout passes.

import serial
s = serial.Serial(port=0,baudrate=4800, timeout=20)
while 1:
line = s.readline()
#   byte = s.read(1) # or you can read No. of bytes according your
needs

Alternatively you can monitor buffer of the serial port and while data
in it, you can read it.

while fd.inWaiting() != 0:
s.read(1)

you can find plenty of examples about pyserial here
http://tinyurl.com/p8tt5

What I am not able to figure out is why are you trying to print out
input and output buffers (print self.ser.flushInput()) Does it print
out something?

Petr Jakes

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


Re: why don't many test frameworks support file-output?

2006-02-23 Thread kanchy kang

I don't think redirecting stdout to a file is a good resolution.
How to organize the output file is very important.
in my imagination, there should be one directory "log", where log files are 
saved.
and, log files should be separated according to some method(for example, one 
test file one log file).

also, from my point of view, there is one confusion between "log files" and 
normal stdout stream.

stdout stream is used to display some imediate information, for example, 
"print" statement, or exception also can be outputed to the screen...

but, stdout stream can't satisfy many requirements...
for example, in one "big" project, there are many test cases, in which we 
need record many useful data, whether correct or not. how to do this? print 
statement is not a good idea.

there should be another "stream" to do this. it can record infomation, same 
to stdout or not.
so, a good log frame will satisfy:
1) "log" is not the stdout stream.
2) log files are oganized systematically, not only one big log file.
3) log information should be written to file imediately, not be delayed 
until one case is finished. why?
test script writter may not know the test framework. if he/she write one 
test case with many output data(maybe it is necesary), this will consume the 
system memory greatly, ...
4) also, log directory should be one limited cyclic...for example, from 1 to 
10.
this will avoid imediate overwriting...sometimes the previous log 
information would be useful.

...hehe...

best regards.


>From: Benji York <[EMAIL PROTECTED]>
>To: kanchy kang <[EMAIL PROTECTED]>
>CC: python-list@python.org
>Subject: Re: why don't many test frameworks support file-output?
>Date: Thu, 23 Feb 2006 14:55:07 -0500
>
>kanchy kang wrote:
>>i browsed the following frameworks briefly: nose, OOBTest,
>>testosterone,  py.test, Sancho ... and found out they do support imediate 
>>screen-output only.
>
>You can redirect stdout to a file.
>--
>Benji York

_
Express yourself instantly with MSN Messenger! Download today - it's FREE! 
http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/

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


Re: What's up with this code?

2006-02-23 Thread Kent Johnson
Gregory Petrosyan wrote:
> Again, thanks a lot!
> I'm optimising my polynomial module as hard as possible, because when
> it used native floats/integers it was very fast, but in some specific
> cases -- too inaccurate. So, I migrated to decimals, and module began
> to be very slow. Current success is nearly 4x speedup, and now it seems
> to me that decimals are the bottleneck. Is anybody working on C version
> of decimals? Is it a really hard work? (I am thinking about
> re-implementing decimals in C by myself)

Maybe gmpy would help?
http://gmpy.sourceforge.net/

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


Re: A C-like if statement

2006-02-23 Thread Paul Rubin
"Bob Greschke" <[EMAIL PROTECTED]> writes:
> I miss being able to do something like this in Python
> 
> 1f (I = a.find("3")) != -1:
> print "It's here: ", I
> else:
> print "No 3's here"
> 
> where I gets assigned the index returned by find() AND the if statement gets 
> to do its job in the same line.  Then you don't have to have another like 
> that specifically gets the index of the "3".  Is there a way to do this in 
> Python?

For regexps I sometimes do it with a specially created class instance.
Something like:
  
  save = Cache_match()

  if save.find(a, "3"):
print "it's here:", save.result
  else:
print "no 3's here"

Implementing Cache_match is left to you as an exercise.  It does make
your code a bit cleaner if you're doing lots of matching.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pyFltk-1.1

2006-02-23 Thread James Stroud
george williams wrote:
> By god this sounds interesting I wish I 
> knew what you are talking about
> George-- Original Message - 
> From: "andreas" <[EMAIL PROTECTED]>
> Newsgroups: comp.lang.python.announce
> To: <[EMAIL PROTECTED]>
> Sent: Wednesday, February 22, 2006 6:14 AM
> Subject: ANN: pyFltk-1.1
> 
> 
> 
>>This is to announce the first official release of pyFltk-1.1,
>>the Python bindings for the cross platform GUI toolkit fltk-1.1



This reminds me, whatever happened to the FLWM? It was sweet.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A C-like if statement

2006-02-23 Thread bonono

Steven D'Aprano wrote:
> On Thu, 23 Feb 2006 12:04:38 -0700, Bob Greschke wrote:
>
> >> try:
> >>i = a.find("3")
> >>print "It's here: ", i
> >> except NotFound:
> >>print "No 3's here"
> >
> > Nuts.  I guess you're right.  It wouldn't be proper.  Things are added or
> > proposed every day for Python that I can't even pronounce, but a simple 'if
> > (I = a.find("3")) != -1' isn't allowed.  Huh.  It might be time to go back
> > to BASIC. :)
>
> There are *reasons* why Python discourages functions with side-effects.
> Side-effects make your code hard to test and harder to debug.
>

>>> "test".index("a")
Traceback (most recent call last):
  File "", line 1, in -toplevel-
"test".index("a")
ValueError: substring not found
>>> "test".find("a")
-1

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


PYTHONPATH?

2006-02-23 Thread Dr. Pastor
Several Documents about Python
refer to PYTHONPATH.
I could not find such variable.
(Python 2.4.2, IDLE 1.1.2, Windows XP)
How should/could I nominate a Directory to be
the local Directory?
Thanks for any guidance.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: time.sleep(1) sometimes runs for 200 seconds under windows

2006-02-23 Thread Benji York
Paul Probert wrote:

[snip my slightly-snotty quoting of the sleep.time docs]

>Thanks, but yes, I had read that before posting. One would think, 
> though, that the extra 200 seconds is a bit extreme to be blamable on 
> system scheduling granularity.

I didn't intend to invoke scheduling granularity, I was implying that 
under high system load it may take much longer for the sleep to "come back".

>I'm starting to think we've got a worm of some kind. If so, its 
> invisible to our Norton AV corporate.

If you don't see any appreciable load on the machines (I read that 
you're seeing the same thing on several diverse machines elsewhere in 
this thread), then yes, I'd agree that /something/ strange is going on.

Unfortunately this sounds like one of those things that will require 
"laying on of hands" to diagnose.  Good luck!  Let us know how it turns 
out, I'm curious. :)
--
Benji York
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Temporary" Variable

2006-02-23 Thread Jeffrey Schwab
Steven D'Aprano wrote:
> On Thu, 23 Feb 2006 12:05:59 -0800, darthbob88 wrote:
> 
> My comments inserted inline.
> 
> 
> 
>>#!/usr/bin/python
>>#simple guessing game, with numbers
>>import random
>>spam = random.randint(1, 100)
> 
> 
> It is bad programming practice to give variables uninformative joke names.

Lighten up.  This isn't the middle of a 100-KLOC corporate monstrosity, 
it's a 1/2-page usenet post.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: spaces at ends of filenames or directory names on Win32

2006-02-23 Thread Jeffrey Schwab
Larry Bates wrote:

> IMHO leading and/or trailing spaces in filenames is asking for
> incompatibilities with cross-platform file access.

With what platforms specifically?

> Much like
> using single-quote in filenames which are perfectly legal in
> DOS/Windows, but Linux doesn't like much.

Uh...  What Linux are you using?  And what FS?

$ touch "'" && ls
'
$ rm "'"
$
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How would you open this file?

2006-02-23 Thread Bob
Thanks all! That helps out a lot!

Python is kinda' cool...

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


Re: time.sleep(1) sometimes runs for 200 seconds under windows

2006-02-23 Thread Claudio Grondi
Paul Probert wrote:
> Peter Hansen wrote:
> 
>> Are you saying that you believe the time.sleep(1) call is actually 
>> blocking for 200 seconds?  Or just that your loop (and we can only 
>> guess what it looks like) is the one taking that long?
>>
>> If the former, try something like putting "print 'before'" and "print 
>> 'after'" before and after the sleep, and observe what happens when you 
>> run the program.  I'm fairly confident in saying there's no chance 
>> you'll see the "before" sit for 200s before you see the "after" and 
>> that your problem lies elsewhere, not with time.sleep(1).
>>
>> If the latter, um, obviously we can't help without more info.
>>
>> -Peter
>>
>>  
>>
> Yes, I'm doing this:
>   .
>  oldtime=time.time()
>  time.sleep(1)
>  newtime=time.time()
>  dt=newtime-oldtime
>   if dt > 2:
>   print 'dt=',dt,' time=',time.strftime('%Y_%m_%d_%Hh_%Mm_%Ss')
> Its happening roughly 4 times a day total on our 20 machines, ie about 
> once every 5 days on a given machine.
> 
> Paul Probert
> University of Wisconsin
> 
With such rare occurrence it is very hard to tell what is going on. 
Usually I put such strange things on a list of curiosities I don't want 
to know the reason of, because it is in my eyes not worth the effort. 
Maybe it is even a common problem not yet detected by me, because I have 
never run this kind of tests for such a long time.
Starting today, I can tell you statistically not earlier than in one 
week, if I have the same problem on my machines (currently I am running 
only one or two at the same time).

In between let's try to use some logic:
If the machine and the operating system are not the cause, what have all 
these machines in common?
  1. The software they are running (kind of not often triggered bug)
  2. The network cards used (bug in hardware or drivers)
  3. Another piece of hardware common to all the machines
  3. The harddisks (recalibration)
  4. The network router/switch and/or the server.

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


Help with questor

2006-02-23 Thread S Streat
   I am new to python and computer programming. I am trying to save the questor.py file so that it retains it's data. My problem is that I don't really understand how to do it. I have been reviewing tutorials and I have gotten this far, but the data still doesn't save. Can someone tell me what it is I am overlooking?     # questor.py    # define some constants for future use  kQuestion = 'question'kGuess = 'guess'  # define a function for asking yes/no questionsdef yesno(prompt): ans = raw_input(prompt) return (ans[0]=='y' or ans[0]=='Y')  # define a node in the question tree (either question or guess)class Qnode:  # initialization method def __init__(self,guess):  self.nodetype = kGuess  self.desc = guess  def retrieve(self, file):  self.desc =
 file.readline().rstrip()  self.nodetype = file.readline().rstrip()  if self.nodetype == kQuestion:   slef.nodes = {0:Qnode(''), 1:Qnode('')}   retrieve(self.nodes[0], file)   retrieve(self.nodes[1], file)  return   def save(self, file):  file.write(self.desc + "\n")  file.write(self.nodetype + "\n")  if self.nodetype == kQuestion:   save(self.nodes[0], file)   save(self.nodes[1], file)  return # get the question to ask  def query(self):  if (self.nodetype == kQuestion):   return self.desc + " "  elif (self.nodetype == kGuess):   return "Is it a " + self.desc + "? "  else:   return "Error: invalid node type!"   # return new nod!
 e, given
 a boolean response def nextnode(self,answer):  return self.nodes[answer]   # turn a guess node into a question node and add new item # give a question, the new item, and the answer for that item def makeQuest( self, question, newitem, newanswer ):    # create new nodes for the new answer and old answer  newAnsNode = Qnode(newitem)  oldAnsNode = Qnode(self.desc)    # turn this node into a question node  self.nodetype = kQuestion  self.desc = question    # assign the yes and no nodes appropriately  self.nodes = {newanswer:newAnsNode, not newanswer:oldAnsNode}    def traverse(fromNode): # ask the question yes = yesno( fromNode.query() )  # if this is a guess node, then did we get it right? if (fromNode.nodetype ==
 kGuess):  if (yes):   print "I'm a genius!!!"   return  # if we didn't get it right, return the node  return fromNode  # if it's a question node, then ask another question return traverse( fromNode.nextnode(yes) )  def run(): # start with a single guess node try:  f = open('c:\nodetree.txt', 'r')  cont = f.readlines()  known = cont.count('guess\n')  del cont  f.seek(0)  topNode = Qnode('')  retrieve(topNode, f)  f.close() except:  topNode = Qnode('python')  known = 1done = 0 while not done:  # ask questions till we get to the end  result = traverse( topNode )# if result is a node, we nee!
 d to add
 a question  if (result):   item = raw_input("OK, what were you thinking of? ")   print "Enter a question that distinguishes a",   print item, "from a", result.desc + ":"   q = raw_input()   ans = yesno("What is the answer for " + item + "? ")   result.makeQuest( q, item, ans )   print "Got it."# repeat until done  print  done = not yesno("Do another? ")  print  # immediate-mode commands, for drag-and-drop or execfile() executionif __name__ == '__main__': run() print raw_input("press Return>")else: print "Module questor imported." print "To run, type: questor.run()" print "To reload after changes to the source, type: reload(questor)"  # end of questor.py
		Relax. Yahoo! Mail 
virus scanning helps detect nasty viruses!-- 
http://mail.python.org/mailman/listinfo/python-list

Re: remote module importing (urlimport)

2006-02-23 Thread Jure Vrscaj
Sorry for the duplicate, I had some postfix issues.
cheers,
jure
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fail in sending UDP packet

2006-02-23 Thread Sbaush
No one of you has a idea??On 2/23/06, Sbaush <[EMAIL PROTECTED]> wrote:
Hi all. I've attached my SendReceive class. I have e a big problem! My program create a packet, then call the send function to send this. the first time the packet is not sent, then it works perfectly!WHY??? Have you idea??
-- Sbaush

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

Re: time.sleep(1) sometimes runs for 200 seconds under windows

2006-02-23 Thread Felipe Almeida Lessa
Em Qui, 2006-02-23 às 15:26 -0600, Paul Probert escreveu:
>My app runs in a loop looking for changes in a database, and like a 
> good boy I call time.sleep(1) inside the loop. Unfortunately this 
> sometimes runs for 200 seconds or so, presumably while my OS is calling 
> Bill Gates to tell him what I've been doing. This happens under NT4, 
> W2k, and XP. What do people do to fix this? Thanks!

What about the interpreter? Have you tried sleeping there?

-- 
"Quem excele em empregar a força militar subjulga os exércitos dos
outros povos sem travar batalha, toma cidades fortificadas dos outros
povos sem as atacar e destrói os estados dos outros povos sem lutas
prolongadas. Deve lutar sob o Céu com o propósito primordial da
'preservação'. Desse modo suas armas não se embotarão, e os ganhos
poderão ser preservados. Essa é a estratégia para planejar ofensivas."

  -- Sun Tzu, em "A arte da guerra"

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

Re: Concantenation and string slicing

2006-02-23 Thread Larry Bates
DannyB wrote:
> I've written a program that takes a phrase and spits it back out
> backwards.  My problem is it throws each character on a new line.  I'd
> like the phrase to be on the same line.  Is this possible?
> 
> #Backward Message
> 
> message = raw_input("Enter a message:  ")
> letter = len(message)
> while (letter > 0):
> newMessage = ""
> newMessage += message[letter-1]
> letter -= 1
> print newMessage
> 
> 
> Thanks!!
> 
> Dan
> 
Better was is:

message = raw_input("Enter a message:  ")
print message[::-1]

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


IRC Bot trouble..

2006-02-23 Thread yawgmoth7
I'm currently writing a IRC bot for fun...here is the code that I have
writen so far:

import sys
import socket
import string
import time
HOST="irc.freenode.net"
PORT=6667
NICK="PapaJorgio_"
IDENT="Papa"
REALNAME="Jorgio"
CHANNEL = "#holder"
buffer = ""
clientsock=socket.socket()
clientsock.connect((HOST, PORT))
clientsock.send("NICK %s\r\n" % NICK)
clientsock.send("USER %s %s bla :%s\r\n" % (IDENT, HOST, REALNAME))
clientsock.send("JOIN %s\r\n" % (CHANNEL))
clientsock.send("PRIVMSG #holder :There's a new AI in town foo.\r\n")
while 1:
buffer=buffer+clientsock.recv(1024)
temp=string.split(buffer, "\n")
print buffer
buffer=temp.pop()
for line in temp:
print "|%s|" % repr(line)
line=string.rstrip(line)
if "-part" in line:
clientsock.send("PART #holder :I am 
leet.\r\n")
elif "hello" in line:
clientsock.send("PRIVMSG #holder :Hey...\r\n")
elif "BlueInferno" in line:
clientsock.send("PRIVMSG #holder :OH NOES! 
>:o\r\n")
elif "-whois" in line:
query = line.split()[4]
clientsock.send("WHOIS eff.org %s\r\n" 
% query)
buffer2 = clientsock.recv(1024)
clientsock.send("PRIVMSG #holder 
:%s\r\n" % buffer2)
elif "-nick" in line:
nick = line.split()[4]
clientsock.send("NICK %s\n" % nick)
elif "PING" in line:
clientsock.send("PONG %s\r\n" % line[1])

Now...it is in a very early stage (started writing it maybe 45 minutes
ago). But, I have a few questions regarding some of the code that is
not working. One of the things I ham having a big trouble with is the
-whois part. I know that I cannot assign a variable like that (Since
socket's don't really work that way..I believe?). Basically I want to
it run a -whois query and print it to the channel..but I can not get
it to print it to the channel.Another problem is the 'PING' part. I
have no clue why it doesn't respond with PONG...it should work. I am
our of ideas >:(. Does anyone have any suggestions? Thank you for your
time/help.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: time.sleep(1) sometimes runs for 200 seconds under windows

2006-02-23 Thread Peter Hansen
Paul Probert wrote:
> Peter Hansen wrote:
>>Are you saying that you believe the time.sleep(1) call is actually 
>>blocking for 200 seconds?  Or just that your loop (and we can only guess 
>>what it looks like) is the one taking that long?
> 
> Yes, I'm doing this:
>.
>   oldtime=time.time()
>   time.sleep(1)
>   newtime=time.time()
>   dt=newtime-oldtime
>if dt > 2:
>print 'dt=',dt,' time=',time.strftime('%Y_%m_%d_%Hh_%Mm_%Ss')
> Its happening roughly 4 times a day total on our 20 machines, ie about 
> once every 5 days on a given machine.

So the above is printing "dt=200" or something like that?  Or just low 
values slightly larger than 2s?  Or a wide range of values?  Can you 
post samples of the print output for some of those failing runs?

-Peter

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


remote module importing (urlimport)

2006-02-23 Thread Jure Vrscaj
Hi,

as title implies, I wrote a simple module that allows importing modules 
or even packages via http, conceptually similar to zipimport (of which I 
learned about during the process of writing urlimport, and found it very 
useful).

The module is fresh new as it was written today, and tested only on a 
few packages (moinmoin wiki and twisted).

The motives: well, I kinda like the idea of having python modules 
available in an instant everywhere python and internet is, no pre-usage 
download required, especially when you need modules from different 
versions of python. Besides, I hope this will be a valid faculty project 
that I have to do. :)

This module is heavily based on specification and examples from PEP 302.

It can be found at: http://urlimport.codeshift.net/

Comments are welcome :)

Long live python.

regards,
Jure

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


Re: What's up with this code?

2006-02-23 Thread Gregory Petrosyan
Again, thanks a lot!
I'm optimising my polynomial module as hard as possible, because when
it used native floats/integers it was very fast, but in some specific
cases -- too inaccurate. So, I migrated to decimals, and module began
to be very slow. Current success is nearly 4x speedup, and now it seems
to me that decimals are the bottleneck. Is anybody working on C version
of decimals? Is it a really hard work? (I am thinking about
re-implementing decimals in C by myself)

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


Re: How would you open this file?

2006-02-23 Thread Larry Bates
Bob wrote:
> I want to open a file in a function and pass the file back to main so
> another function can manipulate the file, something like this:
> 
> # begin
> def open_file()
>   filename=open(options.filename_input,'r')
>   return filename
> 
> open_file()
> print filename.read()
> filename.close()
> # end
> 
> But this doesn't work... It appears that "open_file()" needs a
> variable, but in order to pass a variable to "open_file()" I first need
> a variable... but I would rather have the function send me "filename"
> without creating it main. Is that possible?
> 
> Is there a better way to have a function open a file and pass the file
> back to main than what I am trying to do?  Thanks!
> 

Your function returned filename but in the main program you didn't
have anywhere for it to be saved.

fp=open_file()
print fp.read()
fp.close()

Others have pointed out the filename is a bad choice for a
variable name as it is a pointer to a file object.  Most
tutorials and a lot of standard library code use fp.

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


Re: How would you open this file?

2006-02-23 Thread Dave Hansen
On Thu, 23 Feb 2006 18:01:32 -0500 in comp.lang.python, Kent Johnson
<[EMAIL PROTECTED]> wrote:

[...]
>
>filename = open_file()
>
>By the way 'filename' is a pretty bad name, since it contains a file 
>object, not a string. Maybe call it f instead. ('file' is also a bad 
>name because it is the name of a Python built-in function.)

I write a lot of simple scripts.  Those that have input and/or output
files tend to call them infile and outfile.  Given the name of the
OP's file, perhaps optfile would work for him...

Regards,
-=Dave

-- 
Change is inevitable, progress is not.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Concantenation and string slicing

2006-02-23 Thread CatDude
On Thu, 23 Feb 2006 14:55:16 -0800, DannyB wrote:

> I've written a program that takes a phrase and spits it back out
> backwards.  My problem is it throws each character on a new line.  I'd
> like the phrase to be on the same line.  Is this possible?

First suggestion: Put a comma at the end of the "print" line:

> print newMessage,


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


remote module importing (urlimport)

2006-02-23 Thread Jure Vrscaj
Hi,

as title implies, I wrote a simple module that allows importing modules 
or even packages via http, conceptually similar to zipimport (of which I 
learned about during the process of writing urlimport, and found it very 
useful).

The module is fresh new as it was written today, and tested only on a 
few packages (moinmoin wiki and twisted).

The motives: well, I kinda like the idea of having python modules 
available in an instant everywhere python and internet is, no pre-usage 
download required, especially when you need modules from different 
versions of python. Besides, I hope this will be a valid faculty project 
that I have to do. :)

This module is heavily based on specification and examples from PEP 302.

It can be found at: http://urlimport.codeshift.net/

Comments are welcome :)

Long live python.

regards,
Jure

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


Re: spaces at ends of filenames or directory names on Win32

2006-02-23 Thread Larry Bates

Steven D'Aprano wrote:
> On Thu, 23 Feb 2006 14:30:22 -0600, Larry Bates wrote:
> 
>> How about not naming files with leading and trailing spaces on
>> the Mac?  Seems like a bad habit that needs breaking ;-).
> 
> Why is it a bad habit? Because *Windows* is primitive enough that it can't
> cope with leading and trailing spaces? I don't see why Windows' lack is
> Mac users' problem.
> 
> 
It is a problem because the poster says it is a problem for him.
If they want to leave the files on a Mac, there is no problem.

IMHO leading and/or trailing spaces in filenames is asking for
incompatibilities with cross-platform file access.  Much like
using single-quote in filenames which are perfectly legal in
DOS/Windows, but Linux doesn't like much.

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


Re: a little more help with python server-side scripting

2006-02-23 Thread Paul Boddie
John Salerno wrote:
> Paul Boddie wrote:
>
> > No, it means that you either write Python programs which produce pages
> > as output, according to the CGI specification, or that you embed Python
> > code inside ASP files, as described in the above document.
>
> > I haven't used ASP, and I've been working hard to remove from my memory
> > any trace of similar systems (eg. JSP), but I imagine that if you want
> > to include normal Python programs inside ASP files, there may be a way
> > of using some kind of "include" directive. Take a look at the above
> > document for some ideas.
>
> Why do you mention ASP though? Can't this be done without it?

You mean, can't you just write normal HTML files, add some kind of
"include" directive, call them something ending in .html, and then have
the server produce a combination of normal HTML and the output from
Python code? Well, not really, since that (apart from the .html
extension on the filename) is a description of what ASP is about, more
or less.

But yes, if you want to run Python code without doing strange things
with ASP files, then just write a program (not a Web page, but an
actual Python program) as described in the Microsoft document (or
virtually any introduction to CGI with Python), upload it into the
appropriate folder/directory with a filename ending in .py and test it
out! See this recipe for other examples (found using the search text
"CGI Python" with Google):

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

Paul

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


Re: Concantenation and string slicing

2006-02-23 Thread DannyB
Wow - thats simple =).  Thanks a ton!!

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


Re: a little more help with python server-side scripting

2006-02-23 Thread Gerard Flanagan
John Salerno wrote:
>
> Ok, seems like the verdict is that the server doesn't have mod_python
> nor does it detect the .psp extension. It can, however, detect the .py
> extension. But does this mean I can simply include Python code in my
> HTML files, and then give my HTML files a .py extension?

No.

[...]

>
> ? They say:
>
> "Please note that you may map .py to .html extension. However, if you
> set this mapping, .html will not work with the normal html tags anymore."
>
> But I don't know what this means about 'mapping' the extension and what
> it means that html tags won't work anymore.

John

There is a configuration section in the IIS management tool
(inetmgr.exe) called 'Application Mappings' which maps file extensions
to applications.  For example, on my (WinXP) machine I have:

  .aspx -->
C:\WINDOWS\Microsoft.NET\Framework\v1.14322\aspnet_isapi.dll
  .asp   -->  C:\WINDOWS\system32\inetsrv\asp.dll
  .php   -->  C:\Program Files\PHP\Php51\php-cgi.exe

among others.  So if IIS receives a request for a url with one of these
extensions it passes that request on to the relevant program.  You
could map '.py' to 'python.exe %s %s' but any '.py' files would have to
be pure Python.

IIS doesn't need any help with standard, static .html requests, it can
serve those itself.  It may be possible to map '.html' to any of the
three applications above and still have static HTML pages function
identically (even if this would create a pointless overhead ), however
you couldn't map '.html' to 'python.exe' and expect anything meaningful
- there is nothing like 'python-cgi.exe' that understands HTML with or
without inlined python code.

Gerard

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


Re: Concantenation and string slicing

2006-02-23 Thread nak
add a dash like shown below

>>> print newMessage,

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


Re: What's up with this code?

2006-02-23 Thread Scott David Daniels
Gregory Petrosyan wrote:
> Oh, by the way, is there any documentation about time of execution of
> standard functions?
Nope.  The reason is (A) that's a lot of work, (B) there are too many
caveats in practice to make such information useful, (C) any such spec
might corner the possible implementations in a later version.

 > is len(list) O(1) or O(n), etc) and is there any C version of decimal?
len(list) is O(1), list[n] is O(1), and if you (and others) continue
using decimal and it gets popular, rest assured that it will get faster.
Also, dictionary access is \Theta(1) (but only because you run on
machines with quite finite limitations).

The general Python rule when writing is "only worry about fast enough"
and optimize only after the code works and it needs to be faster.
Further, to determine speed, measure (use the timeit module) rather than
guess.  Nobody's intuition is great WRT performance, and you'd be
shocked at the number of hours people spend speeding up a chunk of code
that cannot possibly substantially affect an applications performance.

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


Re: How would you open this file?

2006-02-23 Thread Kent Johnson
Bob wrote:
> I want to open a file in a function and pass the file back to main so
> another function can manipulate the file, something like this:
> 
> # begin
> def open_file()
>   filename=open(options.filename_input,'r')
>   return filename
> 
> open_file()
> print filename.read()
> filename.close()
> # end

You need to assign the result of open_file() to a variable. The 
'filename' variable inside open_file() is not available outside the 
function:

filename = open_file()

By the way 'filename' is a pretty bad name, since it contains a file 
object, not a string. Maybe call it f instead. ('file' is also a bad 
name because it is the name of a Python built-in function.)

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


Concantenation and string slicing

2006-02-23 Thread DannyB
I've written a program that takes a phrase and spits it back out
backwards.  My problem is it throws each character on a new line.  I'd
like the phrase to be on the same line.  Is this possible?

#Backward Message

message = raw_input("Enter a message:  ")
letter = len(message)
while (letter > 0):
newMessage = ""
newMessage += message[letter-1]
letter -= 1
print newMessage


Thanks!!

Dan

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


How would you open this file?

2006-02-23 Thread Bob
I want to open a file in a function and pass the file back to main so
another function can manipulate the file, something like this:

# begin
def open_file()
  filename=open(options.filename_input,'r')
  return filename

open_file()
print filename.read()
filename.close()
# end

But this doesn't work... It appears that "open_file()" needs a
variable, but in order to pass a variable to "open_file()" I first need
a variable... but I would rather have the function send me "filename"
without creating it main. Is that possible?

Is there a better way to have a function open a file and pass the file
back to main than what I am trying to do?  Thanks!

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


Re: Using a list of RGB data for Canvas widget? [(R1, G1, B1), (R2, G2, B2) etc.]

2006-02-23 Thread Nainto
Just to clarify. I'm not asking for any code. A ink or explination of
how to convert a list of this type to BitmapImage or PhotoImage data
would be very helpful.

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


Re: spaces at ends of filenames or directory names on Win32

2006-02-23 Thread Steven D'Aprano
On Thu, 23 Feb 2006 14:30:22 -0600, Larry Bates wrote:

> How about not naming files with leading and trailing spaces on
> the Mac?  Seems like a bad habit that needs breaking ;-).

Why is it a bad habit? Because *Windows* is primitive enough that it can't
cope with leading and trailing spaces? I don't see why Windows' lack is
Mac users' problem.


-- 
Steven.

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


Re: "Temporary" Variable

2006-02-23 Thread Steven D'Aprano
On Thu, 23 Feb 2006 12:05:59 -0800, darthbob88 wrote:

My comments inserted inline.


> #!/usr/bin/python
> #simple guessing game, with numbers
> import random
> spam = random.randint(1, 100)

It is bad programming practice to give variables uninformative joke names.

How about target instead?

> print spam #debugging purposes
> while 1:
>   guess = raw_input("What's your guess, friend? ")

Why don't you stick a "print guess" in here to see what your guess is?

(Hint: what is the difference between 1 and '1'?)

>   if guess == spam:
>   print "You got it! Nicely done."
>   break
>   elif guess < spam:
>   print "Sorry, too low. Try again."
>   elif guess > spam:
>   print "Sorry, too high. Try again."
>   else:
>   print "You guessed ", guess



>> You could try this:
>>
>> while 1:
>>  var = raw_input("Give me some data! ")
>>  if var == "some data":
>>  print "Success!"
>>  break
>>  else:
>>  print "No good, try again."
> That works fine with strings and when "some_data" is hardcoded. I run
> into trouble when "some data" is replaced with a number, unquoted. It
> simply says "No good, etc"

Try this, at a command line:

5 == '5'


and see what you get.


-- 
Steven.

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


Re: time.sleep(1) sometimes runs for 200 seconds under windows

2006-02-23 Thread Paul Probert
Peter Hansen wrote:

>Are you saying that you believe the time.sleep(1) call is actually 
>blocking for 200 seconds?  Or just that your loop (and we can only guess 
>what it looks like) is the one taking that long?
>
>If the former, try something like putting "print 'before'" and "print 
>'after'" before and after the sleep, and observe what happens when you 
>run the program.  I'm fairly confident in saying there's no chance 
>you'll see the "before" sit for 200s before you see the "after" and that 
>your problem lies elsewhere, not with time.sleep(1).
>
>If the latter, um, obviously we can't help without more info.
>
>-Peter
>
>  
>
Yes, I'm doing this:
   .
  oldtime=time.time()
  time.sleep(1)
  newtime=time.time()
  dt=newtime-oldtime
   if dt > 2:
   print 'dt=',dt,' time=',time.strftime('%Y_%m_%d_%Hh_%Mm_%Ss')
Its happening roughly 4 times a day total on our 20 machines, ie about 
once every 5 days on a given machine.

Paul Probert
University of Wisconsin

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


Re: A C-like if statement

2006-02-23 Thread Steven D'Aprano
On Thu, 23 Feb 2006 12:04:38 -0700, Bob Greschke wrote:

>> try:
>>i = a.find("3")
>>print "It's here: ", i
>> except NotFound:
>>print "No 3's here"
> 
> Nuts.  I guess you're right.  It wouldn't be proper.  Things are added or 
> proposed every day for Python that I can't even pronounce, but a simple 'if 
> (I = a.find("3")) != -1' isn't allowed.  Huh.  It might be time to go back 
> to BASIC. :)

There are *reasons* why Python discourages functions with side-effects.
Side-effects make your code hard to test and harder to debug.

> I think your way would work if .find() were replaced with .index().  I'm 
> just trying to clean up an if/elif tree a bit, so using try would make 
> things bigger.

Then write a function! Instead of calling the try..except block in every
branch directly, pull it out into a function:

def test(s,what):
try:
i = s.index(what)
print "It's here: ", i
except ValueError:
print "No 3's here"


-- 
Steven.

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


Re: time.sleep(1) sometimes runs for 200 seconds under windows

2006-02-23 Thread Paul Probert
Benji York wrote:

>Paul Probert wrote:
> > Hi, My app runs in a loop looking for changes in a database, and like
> > a good boy I call time.sleep(1) inside the loop. Unfortunately this
> > sometimes runs for 200 seconds or so, presumably while my OS is
> > calling Bill Gates to tell him what I've been doing. This happens
> > under NT4, W2k, and XP. What do people do to fix this? Thanks!
>
> From the docs for time.sleep:
>
> The actual suspension time may be less than that requested because
> any caught signal will terminate the sleep() following execution of
> that signal's catching routine. Also, the suspension time may be
> longer than requested by an arbitrary amount because of the
> scheduling of other activity in the system.
>--
>Benji York
>  
>
Benji,
   Thanks, but yes, I had read that before posting. One would think, 
though, that the extra 200 seconds is a bit extreme to be blamable on 
system scheduling granularity.
   I'm starting to think we've got a worm of some kind. If so, its 
invisible to our Norton AV corporate.

Paul Probert
University of Wisconsin

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


Re: Unexpected timing results

2006-02-23 Thread Steven D'Aprano
On Thu, 23 Feb 2006 10:07:14 -0600, Larry Bates wrote:

>> Of course I expect timer2 should take longer to execute in total,
>> because it is doing a lot more work. But it seems to me that all that
>> extra work should not affect the time measured, which (I imagine) should
>> be about the same as timer1. Possibly even less as it isn't timing the
>> setup of the for loop.

...

> In timer2 you are making a million extra calls to timer()
> function and doing a million additions and a million
> subtractions that are not being done in timer1() function.
> I think that is where your "extra" time is located.

But those extra additions, subtractions, etc. are not being timed, because
they are outside the part where the stopwatch is ticking, in a manner of
speaking.

I know that timer2 will take longer to execute than timer1. That's not
the surprising bit. But I'm not measuring all the execution time, only
part of it, and not all that execution time is being timed.

The only extra work I can see is a call to timer() each loop. The first
call shouldn't count, because it happens before the clock starts. Is
calling time.time() really such as expensive operation, especially when
I've rebound the name so as to avoid a name lookup?

I guess it is: I've run two more tests, both going back to the form of
timer1, but changing the function being timed. The first uses math.sin.
The second uses time.timer.

Here is the code:

def timer3():
timer = time.time
func = math.sin
itr = [None] * 100
t0 = timer()
for _ in itr:
func(0.1)
t1 = timer()
return t1 - t0

def timer4():
timer = time.time
func = timer
itr = [None] * 100
t0 = timer()
for _ in itr:
func()
t1 = timer()
return t1 - t0

And the results:

>>> timer.timer3()
0.64760088920593262
>>> timer.timer4()
5.2274949550628662



It looks like the time function under Linux at least is very slow.


-- 
Steven.

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


Re: PyDev/Eclipse Help

2006-02-23 Thread Don Taylor
Greg Lindstrom wrote:
> I am running Python 2.4 on Windows XP "Professional" and Eclipse 3.1.  I 
> would like to take a look at PyDev on Eclipse and downloaded the PyDev 
> (1.0.2?) via the Help->SotwareUpdates->FindAndInstall wizard.  Then then 
> go to create a Python Project with File->New->Project and then select 
> Pydev->Pydev Project and get an Error Dialog stating: "The selected 
> wizard could not be started.  Reason: Plug-in org.python.pydev was 
> unable to load class 
> org.python.pydev.ui.wazards.project.PythonProjectWizard."  Can any of 
> you wizards tell me what this means (well, OK, I *know* it means I can't 
> load PythonProjectWizard, but you get my drift, right?).
> 
> Thanks for your help...see yo in Dallas!
> --greg
> 
> 
I don't know the answer, but you might get one from the Pydev forum

http://sourceforge.net/forum/forum.php?forum_id=293649

Don.

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


Re: 2.4.2 + Zone Alarm

2006-02-23 Thread DaveM
On 20 Feb 2006 16:26:15 -0800, "DannyB" <[EMAIL PROTECTED]> wrote:

>I believe this issue is known - I haven't found a way around it.
>
>ZoneAlarm seems to be stopping IDLE from running.
>I get two errors:
>
>"Socket Error:  Connection refused"
>and
>"IDLE's subprocess didn'tt make connection.  Either IDLE can't start a
>subprocess or personal firewall software is blocking the connection."
>
>I know they are both due to ZA - I've set up ZA to allow Python to
>access the internet w/o prompting me (even though I now it doesn't
>actually access the internet.)
>
>This usually happens after I create a script and run it in the GUI - if
>the script ends up being a never ending loop - I X out of IDLE to stop
>it.  The next time I try to run a script I get the errors until I
>reboot the computer.
>
>IIs there a fix?  I'm pretty sure that this problem started with 2.3.1
>(i'm suing 2.4.2).

I get an the same problem in those circumstances, although I can't remember
if I get that error message (and I use ZoneAlarm).

Windows task manager shows pythonw.exe still running and terminating the
process allows IDLE to start normally. Easier than rebooting. PythonWin
doesn't suffer this problem, btw.

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


Re: time.sleep(1) sometimes runs for 200 seconds under windows

2006-02-23 Thread Paul Probert
Claudio Grondi wrote:

>In similar situation I would start to blame the hardware for the 
>problem, so below a kind of checklist to go through:
>
>   1. have you changed any hardware?
>   2. have you installed new drivers?
>   3. have you connected via USB/Firewire/IDE or other interfaces/ports 
>etc. some new devices?
>   4. have you installed new BIOS?
>   5. is your RAM ok?
>   6. are you sure there is no CD/DVD in your CD/DVD drive?
>   7. are you sure there is no floppy disk in your floppy drive?
>   8. are you sure your CPU/motherboard/RAM is not overheating?
>
>Claudio
>  
>
Claudio,
  Thanks for the reply. I should have mentioned, this happens to just 
about every machine in our collection of about 20 machines. Each is of a 
different age, and the hardware is completely diverse. Each has either 
of NT4, win2k, or XP installed. They all belong to our domain

Paul Probert
University of Wisconsin

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


Re: time.sleep(1) sometimes runs for 200 seconds under windows

2006-02-23 Thread Ivan Shevanski
On 2/23/06, Claudio Grondi <[EMAIL PROTECTED]> wrote:
Paul Probert wrote:> Hi,>   My app runs in a loop looking for changes in a database, and like a> good boy I call time.sleep(1) inside the loop. Unfortunately this> sometimes runs for 200 seconds or so, presumably while my OS is calling
> Bill Gates to tell him what I've been doing. This happens under NT4,> W2k, and XP. What do people do to fix this? Thanks!>> Paul Probert> University of Wisconsin>In similar situation I would start to blame the hardware for the
problem, so below a kind of checklist to go through:   1. have you changed any hardware?   2. have you installed new drivers?   3. have you connected via USB/Firewire/IDE or other interfaces/portsetc. some new devices?
   4. have you installed new BIOS?   5. is your RAM ok?   6. are you sure there is no CD/DVD in your CD/DVD drive?   7. are you sure there is no floppy disk in your floppy drive?   8. are you sure your CPU/motherboard/RAM is not overheating?
Claudio--http://mail.python.org/mailman/listinfo/python-listSo what exactly does the loop do? Try running the loop without sleep and then see how long that takes.
-- -Ivan
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: time.sleep(1) sometimes runs for 200 seconds under windows

2006-02-23 Thread Peter Hansen
Paul Probert wrote:
>My app runs in a loop looking for changes in a database, and like a 
> good boy I call time.sleep(1) inside the loop. Unfortunately this 
> sometimes runs for 200 seconds or so, presumably while my OS is calling 
> Bill Gates to tell him what I've been doing. This happens under NT4, 
> W2k, and XP. What do people do to fix this? Thanks!

Are you saying that you believe the time.sleep(1) call is actually 
blocking for 200 seconds?  Or just that your loop (and we can only guess 
what it looks like) is the one taking that long?

If the former, try something like putting "print 'before'" and "print 
'after'" before and after the sleep, and observe what happens when you 
run the program.  I'm fairly confident in saying there's no chance 
you'll see the "before" sit for 200s before you see the "after" and that 
your problem lies elsewhere, not with time.sleep(1).

If the latter, um, obviously we can't help without more info.

-Peter

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


Re: time.sleep(1) sometimes runs for 200 seconds under windows

2006-02-23 Thread Claudio Grondi
Paul Probert wrote:
> Hi,
>   My app runs in a loop looking for changes in a database, and like a 
> good boy I call time.sleep(1) inside the loop. Unfortunately this 
> sometimes runs for 200 seconds or so, presumably while my OS is calling 
> Bill Gates to tell him what I've been doing. This happens under NT4, 
> W2k, and XP. What do people do to fix this? Thanks!
> 
> Paul Probert
> University of Wisconsin
> 

In similar situation I would start to blame the hardware for the 
problem, so below a kind of checklist to go through:

   1. have you changed any hardware?
   2. have you installed new drivers?
   3. have you connected via USB/Firewire/IDE or other interfaces/ports 
etc. some new devices?
   4. have you installed new BIOS?
   5. is your RAM ok?
   6. are you sure there is no CD/DVD in your CD/DVD drive?
   7. are you sure there is no floppy disk in your floppy drive?
   8. are you sure your CPU/motherboard/RAM is not overheating?

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


Re: time.sleep(1) sometimes runs for 200 seconds under windows

2006-02-23 Thread Benji York
Paul Probert wrote:
 > Hi, My app runs in a loop looking for changes in a database, and like
 > a good boy I call time.sleep(1) inside the loop. Unfortunately this
 > sometimes runs for 200 seconds or so, presumably while my OS is
 > calling Bill Gates to tell him what I've been doing. This happens
 > under NT4, W2k, and XP. What do people do to fix this? Thanks!

 From the docs for time.sleep:

 The actual suspension time may be less than that requested because
 any caught signal will terminate the sleep() following execution of
 that signal's catching routine. Also, the suspension time may be
 longer than requested by an arbitrary amount because of the
 scheduling of other activity in the system.
--
Benji York
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a little more help with python server-side scripting

2006-02-23 Thread John Salerno
Paul Boddie wrote:

> No, it means that you either write Python programs which produce pages
> as output, according to the CGI specification, or that you embed Python
> code inside ASP files, as described in the above document.

> I haven't used ASP, and I've been working hard to remove from my memory
> any trace of similar systems (eg. JSP), but I imagine that if you want
> to include normal Python programs inside ASP files, there may be a way
> of using some kind of "include" directive. Take a look at the above
> document for some ideas.

Why do you mention ASP though? Can't this be done without it?
-- 
http://mail.python.org/mailman/listinfo/python-list


time.sleep(1) sometimes runs for 200 seconds under windows

2006-02-23 Thread Paul Probert
Hi,
   My app runs in a loop looking for changes in a database, and like a 
good boy I call time.sleep(1) inside the loop. Unfortunately this 
sometimes runs for 200 seconds or so, presumably while my OS is calling 
Bill Gates to tell him what I've been doing. This happens under NT4, 
W2k, and XP. What do people do to fix this? Thanks!

Paul Probert
University of Wisconsin

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


Re: spaces at ends of filenames or directory names on Win32

2006-02-23 Thread [EMAIL PROTECTED]
rtilley wrote:
> # Spaces are present before and after the XXX
> filename = ' XXX '
>
> new_filename = filename.strip()
>
> if new_filename != filename:
>  print filename
>
> Macs allow these spaces in file and folder names. Which is OK. The
> problem arises when the file or folder is copied to a PC running Windows
> from a Mac. Windows allows the Mac to copy the file to it, but when
> Windows itself attempts to do anything with the file it strips the
> spaces and then tries to move it, copy it, etc and complains that the
> file isn't there!
>
> I can rectify this by striping the spaces from the files and folders on
> the Mac before they are copied to the PC or mounting the Windows share
> from the Mac and running a recursive strip program I wrote, but Windows
> will not allow the whitespace removal directly from within Windows
> how annoying!
>
> For example... tell windows to move a file named ' XXX ' (one space
> before and one space after the filename). Windows will complain that
> file 'XXX' does not exist. It's correct of course, 'XXX' does not exist,
> but ' XXX ' does indeed exist.
>
> Can anyone rescue me from this madness :(

Use quatation marks.

>copy tt1.txt " XXX "
1 file(s) copied.

>dir XXX
 Volume in drive C is PXXABA
 Volume Serial Number is 90C0-740E

 Directory of C:\Documents and Settings\Desktop

File Not Found

>dir " XXX
 Volume in drive C is PXXABA
 Volume Serial Number is 90C0-740E

 Directory of C:\Documents and Settings\Desktop

02/06/2006  07:05p  10  XXX
   1 File(s) 10 bytes
   0 Dir(s)   2,063,822,848 bytes free

>dir *.
 Volume in drive C is PXXABA
 Volume Serial Number is 90C0-740E

 Directory of C:\Documents and Settings\Desktop

02/23/2006  03:20p.
02/23/2006  03:20p..
02/06/2006  07:05p  10  XXX
01/20/2006  04:53pAGMP
01/20/2006  04:53pBPWR Fe-Mn
01/20/2006  04:53pGM
01/20/2006  04:53pIDEM response
01/20/2006  04:53pmsgs
01/20/2006  04:53pNew Folder
02/08/2006  05:29pNew Folder (2)
01/20/2006  04:53pOCAML
01/20/2006  04:53preview05
01/20/2006  04:53pscanned docs
02/17/2006  03:07pUSS repository
   1 File(s) 10 bytes
  13 Dir(s)   2,063,822,848 bytes free

Note that the trailing quote isn't always necessary.
Note from the last listing that the  XXX  file is indented one space.

> 
> Many Thanks,
> Brad

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


Re: a little more help with python server-side scripting

2006-02-23 Thread Paul Boddie
John Salerno wrote:
> John Salerno wrote:
>
> > Unfortunately, I don't completely understand what it is I need to do
> > now. Where do I put the path they mentioned? And what do they mean by my
> > script path?
>
> Ok, seems like the verdict is that the server doesn't have mod_python
> nor does it detect the .psp extension. It can, however, detect the .py
> extension.

>From what I understand of the situation, noting that I haven't used IIS
with Python at all as far as I remember (and it'd be about six or seven
years ago if I did), you're using Windows hosting where .py files get
special treatment - ie. they don't get served up as text files but are
executed somehow - and that this is probably configured by your
provider as described in this document (found via Google using the
search text "IIS Python"):

http://support.microsoft.com/default.aspx?scid=kb%3Ben-us%3B276494

> But does this mean I can simply include Python code in my
> HTML files, and then give my HTML files a .py extension?

No, it means that you either write Python programs which produce pages
as output, according to the CGI specification, or that you embed Python
code inside ASP files, as described in the above document.

> I don't know how to test this because I don't know how to write inline code 
> yet. Is
> it something like:
>
> <%@ include file=something %>

I haven't used ASP, and I've been working hard to remove from my memory
any trace of similar systems (eg. JSP), but I imagine that if you want
to include normal Python programs inside ASP files, there may be a way
of using some kind of "include" directive. Take a look at the above
document for some ideas.

> ? They say:
>
> "Please note that you may map .py to .html extension. However, if you
> set this mapping, .html will not work with the normal html tags anymore."
>
> But I don't know what this means about 'mapping' the extension and what
> it means that html tags won't work anymore.

I think they're just trying to say that if you decide that your Python
programs should have a .html extension and still be executed as Python
programs, don't expect the server to serve up HTML pages any more.

Paul

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


Re: problem with newlines in regexp substitution

2006-02-23 Thread James Stroud
Florian Schulze wrote:
> See the following results:
> 
> Python 2.3.5 (#62, Feb  8 2005, 16:23:02) [MSC v.1200 32 bit (Intel)] on 
> win32
> Type "help", "copyright", "credits" or "license" for more information.
> 
 import re
 s = "1"
 re.sub('1','\\n',s)
> 
> '\n'
> 
 '\\n'
> 
> '\\n'
> 
 re.sub('1',r'\\n',s)
> 
> '\\n'
> 
 s.replace('1','\\n')
> 
> '\\n'
> 
 repl = '\\n'
 re.sub('1',repl,s)
> 
> '\n'
> 
 s.replace('1',repl)
> 
> '\\n'
> 
> Why is the behaviour of the regexp substitution so weird and can I 
> prevent that? It breaks my asumptions and thus my code.
> 
> Regards,
> Florian Schulze
> 

"Why" questions are always tough to answer. E.g.: Why are we here?

The answer to "what is happening" is much easier. Strings passed to the 
regex engine are processed first, so escapes must be escaped. This is 
why raw strings were invented. If it weren't for these, I'd still be 
using perl. In raw strings, as you have noticed, a '\' is already 
escaped. In the olden days, you'd have to type "" to mean a literal 
backslash, so creating a literal backslash in a regex that produced a 
string that would then itself be used in a regex would be 
'', which scared me away from Python for a couple of 
years (rmember, the final printed product would be '\').

That patently doesn't answer your question, but here is something to ponder:

py> s.replace('1',repl)[0]
'\\'
py> print s.replace('1',repl)
\n

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


Re: spaces at ends of filenames or directory names on Win32

2006-02-23 Thread Larry Bates
rtilley wrote:
> Larry Bates wrote:
>> How about not naming files with leading and trailing spaces on
>> the Mac?  Seems like a bad habit that needs breaking ;-).
>>
>> -Larry Bates
> 
> Users will be users! Tell that to the guys and gals on Macs who like to
> make a folder sort based on the number of spaces they've placed in the
> front of the filenames :)

Sounds like you should change leading/trailing spaces to something
like underlines instead of stripping them off the filename.  That way
you preserve the character positions, visually the filenames are very
close.  Problem is that underlines sort to bottom instead of to the
top of a list of files.

On second thought, if you replace spaces with dashes they will sort
correctly, but they will look odd.

Pick your poison.

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


Re: ANN: Urwid 0.9.0 - Console UI library

2006-02-23 Thread Ian Ward
Thomas Dickey wrote:
> Ian Ward <[EMAIL PROTECTED]> wrote:
> 
>>  - New raw_display module that handles console display without relying
>>on external libraries.  This module was written as a work around
>>for the lack of UTF-8 support in the standard version of ncurses.
> 
> 
> The "standard version" of ncurses has supported UTF-8 for the past few
> years.  You may perhaps mean "default configuration", which has a
> different connotation.
> 

You're right.

I was looking for a short way of saying "a work around for lack of UTF-8 
support in the version of ncurses that Python links against by default".

Ian Ward

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


Re: "Temporary" Variable

2006-02-23 Thread Rick Zantow
[EMAIL PROTECTED] wrote in news:1140725159.143882.202630
@j33g2000cwa.googlegroups.com:

> 
> Steven D'Aprano wrote:
>> You could try this:
>>
>> while 1:
>>  var = raw_input("Give me some data! ")
>>  if var == "some data":
>>  print "Success!"
>>  break
>>  else:
>>  print "No good, try again."
> That works fine with strings and when "some_data" is hardcoded. I run
> into trouble when "some data" is replaced with a number, unquoted. It
> simply says "No good, etc"

Raw_input isn't giving you what you think it is. You're comparing it to 
an integer, not a string. Does that help?

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


Re: MySQLdb slow on MySQL 5

2006-02-23 Thread [EMAIL PROTECTED]

Gerhard Häring wrote:
>
> Maybe you're running in autocommit mode. I. e. an implicit COMMIT is
> done for each insert. This slows any database down.
>
> Or are you calling commit() yourself too often?
>
> -- Gerhard

I'm not calling COMMIT at all. I'm using MyISAM tables. I'll check on
autocommit. Thanks.

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


Re: spaces at ends of filenames or directory names on Win32

2006-02-23 Thread rtilley
Larry Bates wrote:
> How about not naming files with leading and trailing spaces on
> the Mac?  Seems like a bad habit that needs breaking ;-).
> 
> -Larry Bates

Users will be users! Tell that to the guys and gals on Macs who like to 
make a folder sort based on the number of spaces they've placed in the 
front of the filenames :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to move optparse from main to function?

2006-02-23 Thread Bob
Yes the documentation is helpful, but I wouldn't have been able to do
what you did in your code by just looking at section 6.21.2.9. I
thought I could put "parser = parserSetup()" and "(options, args) =
parser.parse_args()" in the function. Thanks for helping out with that!

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


Re: spaces at ends of filenames or directory names on Win32

2006-02-23 Thread Larry Bates
rtilley wrote:
> # Spaces are present before and after the XXX
> filename = ' XXX '
> 
> new_filename = filename.strip()
> 
> if new_filename != filename:
> print filename
> 
> Macs allow these spaces in file and folder names. Which is OK. The
> problem arises when the file or folder is copied to a PC running Windows
> from a Mac. Windows allows the Mac to copy the file to it, but when
> Windows itself attempts to do anything with the file it strips the
> spaces and then tries to move it, copy it, etc and complains that the
> file isn't there!
> 
> I can rectify this by striping the spaces from the files and folders on
> the Mac before they are copied to the PC or mounting the Windows share
> from the Mac and running a recursive strip program I wrote, but Windows
> will not allow the whitespace removal directly from within Windows
> how annoying!
> 
> For example... tell windows to move a file named ' XXX ' (one space
> before and one space after the filename). Windows will complain that
> file 'XXX' does not exist. It's correct of course, 'XXX' does not exist,
> but ' XXX ' does indeed exist.
> 
> Can anyone rescue me from this madness :(
> 
> Many Thanks,
> Brad

How about not naming files with leading and trailing spaces on
the Mac?  Seems like a bad habit that needs breaking ;-).

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


Re: How to move optparse from main to function?

2006-02-23 Thread Bob
The module documentation helped me construct the meat of my code bu it
didn't lend a hand on how to build the real meal deal the way Jason's
explanation did.

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


Re: a little more help with python server-side scripting

2006-02-23 Thread John Salerno
John Salerno wrote:

> Unfortunately, I don't completely understand what it is I need to do 
> now. Where do I put the path they mentioned? And what do they mean by my 
> script path?

Ok, seems like the verdict is that the server doesn't have mod_python 
nor does it detect the .psp extension. It can, however, detect the .py 
extension. But does this mean I can simply include Python code in my 
HTML files, and then give my HTML files a .py extension? I don't know 
how to test this because I don't know how to write inline code yet. Is 
it something like:

<%@ include file=something %>

? They say:

"Please note that you may map .py to .html extension. However, if you 
set this mapping, .html will not work with the normal html tags anymore."

But I don't know what this means about 'mapping' the extension and what 
it means that html tags won't work anymore.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Temporary" Variable

2006-02-23 Thread darthbob88

Steven D'Aprano wrote:
> [EMAIL PROTECTED] wrote:
>
> > Problem: I wish to run an infinite loop and initialize a variable on
> > each iteration. Sort of like, "Enter Data", test it, "No good!", "Next
> > Try?", test it, etc. What I've tried is simply while 1: var1 =
> > raw_input, test var1, then run through the loop again. What results is
> > var1 gets and keeps the first value it receives.
>
> Hmmm. I get a syntax error.
>
>  >>> while 1:
> ... var1 = raw_input
> ... test var1
>File "", line 3
>  test var1
>  ^
> SyntaxError: invalid syntax
>
> How about posting your actual code?
Soitenly.
#!/usr/bin/python
#simple guessing game, with numbers
import random
spam = random.randint(1, 100)
print spam #debugging purposes
while 1:
guess = raw_input("What's your guess, friend? ")
if guess == spam:
print "You got it! Nicely done."
break
elif guess < spam:
print "Sorry, too low. Try again."
elif guess > spam:
print "Sorry, too high. Try again."
else:
print "You guessed ", guess
> You could try this:
>
> while 1:
>  var = raw_input("Give me some data! ")
>  if var == "some data":
>  print "Success!"
>  break
>  else:
>  print "No good, try again."
That works fine with strings and when "some_data" is hardcoded. I run
into trouble when "some data" is replaced with a number, unquoted. It
simply says "No good, etc"
> -- 
> Steven.

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


Re: How to move optparse from main to function?

2006-02-23 Thread Jason Drew
As pointed out, the module documentation is helpful.

For your 'test' option, I don't think 'action="count"' is the best
action. 'Test' is basically an on/off option, so why count it? I would
use:

parser.add_option("-t", "--test", action="store_true",
dest="optparse_test", default=False, help="testing optparse")

Then your code can use
if options.optparse_test == True: ...
or briefer:
if options.optparse_test: ...


As for putting the optparse code into a function, I sometimes use:

def parserSetup():
"""Return a configured option parser for this program."""
parser = OptionParser()
parser.add_option( ... your option stuff ... )
parser.add_option( ... )
return parser

if __name__=="__main__":
parser = parserSetup()
(options, args) = parser.parse_args()
# Then in your case:
if options.optparse_test: ...

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


Re: why don't many test frameworks support file-output?

2006-02-23 Thread Benji York
kanchy kang wrote:
> i browsed the following frameworks briefly: nose, OOBTest,
> testosterone,  py.test, Sancho ... and found out they do support 
> imediate screen-output only.

You can redirect stdout to a file.
--
Benji York
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A C-like if statement

2006-02-23 Thread Dave Hansen
On Thu, 23 Feb 2006 12:04:38 -0700 in comp.lang.python, "Bob Greschke"
<[EMAIL PROTECTED]> wrote:

>
>"Roy Smith" <[EMAIL PROTECTED]> wrote in message 
>news:[EMAIL PROTECTED]
[...]

>> try:
>>i = a.find("3")
>>print "It's here: ", i
>> except NotFound:
>>print "No 3's here"
>
>Nuts.  I guess you're right.  It wouldn't be proper.  Things are added or 
>proposed every day for Python that I can't even pronounce, but a simple 'if 
>(I = a.find("3")) != -1' isn't allowed.  Huh.  It might be time to go back 
>to BASIC. :)

I think you'll find that BASIC doesn't allow it either...

Of the "missing" "features" of Python, this one is waay down on my
list.  In fact, it's not there at all.  What I _really_ miss is
do{...}while.  The best workaround I've found is unaesthetic, IMHO:

   while 1:
  # stuff
  if exit_condition: break

Regards,
-=Dave

-- 
Change is inevitable, progress is not.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: editor for Python on Linux

2006-02-23 Thread Philippe Martin
Mladen Adamovic wrote:

> Hi!
> 
> I wonder which editor or IDE you can recommend me for writing Python
> programs. I tried with jEdit but it isn't perfect.

Eclipse + pydev

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


Re: pyserial

2006-02-23 Thread Philippe Martin
Hi,

I never found the need to flush anything and I always use inWaiting prior to
reader.

A+

Philippe



Mimi wrote:

> Hi,
> I use the pyserial to read data from a serial port.
> My code is in window Xp and python 2.4. when I use Hyperteminal I can
> read data without try and try again that it is not the case with
> pyserial library.
> anyone can help me ?
> this is a part of my code:
> 
> self.ser = serial.Serial()
> self.ser.baudrate = 9600
> self.ser.port = 3
> self.ser.timeout= 10
> self.ser.bytesize = serial.EIGHTBITS
> self.ser.stopbits = serial.STOPBITS_ONE
> self.ser.xonxoff = 0
> 
>nbHisto = 144
>for i in range(0,nbHisto):
> while 1:
> print self.ser.flushInput()
> print self.ser.flushOutput()
> cmd = "%xs\r" %(i+1)
> self.ser.write("%s" %cmd)
> 
> #print cmd
> 
> histo = self.ser.readlines()
> #print histo
> if histo:
> if histo=="\r\n":
> pass
> else:
> 
> histoAdresse = int(histo[0].strip('\r\n'))
> print histoAdresse
> 
> try:
> dateHisto_cur = listeFenetreNonNul["%s"
> %(histoAdresse)]
> print dateHisto_cur
> 
> 
> self.ecrireHistoDansFic(histo,histoAdresse,dateHisto_cur,histoAdresse,i)
> break
> except:
> 
> print "Adresse pas trouvee dans le
> systeme %s" %(histoAdresse)
> break
> # End if
> 
> sleep(10)
> # End while
> #End for
> 
> 
> self.ser.close()

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


Re: Python vs. Lisp -- please explain

2006-02-23 Thread dlp
> Paul Rubin wrote:
> I think both of you are missing the point of the question, which is
> that Lisp is dynamically typed exactly the way Python is and maps to
> Python almost directly; yet good Lisp implementations are much faster
> than CPython.

But Lisp isn't dynamically typed "exactly the way Python is".  Python
documents ways to manipulate the internals of objects at runtime.  It
is
possible to add, change or delete methods and slots by directly
changing
the hashtable they're stored in.  While CLOS does permit a certain
amount
of runtime redefinition, it is not as completely free wheeling and
unpredicatable.

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


Re: How to move optparse from main to function?

2006-02-23 Thread Giles Brown
Doesn't the module documentation ...

http://docs.python.org/lib/optparse-putting-it-all-together.html

... tell you what you need?

Giles

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


execfile time out?

2006-02-23 Thread Brian Blais
Hello,


I'd like to do something like:

try:
execfile_timeout("somefile.py",5)   # time out after 5 seconds
except TimeOutError:
print "this timed out!"


is there something that would do this?  I'd like to call "somefile.py", but if 
it has 
an infinite loop, I don't want to freeze at that point.  If it helps, this part 
of 
the code is already running in a thread, so I guess I could time-out the thread 
rather than the execfile.  Is there an easy way to do that?


thanks,

Brian Blais

-- 
-

 [EMAIL PROTECTED]
 http://web.bryant.edu/~bblais
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A C-like if statement

2006-02-23 Thread Giles Brown
But maybe we're talking about string methods so to get an exception
we'd want to use "index" instead of "find".

Giles

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


execfile error exception line number?

2006-02-23 Thread Brian Blais
Hello,

I'd like to do the following:

import sys
try:
execfile("somefile.py")
except:
s=sys.exc_info()
print "Error '%s' happened on line %d" % (s[1],s[2].tb_lineno)


(I'm going to replace the print later with a gui dialog)

how can I get the line number in "somefile.py" where the error occurs?  When I 
do the 
above, I get the line number in the script which calls execfile instead.


thanks,


Brian Blais

-- 
-

 [EMAIL PROTECTED]
 http://web.bryant.edu/~bblais
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A C-like if statement

2006-02-23 Thread Bob Greschke

"Roy Smith" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Bob Greschke <[EMAIL PROTECTED]> wrote:
>>I miss being able to do something like this in Python
>>
>>1f (I = a.find("3")) != -1:
>>print "It's here: ", I
>>else:
>>print "No 3's here"
>>
>>where I gets assigned the index returned by find() AND the if statement 
>>gets
>>to do its job in the same line.  Then you don't have to have another like
>>that specifically gets the index of the "3".  Is there a way to do this in
>>Python?
>
> It is a deliberate and fundamental design decision in Python that
> assignment is a statement, not an expression with side effects.  This
> means you often need an "extra" line compared to a classic C "assign
> and test" idiom such as you have above.  I, like you, often miss the
> compactness of the C idiom, but there it is.
>
> It's also unpythonic to return magic values to indicate failure.
> Throwing an exception would be the more normal way of doing it.  So,
> I'd expect the above to translate into something like:
>
> try:
>i = a.find("3")
>print "It's here: ", i
> except NotFound:
>print "No 3's here"

Nuts.  I guess you're right.  It wouldn't be proper.  Things are added or 
proposed every day for Python that I can't even pronounce, but a simple 'if 
(I = a.find("3")) != -1' isn't allowed.  Huh.  It might be time to go back 
to BASIC. :)

I think your way would work if .find() were replaced with .index().  I'm 
just trying to clean up an if/elif tree a bit, so using try would make 
things bigger.

Thanks!

Bob


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


Re: MySQLdb slow on MySQL 5

2006-02-23 Thread Gerhard Häring
[EMAIL PROTECTED] wrote:
> Hi.
> 
> I have a Python program that parses a file and inserts records into a
> database with MySQLdb. I recently upgraded to MySQL 5.0.8, and now my
> parser runs *really* slow. Writing out to CSV files is fine, but when I
> try to insert the same records in a MySQL5 database, it slows to a
> crawl. Using MySQL 4.1 seems fine. The data seems to be inserted
> correctly, it's just really slow.
> 
> Has anyone else noticed a similar problem using MySQL5 and MySQLdb?

Maybe you're running in autocommit mode. I. e. an implicit COMMIT is 
done for each insert. This slows any database down.

Or are you calling commit() yourself too often?

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


Re: need help regarding compilation

2006-02-23 Thread fidlee

Kent Johnson wrote:
> fidlee wrote:
> >>Try this:
> >>
> >>def fac(x):
> >> if x<=1:return 1
> >> return x*fac(x-1)
> >
> >
> > I am still getting an error in compilation. Would be really thankful if
> > someone could tell me as to what is going wrong.
>
> Try running the compiler under Java 1.4, or just run the class in the
> jython interpreter without compiling it first. For simple examples like
> this you don't need to compile, just run it with
>jython factor.py
>
> Kent

Thanks. i noticed that it runs. But why is it throwing a compilation
error in my case here?

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


frozen codecs

2006-02-23 Thread Robin Becker
I'm having a problem with freeze vs Python-2.4. I need to get various codecs 
into the freeze, but suspect I need to explicitly import them. Must I just 
import codecs or all the ones I'm likely to use?
-- 
Robin Becker

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


How to move optparse from main to function?

2006-02-23 Thread Bob
I'm playing around with optparse and created the code below. How do I
move that to a function and what variable do I pass?

>From the documentation it seems like "options.optparse_test" would have
the value zero if its option, either "-t" or "--test", is not detected
at the command line. When I issue "print options.optparse_test" when no
command options are used, "None" is sent to the screen (IIRC)... Is a
proper check if a command line argument is not used to use the
following:

# being check
if options.optparse_test <> 1:
 print "test parameter NOT detected"
# end check

Thanks.

# begin program
#!/usr/bin/python

from optparse import OptionParser
import string

parser = OptionParser()
parser.add_option("-t", "--test", action="count", dest="optparse_test",
 help="testing optparse")

(options, args) = parser.parse_args()
print options.optparse_test
if options.optparse_test == 1:
 print "test parameter detected"
if options.optparse_test <> 1:
 print "test parameter NOT detected"
#parser.print_help()

# end program

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


Re: Pyserial never read

2006-02-23 Thread Peter Hansen
Dennis Lee Bieber wrote:
dt = "D036EC"
print repr("".join([chr(int(dt[2*x:2*x+2],16)) for x in range(len(dt)//2)]))
> 
> '\xd06\x00\x00\xec'

By the way, for future reference, this way beats the above hands down:

 >>> import binascii
 >>> binascii.unhexlify("D036EC")
'\xd06\x00\x00\xec'


-Peter

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


Re: A C-like if statement

2006-02-23 Thread Roy Smith
Bob Greschke <[EMAIL PROTECTED]> wrote:
>I miss being able to do something like this in Python
>
>1f (I = a.find("3")) != -1:
>print "It's here: ", I
>else:
>print "No 3's here"
>
>where I gets assigned the index returned by find() AND the if statement gets 
>to do its job in the same line.  Then you don't have to have another like 
>that specifically gets the index of the "3".  Is there a way to do this in 
>Python?

It is a deliberate and fundamental design decision in Python that
assignment is a statement, not an expression with side effects.  This
means you often need an "extra" line compared to a classic C "assign
and test" idiom such as you have above.  I, like you, often miss the
compactness of the C idiom, but there it is.

It's also unpythonic to return magic values to indicate failure.
Throwing an exception would be the more normal way of doing it.  So,
I'd expect the above to translate into something like:

try:
i = a.find("3")
print "It's here: ", i
except NotFound:
print "No 3's here"
-- 
http://mail.python.org/mailman/listinfo/python-list


A C-like if statement

2006-02-23 Thread Bob Greschke
I miss being able to do something like this in Python

1f (I = a.find("3")) != -1:
print "It's here: ", I
else:
print "No 3's here"

where I gets assigned the index returned by find() AND the if statement gets 
to do its job in the same line.  Then you don't have to have another like 
that specifically gets the index of the "3".  Is there a way to do this in 
Python?

Thanks!

Bob


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


Re: need help regarding compilation

2006-02-23 Thread Kent Johnson
fidlee wrote:
>>Try this:
>>
>>def fac(x):
>> if x<=1:return 1
>> return x*fac(x-1)
> 
> 
> I am still getting an error in compilation. Would be really thankful if
> someone could tell me as to what is going wrong.

Try running the compiler under Java 1.4, or just run the class in the 
jython interpreter without compiling it first. For simple examples like 
this you don't need to compile, just run it with
   jython factor.py

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


  1   2   3   >