Re: [Tutor] XP & catching execl o/p ?

2006-12-06 Thread Tim Golden
| Struggling with python & XP again. My app needs to know if a 
| certain program is running on my XP box

As a complete alternative, consider using WMI:


import os, sys
import wmi

c = wmi.WMI ()
for process in c.Win32_Process (Name="excel.exe"):
  print "Excel is running"
  break
else:
  print "Excel is not running"



(Uses: http://timgolden.me.uk/python/wmi.html)

TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Integer?

2006-12-06 Thread Luke Paireepinart

> Very interesting. But what is "duckly-typed"? I'm so dumb I can't 
> distinguish between a typo and a technical term..
>
> Dick Moores
>
>   
Refer to the Wikipedia article on Duck Typing:
http://en.wikipedia.org/wiki/Duck_typing

Basically, if you saw my example earlier of substituting stdout:
#test.py
class FileLikeObject(object):
   def __init__(self,current_stdout):
   self.data = []
   self.oldstdout = current_stdout
   sys.stdout = self

   def write(self,arg):
   if arg != '\n':
   self.data.append(arg)

   def output(self):
   sys.stdout = self.oldstdout
   print self.data
   sys.stdout = self

import sys
f = FileLikeObject(sys.stdout)
print "hello."
f.output()
print "hi"
f.output()
#-

sys.stdout expects a file-like object, that has methods such as 'write'.
So I implemented a class with a 'write' method, and sys.stdout happily 
used it as an output stream.
It's not the same type of object as the original sys.stdout was.

 From IDLE,
 >>> print sys.stdout


So you see idle itself has replaced the default console stream of
 >>> print sys.stdout
', mode 'w' at 0x0097E068>

with its own version, which I replaced with my own version (the class 
instance with the write method).

All that matters is that the object has a 'write' method for it to be 
used as stdout (AFAIK).

HTH,
-Luke
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to kill an app from python on windows? (Tim Golden)

2006-12-06 Thread Tim Golden
[Tim Golden]
| > This link may get you started:
| >
| > http://effbot.org/pyfaq/how-do-i-emulate-os-kill-in-windows.htm
| >
| > although it may not apply, depending on the exact
| > circumstances of what you're doing.

[Paulino]
| Thank you Tim,
| 
| How do i get the pid of the process?

I'm going to cheat slightly, because I'm fairly sure
this is a sticky area, by going back to your original
requirement. I think that what you want to do is:

1) Use a document name to start the appropriate 
   viewer/app (without knowing what that app is)

2) Close that app at will so the file can be updated.

The problem is that while os.startfile will satisfy (1),
it returns no useful information about the process it
started. And that's because the underlying win32api,
ShellExecute, doesn't return anything useful. This is
specifically stated in the MS documentation.

What you can do, though, is to determine the correct
executable, setup a new process under your control,
and then terminate it when you want. This assume you
have the pywin32 extensions available. In the example
below, I'm using an .html file to demonstrate the point,
because I can generate one so the code works for both
of us. Obviously, it should work for any recognised
document type, including .pdf.


import os, sys
import win32api
import win32process
import win32event

filename = os.path.abspath ("temp.html")
open (filename, "w").write ("Hello,
world!")

hInstance, exe_filename = win32api.FindExecutable (filename)
print exe_filename, filename

hProcess, hThread, pid, tid = win32process.CreateProcess (
  None,
  '"%s" "%s2' % (exe_filename, filename),
  None, # process attributes
  None, # process attributes
  0, # inherit handles
  0, # creation flags
  None, # new environment
  None, # current directory
  win32process.STARTUPINFO ()
)
print pid

#
# This snippet waits until the app closes
#
win32event.WaitForSingleObject (hProcess, win32event.INFINITE)

#
# To kill the process either use the hProcess
# above, or retrieve it from the pid using:
#
hProcess = win32api.OpenProcess (1, 0, pid)

#
# and then
#
win32process.TerminateProcess (hProcess, 0)




This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] order of arguments in function

2006-12-06 Thread Michael Lange
On Tue, 05 Dec 2006 22:18:02 -0800
Dick Moores <[EMAIL PROTECTED]> wrote:

> Say I have a function,
> 
> def my_function(max, min=0):
>  return max - min
> 
> The order of arguments is counterintuitive, but it seems it can't be 
> changed if I want to have a default min. Is there way to write
> 
> def my_function(min=0, max):
>   stuff
> 

def my_function(min, max=None):
if max is None:
max = min
min = 0
# stuff

I am not sure if this is more intuitive though.

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] XP & catching execl o/p ?

2006-12-06 Thread Kent Johnson
Dave S wrote:
> Hi all,
> 
> Struggling with python & XP again. My app needs to know if a certain program 
> is running on my XP box
> 
> Ideal world - I can get the output of 'tasklist.exe' into a string.
> 
> I have tried
> 
> os.execl('')
> It throws the output to the terminal + I need the exact path to the 
> executable 
> (a bit of a trial)
> 
> and
> os.startfile('...') 
> it throws the output to a different window, but no exact path needed

I'm not sure if this is helpful, but here is a program that uses 
subprocess.Popen() to capture the output of cmd.exe. It makes a text 
file which contains all the command help. By Scott David Daniels, taken from
http://groups.google.com/group/comp.lang.python/msg/9fa3a3c287e8e2a3?hl=en&;

import subprocess as subp

p = subp.Popen("cmd.exe /X/D/F:ON", stdin=subp.PIPE,
  stdout=subp.PIPE, stderr=subp.STDOUT)
flag = "(@@}"
print >>p.stdin, "PROMPT", flag
print >>p.stdin, "HELP"
print >>p.stdin, "EXIT"
text = p.stdout.read()
p.wait()
helptext = text[text.index(flag + 'HELP') + len(flag) + 4 :
   text.index(flag + 'EXIT')]
words = [line.split(None, 1)[0]
for line in helptext.split('\n')
if line.strip()]
commands = [word for word in words if word.isupper()]

dest = open('cmd_help.txt', 'wb')
p = subp.Popen("cmd.exe /X/D/F:ON", stdin=subp.PIPE,
  stdout=dest, stderr=subp.STDOUT)
print >>p.stdin, "PROMPT ()"
print >>p.stdin, "HELP"
for command in commands:
   print >>p.stdin, "HELP", command
print >>p.stdin, "EXIT"
p.wait()
dest.close()


Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] changing a variable over simple network (with pyOpenGL)

2006-12-06 Thread Michael Shulman
Hello,

I am trying to write a very simple py-opengl program pair causing a 
variable in each program to be changed by the other.  I am able to open 
a command window in which I manually assign a value to the variable, but 
I cannot seem to implement  the udp/ip information I wish to send into a 
function which I can call at will.  I have tried updating the function 
through both a cyclic update function, and the keyboard (keyboard is 
preferred, but I tried eliminating it to see if that was the 
incompatibility).   I do not list any coding for the receiving program, 
since it works perfectly with the above code, and is probably correct.

Currently, the program crashes when I press the assigned key.  I can't 
tell if the issue here is python, or OpenGL, but any help would be very 
greatly appreciated!!!

##Here is what DOES work:
#

from socket import *
udpsock = socket(AF_INET, SOCK_DGRAM)
udpsock.bind(('', 0))
udpsock.connect(('localhost', 4550))

try:

while True:
s = raw_input('command> ')
udpsock.send(s)

except EOFError: pass
###

#This is what DOES NOT work:
##
from socket import *
udpsock = socket(AF_INET, SOCK_DGRAM)
udpsock.bind(('', 0))
udpsock.connect(('localhost', 4550))
R = 0
def datasender():
global R
try:

