Re: How python source code in large projects are organized?

2009-09-26 Thread Christopher Arndt
On 20 Sep., 22:10, [email protected] wrote:
> On 07:10 pm, [email protected] wrote:
>
> >On Sun, Sep 20, 2009 at 11:31 AM, Daniel Fetchinson
> > wrote:
> >>>I am wondering what is the best way of organizing python source code
> >>>in a large projects. There are package code, testing code. I'm
> >>>wondering if there has been any summary on previous practices.
>
> >>I suggest looking at the source code of large projects like twisted,
> >>PIL, django, turbogears, etc. These have different styles, pick the
> >>one you like best.

Start by having a standard for structuring the single Python files. I
like to have mine organized like this:

- (shebang)
- encoding declaration
- module docstring
- __all__ symbol export list
- imports
  - standard library
  - third-party
  - project specific
- author, version, date and copyright information
- globals (logging setup, constants, etc.)
- utility functions
- classes
- "main" function (some like to have this at the top)
- if __name__ ==  '__main__': clause

For sub-packages, like to have the following layout:

mainpackage/
subpackage2/
test/test_subpackage2.py
__init__.py
base.py
exceptions.py
module1.py
module1.py
subpackage2/
...
__init__.py
mainpackage.py

If a package is not too big, the test may also go into a "test" sub-
directory of the main package.

I have an __all__ symbol export list in all module file, so then in in
__init__.py I can do:

from base import *
from exception import *
from module1 import this, that
from module2 import foo, bar

without worrying about import too much and in my main package I can
use:

from package import this, bar

And in e.g. package.module1 I can do

from package.exceptions import SomeError

without having to worry about circular imports.

If my package has any code to be called directly from the command
line, I create a script in the root of the distribution or in a "bin"
subdirectory:

mydistro/
bin/
script1
mainpackage/
...

and in that script:

#!/usr/bin/env python

from mainpackage import run
# or
# from mainpackage.command.mycommand import run
run()


you can also add a command line script entry point to your setup
script to let this script be automatically created on installation by
setuptools/easy_install. Look at the TurboGears 1.1 branch for
examples.

HTH, Chris

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


Is there a method (similar to str() method in R) that can print the data structure in python?

2009-09-26 Thread Peng Yu
Hi,

I am looking for a method in python that is similar to the function
str() in R, if you are familiar with R,

If you have no idea of R, what I want is to print the class
information of an object and the values of its members. Overloading
'__expr__' and '__repr__' then using 'print' can sort of do what I
want. But not quite. For example, if I have a list of many elements, I
don't want to print all the elements. R's str() function can
automatically take care of this issue. It also has other advantages, I
am wondering if there is something similar available in python?

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


Re: How to control I/O buffering besides -u?

2009-09-26 Thread Dave Angel

kj wrote:

Is there any way to specify unbuffered I/O from *within* the code
(rather than via the command-line -u flag)?

TIA!

kynn

  
When creating a file object, specify a buffer size of zero.  I don't 
know how to change the buffering of a file object that's already been 
created, as stdin, stdout, and stderr are.


DaveA


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


Re: Signing extensions

2009-09-26 Thread Roger Binns
Neil Hodgson wrote:
>Code signing certificates that will be be valid for Windows
> Authenticode cost $129 per year through CodeProject

That isn't an amount I am prepared to pay either :-)  (I don't even use
Windows except as a glorified boot loader for Rise of Nations and to build
Python extensions.)  With the amount of hassle it causes me, I should be
paid for the development time spent on Windows issues!

>I'd like to see a certificate authority for open source projects
> based mainly on project reputation and longevity. There may need to be
> some payment to avoid flooding the CA with invalid requests - say $30
> per year. It would be great if this CA was recognised by Microsoft and
> Apple as well as Linux and BSD distributions.

It can also be solved as low down as Python itself, as opposed to open
source in general.  The Python installation could install a root CA for the
PSF certifying authority although I suspect you can't then limit its use to
only Python extensions.  (I still find it amusing that the browser will
silently accept certificates from any of the ~100 CAs that come with it.
Your identity proof is only as strong as the weakest CA in the list, not the
strongest.)

It could also be solved by the download sites. For example Google Code does
allow you to visit it via https and even displays the download page over
https, but the downloads are over http.  If it occurred to you then you can
click on the "Summary+Labels" for an item where they show the SHA1 of the
file, but that is even more hassle for most users.

>There are some issues about identity here.

You don't really need to worry about maliciousness.  Ultimately that will
come down to reputation.  I am more concerned about download sites being
hacked or malicious proxies being inserted into the network somewhere.  It
is good enough to be able to establish if this new version of the extension
was produced by the same person as the previous version I have installed.
PGP works wonderfully for that, except for Windows where no one has it.

> The Ext1 project should be able to revoke ...

That is pretty trivial to do if using regular CAs and OCSP.  Of course
someone still has to decide if the claim of maliciousness is correct or a
joe job.

Roger

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


Re: nested structure with "internal references"

2009-09-26 Thread Hendrik van Rooyen
On Friday, 25 September 2009 19:11:06 Torsten Mohr wrote:

> I'd like to use a nested structure in memory that consists
> of dict()s and list()s, list entries can be dict()s, other list()s,
> dict entries can be list()s or other dict()s.
>
> The lists and dicts can also contain int, float, string, ...

This sounds terribly convoluted.
What are you trying to do?

>
> But i'd also like to have something like a "reference" to another
> entry.

Everything and its brother in Python is an object, and things like lists and 
dicts reference objects automagically.

> I'd like to refer to another entry and not copy that entry, i need to
> know later that this is a reference to another entry, i need to find
> also access that entry then.

Depending on how I read this, it is either trivial or impossible:

A name is bound to an object by assignment.
An object can have many names bound to it.
A name can, at different times, refer to different objects.
An object does not know which names are bound to it, or in what sequence it 
was done.

So you can go from name to object, but not the other way around.
You can use the same name in a loop to refer to different objects, and in each 
iteration, use the name to store a reference to the current object in a list 
or dict.

> Is something like this possible in Python?

Not too sure what you are trying to do.

> The references only need to refer to entries in this structure.
> The lists may change at runtime (entries removed / added), so
> storing the index may not help.

You could start off with a list of lists of lists, to any level of nesting 
that you want.   This will give you a structure like a tree with branches and 
twigs and leaves, but I am not sure if this is what you want or need, or if a 
flat structure like third normal form would suffice, or if you need a 
relational database.

- Hendrik

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


Re: raise errors

2009-09-26 Thread Gabriel Genellina

En Mon, 21 Sep 2009 06:17:20 -0300, daved170  escribió:


I need help with exceptions raising.
My goal is to print at the outer functions all the errors including
the most inner one.


The default exception report contains a lot of information, you don't have  
to do anything special.



def foo1(self):
   try:
foo2()
   except ? :
 print "outer Err at foo1" + ??

def foo2(self):
   try:
error occured
   except ? :
 raise "inner Err at foo2"


The bare bones structure is:

def foo1():
  foo2()

def foo2():
  undefinedname()

foo1()

and you get this error:

D:\temp>python test638580.py
Traceback (most recent call last):
  File "test638580.py", line 7, in 
foo1()
  File "test638580.py", line 2, in foo1
foo2()
  File "test638580.py", line 5, in foo2
undefinedname()
NameError: global name 'undefinedname' is not defined



I would like the print to be : outer Err at foo1 , inner Err at foo1