while True:   
s = input(R)
udpsock.send(s)

except EOFError: pass

def keyboard(key, x, y):  ###the keyboard and window OpenGL calls 
are not mentioned here, but included properly in the program (they work 
with everything except this)
global R
if key == 'k':  #key is arbitrary, I have also tried with 
"special keys" as defined by glut
  R = R + .01
  datasender()



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] XP & catching execl o/p ?

2006-12-06 Thread Dave S
On Tuesday 05 December 2006 23:32, Alan Gauld wrote:
> "Dave S" <[EMAIL PROTECTED]> wrote
>
> > Struggling with python & XP again. My app needs to know if a certain
> > program
> > is running on my XP box
> >
> > os.execl('')
> > It throws the output to the terminal + I need the exact path to the
> > executable
> > (a bit of a trial)
> >
> > Any ideas how I can catch the output ?
>
> Look at the popen family of functions in the os module, and then
> look at the subporocess module which supercedees them
> (but the docs are expressed in tems of the oold functions!)
>
> Use subprocess because the older popen functions don't always
> work reliably on Windows - there is a separate popen as part of
> the winall package, but I think subprocess.Popen works Ok.
>
> There is more on this, including a simple example using subprocess,
> in my OS topic in my tutorial.
>
> HTH,

OK playing around I knocked up some test code ...

#!/usr/bin/env python
# -*- coding: iso8859_1 -*- 
import subprocess

a = subprocess.Popen('tasklist.exe', bufsize=0, shell=False, 
stdout=subprocess.PIPE, stderr=None, stdin=None, universal_newlines=True)
op = a.stdout.readlines()
for i in op:
#print i
#print
pass

#raw_input()

This gives me what I need except when it runs windows flashes up a large black 
terminal window for a split second (yuk) 

This test would be performed while my app is running so thats not so good :)

Any ideas on how to stop it displaying ?

Dave
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] XP & catching execl o/p ?

2006-12-06 Thread Dave S
On Wednesday 06 December 2006 08:48, Tim Golden wrote:
> | Struggling with python & XP again. My app needs to know if a
> | certain program is running on my XP box
>
> As a complete alternative, consider using WMI:
>
> 
> import os, sys
> import wmi
>
> c = wmi.WMI ()
> for process in c.Win32_Process (Name="excel.exe"):
>   print "Excel is running"
>   break
> else:
>   print "Excel is not running"
>
> 
>
> (Uses: http://timgolden.me.uk/python/wmi.html)
>
> TJG

Just looked at WMI - didn't know it existed !
Am going down the subprocess route first as its 'built in'. If that does not 
work - hello WMI

Cheers

Dave








>
> 
> This e-mail has been scanned for all viruses by Star. The
> service is powered by MessageLabs. For more information on a proactive
> anti-virus service working around the clock, around the globe, visit:
> http://www.star.net.uk
> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] XP & catching execl o/p ?

2006-12-06 Thread Dave S
On Wednesday 06 December 2006 11:04, Kent Johnson wrote:
> Dave S wrote:
> > Hi all,
> >
> > Struggling with python & XP again. My app needs to know if a certain
> > program is running on my XP box
> >
> > Ideal world - I can get the output of 'tasklist.exe' into a string.
> >
> > I have tried
> >
> > os.execl('')
> > It throws the output to the terminal + I need the exact path to the
> > executable (a bit of a trial)
> >
> > and
> > os.startfile('...')
> > it throws the output to a different window, but no exact path needed
>
> I'm not sure if this is helpful, but here is a program that uses
> subprocess.Popen() to capture the output of cmd.exe. It makes a text
> file which contains all the command help. By Scott David Daniels, taken
> from
> http://groups.google.com/group/comp.lang.python/msg/9fa3a3c287e8e2a3?hl=en&;
>
> import subprocess as subp
>
> p = subp.Popen("cmd.exe /X/D/F:ON", stdin=subp.PIPE,
>   stdout=subp.PIPE, stderr=subp.STDOUT)
> flag = "(@@}"
> print >>p.stdin, "PROMPT", flag
> print >>p.stdin, "HELP"
> print >>p.stdin, "EXIT"
> text = p.stdout.read()
> p.wait()
> helptext = text[text.index(flag + 'HELP') + len(flag) + 4 :
>text.index(flag + 'EXIT')]
> words = [line.split(None, 1)[0]
> for line in helptext.split('\n')
> if line.strip()]
> commands = [word for word in words if word.isupper()]
>
> dest = open('cmd_help.txt', 'wb')
> p = subp.Popen("cmd.exe /X/D/F:ON", stdin=subp.PIPE,
>   stdout=dest, stderr=subp.STDOUT)
> print >>p.stdin, "PROMPT ()"
> print >>p.stdin, "HELP"
> for command in commands:
>print >>p.stdin, "HELP", command
> print >>p.stdin, "EXIT"
> p.wait()
> dest.close()
>
>
> Kent

The above is usefull, 

I am starting to print out these snippets for reference :). I have got 
subprocess to get the data I am now trying to get rid of the windows terminal 
flashing on my screen.

Cheers

Dave

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] XP & catching execl o/p ?

2006-12-06 Thread Tim Golden
[Dave S]

| Just looked at WMI - didn't know it existed !
| Am going down the subprocess route first as its 'built in'. 
| If that does not work - hello WMI

Personally, I find having both (and other) tools
in my toolbelt useful -- I've just answered another
question elsewhere about starting and stopping
a process on Win32 using the pywin32 win32process
module, so that's another option...

Generally subprocess is the recommended approach
these days because it's specifically designed to
superseded the various popen/spawn/system choices
previously available. The only problem is that its
general-purpose nature means fossicking around to
mimic the relative simplicity of os.popen:


import os

pipe = os.popen ("tasklist")

# skip unwanted headers
pipe.readline ()
pipe.readline ()
pipe.readline ()

for line in pipe.readlines ():
  print line.split ()[0]



TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] order of arguments in function

2006-12-06 Thread Dick Moores
At 02:28 AM 12/6/2006, Michael Lange wrote:
>On Tue, 05 Dec 2006 22:18:02 -0800
>Dick Moores <[EMAIL PROTECTED]> wrote:
>
> > Say I have a function,
> >
> > def my_function(max, min=0):
> >  return max - min
> >
> > The order of arguments is counterintuitive, but it seems it can't be
> > changed if I want to have a default min. Is there way to write
> >
> > def my_function(min=0, max):
> >   stuff
> >
>
>def my_function(min, max=None):
> if max is None:
> max = min
> min = 0
> # stuff

Great!

>I am not sure if this is more intuitive though.

 >>>
def my_function(min, max=None):
 if max is None:
 max, min = min, 0
 return max - min
 >>> my_function(3, 7)
4

I meant that the order "min, max" is more intuitive than "max, min". 
Don't you agree? And it's the order used in random.randint(), 
random.randrange(), and random.uniform(), for examples.

Anyway, thanks, Michael.

Dick


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] XP & catching execl o/p ?

2006-12-06 Thread Dave S
On Wednesday 06 December 2006 11:43, Dave S wrote:
> On Tuesday 05 December 2006 23:32, Alan Gauld wrote:
> > "Dave S" <[EMAIL PROTECTED]> wrote
> >
> > > Struggling with python & XP again. My app needs to know if a certain
> > > program
> > > is running on my XP box
> > >
> > > os.execl('')
> > > It throws the output to the terminal + I need the exact path to the
> > > executable
> > > (a bit of a trial)
> > >
> > > Any ideas how I can catch the output ?
> >
> > Look at the popen family of functions in the os module, and then
> > look at the subporocess module which supercedees them
> > (but the docs are expressed in tems of the oold functions!)
> >
> > Use subprocess because the older popen functions don't always
> > work reliably on Windows - there is a separate popen as part of
> > the winall package, but I think subprocess.Popen works Ok.
> >
> > There is more on this, including a simple example using subprocess,
> > in my OS topic in my tutorial.
> >
> > HTH,
>
> OK playing around I knocked up some test code ...
>
> #!/usr/bin/env python
> # -*- coding: iso8859_1 -*-
> import subprocess
>
> a = subprocess.Popen('tasklist.exe', bufsize=0, shell=False,
> stdout=subprocess.PIPE, stderr=None, stdin=None, universal_newlines=True)
> op = a.stdout.readlines()
> for i in op:
> #print i
> #print
> pass
>
> #raw_input()
>
> This gives me what I need except when it runs windows flashes up a large
> black terminal window for a split second (yuk)
>
> This test would be performed while my app is running so thats not so good
> :)
>
> Any ideas on how to stop it displaying ?
>
> Dave


10 carrot idiot here :)

change from 
test.py
to 
test.pyw

:)

dave









> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Integer?

2006-12-06 Thread Dick Moores
At 01:07 AM 12/6/2006, Luke Paireepinart wrote:

> > Very interesting. But what is "duckly-typed"? I'm so dumb I can't
> > distinguish between a typo and a technical term..
> >
> > Dick Moores
> >
> >
>Refer to the Wikipedia article on Duck Typing:
>http://en.wikipedia.org/wiki/Duck_typing

Thanks, Luke.

Dick



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Decimal module question

2006-12-06 Thread Dick Moores
I wrote this function:

def numberRounding(n, significantDigits=4):
"""
Rounds a number (float or integer, negative or positive) to any number 
of
significant digits. If an integer, there is no limitation on it's size.
"""
import decimal
def d(x):
return decimal.Decimal(str(x))
decimal.getcontext().prec = significantDigits
return d(n)/1

If the last line is written as the more normal-looking "return d(n)", 
it won't work. Why?

Thanks,

Dick Moores

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Decimal module question

2006-12-06 Thread Kent Johnson
Dick Moores wrote:
> I wrote this function:
> 
> def numberRounding(n, significantDigits=4):
>   """
>   Rounds a number (float or integer, negative or positive) to any number 
> of
>   significant digits. If an integer, there is no limitation on it's size.
>   """
>   import decimal
>   def d(x):
>   return decimal.Decimal(str(x))
>   decimal.getcontext().prec = significantDigits
>   return d(n)/1
> 
> If the last line is written as the more normal-looking "return d(n)", 
> it won't work. Why?

The context precision is applied to *operations* on decimals, not to 
construction.

The docs for the constructor Decimal([value [, context]]) say, "The 
context precision does not affect how many digits are stored. That is 
determined exclusively by the number of digits in value. For example, 
"Decimal("3.0")" records all five zeroes even if the context 
precision is only three."

The docs for Context say, "The prec field is a positive integer that 
sets the precision for *arithmetic operations* in the context." (my 
emphasis)

So you have to perform an operation for the precision to have any 
effect. Dividing by 1 is an operation.

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python scrypts and daemons

2006-12-06 Thread emilia12


Hi all,

I have a python script (with endless loop) and i want to
start it from the rc.config file. So, the question is: how
to covert this script to work as daemon ... or how to start
the python interpreter ... to work as background process ?

E.


-

Спортни залагания!
bg.sportingbet.com

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Decimal module question

2006-12-06 Thread Dick Moores
At 05:35 AM 12/6/2006, Kent Johnson wrote:
>Dick Moores wrote:
>>I wrote this function:
>>def numberRounding(n, significantDigits=4):
>> """
>> Rounds a number (float or integer, negative or positive) 
>> to any number of
>> significant digits. If an integer, there is no limitation 
>> on it's size.
>> """
>> import decimal
>> def d(x):
>> return decimal.Decimal(str(x))
>> decimal.getcontext().prec = significantDigits
>> return d(n)/1
>>If the last line is written as the more normal-looking "return 
>>d(n)", it won't work. Why?
>
>The context precision is applied to *operations* on decimals, not to 
>construction.
>
>The docs for the constructor Decimal([value [, context]]) say, "The 
>context precision does not affect how many digits are stored. That 
>is determined exclusively by the number of digits in value. For 
>example, "Decimal("3.0")" records all five zeroes even if the 
>context precision is only three."
>
>The docs for Context say, "The prec field is a positive integer that 
>sets the precision for *arithmetic operations* in the context." (my emphasis)
>
>So you have to perform an operation for the precision to have any 
>effect. Dividing by 1 is an operation.
>
>Kent

Thanks very much, Kent.

Dick





___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python scrypts and daemons

2006-12-06 Thread Christopher Arndt
[EMAIL PROTECTED] schrieb:
> 
> Hi all,
> 
> I have a python script (with endless loop) and i want to
> start it from the rc.config file. So, the question is: how
> to covert this script to work as daemon ... or how to start
> the python interpreter ... to work as background process ?

Search google for "daemonize python" and the first hit (at least here) links to
a recipe in the Python Cookbook that does exactly what you want.

HTH, Chris
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Integer?

2006-12-06 Thread Mike Hansen
> > How can I check if a variable is an integer?
> 
> Luke and John have answered your question, but we should also 
> ask, why 
> do you want to do that? Explicit type testing is a code 
> smell, perhaps 
> there is a better way to do what you want.
> 
> Kent
> 

Kent,

Can you explain further? Refactoring is in my queue of books to read. In
a web app I'm writing, I'm checking the input kind of like this...

try:
form_value = int(form.getvalue('num_widgets')
except ValueError:
display_error("Number of Widgets must be a number")

Mike 
-

  NOTICE:  This e-mail transmission and any documents or files attached to
  it contain information for the sole use of the above-identified individual or 
entity.

  Its contents may be privileged, confidential, and exempt from disclosure 
under the law.
  Any dissemination, distribution, or copying of this communication is strictly 
prohibited.

  Please notify the sender immediately if you are not the intended recipient.

FGNS
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Q: win32 download (attack of the newbies)

2006-12-06 Thread Toon Pieton

Hey, friendly person who took the time to read this!

I'm cutting right to the case. Trying to get certain information into Excel.
However, I can't:

from win32com.client import Dispatch

xlApp = Dispatch("Excel.Application")
# continues

As soon as I start the program, I get a error: win32com.client not found.
This - of course - leads to the conclusion that I don't have the win32com
module installed. I tried to find it (Google), but all I could find when
searching for "python win32 module (download)", I can only find the normal
python install. I'm running Win XP Pro, and have Python ver 2.5.

What am I doing wrong?

BTW: I really need to get that information into Excel. This program is for
some beginner computer users, and all they really know is Word and Excel.

Thanks in advance!
Toon Pieton.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Q: win32 download (attack of the newbies)

2006-12-06 Thread Tim Golden
[Toon Pieton]

| As soon as I start the program, I get a error: 
| win32com.client not found. This - of course - leads to the 
| conclusion that I don't have the win32com module installed. I 
| tried to find it (Google), but all I could find when 
| searching for "python win32 module (download)", I can only 
| find the normal python install. I'm running Win XP Pro, and 
| have Python ver 2.5.

Most immediate answer:

https://sourceforge.net/project/showfiles.php?group_id=78018&package_id=
79063

and pick the right package / mirror

| BTW: I really need to get that information into Excel. This 
| program is for some beginner computer users, and all they 
| really know is Word and Excel.

Using win32com and Excel is very easy, but there
are alternatives if you want: 

http://cheeseshop.python.org/pypi/xlrd/0.5.2

http://cheeseshop.python.org/pypi/pyExcelerator/0.6.0a

TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] subprocess & pyw conflict ?