It already includes that info.

  File "test638580.py", line 2, in foo1
foo2()

means that in line 2 of test638580.py, inside function foo1, there was a  
call to foo2.


  File "test638580.py", line 5, in foo2
undefinedname()

and that means that foo2 tried to call undefinedname.

  NameError: global name 'undefinedname' is not defined

And that's the actual error.

Do you want it to be more nicely formatted? Do you want to include  
additional information? Or what?


--
Gabriel Genellina

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


Re: Format string with single quotes in it

2009-09-26 Thread Bahadir
On Sep 26, 6:33 am, "Gabriel Genellina" 
wrote:
>
> So, look in your file for lines ending in %
>
> --
> Gabriel Genellina


Hello All,

I fixed it with your help. Sometimes you need that extra insight from
comp.lang.python.

Thank you so much,

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


Why the file mode of .pyc files has x?

2009-09-26 Thread Peng Yu
Hi,

It is strange that the file mode of .pyc files are changed to
executable (x mode) after the corresponding .py files have been run. I
have the follow python, which is compiled from source code by me.

$ python --version
Python 2.6.2

Should .pyc files have the x mode?

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


How to control I/O buffering besides -u?

2009-09-26 Thread kj


Is there any way to specify unbuffered I/O from *within* the code
(rather than via the command-line -u flag)?

TIA!

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


Re: is this whiff/wsgi claim true?

2009-09-26 Thread exarkun

On 25 Sep, 02:26 pm, [email protected] wrote:

Hi folks.  I just modified the WHIFF concepts index page

   http://aaron.oirt.rutgers.edu/myapp/docs/W1000.concepts

To include the following paragraph with a startling and arrogant
claim in the final sentence :)

"""
Developers build WHIFF applications much like they build
static web content, PHP applications, JSP pages, or ASP
pages among others -- the developer "drops" files into a
directory, and the files are automatically used to respond
to URLs related to the filename.
**This intuitive and ubiquitous approach to organizing
web components is not automatically supported by other
WSGI infrastructures.**
"""


This sounds like Twisted Web's RPY files:

 http://twistedmatrix.com/projects/web/documentation/howto/using- 
twistedweb.html#auto5


Although you may be talking about something that is more closely tied to 
WSGI than this feature is in Twisted Web.


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


Re: Twisted: 1 thread in the reactor pattern

2009-09-26 Thread exarkun

On 25 Sep, 05:25 am, [email protected] wrote:

On Sep 24, 7:54�pm, [email protected] wrote:

On 07:10 am, [email protected] wrote:
>On Sep 23, 5:57�pm, [email protected] wrote:
>[snip]

[snip]


If you have a function that takes 5 minutes to run, then you're 
blocking
the reactor thread for 5 minutes and no other events are serviced 
until

the function finishes running.

You have to avoid blocking the reactor thread if you want other events
to continue to be serviced. �There are various strategies for avoiding
blocking. �Different strategies are appropriate for different kinds of
blocking code.

Jean-Paul- Hide quoted text -

- Show quoted text -


Even if the server is engaged in a 5 minutes processing other arriving
requests of callRemote() are queued and  Deferreds are returned
immediately.


Nope, they're not.  The bytes representing the new requests sit in the 
socket buffer until the function finishes processing and the reactor 
gets an opportunity to read them.


Could you suggest me any doc to better understand?


If you haven't read 
http://twistedmatrix.com/projects/core/documentation/howto/async.html 
yet, that may be a good idea.


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


multiprocessing + console + windows = challenge?

2009-09-26 Thread Valery
Hi all.

So, the doc is pitiless:

   "Note Functionality within this package requires that the __main__
method be importable by the children. This is covered in Programming
guidelines however it is worth pointing out here. This means that some
examples, such as the multiprocessing.Pool examples will not work in
the interactive interpreter. For example:"

My question:

Q: did any one manage to resurrect multiprocessing module in
interactive Python console? Especially interesting would be on
Windows :)

pprocess library works in console when on Linux, but it doesn't on
Windows :-/

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


Python-URL! - weekly Python news and links (Sep 26)

2009-09-26 Thread Gabriel Genellina
QOTW:  "Forget ethical. We can do his homework for him, we can perhaps pass 
exams for him, maybe graduate for him, and then with our luck, he'll get a
job in our office and we get to do his work for him." - Mel
 http://groups.google.com/group/comp.lang.python/msg/8f7c1fa393c23476


How to set up printing/logging so they still work even with Unicode
encoding errors:
http://groups.google.com/group/comp.lang.python/t/8e93b219139532a6/

Review of available parsers/lexers:
http://groups.google.com/group/comp.lang.python/t/d45d15da2cf4f304/

How is it behind the scenes at the first Spanish-language Pycon?
 http://www.taniquetil.com.ar/facundo/pyconar09_report.txt

Developing a custom data warehouse vs. out-of-the-box ETL tool:
http://groups.google.com/group/comp.lang.python/t/d679836c1dba554e/

How to delete items from list given their indices:
http://groups.google.com/group/comp.lang.python/t/de185f9212e53fb6/

Determining the target name in an assignment:
http://groups.google.com/group/comp.lang.python/t/fe92da9d8952c376/
http://groups.google.com/group/comp.lang.python/t/c312ffd8011a0e17/

Best way to distribute Python programs:
http://groups.google.com/group/comp.lang.python/t/229c2c0059f5be8a/

In some corner cases, a module could get imported twice:
http://groups.google.com/group/comp.lang.python/t/ca861eb01989942/

Very creative answers to a really trivial homework question:
http://groups.google.com/group/comp.lang.python/t/c8630b7ec60df888/

Coroutines and generators:
http://groups.google.com/group/comp.lang.python/t/62160f74d76e3cbc/

Getting "the other" element from a dictionary containing only two keys:
http://groups.google.com/group/comp.lang.python/t/4fa0ce86e4b97850/

Review of several webapp testing tools:
http://groups.google.com/group/comp.lang.python/t/58b7513596ab648c/

J. P. Calderone shares his reccomendations on structuring a Python
project:
http://groups.google.com/group/comp.lang.python/t/2122c45d0d913a31/

Python beginner asks for comments about his coding style:
http://groups.google.com/group/comp.lang.python/t/b6e19551381cf869/

Basic logging usage explained:
http://groups.google.com/group/comp.lang.python/t/6359d3ac2089bddc/

Checking for possible error conditions in advance isn't a substitute for
correct exception handling:
http://groups.google.com/group/comp.lang.python/t/fd78edec3c2ef889/



Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily

Just beginning with Python?  This page is a great place to start:
http://wiki.python.org/moin/BeginnersGuide/Programmers

The Python Papers aims to publish "the efforts of Python enthusiasts":
http://pythonpapers.org/
The Python Magazine is a technical monthly devoted to Python:
http://pythonmagazine.com

Readers have recommended the "Planet" site:
http://planet.python.org

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.
http://groups.google.com/group/comp.lang.python.announce/topics

Python411 indexes "podcasts ... to help people learn Python ..."
Updates appear more-than-weekly:
http://www.awaretek.com/python/index.html

The Python Package Index catalogues packages.
http://www.python.org/pypi/

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/sigs/

Python Success Stories--from air-traffic control to on-line
match-making--can inspire you or decision-makers to whom you're
subject with a vision of what the language makes practical.
http://www.pythonology.com/success

The Python Software Foundation (PSF) has replaced the Python
Consortium as an independent nexus of activity.  It has official
responsibility for Python's development and maintenance.
http://www.python.org/psf/
Among the ways you can support PSF is with a donation.
http://www.python.org/psf/donations/

The Summary of Python Tracker Issues is an automatically generated
report summarizing new bugs, closed ones, and patch submissions. 

http://search.gmane.org/?author=status%40bugs.python.org&group=gmane.comp.python.devel&sort=date

Although unmaintained since 2002, the Cetus collection of Python
  

Re: [Tutor] Help required

2009-09-26 Thread Lie Ryan

waqas ahmad wrote:
Now i want to search all those pages, where i have *NOT* written "#acl 
InternationalGroup:read" *But*  i have written only "CatInternational" 
in the page text.


You can split the two queries into two regexes:

import re
acl = re.compile(r'#acl InternationalGroup:read')
cat = re.compile(r'CatInternational')
s = ' ... '

if not acl.search(s) and cat.search(s):
print 's contains cat but not acl'

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


Re: What does the list_folders() method of mailbox.Maildir actually ??do (if anything)?

2009-09-26 Thread tinnews
Jeff McNeil  wrote:
> > > The Maildir++ spec states that folders need to begin with a period.
> > > The list_folders method enforces that:
> >
> > >     def list_folders(self):
> > >         """Return a list of folder names."""
> > >         result = []
> > >         for entry in os.listdir(self._path):
> > >             if len(entry) > 1 and entry[0] == '.' and \
> > >                os.path.isdir(os.path.join(self._path, entry)):
> > >                 result.append(entry[1:])
> > >         return result
> >
> > > The above example is from 2.6.  Your structure is simply a list of
> > > Maildir compliant directories below '/home/chris/Mail/apex.' They're
> > > not, in the Maildir++ sense of the word, folders.
> >
> > So where does it say in the Python documentation that list_folders()
> > works only with Maildir++?  It's a big and non-obvious limitation to
> > my mind.
> >
> > My maildir hierarchy is created by mutt which is a *very* standards
> > compliant MUA, surely standard python libraries should work with
> > standard maildirs not some wierd extension thereof.
> >
> > --
> > Chris Green
> 
> 
> The doc says that "Folders of the style introduced by the Courier mail
> transfer agent are also supported. Any subdirectory of the main

"... are also supported." says to me that 'standard' ones are
supported as well and they're *not*.

> mailbox is considered a folder if '.' is the first character in its
> name."  It's not an explicit endorsement of Maildir++, but it touches
> on what it considers a folder definition. I'm treading on hazy memory
> here, but I believe Maildir++ is the definition provided by the
> Courier folks.
> 
So why isn't the class called mailbox.Maildir++ ?   :-)

-- 
Chris Green

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


Re: Why the file mode of .pyc files has x?

2009-09-26 Thread Peng Yu
On Sat, Sep 26, 2009 at 8:10 AM, Steven D'Aprano
 wrote:
> On Sat, 26 Sep 2009 06:57:52 -0500, Peng Yu wrote:
>
>> Hi,
>>
>> It is strange that the file mode of .pyc files are changed to executable
>> (x mode) after the corresponding .py files have been run.
>
> Are you sure? They don't on my system.
>
>
> [st...@sylar test]$ ls -l
> total 8
> -rw-rw-r-- 1 steve steve 6 2009-09-26 23:06 test.py
> [st...@sylar test]$ python2.6 test.py
> [st...@sylar test]$ ls -l
> total 8
> -rw-rw-r-- 1 steve steve 6 2009-09-26 23:06 test.py
>
>
> Running a .py file does not generally create a .pyc file. Normally you
> have to import it:
>
> [st...@sylar test]$ python2.6
> Python 2.6.1 (r261:67515, Dec 24 2008, 00:33:13)
> [GCC 4.1.2 20070502 (Red Hat 4.1.2-12)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
 import test
 exit()
> [st...@sylar test]$ ls -l
> total 16
> -rw-rw-r-- 1 steve steve  6 2009-09-26 23:06 test.py
> -rw-rw-r-- 1 steve steve 94 2009-09-26 23:08 test.pyc
>
>
> Have you checked the umask of your system?

Here are my test case. If the .py file has the 'x' mode, the
corresponding .pyc file also has the 'x' mode after the .py file is
imported.

pe...@selenium:~/test/python/pyc_mode$ umask
0077
pe...@selenium:~/test/python/pyc_mode$ ll
total 8
-rw--- 1 pengy lilab  29 2009-09-26 10:10:45 main.py
-rwx-- 1 pengy lilab 106 2009-09-26 10:19:17 test.py
pe...@selenium:~/test/python/pyc_mode$ for f in *.py; do echo "###$f";
cat $f;done
###main.py
import test
test.test_func()
###test.py
#!/usr/bin/env python

def test_func() :
  print "in_test_func"

if __name__ == '__main__':
  test_func()
pe...@selenium:~/test/python/pyc_mode$ python main.py
in_test_func
pe...@selenium:~/test/python/pyc_mode$ ll
total 12
-rw--- 1 pengy lilab  29 2009-09-26 10:10:45 main.py
-rwx-- 1 pengy lilab 106 2009-09-26 10:19:17 test.py
-rwx-- 1 pengy lilab 339 2009-09-26 10:20:39 test.pyc
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What does the list_folders() method of mailbox.Maildir actually ??do (if anything)?

2009-09-26 Thread tinnews
Jeff McNeil  wrote:
> > > My maildir hierarchy is created by mutt which is a *very* standards
> > > compliant MUA, surely standard python libraries should work with
> > > standard maildirs not some wierd extension thereof.
> >
> > > --
> > > Chris Green
> >
> > The doc says that "Folders of the style introduced by the Courier mail
> > transfer agent are also supported. Any subdirectory of the main
> > mailbox is considered a folder if '.' is the first character in its
> > name."  It's not an explicit endorsement of Maildir++, but it touches
> > on what it considers a folder definition. I'm treading on hazy memory
> > here, but I believe Maildir++ is the definition provided by the
> > Courier folks.
> >
> > --
> > Thanks,
> >
> > Jeff
> > mcjeff.blogspot.com
> 
> http://wiki.mutt.org/?MuttFaq/Maildir
> 
> That might help as well. You can have Mutt setup your folders using
> that extended method.
> 
Thanks, but no thanks.  It creates 'folders' which aren't proper
hierarchical directories at all and breaks all sorts of standard
Unix/Linux ways of handling data.  It's basically *horrible* and
to be avoided at all costs if you actually want to have a local mail
spool. It's OK if it's hidden behind an IMAP mail server or something
but otherwise no.

-- 
Chris Green

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


Re: Most "active" coroutine library project?

2009-09-26 Thread Dave Angel

Dennis Lee Bieber wrote:

On Fri, 25 Sep 2009 14:22:51 + (UTC), Grant Edwards
 declaimed the following in
gmane.comp.python.general:

  

EXX accomplised much of the context switch operation.  I don't
remember how much RAM was available, but it wasn't much...



Zilog Z80... as with the rest of the "improved" 8080 family -- 64kB
address space... 
  
I knew of one Z80 implementation which gave nearly 128k to the user.  
Code was literally in a separate 64k page from data, and there were 
special ways to access it, when you needed to do code-modification on 
the fly.  The 64k bank select was normally chosen on each bus cycle by 
status bits from the CPU indicating whether it was part of an 
instruction fetch or a data fetch.


Actually even 64k looked pretty good, compared to the 1.5k of RAM and 2k 
of PROM for one of my projects, a navigation system for shipboard use.


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


Re: flow control and nested loops

2009-09-26 Thread Raymond Hettinger
On Sep 25, 12:01 pm, kj  wrote:
> In Perl, one can label loops for finer flow control.  For example:
>
> X: for my $x (@X) {
>   Y: for my $y (@Y) {
>     for my $z (@Z) {
>       next X if test1($x, $y, $z);
>       next Y if test2($x, $y, $z);
>       frobnicate($x, $y, $z);
>     }
>     glortz($x, $y);
>   }
>   splat($x);
>
> }
>
> What's considered "best practice" in the Python world for this sort
> of situation?  The only approach I can think of requires setting
> up indicator variables that must be set and tested individually;
> e.g.
 
> Whereas I find the Perl version reasonably readable, the Python
> one I find nearly incomprehensible.  In fact, I'm not even sure
> that the Python version faithfully replicates what the Perl one is
> doing!
>
> Is there a better approach?

The Perl syntax is elegant and readable.
There is not a Python direct equivalent,
but then the situation doesn't come up often.

For the outermost loop, a break or continue suffices.
To exit multiple levels of loop, there a several choices
including try/except, flags, and functions with returns.

A try/except approach looks like this:

   class NextX(Exception):pass
   class NextY(Exception):pass

   for x in X:
 try:
 for y in Y:
   try:
 for z in Z:
 if test1(x,y,z):
 raise NextX
 if test2(x,y,z):
 raise NextY
 frobnicate(x,y,z)
   except NextY: pass
 except NextX: pass


Another approach for exiting multiple levels of loops is wrap the
inner calls in a function and return from them when needed:

   def f(x):
   for y in y:
   for z in Z:
   if test1(x,y,z):
   return
   frobnicate(x,y,z)

   for x in X:
  f(x)

Or you can write a little state machine with flags and a single loop
but that isn't very readable or satisfying.


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


RE: [Tutor] Help required

2009-09-26 Thread waqas ahmad

Hi, 

First of all thanks a lot for your reply. "search.findall" is not working. here 
is my complete small program.

 

def getAcl(request, pg):
pged = PageEditor(request, pg)
pagetext = pged.get_raw_body()
search=re.compile("^#acl InternationalGroup.*\n", re.M).search(pagetext)
if search:
ret=search.group()
else:
ret='not defined'
return ret


def execute(macro, args):

html="ACL List For International Group:"
all={}
pages = macro.request.rootpage.getPageList()
for pagename in pages:
if Page(macro.request,pagename).isStandardPage():
all[Page(macro.request, 
pagename).link_to(macro.request)]=getAcl(macro.request, pagename)

html+=""
all1=sorted(all.items())
for pg, ac in all1:
if ac != "not defined":
html+="%s" % pg
html+="%s" % ac
html+=""
return macro.formatter.rawHTML(html)



 
Now i explain this.

I have some wiki pages(or you can say documents). 

This python program is giving me list of all those pages, where i have written 
"#acl InternationalGroup:read" line in the pages and these pages may have also 
"CatInternational" line in the page. 

 



Now i want to search all those pages, where i have NOT written "#acl 
InternationalGroup:read" But  i have written only "CatInternational" in the 
page text.

 

I dont know how can i find only those pages where i have written only 
"CatInternational" line in the page. 

 

I shall be veryy thankful to you really for help. 

 

Best Regards, 

Waqas

 

 





Date: Fri, 25 Sep 2009 15:39:27 -0600
Subject: Re: [Tutor] Help required
From: [email protected]
To: [email protected]
CC: [email protected]; [email protected]





On Fri, Sep 25, 2009 at 1:56 PM, waqas ahmad  wrote:





 Hi, 
 
I dont know it is the right place to post this question. I need help to change 
one search code line . can you help me please.
 
here is my search method code:
 
search=re.compile("^#acl InternationalGroup.*\n", re.M).search(pagetext)
if search:
ret=search.group()
else:
ret='not defined'
return ret

 
here i am searching for "#acl InternationalGroup" in the pageText and when it 
true is then give me search group.
 
 
I want to change this for following requirement:
 
I want to search  for "#acl InternationalGroup" and  "CatInternational" for 
both in the pageText.
when "#acl InternationalGroup" is not there but only "CatInternational" is 
there. then return me search group.
I shall be thankful to you for any help.
 
Best Regards, 
Waqas





What can you do with the new Windows Live? Find out
___
Tutor maillist  -  [email protected]
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


i think this is what you are looking for:



search=re.compile("(#acl\sInternationalGroup|CatInternational).*\n", 
re.M).search(pagetext)
if search:
ret=search.findall()
else:
ret='not defined'
return ret

  
_
Show them the way! Add maps and directions to your party invites. 
http://www.microsoft.com/windows/windowslive/products/events.aspx-- 
http://mail.python.org/mailman/listinfo/python-list


How to run python script in emacs

2009-09-26 Thread devilkin
I'm just starting learning python, and coding in emacs. I usually
split emacs window into two, coding in one, and run script in the
other, which is not very convenient. anyone can help me with it? is
there any tricks like emacs short cut?

also please recommand some emacs plug-ins for python programming, i'm
also beginner in emacs.currently i'm only using python.el. Are any
plugins supply code folding and autocomplete?

BTW, I'm not a english native speaker, any grammer mistakes, please
correct them. :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparison of parsers in python?

2009-09-26 Thread andrew cooke
On Sep 21, 10:59 am, Nobody  wrote:
> I have a similar question.
>
> What I want: a tokeniser generator which can take a lex-style grammar (not
> necessarily lex syntax, but a set of token specifications defined by
> REs, BNF, or whatever), generate a DFA, then run the DFA on sequences of
> bytes. It must allow the syntax to be defined at run-time.
>
> What I don't want: anything written by someone who doesn't understand the
> field (i.e. anything which doesn't use a DFA).

lepl will do this, but it's integrated with the rest of the parser
(which is recursive descent).

for example:

  float = Token(Float())
  word = Token(Word(Lower())
  punctuation = ~Token(r'[\.,]')

  line = (float | word)[:, punctuation]
  parser = line.string_parser()

will generate a lexer with three tokens.  here two are specified using
lepl's matchers and one using a regexp, but in all three cases they
are converted to dfas internally.

then a parser is generated that will match a sequence of floats and
words, separated by punctuation.  spaces are discarded by the lexer by
default, but that can be changed through the configuration (which
would be passed to the string_parser method).

it's also possible to specify everything using matchers and then get
lepl to compile "as much as possible" of the matcher graph to nfas
before matching (nfas rather than dfas because they are implemented
with a stack to preserve the backtracking abilities of the recursive
descent parser they replace).  the problem here is that not all
matchers can be converted (matchers can contain arbitrary python
functions, while my nfa+dfa implementations cannot, and also my
"compiler" isn't very smart), while using tokens explicitly gives you
an error if the automatic compilation fails (in which case the simple
fix is to just give the regexp).

(also, you say "sequence of bytes" rather than strings - lepl will
parse the byte[] type in python3 and even has support for matching
binary values).

disclaimer: newish library, python 2.6+ only, and while i have quite a
few users (or, at least, downloads), i doubt that many use these more
advanced features, and everything is pure python with little
performance tuning so far.

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


Re: Most "active" coroutine library project?

2009-09-26 Thread Grant Edwards
On 2009-09-26, Dennis Lee Bieber  wrote:
> On Fri, 25 Sep 2009 14:22:51 + (UTC), Grant Edwards
> declaimed the following in
> gmane.comp.python.general:
>
>> 
>> EXX accomplised much of the context switch operation.  I don't
>> remember how much RAM was available, but it wasn't much...
>
> Zilog Z80... as with the rest of the "improved" 8080 family --
> 64kB address space... 

Right.  I meant I didn't recall how much RAM was available in
that particular product.  Using the shadow register set to
store context is limiting when compared to just pushing
everything onto the stack and then switching to another stack,
but that does require more RAM.

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


Re: importing with .m instead of .py

2009-09-26 Thread wisccal
Wanderer wrote:
> Is there a way to get python to import files that don't end in .py?

How about using imp.load_source?

y...@x:/tmp$ cat out.m
print("this is my module")
# comment
y=[1,2,3,4,5,6,7,8,9];
# comment
y...@x:/tmp$ cat load_my_module.py
import imp
MyModule=imp.load_source('MyModule','out.m')
print("y is {0}".format(MyModule.y))
y...@x:/tmp$ p31 load_my_module.py
this is my module
y is [1, 2, 3, 4, 5, 6, 7, 8, 9]

Regards
wisccal
http://skre.ch

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


Re: Why the file mode of .pyc files has x?

2009-09-26 Thread Steven D'Aprano
On Sat, 26 Sep 2009 06:57:52 -0500, Peng Yu wrote:

> Hi,
> 
> It is strange that the file mode of .pyc files are changed to executable
> (x mode) after the corresponding .py files have been run.

Are you sure? They don't on my system.


[st...@sylar test]$ ls -l
total 8
-rw-rw-r-- 1 steve steve 6 2009-09-26 23:06 test.py
[st...@sylar test]$ python2.6 test.py
[st...@sylar test]$ ls -l
total 8
-rw-rw-r-- 1 steve steve 6 2009-09-26 23:06 test.py


Running a .py file does not generally create a .pyc file. Normally you 
have to import it:

[st...@sylar test]$ python2.6
Python 2.6.1 (r261:67515, Dec 24 2008, 00:33:13)
[GCC 4.1.2 20070502 (Red Hat 4.1.2-12)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
>>> exit()
[st...@sylar test]$ ls -l
total 16
-rw-rw-r-- 1 steve steve  6 2009-09-26 23:06 test.py
-rw-rw-r-- 1 steve steve 94 2009-09-26 23:08 test.pyc


Have you checked the umask of your system?



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


[ANN] python-daemon 1.5.1

2009-09-26 Thread Ben Finney
Howdy all,

I'm pleased to announce the release of version 1.5.1 of ‘python-daemon’.

What is python-daemon
=

The ‘python-daemon’ library is the reference implementation of PEP 3143
http://www.python.org/dev/peps/pep-3143/>, “Standard daemon process
library”.

The source distribution is available via the PyPI page for this version,
http://pypi.python.org/pypi/python-daemon/1.5.1/>. The latest
version is always available via the library's PyPI page
http://pypi.python.org/pypi/python-daemon/>.

What's new in this version
==

Since version 1.4.8 the following significant improvements have been
made:

* Raise specific errors on failures from the library, distinguishing
  different conditions better.

* Write the PID file using correct OS locking and permissions.

* Implement ‘PIDLockFile’ as subclass of ‘lockfile.LinkFileLock’.

The ‘PIDLockFile’ and ‘TimeoutPIDLockFile’ implementation is in the
process of migrating to the more specific ‘lockfile’ library, with the
assistance of Skip Montanaro; at some future point it will no longer be
part of ‘python-daemon’.

-- 
 \   “A computer once beat me at chess, but it was no match for me |
  `\ at kick boxing.” —Emo Philips |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to control I/O buffering besides -u?

2009-09-26 Thread Matt Joiner
You can try flushing, or reopening with no buffering

sys.stdout.flush()
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

On Sun, Sep 27, 2009 at 2:20 AM, Dave Angel  wrote:
> kj wrote:
>>
>> Is there any way to specify unbuffered I/O from *within* the code
>> (rather than via the command-line -u flag)?
>>
>> TIA!
>>
>> kynn
>>
>>
>
> When creating a file object, specify a buffer size of zero.  I don't know
> how to change the buffering of a file object that's already been created, as
> stdin, stdout, and stderr are.
>
> DaveA
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Most "active" coroutine library project?

2009-09-26 Thread Grant Edwards
On 2009-09-26, Dave Angel  wrote:

> Actually even 64k looked pretty good, compared to the 1.5k of
> RAM and 2k of PROM for one of my projects, a navigation system
> for shipboard use.

I've worked on projects as recently as the past year that had
only a couple hundred bytes of RAM, and most of it was reserved
for a message buffer.

-- 
Grant

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


Re: Is there a method (similar to str() method in R) that can print the data structure in python?

2009-09-26 Thread Robert Kern

On 2009-09-26 09:32 AM, Peng Yu wrote:

Hi,

I am looking for a method in python that is similar to the function
str() in R, if you are familiar with R,

If you have no idea of R, what I want is to print the class
information of an object and the values of its members. Overloading
'__expr__' and '__repr__' then using 'print' can sort of do what I
want. But not quite. For example, if I have a list of many elements, I
don't want to print all the elements. R's str() function can
automatically take care of this issue. It also has other advantages, I
am wondering if there is something similar available in python?


I use Armin Ronacher's pretty.py as a pluggable pretty-printer. You can plug 
into its logic to implement these kinds of tools.


  http://dev.pocoo.org/hg/sandbox/file/tip/pretty

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: Anyone with Experience Using WinTV Capture Cards?

2009-09-26 Thread Tim Roberts
"W. eWatson"  wrote:

>W. eWatson wrote:
>> A friend is looking for some help with how to use Python to access a 
>> WinTV (Go Plus) capture card, and how to display an image from it. Is 
>> there some facility that might help him, or does anyone have experience 
>> with such use that might suggest sources?
>
>Win XP OS. Any general methods for dealing with such commercially built 
>capture cards?

Let me Google that for you.

http://www.lmgtfy.com?q=python+video+capture+windows

Most such devices use DirectShow, so you need a C++ extension.
-- 
Tim Roberts, [email protected]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What does the list_folders() method of mailbox.Maildir actually ?do (if anything)?

2009-09-26 Thread Tim Roberts
[email protected] wrote:
>
>My maildir hierarchy is created by mutt which is a *very* standards
>compliant MUA, surely standard python libraries should work with
>standard maildirs not some wierd extension thereof.

The Maildir specification does not allow for subfolders.  That was added in
Maildir++, and the subfolder names start with a dot.  It's not a "wierd
extension thereof".
-- 
Tim Roberts, [email protected]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: flow control and nested loops

2009-09-26 Thread Bearophile
Raymond Hettinger:

> Another approach for exiting multiple levels of loops is wrap the
> inner calls in a function and return from them when needed:
>
>    def f(x):
>        for y in y:
>            for z in Z:
>                if test1(x,y,z):
>                    return
>                frobnicate(x,y,z)
>
>    for x in X:
>       f(x)

That's usual the solution I use for this problem, it's a little rough
and it has some performance cost, but it's readable and simple.

In PHP break and continue accept an optional numeric value (default is
1, 0 is of course ignored) "which tells it how many nested enclosing
structures are to be broken out of.":
http://us2.php.net/manual/en/control-structures.break.php
http://us2.php.net/manual/en/control-structures.continue.php
That PHP design gives me shivers, it's horrid, bug-prone and fragile:

for x in X:
for y in Y:
for z in Z:
if test1(x, y, z):
continue 3
if test2(x, y, z):
continue 2
frobnicate(x, y, z)
glortz(x, y)
splat(x)


A better solution is to add labels to Python (I hope this code is
equivalent to the original Perl one), that can optionally be used by
"continue" and "break". This solution design is also used by D:

label OUTER:
for x in X:
label INNER:
for y in Y:
for z in Z:
if test1(x, y, z):
continue OUTER
if test2(x, y, z):
continue INNER
frobnicate(x, y, z)
glortz(x, y)
splat(x)

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


Plugins for a Python program

2009-09-26 Thread OldAl
I am impressed with Bazaar's implementation of plugins: a Python
plugin is simply copied to a ./bazaar/plugin/ directory and
the plugin is recognized by Bazaar and can be run from CLI as:

bzr 

I would like to implement something similar in my Finite Element
Method program, so that any user can write certain element properties
(in a predetermined format) to use with the program.

The references that I looked at seem to use "distutils" as part of the
plugin installation.  Would you recommend to go  in that direction?
Any other good references?

BTW, the FEM program is currently designed to solve Engineering
structure analysis with the implemented elements for beams (frame
members) or truss members for 2D structures and also trusses in 3D
structures.

OldAl
PS: Trust me, I am really, really old...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: can i use the browser to show the result of python

2009-09-26 Thread Hacken
On Sep 25, 6:27 pm, Dave Angel  wrote:
> Hacken wrote:
> > I have write some python script
>
> > i want to use browser(IE or FF) to call it, an show the returns!
>
> > how to?
>
> You don't say much about your environment, nor the nature of your
> script. So my response will be very generic.
>
> If your script writes a valid html/xml/xhtml format to stdout, then you
> could put the script onto a web server with cgi enabled, and mark it
> executable.  Then you could enter the URL for that cgi file into your
> browser, and see that generated web page.
>
> Interesting additional gotchas:  You need rights to upload (ftp) to such
> a server.  The server needs to have an appropriate Python available, and
> configured to permit cgi access for files with the .py extension.  
> Further, if the server is Unix, your file must be in Unix text format,
> with a shebang line that matches the location of the appropriate version
> of python on that particular server.
>
> DaveA


Thanks.

but,i do not want to setup a webserver, i think that is so big for
other user.

i just want write my programes in python, and i use Browser to show my
GUI,

can i do that?and how to?

thanks,waitting..
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: can i use the browser to show the result of python

2009-09-26 Thread Steven D'Aprano
On Sat, 26 Sep 2009 19:05:37 -0700, Hacken wrote:

> i just want write my programes in python, and i use Browser to show my
> GUI,
> 
> can i do that?and how to?
> 
> thanks,waitting..


In Python 2.6, you can use the webbrowser module.




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


unexplainable python

2009-09-26 Thread dads
When creating a script that converts digits to words I've come across
some unexplainable python. The script works fine until I use a 5 digit
number and get a 'IndexError: string index out of range'. After
looking into it and adding some print calls, it looks like a variable
changes for no reason. The example beneath is using the digits 34567,
the _5digit function slices 34 off and passes it to the _2digit
function, which works with 2 digit strings but the IndexError is
raised. Please accept my apologies for the explanation, I'm finding it
hard to put into words. Has anyone any idea why it's acting the way it
is?

enter number: 34567
_5digit function used
34 before sent to _2digit
34 slice when at _2digit function
34 before sent to plus_ten function
7 slice when at _2digit function
7 before sent to plus_ten function


from __future__ import print_function
import sys

class number(object):

def __init__(self, number):

#remove any preceding zero's
num = int(number)
self.num = str(num)
self.num = number

self.single =
{'0':'zero','1':'one','2':'two','3':'three','4':'four',
 
'5':'five','6':'six','7':'seven','8':'eight','9':'nine'}
self.teen = {'11':'eleven','12':'twelve','13':'thirteen',
  '14':'fourteen','15':'fifteen','16':'sixteen',
 
'17':'seventeen','18':'eighteen','19':'nineteen'}
self.plus_ten =
{'10':'ten','20':'twenty','30':'thirty','40':'forty',
  '50':'fifty','60':'sixty','70':'seventy',
  '80':'eighty','90':'ninety'}
self._translate()

def _translate(self):

fns = [ i for i in number.__dict__ if 'digit' in i ]
fns.sort()
fn_name = fns[len(self.num)-1]
print(fn_name,'function used')
fn = number.__dict__[fn_name]
print(fn(self, self.num))


def _1digit(self, n):

return self.single[n]

def _2digit(self, n):

print(n, 'slice when at _2digit function')
if '0' in self.num:
return self.plus_ten[n]
elif self.num[0] == '1':
return self.teen[n]
else:
print(n,'before sent to plus_ten function')
var = self.plus_ten[n[0]+'0'] + ' ' + self._1digit(n[1])
return var

def _3digit(self, n):

var = self._1digit(n[0]) + ' hundred and ' + self._2digit(n
[1:])
return var

def _4digit(self, n):

var = self._1digit(n[0]) + ' thousand ' + self._3digit(n[1:])
return var


def _5digit(self, n):

print(n[:2],'before sent to _2digit')
var = self._2digit(n[:2]) + ' thousand ' + self._4digit(n[2:])
return var

class control(object):

def __init__(self):
pass

def data_input(self):


while True:
i = raw_input('enter number: ')
if i == 's':
break
#try:
n = number(i)
#except:
#print('not a number')


if __name__ in '__main__':
c = control()
c.data_input()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unexplainable python

2009-09-26 Thread dads
Sorry forgot to mention I'm using python 2.6
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unexplainable python

2009-09-26 Thread Chris Rebert
On Sat, Sep 26, 2009 at 7:37 PM, dads  wrote:
> When creating a script that converts digits to words I've come across
> some unexplainable python. The script works fine until I use a 5 digit
> number and get a 'IndexError: string index out of range'.

Please provide the full error traceback. Help us help you.


>    def __init__(self, number):
>
>        #remove any preceding zero's
>        num = int(number)
>        self.num = str(num)
>        self.num = number

I can tell you right now, the first 2 lines of this method have no net effect.

Cheers,
Chris
--
http://blog.rebertia.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to run python script in emacs

2009-09-26 Thread Join hack
you can use emacs command shell for that

2009/9/26 devilkin 

> I'm just starting learning python, and coding in emacs. I usually
> split emacs window into two, coding in one, and run script in the
> other, which is not very convenient. anyone can help me with it? is
> there any tricks like emacs short cut?
>
> also please recommand some emacs plug-ins for python programming, i'm
> also beginner in emacs.currently i'm only using python.el. Are any
> plugins supply code folding and autocomplete?
>
> BTW, I'm not a english native speaker, any grammer mistakes, please
> correct them. :)
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unexplainable python

2009-09-26 Thread Banibrata Dutta
Without reading or trying to understand the program well enough, at the very
outset, looks like it's a program to convert a set of numeric digits into
it's equivalent whole number representation, in textual form, and that while
author of this piece of code has taken care of english numeric nuances upto
the number 99, he doesn't have anything for hundreds or thousands. So,
feeding a 5-digit code, IMHO would get you to run into a situation where
barring right-most 3 digits, the remaining 2 digits don't have their english
textual names available in the logic.

Why don't you run the thing in a debugger. It's lot easier than adding
prints !!

On Sun, Sep 27, 2009 at 8:07 AM, dads  wrote:

> When creating a script that converts digits to words I've come across
> some unexplainable python. The script works fine until I use a 5 digit
> number and get a 'IndexError: string index out of range'. After
> looking into it and adding some print calls, it looks like a variable
> changes for no reason. The example beneath is using the digits 34567,
> the _5digit function slices 34 off and passes it to the _2digit
> function, which works with 2 digit strings but the IndexError is
> raised. Please accept my apologies for the explanation, I'm finding it
> hard to put into words. Has anyone any idea why it's acting the way it
> is?
>
> enter number: 34567
> _5digit function used
> 34 before sent to _2digit
> 34 slice when at _2digit function
> 34 before sent to plus_ten function
> 7 slice when at _2digit function
> 7 before sent to plus_ten function
>
>
> from __future__ import print_function
> import sys
>
> class number(object):
>
>def __init__(self, number):
>
>#remove any preceding zero's
>num = int(number)
>self.num = str(num)
>self.num = number
>
>self.single =
> {'0':'zero','1':'one','2':'two','3':'three','4':'four',
>
> '5':'five','6':'six','7':'seven','8':'eight','9':'nine'}
>self.teen = {'11':'eleven','12':'twelve','13':'thirteen',
>  '14':'fourteen','15':'fifteen','16':'sixteen',
>
> '17':'seventeen','18':'eighteen','19':'nineteen'}
>self.plus_ten =
> {'10':'ten','20':'twenty','30':'thirty','40':'forty',
>  '50':'fifty','60':'sixty','70':'seventy',
>  '80':'eighty','90':'ninety'}
>self._translate()
>
>def _translate(self):
>
>fns = [ i for i in number.__dict__ if 'digit' in i ]
>fns.sort()
>fn_name = fns[len(self.num)-1]
>print(fn_name,'function used')
>fn = number.__dict__[fn_name]
>print(fn(self, self.num))
>
>
>def _1digit(self, n):
>
>return self.single[n]
>
>def _2digit(self, n):
>
>print(n, 'slice when at _2digit function')
>if '0' in self.num:
>return self.plus_ten[n]
>elif self.num[0] == '1':
>return self.teen[n]
>else:
>print(n,'before sent to plus_ten function')
>var = self.plus_ten[n[0]+'0'] + ' ' + self._1digit(n[1])
>return var
>
>def _3digit(self, n):
>
>var = self._1digit(n[0]) + ' hundred and ' + self._2digit(n
> [1:])
>return var
>
>def _4digit(self, n):
>
>var = self._1digit(n[0]) + ' thousand ' + self._3digit(n[1:])
>return var
>
>
>def _5digit(self, n):
>
>print(n[:2],'before sent to _2digit')
>var = self._2digit(n[:2]) + ' thousand ' + self._4digit(n[2:])
>return var
>
> class control(object):
>
>def __init__(self):
>pass
>
>def data_input(self):
>
>
>while True:
>i = raw_input('enter number: ')
>if i == 's':
>break
>#try:
>n = number(i)
>#except:
>#print('not a number')
>
>
> if __name__ in '__main__':
>c = control()
>c.data_input()
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
regards,
Banibrata
http://www.linkedin.com/in/bdutta
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: unexplainable python

2009-09-26 Thread tec

dads 写道:

...
enter number: 34567
_5digit function used
34 before sent to _2digit
34 slice when at _2digit function
34 before sent to plus_ten function
7 slice when at _2digit function
This is the point. _2digit() only gets 1 digit("7") and needs accessing 
the second byte in:

 var = self.plus_ten[n[0]+'0'] + ' ' + self._1digit(n[1])


7 before sent to plus_ten function

...
from __future__ import print_function
import sys

class number(object):

def _5digit(self, n):

print(n[:2],'before sent to _2digit')
var = self._2digit(n[:2]) + ' thousand ' + self._4digit(n[2:])

You passed the last 3 digits to _4digit function.


return var

class control(object):

def __init__(self):
pass

def data_input(self):


while True:
i = raw_input('enter number: ')
if i == 's':
break
#try:
n = number(i)
#except:
#print('not a number')


if __name__ in '__main__':
c = control()
c.data_input()

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


Re: unexplainable python

2009-09-26 Thread Mel
dads wrote:

> When creating a script that converts digits to words I've come across
> some unexplainable python. The script works fine until I use a 5 digit
> number and get a 'IndexError: string index out of range'. After
> looking into it and adding some print calls, it looks like a variable
> changes for no reason. The example beneath is using the digits 34567,
> the _5digit function slices 34 off and passes it to the _2digit
> function, which works with 2 digit strings but the IndexError is
> raised. Please accept my apologies for the explanation, I'm finding it
> hard to put into words. Has anyone any idea why it's acting the way it
> is?

Yeah.  You convert a 5 digit number by calling _2digit for the thousands, 
and _4digit for the rest.  Why?

Mel.


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


Re: can i use the browser to show the result of python

2009-09-26 Thread Dave Angel

Hacken wrote:

On Sep 25, 6:27 pm, Dave Angel  wrote:
  

Hacken wrote:


I have write some python script
  
i want to use browser(IE or FF) to call it, an show the returns!
  
how to?
  

You don't say much about your environment, nor the nature of your
script. So my response will be very generic.

If your script writes a valid html/xml/xhtml format to stdout, then you
could put the script onto a web server with cgi enabled, and mark it
executable.  Then you could enter the URL for that cgi file into your
browser, and see that generated web page.

Interesting additional gotchas:  You need rights to upload (ftp) to such
a server.  The server needs to have an appropriate Python available, and
configured to permit cgi access for files with the .py extension.  
Further, if the server is Unix, your file must be in Unix text format,

with a shebang line that matches the location of the appropriate version
of python on that particular server.

DaveA




Thanks.

but,i do not want to setup a webserver, i think that is so big for
other user.

i just want write my programes in python, and i use Browser to show my
GUI,

can i do that?and how to?

thanks,waitting..

  
What I described is all I've done firsthand.  But more is possible.  And 
I've worked on fancier setups, but somebody else did the plumbing.


As Stephen points out, you can use webbrowser module to launch a 
browser.  So you could write python code to create a web page(s), write 
it to a file, then launch the browser using the "file://.." 
protocol.  That'd be fine for displaying pages that are generated 
entirely before launching the browser.  But if you want the python 
program to get feedback from the browser (which is usually what's meant 
by using the browser for a GUI), you're going to have to simulate a 
webserver.


That can be done on a single machine using the "localhost" shortcut.  I 
don't know how to do it, but there is a sample in the 2.6 release of 
Python, at least in the Windows version.  You run it from the Start 
menu->Python2.6->module docs.


The source for the main server is in 
c:\Python26\Tools\Scripts\pydocgui.pyw.  (though all it does is import 
pydoc.py and call it.)  Now that particular program's purpose is to 
generate and display docs for the python files on the system, but 
presumably it's a starting place.


Now, this is the first I've looked at this file, but at line 1967 is a 
function serve(), which is commented as the web browser interface.   The 
function serve()  probably has much of what you're interested.  In 
particular, it contains a few class definitions, including DocServer and 
DocHandler, which send data back and forth to the browser, over the 
localhost connection.


It looks like it gets its core code from BaseHTTPServer module.

At line 2058 is a function gui(), which is a small tkinter program that 
just displays a few buttons and such.  That's not what you're asking about.


Hopefully somebody else has actually used some of this stuff, and can 
elaborate.


DaveA


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


Re: How to run python script in emacs

2009-09-26 Thread Nobody
On Sat, 26 Sep 2009 08:54:49 -0700, devilkin wrote:

> I'm just starting learning python, and coding in emacs. I usually
> split emacs window into two, coding in one, and run script in the
> other, which is not very convenient. anyone can help me with it? is
> there any tricks like emacs short cut?

According to "C-h m":

M-C-x   py-execute-def-or-class
C-c !   py-shell
C-c |   py-execute-region
C-c return  py-execute-import-or-reload
C-c C-c py-execute-buffer
C-c C-s py-execute-string

Also, "C-c ?" from within a python-mode buffer provides an introductory
tutorial on python-mode.

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


Re: unexplainable python

2009-09-26 Thread Dave Angel

dads wrote:

When creating a script that converts digits to words I've come across
some unexplainable python. The script works fine until I use a 5 digit
number and get a 'IndexError: string index out of range'. After
looking into it and adding some print calls, it looks like a variable
changes for no reason. The example beneath is using the digits 34567,
the _5digit function slices 34 off and passes it to the _2digit
function, which works with 2 digit strings but the IndexError is
raised. Please accept my apologies for the explanation, I'm finding it
hard to put into words. Has anyone any idea why it's acting the way it
is?

enter number: 34567
_5digit function used
34 before sent to _2digit
34 slice when at _2digit function
34 before sent to plus_ten function
7 slice when at _2digit function
7 before sent to plus_ten function


from __future__ import print_function
import sys

class number(object):

def __init__(self, number):

#remove any preceding zero's
num = int(number)
self.num = str(num)
self.num = number

self.single =
{'0':'zero','1':'one','2':'two','3':'three','4':'four',
 
'5':'five','6':'six','7':'seven','8':'eight','9':'nine'}

self.teen = {'11':'eleven','12':'twelve','13':'thirteen',
  '14':'fourteen','15':'fifteen','16':'sixteen',
 
'17':'seventeen','18':'eighteen','19':'nineteen'}

self.plus_ten =
{'10':'ten','20':'twenty','30':'thirty','40':'forty',
  '50':'fifty','60':'sixty','70':'seventy',
  '80':'eighty','90':'ninety'}
self._translate()

def _translate(self):

fns = [ i for i in number.__dict__ if 'digit' in i ]
fns.sort()
fn_name = fns[len(self.num)-1]
print(fn_name,'function used')
fn = number.__dict__[fn_name]
print(fn(self, self.num))


def _1digit(self, n):

return self.single[n]

def _2digit(self, n):

print(n, 'slice when at _2digit function')
if '0' in self.num:
return self.plus_ten[n]
elif self.num[0] == '1':
return self.teen[n]
else:
print(n,'before sent to plus_ten function')
var = self.plus_ten[n[0]+'0'] + ' ' + self._1digit(n[1])
return var

def _3digit(self, n):

var = self._1digit(n[0]) + ' hundred and ' + self._2digit(n
[1:])
return var

def _4digit(self, n):

var = self._1digit(n[0]) + ' thousand ' + self._3digit(n[1:])
return var


def _5digit(self, n):

print(n[:2],'before sent to _2digit')
var = self._2digit(n[:2]) + ' thousand ' + self._4digit(n[2:])
return var

class control(object):

def __init__(self):
pass

def data_input(self):


while True:
i = raw_input('enter number: ')
if i == 's':
break
#try:
n = number(i)
#except:
#print('not a number')


if __name__ in '__main__':
c = control()
c.data_input()

  
This program would be much simpler if you didn't use classes.   So far, 
they don't contribute anything but obfuscation.


Random observations:
in _2digit(), line:
  if '0' in self.num

test makes no sense.  Presumably what you really are trying to check is 
whether the low digit of n is zero.  But in fact you're checking whether 
any of the 5 digits of the whole number is 0.


in _5digit(), line:
  var = self._2digit(n[:2]) + ' thousand ' + self._4digit(n[2:])

should be calling self._3digit(),  not self._4digit().  I presume that's 
the immediate cause of your error.  You'll notice that _4digit() calls 
_2digit(), but by that time the problem has already been triggered.


DaveA



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


Re: Anyone with Experience Using WinTV Capture Cards?

2009-09-26 Thread W. eWatson

Tim Roberts wrote:

"W. eWatson"  wrote:


W. eWatson wrote:
A friend is looking for some help with how to use Python to access a 
WinTV (Go Plus) capture card, and how to display an image from it. Is 
there some facility that might help him, or does anyone have experience 
with such use that might suggest sources?
Win XP OS. Any general methods for dealing with such commercially built 
capture cards?


Let me Google that for you.

http://www.lmgtfy.com?q=python+video+capture+windows

Most such devices use DirectShow, so you need a C++ extension.
He's headed down the c++ path now, and MSDN might be a better place to 
discover what can be done with Python and WinTV. A google there has 
proven fruitful, but my friend will have to determine how fruitful. I'm 
waiting for Hauppauge to respond to my request.


His facilities do not allow him to get out to the internet.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Plugins for a Python program

2009-09-26 Thread John Nagle

OldAl wrote:

I am impressed with Bazaar's implementation of plugins: a Python
plugin is simply copied to a ./bazaar/plugin/ directory and
the plugin is recognized by Bazaar and can be run from CLI as:

bzr 

I would like to implement something similar in my Finite Element
Method program, so that any user can write certain element properties
(in a predetermined format) to use with the program.


   CPython can execute "import" operations at run time.  The form is

s = "modulename"
X = __import__(s)

So you can load plug-ins from within your running program.

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


Re: unexplainable python

2009-09-26 Thread John Nagle

dads wrote:

Sorry forgot to mention I'm using python 2.6


   This looks like a homework assignment.

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


Re: When is divmod(a,b)[0] == floor(a/b)-1 ?

2009-09-26 Thread Martin v. Löwis
>> In [21]: a = 10.0
> 
>> In [22]: b = 10.0 / 3.0
> 
>> In [24]: divmod(a, b)[0]
>> Out[24]: 2.0
> 
>> In [25]: math.floor(a / b) - 1.0
>> Out[25]: 2.0
> 
> Wow.  To me this stuff is just black magic, with a bit of voodoo
> added for good measure...  Maybe some day I'll understand it.

I think this example is not too difficult to understand (IIUC).
I'll use integer constants to denote exact real numbers and
exact real operations, and the decimal point to denote floating
point numbers.

IIUC, the source of the problem is that 10.0/3.0 > 10/3. 10/3
is not exactly representable, so it needs to be rounded up or
rounded down; the closest representable value is larger than
the exact value.

Therefore, (10.0/3.0)*3 > 10. So 10.0/3.0 doesn't fit three times
into 10.0, but only two times; the quotient is therefore 2.0.
The remainder is really close to 10.0/3.0, though:

py> divmod(a,b)
(2.0, 3.333)
py> divmod(a,b)[1]-b
-4.4408920985006262e-16

So that explains why you get 2.0 as the quotient.

Now, if you do math.floor(a / b), we first need to look at
a/b. Again, 10.0/(10.0/3.0) is not exactly representable. Funnily,
the closest representable value is 3.0, so the quotient gets rounded
up again:

py> a/b
3.0

math.floor doesn't change the value, so it stays at 3.0; qed.

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