2006-12-06 Thread Dave S
Hi all,

I thought I had my solution with subprocess ... my test code ...



#!/usr/bin/env python
# -*- coding: iso8859_1 -*- 

import subprocess

a = subprocess.Popen('tasklist.exe', bufsize=0, stdout=subprocess.PIPE, 
universal_newlines=True)
op = a.stdout.readlines()

for i in op:
if i.split(' ')[0] == 'gmanager.exe':
f = open('E:\Documents and Settings\All 
Users\Desktop\gsr_running', 'w')
f.close()



works a treat when I run it as proc.py detects the process I am looking for & 
writes a dummy file to the desktop. :) but I get a black windows terminal 
flash up.

The code will eventually run in an app.pyw so to check it would be OK I 
renamed my working proc.py to proc.pyw - it fails :(, No window (as 
expected), no dummy file (not expected) - the process gmanager.exe is 
running.

So there seems to be a problem with subprocess & pyw

Googling I found ...
https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1358527&group_id=5470
So I tried the suggested workaround with proc.pyw ...



#!/usr/bin/env python
# -*- coding: iso8859_1 -*- 

import subprocess

a = subprocess.Popen('tasklist.exe', bufsize=0, stdin=subprocess.PIPE, 
stdout=subprocess.PIPE, universal_newlines=True)
op = a.stdout.readlines()
a.stdin.close()

for i in op:
if i.split(' ')[0] == 'gmanager.exe':
f = open('E:\Documents and Settings\All 
Users\Desktop\gsr_running', 'w')
f.close()


Still zip, and because there is no terminal, I cannot view any errors !

Any suggestions welcome :)

Dave



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Q: win32 download (attack of the newbies)

2006-12-06 Thread Kent Johnson
Toon Pieton wrote:
> Hey, friendly person who took the time to read this!
> 
> I'm cutting right to the case. Trying to get certain information into 
> Excel. However, I can't:
> 
> from win32com.client import Dispatch
> 
> xlApp = Dispatch("
> Excel.Application")
> # continues
> 
> As soon as I start the program, I get a error: win32com.client not 
> found. This - of course - leads to the conclusion that I don't have the 
> win32com module installed. I tried to find it (Google), but all I could 
> find when searching for "python win32 module (download)", I can only 
> find the normal python install. I'm running Win XP Pro, and have Python 
> ver 2.5.

https://sourceforge.net/projects/pywin32/

> BTW: I really need to get that information into Excel. This program is 
> for some beginner computer users, and all they really know is Word and 
> Excel.

You might also consider writing CSV files which can be opened in Excel.

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Integer?

2006-12-06 Thread Kent Johnson
Mike Hansen wrote:
>>> How can I check if a variable is an integer?
>> Luke and John have answered your question, but we should also 
>> ask, why 
>> do you want to do that? Explicit type testing is a code 
>> smell, perhaps 
>> there is a better way to do what you want.
>>
>> Kent
>>
> 
> Kent,
> 
> Can you explain further? Refactoring is in my queue of books to read. In

In general, the preference in Python code is to check for a specific 
behaviour, or just assume the behaviour, rather than to check for a 
specific type. Writing code this way supports duck typing. The two 
approaches are sometimes called Easier to Ask Forgiveness than 
Permission (EAFP) and Look Before You Leap (LBYL).

For example Python has the idea of a file-like object, which is anything 
that behaves like a file. If you have a function that works on a file, 
you could check that the parameter is an actual file. This is an example 
of LBYL:

def doSomething(f):
   if type(f) is not file:
 # error

If you do that, you are preventing your clients from passing a file-like 
object, for example a StringIO object.

On the other hand, if you write doSomething() to just use f as a file, 
any object that has the required methods will just work; an object that 
doesn't have the required methods will raise an AttributeError. That is 
EAFP.

This is just a general guideline, there are certainly cases where 
explicit type checking is appropriate.

> a web app I'm writing, I'm checking the input kind of like this...
> 
> try:
>   form_value = int(form.getvalue('num_widgets')
> except ValueError:
>   display_error("Number of Widgets must be a number")

That is fine - you are checking that the string is something that can be 
converted to an int, and catching the error - EAFP. If you tried to 
check the contents of the string before calling int(), that would be LBYL.

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Q: win32 download (attack of the newbies)

2006-12-06 Thread Kent Johnson
Tim Golden wrote:
> Using win32com and Excel is very easy, but there
> are alternatives if you want: 
> 
> http://cheeseshop.python.org/pypi/xlrd/0.5.2

xlrd is for reading only - OP wants to write Excel files.

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Q: win32 download (attack of the newbies)

2006-12-06 Thread Tim Golden
[Kent Johnson]

| Tim Golden wrote:
| > Using win32com and Excel is very easy, but there
| > are alternatives if you want: 
| > 
| > http://cheeseshop.python.org/pypi/xlrd/0.5.2
| 
| xlrd is for reading only - OP wants to write Excel files.

Oops! Quite right. I was moving a bit too fast. Sorry, OP!

TJG


This e-mail has been scanned for all viruses by Star. The
service is powered by MessageLabs. For more information on a proactive
anti-virus service working around the clock, around the globe, visit:
http://www.star.net.uk

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] How to create variable length bar chart ??

2006-12-06 Thread Asrarahmed Kadri

Hi folks,


I have a problem with drawing a BAR-chart. I am drawing a HORIZONTAL bar
chart. I did manage to sort out the length issue of individual bars (with
the help of inputs from this forum's members).

What I want is the height of the bar chart should be determined dynamically
(basically it means the length of the Y-axis), as per the number of
data-items being displayed.

There can be 5 items or there can be 100, so how to manage this issue?

Any input would be highly appreciated ..

Thanks.

Best Regards,
Asrarahmed Kadri

--
To HIM you shall return.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Q: win32 download (attack of the newbies)

2006-12-06 Thread Kent Johnson
Toon Pieton wrote:
> Hey Kent,
> 
> Thanks for your reply. Can you suggest which module I should look at? 
> And can I make diagrams using that module?

Assuming you are asking about modules for writing CSV files, then look 
at the csv module. CSV (comma-separated value) is a simple text format 
that doesn't support diagrams. If you are just creating simple tables to 
read into Excel it will work, for anything more complicated you need COM 
or PyExcelerator.

Kent

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] List to dictionary question

2006-12-06 Thread Morpheus
I'm new to programming, and trying to learn the Python language.  
The following code does what I want it to do, but I have not idea how it
works.  

def scanList(names,temp):
for i in names:
temp[i] = 0
print temp

Names = []
temp = {}

I have a list of names (Names[]) and want to remove duplicate names in
the list.  Here is what I think is happening (please correct me if I'm
wrong, or using the wrong technical terminology):  I'm passing the
variables Names and temp as arguments to the scanList function.  The
statement (for i in names:) is an iteration going through each item in
the list.  The next statement (temp[i] = 0) is where I get confused.
Can someone please explain what is happening here.  

Thanks for your help.


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] WXPython Listbox Problem

2006-12-06 Thread Toon Pieton

Hey friendly users!

I'm trying to make a simple program to calculate the odds when playing
poker. The idea is that you select both your cards from listboxes. However,
no matter what I try, I just can't select a entry in either of the
listboxes! I can click all I want, it just won't select. Here's the code
which I use to create the boxes:

ID_BOX1 = 120
ID_BOX2 = 130
...
   #Boxes, to select cards
   self.box1 = wx.ListBox(parent=self, id=ID_BOX1, size=(60,163) ,
name='Card 1',

choices=['Ace','King','Queen','Ten','9','8','7','6','5','4','3','2'],style=0)
   self.box2 = wx.ListBox(parent=self, id=ID_BOX2, size=(60,163) ,
name='Card 2',

choices=['Ace','King','Queen','Ten','9','8','7','6','5','4','3','2'],style=0)
   self.box1.Bind(wx.EVT_LISTBOX, self.b1func,id=ID_BOX1)
   self.box2.Bind(wx.EVT_LISTBOX, self.b2func,id=ID_BOX2)

I hope anybody can help me. If you need to see the full code, just send me a
reply

Thanks in advance to anybody reading/helping!
Toon Pieton
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List to dictionary question

2006-12-06 Thread Mike Hansen
 

> -Original Message-
> From: [EMAIL PROTECTED] 
> [mailto:[EMAIL PROTECTED] On Behalf Of Morpheus
> Sent: Wednesday, December 06, 2006 9:00 AM
> To: tutor@python.org
> Subject: [Tutor] List to dictionary question
> 
> I'm new to programming, and trying to learn the Python language.  
> The following code does what I want it to do, but I have not 
> idea how it
> works.  
> 
> def scanList(names,temp):
> for i in names:
> temp[i] = 0
> print temp
> 
> Names = []
> temp = {}
> 
> I have a list of names (Names[]) and want to remove duplicate names in
> the list.  Here is what I think is happening (please correct me if I'm
> wrong, or using the wrong technical terminology):  I'm passing the
> variables Names and temp as arguments to the scanList function.  The
> statement (for i in names:) is an iteration going through each item in
> the list.  The next statement (temp[i] = 0) is where I get confused.
> Can someone please explain what is happening here.  
> 
> Thanks for your help.
> 

temp is a dictionary. Dictionaries have unique keys. scanList goes
through each item in names and sets the key of the temp dictionary to
the item. If there are more than one item of the same value, it just
sets the key of the dictionary again. The statement temp[i] = 0 is
setting the value of the key 'i' to 0. (temp[key] = value) To get your
list without duplicates just get the keys of the dictionary after the
list has been run through function.
temp.keys()

If you have names = [1,2,3,2,4]
The temp dictionaries keys become 1,2,3,4.
In the scanList function above
temp[1] = 0
temp[2] = 0
temp[3] = 0
temp[2] = 0 <- It's just setting the same key to zero again.
temp[4] = 0

temp.keys() 
[1,2,3,4]

I hope that makes some sense. 

I think a more explicit way of removing duplicates from a list is using
sets.

In [1]: x = ['a', 'a', 'b', 'c', 'd', 'e', 'f', 'f', 'f']

In [2]: se = set(x)

In [3]: se
Out[3]: set(['a', 'c', 'b', 'e', 'd', 'f'])

In [4]: sel = list(se)

In [5]: sel
Out[5]: ['a', 'c', 'b', 'e', 'd', 'f']
-

  NOTICE:  This e-mail transmission and any documents or files attached to
  it contain information for the sole use of the above-identified individual or 
entity.

  Its contents may be privileged, confidential, and exempt from disclosure 
under the law.
  Any dissemination, distribution, or copying of this communication is strictly 
prohibited.

  Please notify the sender immediately if you are not the intended recipient.

FGNS
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] order of arguments in function

2006-12-06 Thread Michael Lange
On Wed, 06 Dec 2006 04:29:54 -0800
Dick Moores <[EMAIL PROTECTED]> wrote:

(...)
> >
> >def my_function(min, max=None):
> > if max is None:
> > max = min
> > min = 0
> > # stuff
> 
> Great!
> 
> >I am not sure if this is more intuitive though.
> 
>  >>>
> def my_function(min, max=None):
>  if max is None:
>  max, min = min, 0
>  return max - min
>  >>> my_function(3, 7)
> 4
> 
> I meant that the order "min, max" is more intuitive than "max, min". 
> Don't you agree? And it's the order used in random.randint(), 
> random.randrange(), and random.uniform(), for examples.
> 

Sure I agree, although it may depend on what the function actually does
and how you name it (and the arguments). If you e.g. rewrite your example to

def subtract(from_, what=0):
return from_ - what

the changed order of arguments seems quite intuitive to me.

What I meant in the first place is that it might be "unintuitive" that
if you pass only one argument this is the one that comes last in case
you pass two arguments.
As I said, I was not sure and was too lazy to think much about it :-)

Michael
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] WXPython Listbox Problem

2006-12-06 Thread Jorgen Bodde
Try ID's higher then 1 ... low ID's are usually taken by
wxWidgets. To be safe simply create them with wx.ID_ANY (from the top
of my head) and after that:

self.box1.Bind(wx.EVT_LISTBOX, self.b1func,id=self.box1.GetId())

Which is a bit more dynamic anyway and saves you some constants.

Furthermore, wxPython specific questions could be better answered in
the wxPython-users mailinglist to get more succes ;-)

Regards,
- Jorgen


On 12/6/06, Toon Pieton <[EMAIL PROTECTED]> wrote:
> Hey friendly users!
>
> I'm trying to make a simple program to calculate the odds when playing
> poker. The idea is that you select both your cards from listboxes. However,
> no matter what I try, I just can't select a entry in either of the
> listboxes! I can click all I want, it just won't select. Here's the code
> which I use to create the boxes:
>
> ID_BOX1 = 120
> ID_BOX2 = 130
> ...
> #Boxes, to select cards
>  self.box1 = wx.ListBox(parent=self, id=ID_BOX1, size=(60,163) ,
> name='Card 1',
>
> choices=['Ace','King','Queen','Ten','9','8','7','6','5','4','3','2'],style=0)
> self.box2 = wx.ListBox(parent=self, id=ID_BOX2, size=(60,163) ,
> name='Card 2',
>
> choices=['Ace','King','Queen','Ten','9','8','7','6','5','4','3','2'],style=0)
>  self.box1.Bind(wx.EVT_LISTBOX, self.b1func,id=ID_BOX1)
> self.box2.Bind(wx.EVT_LISTBOX, self.b2func,id=ID_BOX2)
>
> I hope anybody can help me. If you need to see the full code, just send me a
> reply
>
> Thanks in advance to anybody reading/helping!
> Toon Pieton
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>


On 12/6/06, Toon Pieton <[EMAIL PROTECTED]> wrote:
> Hey friendly users!
>
> I'm trying to make a simple program to calculate the odds when playing
> poker. The idea is that you select both your cards from listboxes. However,
> no matter what I try, I just can't select a entry in either of the
> listboxes! I can click all I want, it just won't select. Here's the code
> which I use to create the boxes:
>
> ID_BOX1 = 120
> ID_BOX2 = 130
> ...
> #Boxes, to select cards
>  self.box1 = wx.ListBox(parent=self, id=ID_BOX1, size=(60,163) ,
> name='Card 1',
>
> choices=['Ace','King','Queen','Ten','9','8','7','6','5','4','3','2'],style=0)
> self.box2 = wx.ListBox(parent=self, id=ID_BOX2, size=(60,163) ,
> name='Card 2',
>
> choices=['Ace','King','Queen','Ten','9','8','7','6','5','4','3','2'],style=0)
>  self.box1.Bind(wx.EVT_LISTBOX, self.b1func,id=ID_BOX1)
> self.box2.Bind(wx.EVT_LISTBOX, self.b2func,id=ID_BOX2)
>
> I hope anybody can help me. If you need to see the full code, just send me a
> reply
>
> Thanks in advance to anybody reading/helping!
> Toon Pieton
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] (no subject)

2006-12-06 Thread rumpy
Hi Folks,


I'm working through Magnus Lie Hetland's excellent book "Beginning 
Python" and I have a few basic (I think) questions. Specifically, 
regarding his first project in Chapter 20 (Instant Markup).

The outline of the project is to take a plain text file and "mark it 
up" into HTML or XML. Step one is simply getting the tool to recognize 
basic elements of a text document - blocks of text seperated by empty 
lines.

To this end the following file is created as a module(?) to be imported 
into the subsequent primary execution (main?) script.


def lines(file):
for line in file: yield line
yield '\n'

del blocks(file):
block = []
for line in lines(file):
if line.strip():
   block.append(line)
elif block:
   yield ''.join(block).strip()
   block = []


Now, for the most part I understand what's going on here. The part that 
puzzles me a bit is:

elif block:
   yield ''.join(block).strip()
   block = []

1.) Does the yield mean the block list is returned from the function 
AND then wiped out by 'block = []'?

2.) Is block list scrubbed clean by 'block = []' because the function 
is going to iterate over the next block and it needs to be empty?

3.) The statement after the 'yield' threw me. I haven't seen that to 
this point in the book. I figured 'yield' is always last in a function 
because it needs to iterate over itself again. Am I understanding 
generators correctly?

4.) Is it correct to say that a generator is a function that returns 
multiple values and iterates over itself?


Thanks in advance for any feedback/help.


Rumpy.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to create variable length bar chart ??

2006-12-06 Thread Alan Gauld

"Asrarahmed Kadri" <[EMAIL PROTECTED]> wrote in

> What I want is the height of the bar chart should be determined 
> dynamically
> (basically it means the length of the Y-axis), as per the number of
> data-items being displayed.

Hmm, I thought we ansdwered this recently...

Anyhow you just calculate it.
The height will be for an example with 3 bars:

3 times the height of a bar plus the inter bar space.

You might want to add some extra height on at the top.

Or you might want to have a bigger or smaller gap at top
and bottom than between the bars but basically its a case
of work out rthe pattern then calculate according to the data.

The worst case is:


   <- top_gap
X


<- gap_size
XX<- bar_size
 <- bottom_gap
 <-- X axis


height = (bottom_gap+ top_gap) + ((N-1) * (bar_size+gap_size)) + 
bar_size

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Generator questions.

2006-12-06 Thread rumpy
Hi Folks,


I'm working through Magnus Lie Hetland's excellent book "Beginning 
Python" and I have a few basic (I think) questions. Specifically, 
regarding his first project in Chapter 20(Instant Markup).

The outline of the project is to take a plain text file and "mark it 
up" into HTML or XML. Step one is simply getting the tool to recognize 
basic elements of a text document - blocks of text seperated by empty 
lines.

To this end the following file is created as a module(?) to be imported 
into the
subsequent primary execution (main?) script.


def lines(file):
   for line in file: yield line
   yield '\n'

del blocks(file):
   block = []
   for line in lines(file):
   if line.strip():
  block.append(line)
   elif block:
  yield ''.join(block).strip()
  block = []


Now, for the most part I understand what's going on here. The part that 
puzzles me a bit is:

elif block:
  yield ''.join(block).strip()
  block = []

1.) Does the yield mean the block list is returned from the function 
AND then wiped out by 'block = []'?

2.) Is block list scrubbed clean by 'block = []' because the function 
is going to iterate over the next block and it needs to be empty?

3.) The statement after the 'yield' threw me. I haven't seen that to 
this point in the book. I figured 'yield' is always last in a function 
because it needs to iterate over itself again. Am I understanding 
generators correctly?

4.) Is it correct to say that a generator is a function that returns 
multiple values and iterates over itself?


Thanks in advance for any feedback/help.


Rumpy.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to create variable length bar chart ??

2006-12-06 Thread Asrarahmed Kadri

I got that point, what I want is how the dimensions of the canvas would be
adjusted so as to incorporate this Y-axis variable length?

Do I need a scrollbar for that??

Thanks in advance.

Regards,
Asrarahmed Kadri

On 12/6/06, Alan Gauld <[EMAIL PROTECTED]> wrote:



"Asrarahmed Kadri" <[EMAIL PROTECTED]> wrote in

> What I want is the height of the bar chart should be determined
> dynamically
> (basically it means the length of the Y-axis), as per the number of
> data-items being displayed.

Hmm, I thought we ansdwered this recently...

Anyhow you just calculate it.
The height will be for an example with 3 bars:

3 times the height of a bar plus the inter bar space.

You might want to add some extra height on at the top.

Or you might want to have a bigger or smaller gap at top
and bottom than between the bars but basically its a case
of work out rthe pattern then calculate according to the data.

The worst case is:


   <- top_gap
X


<- gap_size
XX<- bar_size
 <- bottom_gap
 <-- X axis


height = (bottom_gap+ top_gap) + ((N-1) * (bar_size+gap_size)) +
bar_size

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor





--
To HIM you shall return.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Generator questions.

2006-12-06 Thread wesley chun
> def lines(file):
>for line in file: yield line
>yield '\n'
>
> del blocks(file):
>block = []
>for line in lines(file):
>if line.strip():
>   block.append(line)
>elif block:
>   yield ''.join(block).strip()
>   block = []
>
> 1.) Does the yield mean the block list is returned from the function
> AND then wiped out by 'block = []'?

the code in question will take all the strings in block, concatenate
them together [with ''.join()], remove leading/trailing whitespace
[.strip()], and yield or "return" it as the next "generated" item
being iterated over.  when .next() is executed again, either
explicitly by the caller or via a for-loop, it will resume immediately
on the next line succeeding the yield statement where execution was
paused.


> 2.) Is block list scrubbed clean by 'block = []' because the function
> is going to iterate over the next block and it needs to be empty?

yes, block is then cleared so that it can process the next few lines of data.


> 3.) The statement after the 'yield' threw me. I haven't seen that to
> this point in the book. I figured 'yield' is always last in a function
> because it needs to iterate over itself again. Am I understanding
> generators correctly?

a "yield" does *not* have to be the last in the function.  wherever a
yield is encountered, the function will resume right after it when
.next() is called again.  generators do "not start from scratch...,"
they pick up right where they left off.


> 4.) Is it correct to say that a generator is a function that returns
> multiple values and iterates over itself?

a generator acts like an iterator in that multiple values are returned
in an iterative process (meaning not all at the same time).  it is
dressed up as a function which contains logic that can "generate" each
successive value to "return."

i have to give kudos to magnus for putting "real world" code when he
teaches generators in his book.  for my core python book, i was more
concerned about getting the point across as to what generators *are*,
so for completeness, here are some of the examples i used, all of
which can be downloaded at the book's website (see below) regardless
of whether you buy the book (or not):

1) simpleGen.py (the world's 2nd simplest generator?):

def simpleGen():
yield 1
yield '2 --> punch!'

if __name__ == '__main__':
for item in simpleGen():
print item

2) randGen.py:

from random import randrange as rr

def randGen(aList):
while aList:
yield aList.pop(rr(len(aList)))

if __name__ == '__main__':
for item in randGen(['rock', 'paper', 'scissors']):
print item

3) counter.py (needs 2.5+):

def counter(start_at=0):
count = start_at
while True:
val = (yield count)
if val is not None:
count = val
else:
count += 1

if __name__ == '__main__':
print 'initializing counter to start counting at 5'
count = counter(5)
print 'calling count.next():', count.next()
print 'calling count.next():', count.next()
print 'calling count.send(9):', count.send(9)
print 'calling count.next():', count.next()
print 'calling count.close():', count.close()
print 'calling count.next():', count.next()

you can get these by clicking on "Source Code" -> ch11 -> alt. i'll
leave it as an exercise to reader to determine the output *and WHY*.
:-) another fun place to go look for iterators is the itertools
module.  it contains a lot of useful iteration code that are all
really just generators(!):

http://docs.python.org/lib/itertools-functions.html

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Beautiful Soup

2006-12-06 Thread Shitiz Bansal
Hi,
I am using beautiful soup to get links from an html document.
I found that beautiful Soup changes the & in the links to & due to which 
some of the links become unusable.
Is there any way I could stop this behaviour?

Regards,
Shitiz

 
-
Access over 1 million songs - Yahoo! Music Unlimited.___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Running drPython and other Pythonscript on Macintosh OS/X

2006-12-06 Thread Markus Rosenstihl

Am 05.12.2006 um 09:44 schrieb Anders Persson:

> Hi!
>
> I try to learn my son Development using Python.
> I have found that drPython was a great enviroment and easy for him to
> understand.
>
> Is't a problem running om Macintosh OS/X i have to start on 
> commandline,
> OS/X
> dosen't understand when i clicked on the drPython.py files.
>
> I have found this is same for all pythonfiles on OS/X, does somone know
> how a
> tell a OS/X system that .py means run Python.
>


Try to right click (Ctrl + Klick) and open it with PythonLauncher. I 
don't know if that is
installed with a stock python but I think so.
If that is working you can get the Info panel of that file (Apple + i) 
and select PythonLauncher
in the "open with" section…

HTH
Markus

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Generator questions.

2006-12-06 Thread rumpy
Hi Wesley,


Thank you very much for the feeback. It helped a lot!


Quoting wesley chun <[EMAIL PROTECTED]>:

>> def lines(file):
>>for line in file: yield line
>>yield '\n'
>>
>> del blocks(file):
>>block = []
>>for line in lines(file):
>>if line.strip():
>>   block.append(line)
>>elif block:
>>   yield ''.join(block).strip()
>>   block = []
>>
>> 1.) Does the yield mean the block list is returned from the function
>> AND then wiped out by 'block = []'?
>
> the code in question will take all the strings in block, concatenate
> them together [with ''.join()], remove leading/trailing whitespace
> [.strip()], and yield or "return" it as the next "generated" item
> being iterated over.  when .next() is executed again, either
> explicitly by the caller or via a for-loop, it will resume immediately
> on the next line succeeding the yield statement where execution was
> paused.
>
>
>> 2.) Is block list scrubbed clean by 'block = []' because the function
>> is going to iterate over the next block and it needs to be empty?
>
> yes, block is then cleared so that it can process the next few lines of data.
>
>
>> 3.) The statement after the 'yield' threw me. I haven't seen that to
>> this point in the book. I figured 'yield' is always last in a function
>> because it needs to iterate over itself again. Am I understanding
>> generators correctly?
>
> a "yield" does *not* have to be the last in the function.  wherever a
> yield is encountered, the function will resume right after it when
> .next() is called again.  generators do "not start from scratch...,"
> they pick up right where they left off.
>
>
>> 4.) Is it correct to say that a generator is a function that returns
>> multiple values and iterates over itself?
>
> a generator acts like an iterator in that multiple values are returned
> in an iterative process (meaning not all at the same time).  it is
> dressed up as a function which contains logic that can "generate" each
> successive value to "return."
>
> i have to give kudos to magnus for putting "real world" code when he
> teaches generators in his book.  for my core python book, i was more
> concerned about getting the point across as to what generators *are*,
> so for completeness, here are some of the examples i used, all of
> which can be downloaded at the book's website (see below) regardless
> of whether you buy the book (or not):
>
> 1) simpleGen.py (the world's 2nd simplest generator?):
>
> def simpleGen():
>yield 1
>yield '2 --> punch!'
>
> if __name__ == '__main__':
>for item in simpleGen():
>print item
>
> 2) randGen.py:
>
> from random import randrange as rr
>
> def randGen(aList):
>while aList:
>yield aList.pop(rr(len(aList)))
>
> if __name__ == '__main__':
>for item in randGen(['rock', 'paper', 'scissors']):
>print item
>
> 3) counter.py (needs 2.5+):
>
> def counter(start_at=0):
>count = start_at
>while True:
>val = (yield count)
>if val is not None:
>count = val
>else:
>count += 1
>
> if __name__ == '__main__':
>print 'initializing counter to start counting at 5'
>count = counter(5)
>print 'calling count.next():', count.next()
>print 'calling count.next():', count.next()
>print 'calling count.send(9):', count.send(9)
>print 'calling count.next():', count.next()
>print 'calling count.close():', count.close()
>print 'calling count.next():', count.next()
>
> you can get these by clicking on "Source Code" -> ch11 -> alt. i'll
> leave it as an exercise to reader to determine the output *and WHY*.
> :-) another fun place to go look for iterators is the itertools
> module.  it contains a lot of useful iteration code that are all
> really just generators(!):
>
> http://docs.python.org/lib/itertools-functions.html
>
> hope this helps!
> -- wesley
> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
> "Core Python Programming", Prentice Hall, (c)2007,2001
>http://corepython.com
>
> wesley.j.chun :: wescpy-at-gmail.com
> python training and technical consulting
> cyberweb.consulting : silicon valley, ca
> http://cyberwebconsulting.com


Regards,

Josh.



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] order of arguments in function

2006-12-06 Thread Eike Welk
On Wednesday 06 December 2006 13:29, Dick Moores wrote:

> I meant that the order "min, max" is more intuitive than "max,
> min". Don't you agree? And it's the order used in random.randint(),
> random.randrange(), and random.uniform(), for examples.

What about two intuitively named functions, like the random module 
does it?

my_function_range(min, max):
#do the sophisticated myfunction work here

my_function_max(max):
return my_function_range(0, max)


Eike.

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] How to create variable length bar chart ??

2006-12-06 Thread ALAN GAULD

--- Asrarahmed Kadri <[EMAIL PROTECTED]> wrote:

> I got that point, what I want is how the dimensions of the
> canvas would be
> adjusted so as to incorporate this Y-axis variable length?
> 

You provide the size of the canvas when you create 
it normally. But you can use at least 2 approaches.

1) Given the fixed size of your canvas you can 
scale the graphs to fit - keeping track oof the 
longest X and Y measures and scaling against the corresponding
size of the canvas.

or

2) Scale the canvas to match the graphs.
If the canvas gets bigger than a certain size
(maybe related to screen size?) youi can add 
scroll bars.

HTH,

Alan G.



___ 
All New Yahoo! Mail – Tired of [EMAIL PROTECTED]@! come-ons? Let our SpamGuard 
protect you. http://uk.docs.yahoo.com/nowyoucan.html
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Create a script to make bootable USB device.

2006-12-06 Thread Chris Hengge

Is this something I can do using just python and libraries? I know I could
automate other utilities, but I'd like to write some kind of neat utility
myself that I could play with for more experience.

Goal:
make USB drive bootable to a dos prompt (dont care what dos, assuming I need
a bootable image for this)
make script prompt for file(s) to move to disk (already know how to do this)

Thanks!
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] subprocess & pyw conflict ?

2006-12-06 Thread Luke Paireepinart
Dave S wrote:
> Hi all,
>
> I thought I had my solution with subprocess ... my test code ...
>
>
>
> #!/usr/bin/env python
> # -*- coding: iso8859_1 -*- 
>
> import subprocess
> 
> a = subprocess.Popen('tasklist.exe', bufsize=0, stdout=subprocess.PIPE, 
> universal_newlines=True)
> op = a.stdout.readlines()
>
> for i in op:
> if i.split(' ')[0] == 'gmanager.exe':
> f = open('E:\Documents and Settings\All 
> Users\Desktop\gsr_running', 'w')
> f.close()
> 
>
>
> works a treat when I run it as proc.py detects the process I am looking for & 
> writes a dummy file to the desktop. :) but I get a black windows terminal 
> flash up.
>
> The code will eventually run in an app.pyw so to check it would be OK I 
> renamed my working proc.py to proc.pyw - it fails :(, No window (as 
> expected), no dummy file (not expected) - the process gmanager.exe is 
> running.
>
> So there seems to be a problem with subprocess & pyw
>
> Googling I found ...
> https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1358527&group_id=5470
> So I tried the suggested workaround with proc.pyw ...
>
>
>
> #!/usr/bin/env python
> # -*- coding: iso8859_1 -*- 
>
> import subprocess
> 
> a = subprocess.Popen('tasklist.exe', bufsize=0, stdin=subprocess.PIPE, 
> stdout=subprocess.PIPE, universal_newlines=True)
> op = a.stdout.readlines()
> a.stdin.close()
>
> for i in op:
> if i.split(' ')[0] == 'gmanager.exe':
> f = open('E:\Documents and Settings\All 
> Users\Desktop\gsr_running', 'w')
> f.close()
> 
>
> Still zip, and because there is no terminal, I cannot view any errors !
>
> Any suggestions welcome :)
>   
Well, because I'm batting 0 on this thread so far, I think I'll just go 
ahead and suggest another bad solution!
You could try redirecting the output of sys.stderr to a file, and you 
might be able to see the error message! :D

If you hadn't said 'any suggestions welcome' I might've kept this to 
myself :P

 >>> import sys
 >>> class TestClass(object):
def __init__(self):
self.data = []
def write(self,item):
self.data.append(item)
 >>> a = TestClass()
 >>> sys.stderr = a
 >>> salfjdsljfka321423
 >>> print a.data
['\nTraceback (most recent call last):', '\n', '  File "", 
line 1, in -toplevel-\n', 'salfjdsljfka321423\n', "NameError: name 
'salfjdsljfka321423' is not defined\n"]

Except instead of a file-like class, you could just use a real file.  
But then it would only leave the last line intact.
So you'd probably want to make a class that wraps a file object, where 
the write method just appends to an internal list,
and it writes it all out to the file when you call the Class.close() or 
whatever.
Actually, I guess the program stops executing on an exception...
Hmm, not really sure what you'd do exactly.


Sure, there are better solutions, and this doesn't really help you with 
your original problem, but it at least lets you see your error message!
HTH,
-Luke
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Is there any good turtorial about numeric python for beginners?

2006-12-06 Thread linda.s
Is there any good tutorial about numeric python for beginners?
I have googled around and many of them are either too old or aims at
experienced users...
Thanks,
Linda
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] List to dictionary

2006-12-06 Thread Morpheus
I'm new to programming, and trying to learn the Python language.  
The following code does what I want it to do, but I have not idea how it
works.  

def scanList(names,temp):
for i in names:
temp[i] = 0
print temp

Names = []
temp = {}

I have a list of names (Names[]) and want to remove duplicate names in
the list.  Here is what I think is happening (please correct me if I'm
wrong, or using the wrong technical terminology):  I'm passing the
variables Names and temp as arguments to the scanList function.  The
statement (for i in names:) is an iteration going through each item in
the list.  The next statement (temp[i] = 0) is where I get confused.
Can someone please explain what is happening here.  

Thanks for your help.


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Is there any good turtorial about numeric python for beginners?

2006-12-06 Thread Dave Kuhlman
On Wed, Dec 06, 2006 at 05:49:22PM -0800, linda.s wrote:
> Is there any good tutorial about numeric python for beginners?
> I have googled around and many of them are either too old or aims at
> experienced users...

Look here:

http://new.scipy.org/Wiki/Documentation

Dave

-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] ***SPAM*** List to dictionary

2006-12-06 Thread Bill Campbell
On Wed, Dec 06, 2006, Morpheus wrote:
>I'm new to programming, and trying to learn the Python language.  
>The following code does what I want it to do, but I have not idea how it
>works.  
>
>def scanList(names,temp):
>for i in names:
>temp[i] = 0
>print temp
>
>Names = []
>temp = {}
>
>I have a list of names (Names[]) and want to remove duplicate names in
>the list.  Here is what I think is happening (please correct me if I'm
>wrong, or using the wrong technical terminology):  I'm passing the
>variables Names and temp as arguments to the scanList function.  The
>statement (for i in names:) is an iteration going through each item in
>the list.  The next statement (temp[i] = 0) is where I get confused.
>Can someone please explain what is happening here.  

The way I usually do this is something like:

outDict = dict(map(lambda x: (x, 1), inList))
names = outDict.keys()
names.sort()

Bill
--
INTERNET:   [EMAIL PROTECTED]  Bill Campbell; Celestial Software LLC
URL: http://www.celestial.com/  PO Box 820; 6641 E. Mercer Way
FAX:(206) 232-9186  Mercer Island, WA 98040-0820; (206) 236-1676

``Find out just what people will submit to, and you have found out the
exact amount of injustice and wrong which will be imposed upon them; and
these will continue until they are resisted with either words or blows, or
both. The limits of tyrants are prescribed by the endurance of those whom
they oppress.'' -- Frederick Douglass.
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] ***SPAM*** List to dictionary

2006-12-06 Thread Luke Paireepinart

>> I have a list of names (Names[]) and want to remove duplicate names in
>> the list.  [snip]
>> 
>
> The way I usually do this is something like:
>
> outDict = dict(map(lambda x: (x, 1), inList))
> names = outDict.keys()
> names.sort()
>   
How about this :D

# Remove duplicates from a list:
>>> L = [1,2,2,3,3,3]
>>> [x for x in L if x not in locals()['_[1]'].__self__]
[1,2,3]

[accessed at 
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/204297 ]

Also, why is there now a **SPAM* in the subject heading?

Wonderingly,
-Luke

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] List to dictionary

2006-12-06 Thread Dick Moores
At 09:53 PM 12/6/2006, Luke Paireepinart wrote:

> >> I have a list of names (Names[]) and want to remove duplicate names in
> >> the list.  [snip]
> >>
> >
> > The way I usually do this is something like:
> >
> > outDict = dict(map(lambda x: (x, 1), inList))
> > names = outDict.keys()
> > names.sort()
> >
>How about this :D
>
># Remove duplicates from a list:
> >>> L = [1,2,2,3,3,3]
> >>> [x for x in L if x not in locals()['_[1]'].__self__]
>[1,2,3]

Why not
 >>> L = [1,2,2,3,3,3]
 >>> list(set(L))
[1, 2, 3]
?

That's a real question.

Dick Moores


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor