Re: Running programs under a python program...

2008-05-21 Thread inhahe
maybe you could instead of killing the program  stop the loop that starts 
new processes and start one that runs until the last process ends?

also, if you killed the program but stdout was still set to fd and stderr 
was still set to subprocesses.STDOUT, what would happen when those two 
objects disappeared?  wouldn't the processes crash or something?

i dunno much about this though, maybe there's some way

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> So I have a python program that runs a bunch of other programsit
> then loops forever, occasionally executing other programs.
>
> To run each of these programs my python code executes:
> subprocess.Popen(command_line, shell=True, stdout=fd,
> stderr=subprocess.STDOUT)
>
> where command_line is an appropriate command line.  :)
>
> Now my problem is when I abort this program it kills off all the child
> processes I've started. In this case I don't want that.   How can I
> stop the child processes from dieing when I kill off the parent?
>
> Thanks! 


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


xpath with big files

2008-05-21 Thread Vladimir Kropylev
Hi,
I've encountered a problem when trying to use lxml.etree.xpath with
big (63Mb) file. It returns empty list on any request.
Is there any restriction on file size for lxml.etree.xpath?

This is what I do:

f=open(filename)
tree = etree.parse(f)
f.close()
r = tree.xpath('//image')
print(r)

it prints:
[]

What is wrong here?
--
http://mail.python.org/mailman/listinfo/python-list


Re: What is wrong with my Python threading?

2008-05-21 Thread Chuckk Hubbard
On Tue, May 20, 2008 at 4:28 PM, castironpi <[EMAIL PROTECTED]> wrote:
> On May 20, 8:19 am, "Chuckk Hubbard" <[EMAIL PROTECTED]>
> wrote:
>> #!/usr/bin/python
>>
>> #why doesn't this run both threads simultaneously?
>> #Thanks for any help.
>> #Chuckk
>>
>> import threading
>> import time
>>
>> def printesc(thrd):
>> for i in range(10):
>> time.sleep(1)
>> print thrd, i
>>
>> def master():
>> thd1 = threading.Thread(target=printesc, args=(1,))
>> thd2 = threading.Thread(target=printesc, args=(2,))
>> thd1.run()
>> thd2.run()
>>
>> master()
>
> You meant 'thd1.start( )' and 'thd2.start( )'.

So I did.  I was mixing what I read of thread and threading.  I'll
never wander beyond my Python module reference html folder again.
Thanks for your help.

-Chuckk

-- 
http://www.badmuthahubbard.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Processing in Python

2008-05-21 Thread Salvatore DI DI0
> He meant it has been re-implemented in Javascript:

Indeed :-)

 There is a jython based NodeBox that runs on windows that can be found
> here:
>
> http://research.nodebox.net/index.php/NodeBoxDev
>
Thank you 


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


getting dir(x), but not as list of strings?

2008-05-21 Thread mh
I want to iterate over members of a module, something like:

for i in dir(x):
if type(i) == types.FunctionType: ...

but of course dir() returns a list of strings.  If x is a module,
how can I get the list of its members as their actual types?

Many TIA!
Mark

-- 
Mark Harrison
Pixar Animation Studios
--
http://mail.python.org/mailman/listinfo/python-list


Re: Processing in Python

2008-05-21 Thread Salvatore DI DI0
Thanks all of you

Regards

Salvatore 


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


Re: getting dir(x), but not as list of strings?

2008-05-21 Thread Marc 'BlackJack' Rintsch
On Wed, 21 May 2008 07:54:32 +, mh wrote:

> I want to iterate over members of a module, something like:
> 
> for i in dir(x):
> if type(i) == types.FunctionType: ...
> 
> but of course dir() returns a list of strings.  If x is a module,
> how can I get the list of its members as their actual types?

Take a look at the `inspect` module.

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


HTMLParser error

2008-05-21 Thread jonbutler88
Just writing a simple website spider in python, keep getting these
errors, not sure what to do. The problem seems to be in the feed()
function of htmlparser.

Traceback (most recent call last):
  File "spider.py", line 38, in 
s.crawl(site)
  File "spider.py", line 30, in crawl
self.parse(url)
  File "spider.py", line 21, in parse
self.feed(urlopen('http://' + page).read())
  File "/Library/Frameworks/Python.framework/Versions/2.5/lib/
python2.5/HTMLParser.py", line 107, in feed
self.rawdata = self.rawdata + data
AttributeError: Spider instance has no attribute 'rawdata'

Any ideas of how to fix this? Im using python 2.5.2 on mac osx
--
http://mail.python.org/mailman/listinfo/python-list


Re: iterate start at second row in file not first

2008-05-21 Thread Chris
On May 20, 8:34 pm, [EMAIL PROTECTED] wrote:
> i have a big file with sentences, the first file of each sentence
> contains a colon(:) somewher eon that line
> i want to jump past that sentence.
>
> if all(x != ':' for x in line):
>
> this way i  can check but i dont want to check for every line in the
> whole file, quite unnecessary when i only need to
> chekc the first line.
>
> so the question is, when dealign with iterators like:
> mov = open(afile)
> for line in mov:
> do y
>
> how do i jump the first step there? i dont want to iterate the first
> row...how do i start at the second?

mov = open(afile)
for i,line in enumerate(mov):
if not i: # Enumeration starts at zero so it is the first line
continue # Use continue to just move to the next iteration if
you
 # don't want/need to do anything
# or you can do a check for what you were looking for
if ':' in line:
break
# Alternatively you could do it as
if not i and ':' in line:
break

# Perform your normal operations on the file, not exactly clear
what you
# want to perform
--
http://mail.python.org/mailman/listinfo/python-list


Typeerror

2008-05-21 Thread Beema shafreen
Hi all,
I getting the following error when i run my scirpt ,
can somebody help me regarding this to solve the type error problem


Traceback (most recent call last):
  File "get_one_prt_pep.py", line 59, in ?
if len(data[res])<=1:
TypeError: string indices must be integers


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

Print HTML from Python

2008-05-21 Thread Jorgen Bodde
Hi All,

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

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

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

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


Re: Typeerror

2008-05-21 Thread Freaky Chris

This is a simple error, you are passing the variable res as an interger to
use for a slice when what ever you are storing in res isn't an integer.

Chris

Beema shafreen wrote:
> 
> Hi all,
> I getting the following error when i run my scirpt ,
> can somebody help me regarding this to solve the type error problem
> 
> 
> Traceback (most recent call last):
>   File "get_one_prt_pep.py", line 59, in ?
> if len(data[res])<=1:
> TypeError: string indices must be integers
> 
> 
> -- 
> Beema Shafreen
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
> 

-- 
View this message in context: 
http://www.nabble.com/Typeerror-tp17358659p17358932.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: scalable xml

2008-05-21 Thread Diez B. Roggisch
hyperboreean wrote:

> Hi, I am writing the application server for a three-tier architecture
> and sending the client's response in xml. My question is: is there a way
> to build the xml dom in a more scalable way and faster way than just
> creating every textNode and element for it? I have tons of data to
> transmit and it drives me crazy having to build that dom manually.
> 
> I am not sure if this is a stupid question as I don't know other
> alternatives ... maybe just provide a template xml which I can fill with
> data but that can introduce some pretty ugly bugs in the application.

You should have a look at the ElementTree-package (which also comes
api-compatible as lxml). These allow for a much more pythonic way of
creating XML-trees.

However you might consider using a much more concise format such as json for
transport (if you have control over the client). It reduces the data-amount
to about a tenth or so (of course depending on your xml-dialect), with
considerable gains in processing time. 

And then there in fact are some template languages such as KID and genshi
that might suit you because they enforce proper XML.

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


Re: Python in non-standard location erring with "No module named _sha256"

2008-05-21 Thread Laurent Rahuel
Maybe you run the configure, make, make install without addind devel
packages on your system. I mean:

openssl-devel
readline-devel
...

Regards,

emallove wrote:

> I'm running into the below "No modules named _sha256" issue, with a
> python installed in a non-standard location.
> 
> $ python
> Python 2.5.2 (r252:60911, May 20 2008, 09:46:50)
> [GCC 3.3.3 (SuSE Linux)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
 import md5
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "/ws/ompi-tools/lib/python2.5/md5.py", line 6, in 
> from hashlib import md5
>   File "/ws/ompi-tools/lib/python2.5/hashlib.py", line 135, in
> 
> sha224 = __get_builtin_constructor('sha224')
>   File "/ws/ompi-tools/lib/python2.5/hashlib.py", line 63, in
> __get_builtin_constructor
> import _sha256
> ImportError: No module named _sha256
> 
> Googling around, this seems to be related to OpenSSL being in a non-
> standard location? I've edited the Setup file to set $(SSL) to the non-
> standard location. Now Python compiles fine, but I still get the above
> error.
> 
> Any help would be much appreciated.
> 
> Thanks,
> Ethan

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


Re: Typeerror

2008-05-21 Thread Beema shafreen
Thanks a lot i had solved the problem

On Wed, May 21, 2008 at 2:32 PM, <[EMAIL PROTECTED]> wrote:

> On May 21, 9:58 am, Freaky Chris <[EMAIL PROTECTED]> wrote:
> > This is a simple error, you are passing the variable res as an interger
> to
> > use for a slice when what ever you are storing in res isn't an integer.
> >
> > Chris
> >
> >
> >
> > Beema shafreen wrote:
> >
> > > Hi all,
> > > I getting the following error when i run my scirpt ,
> > > can somebody help me regarding this to solve the type error problem
> >
> > > Traceback (most recent call last):
> > >   File "get_one_prt_pep.py", line 59, in ?
> > > if len(data[res])<=1:
> > > TypeError: string indices must be integers
> >
> > > --
> > > Beema Shafreen
> >
> > > --
> > >http://mail.python.org/mailman/listinfo/python-list
> >
> > --
> > View this message in context:
> http://www.nabble.com/Typeerror-tp17358659p17358932.html
> > Sent from the Python - python-list mailing list archive at Nabble.com.
>
> If it is an integer, but stored as a string you can use:
>
> if len(data[int(res)])<=1
>
> its not pretty but it should sort out the type errors
> --
> http://mail.python.org/mailman/listinfo/python-list
>



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

scalable xml

2008-05-21 Thread hyperboreean
Hi, I am writing the application server for a three-tier architecture 
and sending the client's response in xml. My question is: is there a way 
to build the xml dom in a more scalable way and faster way than just 
creating every textNode and element for it? I have tons of data to 
transmit and it drives me crazy having to build that dom manually.


I am not sure if this is a stupid question as I don't know other 
alternatives ... maybe just provide a template xml which I can fill with 
data but that can introduce some pretty ugly bugs in the application.



Thanks.

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


How to transfer files over serial?

2008-05-21 Thread RaymondHe
I want to transfer files over serial,but PySerial Module does not
support any protocol such as xmodem/ymodem,and I find nothing about
these protocol write in python

What should I do?Thank you
--
http://mail.python.org/mailman/listinfo/python-list


Re: Typeerror

2008-05-21 Thread jonbutler88
On May 21, 9:58 am, Freaky Chris <[EMAIL PROTECTED]> wrote:
> This is a simple error, you are passing the variable res as an interger to
> use for a slice when what ever you are storing in res isn't an integer.
>
> Chris
>
>
>
> Beema shafreen wrote:
>
> > Hi all,
> > I getting the following error when i run my scirpt ,
> > can somebody help me regarding this to solve the type error problem
>
> > Traceback (most recent call last):
> >   File "get_one_prt_pep.py", line 59, in ?
> >     if len(data[res])<=1:
> > TypeError: string indices must be integers
>
> > --
> > Beema Shafreen
>
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> --
> View this message in 
> context:http://www.nabble.com/Typeerror-tp17358659p17358932.html
> Sent from the Python - python-list mailing list archive at Nabble.com.

If it is an integer, but stored as a string you can use:

if len(data[int(res)])<=1

its not pretty but it should sort out the type errors
--
http://mail.python.org/mailman/listinfo/python-list


Re: HTMLParser error

2008-05-21 Thread jonbutler88
On May 21, 9:53 am, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On Wed, 21 May 2008 01:18:00 -0700 (PDT), [EMAIL PROTECTED]
> declaimed the following in comp.lang.python:
>
> > Any ideas of how to fix this? Im using python 2.5.2 on mac osx
>
>         In the absence of minimal runable code reproducing the error
> message...
>
>         Did you remember to INITIALIZE the attribute to a null value
> somewhere prior to that statement?
> --
>         Wulfraed        Dennis Lee Bieber               KD6MOG
>         [EMAIL PROTECTED]             [EMAIL PROTECTED]
>                 HTTP://wlfraed.home.netcom.com/
>         (Bestiaria Support Staff:               [EMAIL PROTECTED])
>                 HTTP://www.bestiaria.com/

Its not a variable I set, its one of HTMLParser's inbuilt variables. I
am using it with urlopen to get the source of a website and feed it to
htmlparser.

def parse(self, page):
try:
self.feed(urlopen('http://' + page).read())
except HTTPError:
print 'Error getting page source'

This is the code I am using. I have tested the other modules and they
work fine, but I havn't got a clue how to fix this one.
--
http://mail.python.org/mailman/listinfo/python-list


C-like assignment expression?

2008-05-21 Thread boblatest
Hello,

I have an if-elif chain in which I'd like to match a string against
several regular expressions. Also I'd like to use the match groups
within the respective elif... block. The C-like idiom that I would
like to use is this:

if (match = my_re1.match(line):
  # use match
elsif (match = my_re2.match(line)):
  # use match
elsif (match = my_re3.match(line))
  # use match

...buy this is illegal in python. The other way is to open up an else:
block in each level, do the assignment and then the test. This
unneccessarily leads to deeper and deeper nesting levels which I find
ugly. Just as ugly as first testing against the RE in the elif: clause
and then, if it matches, to re-evaluate the RE to access the match
groups.

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


Re: C-like assignment expression?

2008-05-21 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

> Hello,
> 
> I have an if-elif chain in which I'd like to match a string against
> several regular expressions. Also I'd like to use the match groups
> within the respective elif... block. The C-like idiom that I would
> like to use is this:
> 
> if (match = my_re1.match(line):
>   # use match
> elsif (match = my_re2.match(line)):
>   # use match
> elsif (match = my_re3.match(line))
>   # use match
> 
> ...buy this is illegal in python. The other way is to open up an else:
> block in each level, do the assignment and then the test. This
> unneccessarily leads to deeper and deeper nesting levels which I find
> ugly. Just as ugly as first testing against the RE in the elif: clause
> and then, if it matches, to re-evaluate the RE to access the match
> groups.

This might help:

---
s = "foo"

class Tester(object):

def __call__(self, pattern):
self.m = re.match(pattern, s)
return self.m is not None

def __getattr__(self, name):
return getattr(self.m, name)

test = Tester()

if test("bar"):
print "wrong"
elif test("foo"):
print "right"
-


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


Publish a program

2008-05-21 Thread TheSaint
Hello,

I'm not a master of python :) If I would publish my program for reviewing,
where should I upload it?


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


Re: Using Python for programming algorithms

2008-05-21 Thread Bruno Desthuilliers

Roel Schroeven a écrit :

Wow this resulted in far more reactions than I had expected ...

[EMAIL PROTECTED] schreef:

On 19 mai, 15:30, Roel Schroeven <[EMAIL PROTECTED]>
wrote:

Bruno Desthuilliers schreef:


1/ being interpreted or compiled (for whatever definition of these
terms) is not a property of a language, but a property of an
implementation of a language.
2/ actually, all known Python implementations compile to byte-code.

You keep saying that, and in theory you're right.


"In theory" ??? Heck, both points above are mere facts. Well, I may
accept that the 2nd one is a bit overgeneralized, since IIRC there's
an experimental Python to javascript "compiler" in Pypy, but...

 But I'm still inclined to disagree with it,  since the practical 
reality is different.


Do you mean that how source code written in a language (that is : a
grammar  + a syntax) finally become a set of instructions executed by
a CPU depends on the language (I repeat : a grammer + a syntax), and
not on a piece of software turning the source code into something that
can actually be executed by the CPU ?


No, that's not what I said; what I said is that some languages where 
designed with in the back of the head the idea that they were going to 
be compiled to native code, others to be interpreted, and others to be 
compiled to byte code.


I'd put it more simply : some languages were designed with low-level 
access and raw performances in mind, and some were'nt. Roel, I'm totally 
aware of these issues - on which you're of course right -, but that 
doesn't change the fact that a language and it's implementation *are* 
distinct things.


(snip)

So yes, the transformation method from source code to something that the 
CPU understands depends on your tools.


And you can have different tools using different solutions for a same 
language.


But if you want to get work done, 
the most common method by far for C is to use a toolchain that compiles 
to native code and for Python a byte code compiler + virtual machine. 
With possibly a JIT compiler, that's true.




Python is
indeed compiled to byte code, but if you compare that byte code with
assembly code you'll see that there's a whole world of difference
between the two,


Obviously, yes - at least for all assembly language I've seen so far.
But whoever said otherwise ?


Whenever someone says that Python is interpreted, you respond saying 
that that's not true, since it's compiled to byte code.


Whenever someone says that Python is interpreted, I respond saying that 
being interpeted or compiled is not a feature of a language, and that 
CPython compiles to byte-code.


Correct of 
course,


And that's the point : being correct.


but somehow it appears to me that you imply


I don't imply anything - except eventually that the person I'm 
correcting should know better.


that that makes 
Python closer to a C-like language than to an interpreted language,


Strange enough, no one calls Java or C# 'interpreted languages', while 
they (or, to be more exact, their reference implementations) both  use 
the same byte-code/VM scheme[1]. You know, the commonly accepted 
definition of "byte-code" is "something that is going to be passed to a 
virtual machine", not "native binary executable code", so I don't think 
this could be really misleading.


Now what you don't seem to get is the difference between pure 
interpretation - where each and every statement is parsed and 
interpreted again and again - and intermediate byte-code compilation. 
Believe me, *this* can make a huge difference wrt/ performances.


Also and FWIW, there are quite a lot of "C-like languages" that are - in 
their only or reference implementation - interpreted or compiled to 
byte-code. For a definition of "C-like" being "close to the C language's 
syntax and grammar" !-)


[1] Oh, and before some nut-case jump in : no, this doesn't imply that 
the CPython VM is 'equivalent' to Sun's Java VM or MS CLI/.NET VM.


and 
that's not correct (IMO). If that's just a misinterpretation by me, I 
apologize.



 largely because of the dynamical nature of Python. Fact
is that Python was designed from the start to run on a virtual machine,
not on the native hardware.


Nope. The facts are that
1/ Python (the language) has *not* been designed with ease of
implementation of an optimizing native-code compiler in mind,  and
2/ CPython (the first and reference implementation) has been designed
to use a byte-code + VM scheme


Isn't that more or less the same as what I said?


Can't you tell the difference ???

Maybe I don't make enough distinction between Python the language and 
CPython the implementation,  but Python development does happen on the
CPython implementation (Python 3.0 alpha releases are CPython releases, 
for example).





C OTOH was designed to be compiled to assembly code (or directly to
machine code)


Note quite. C has been designed to make it as easy as possible to
write either a C to assembly or C to native bi

Re: Using Python for programming algorithms

2008-05-21 Thread Bruno Desthuilliers

sturlamolden a écrit :

On May 19, 10:42 pm, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:


Well... They do - they are called 'C compilers' !-) As Roel Schroven
mentioned - and he is at least partially right on this point - C has
been designed to make optimizing C compiler not to hairy to write.


C has proven very difficult to optimize, particularly because pointer
aliasing prevents efficient register allocation.


Does this compare to optimizing something like Python ? (serious 
question, but I think I already know part of the answer).

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


Re: HTMLParser error

2008-05-21 Thread alex23
On May 21, 6:58 pm, [EMAIL PROTECTED] wrote:
> Its not a variable I set, its one of HTMLParser's inbuilt variables. I
> am using it with urlopen to get the source of a website and feed it to
> htmlparser.
>
> def parse(self, page):
> try:
> self.feed(urlopen('http://' + page).read())
> except HTTPError:
> print 'Error getting page source'
>
> This is the code I am using. I have tested the other modules and they
> work fine, but I havn't got a clue how to fix this one.

You're not providing enough information. Try to post a minimal code
fragment that demonstrates your error; it gives us all a common basis
for discussion.

Is your Spider class a subclass of HTMLParser? Is it over-riding
__init__? If so, is it doing something like:

super(Spider, self).__init__()

If this is your issue, looking at the HTMLParser code you could get
away with just doing the following in __init__:

self.reset()

This appears to be the function that adds the .rawdata attribute.

Ideally, you should use the former super() syntax...you're less
reliant on the implementation of HTMLParser that way.

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


Re: HTMLParser error

2008-05-21 Thread alex23
On May 21, 8:04 pm, alex23 <[EMAIL PROTECTED]> wrote:
> Is your Spider class a subclass of HTMLParser? Is it over-riding
> __init__? If so, is it doing something like:
>
> super(Spider, self).__init__()
>
> If this is your issue[...]

I'm sorry, this really wasn't clear at all. What I meant was that you
need to call the HTMLParser.__init__ inside your Spider.__init__ in
order to have it initialise properly. Failing to do so would lead to
the .rawdata attribute not being defined. The super() function is the
best way to achieve this.

Sorry for the rambling, hopefully some of that is relevant.

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


Re: Using Python for programming algorithms

2008-05-21 Thread Frédéric Degraeve

> By the way, is it possible (and easy) to call a C function from a
> Python program??

Use SWIG. It's easy, smart and beautiful. After that, you can call C/C+
+ from a lot of scripting languages such as python, R, etc
A lot of open sources projects already use it.

http://www.swig.org/tutorial.html

Boost.Python is also very known (but never tested by myself).

Frédéric
--
http://mail.python.org/mailman/listinfo/python-list


Re: Publish a program

2008-05-21 Thread alex23
On May 21, 7:52 pm, TheSaint <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I'm not a master of python :) If I would publish my program for reviewing,
> where should I upload it?

For simple "look at my code" I like http://paste.turbogears.org/

Sample: http://paste.turbogears.org/paste/2697

There's also http://python.pastebin.com, which lets you create a new
paste by modifying an existing one, and keeps them linked for easy
diff'ing.

Sample: http://python.pastebin.com/d3964b241

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


Re: Using Python for programming algorithms

2008-05-21 Thread Frédéric Degraeve
I reply to myself!

>
> Boost.Python is also very known (but never tested by myself).
>

http://www.boost.org/doc/libs/1_35_0/libs/python/doc/tutorial/doc/html/index.html
here the example. I know that it has been made to simplify the
CPython's use and this is based on CPython.

Frédéric
--
http://mail.python.org/mailman/listinfo/python-list


Re: C-like assignment expression?

2008-05-21 Thread Ulrich Eckhardt
[EMAIL PROTECTED] wrote:
> I have an if-elif chain in which I'd like to match a string against
> several regular expressions. Also I'd like to use the match groups
> within the respective elif... block. The C-like idiom that I would
> like to use is this:
> 
> if (match = my_re1.match(line):
>   # use match
> elsif (match = my_re2.match(line)):
>   # use match
> elsif (match = my_re3.match(line))
>   # use match
> 
> ...buy this is illegal in python. The other way is to open up an else:
> block in each level, do the assignment and then the test. This
> unneccessarily leads to deeper and deeper nesting levels which I find
> ugly.

How about this (untested) code:

for re in (re1, re2, re3):
  match = re.match(line)
  if match:
# use it

This requires that "use it" means the same for each regular expression
though...

Uli

-- 
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932

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

Minimal Python installation?

2008-05-21 Thread Thomas Troeger

Hi,

I'd like to put the python library and interpreter on a small embedded 
Linux x86 compatible device where disk space is an issue. I played 
around with the minimal Python interpreters, but was not entirely happy 
with them, so my question is, is there an (preferably easy) way to put 
the interpreter and a cut-down version of the python library/modules 
that ship with regular Python into a new archive that I can safely copy 
and use? My current method is to copy the python interpreter and the 
python shared library to the device. Then I create a tar archive with 
all startup files from the site package directory to my archive using 
the following one-liner:


strace -f -eopen python -c 'pass' 2>&1 | grep -v ENO | grep '\.py' | awk 
'BEGIN { FS="\"" } { print $2 }' | tar cvf x.tar -T -


This effectively packs all python library files that are accessed upon 
startup into a tar archive. But I figure this method is not what I want 
because there surely are files I am missing here (for example which are 
accessed when starting a script), and what I really want is a minimal 
environment that works. Let's say I want a complete Python install, but 
without all the batteries :-)


Any pointers?

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


Database Query Contains Old Data

2008-05-21 Thread giraffeboy
Hi there,

I'm having a problem with the Python db api, using MySQL.

I've written a program with a GUI using wxPython, the GUI is contained
in main.py which imports another module - reports.py. There are
several reports that are selected using the gui, and each report is a
class in the file reports.py. These classes contain a method which is
passed data as arguments and produces a report, writing HTML to a file
and using matplotlib to create a graph file.

The report class methods are called from the GUI using the following
code:
agentlist = self.getselected()
detail = self.cb1.GetValue()
if self.getdates() != False:
fromdate, todate = self.getdates()
app.mainframe.SetStatusText("Generating Report...")
if self.reportchoice.GetSelection() == 0:
thereport = reports.VehicleRunningCost()
thereport.producereport(agentlist, fromdate=fromdate,
todate=todate, detail=detail)
app.mainframe.SetStatusText("Report Complete")
viewerframe = ViewerFrame(None, -1, "Mileage and Fuel
Report Viewer")
viewerframe.Show(True)

The first time you run a report, everything works as expected but if
you run it a second time, after modifying data, it seems that the data
from before the modification is selected on the second report run.

It would be much appreciated if anyone could give me any hints as to
why the old data is selected. I haven't posted the full code because
it's quite long but will post more if anyone wants to see specific
parts.

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


Re: Newbie: Keep TCP socket open

2008-05-21 Thread Alan Wright
Thanks Roy

Any ideas how to code this child process stuff, as I said I am newbie and 
not from a coding background

to be honest ideally yes, i'd get 50K, but if i can get above 30K that would 
be OK

Alan

"Roy Smith" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> In article <[EMAIL PROTECTED]>,
> "Alan Wright" <[EMAIL PROTECTED]> wrote:
>
>> Thanks for the feedback.
>>
>> Using the socket in a list is great
>>
>> However, as i imagined, I now get a limit of around 1500 conns before the
>> system crashes out, also i have noticed, that the ports loop back to 1025
>> when they hit 5000.
>>
>> Any ideas on how to make the list/socket get to around 50K
>
> Yikes.  Not on any box I know of.  A given process is limited in how many
> descriptors it can have open at once.  I don't know of any that will allow
> anywhere near 50k.  Somewhere in the 1-2000 range would be more typical.
> The 1500 you report is not at all surprising.
>
> You might try creating a bunch of child processes with os.system() or
> something of that ilk.  Create 50 processes and have each one open 1000
> sockets.
>
> The next thing you have to worry about is whether the OS can handle 50k
> file descriptors open per-system.  Or 50k sockets, or TCP connections.  I
> wouldn't be too surprised if many systems couldn't.  The address space 
> (TCP
> port numbers) is 16-bit (unsigned), or about 65k, but you may well run 
> into
> some other system limit long before you exhaust the theoretically 
> available
> ports.
>
> Something like Scapy, recommended by others, may indeed be able to 
> generate
> all those SYN packets you want, but that doesn't mean you'll get all the
> open connections you seek.  You send a SYN packet to the remote host, and
> it sends back a SYN/ACK.  The local kernel now sees a SYN/ACK packet for a
> port it doesn't know about.  I'm not sure what the RFCs say about that, 
> but
> I wouldn't be surprised if the kernel ends up sending a RST or maybe a FIN
> or something like that.  The kernel owns the ports; it's not nice to try
> and mess with them on your own. 


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


Re: Newbie: Keep TCP socket open

2008-05-21 Thread Alan Wright
Same on FC8, sends RST after it sees SYN/ACK

"Ghirai" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> On Mon, 19 May 2008 23:50:50 +0100
> "Alan Wright" <[EMAIL PROTECTED]> wrote:
>
>> Ghirai,
>> Scapy does the same, only it sends RST and not FIN, so still no help
>>
>>  send(IP(dst="10.1.1.2")/TCP(dport=5,flags="S"))
>>
>> Only have windows at the moment sadly.
>>
>> Alan
>>
>
> Are you sure there's no firewall or something else between you and the
> remote host?
>
> Because i just tried that command with scapy and it didn't send any other 
> packets
> except what it was told (1 packet with SYN flag set).
>
> I haven't tried on windows though.
>
> -- 
> Regards,
> Ghirai. 


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


Re: getting dir(x), but not as list of strings?

2008-05-21 Thread akeppke
Use

for i in dir(x):
print i# name of member as string
print getattr(x, i)# member

regards

Arno


On 21 Mai, 09:54, [EMAIL PROTECTED] wrote:
> I want to iterate over members of a module, something like:
>
> for i in dir(x):
> if type(i) == types.FunctionType: ...
>
> but of course dir() returns a list of strings.  If x is a module,
> how can I get the list of its members as their actual types?
>
> Many TIA!
> Mark
--
http://mail.python.org/mailman/listinfo/python-list


Re: Organizing a Python project

2008-05-21 Thread Casey McGinty
> I'm starting work on what is going to become a fairly substantial
> Python project, and I'm trying to find the best way to organize
> everything.


I'd like to add a follow up question.  Are there any idioms for writing
/usr/bin scripts to run installed package modules? For this I am assuming a
simple case where there is a single package with one or more modules all
making up a single application. A have a few thoughts, please correct me if
I'm wrong.

1. Script code should be as basic as possible, ideally a module import line
and function or method call. This is so you don't have to worry about script
errors and/or increase startup time because a *.pyc file can not be store in
/usr/bin.

2. In the top of your package directory it is typical to have a module name
'_package.py'. This is ideally where the main command line entry point for
the package code should be placed.

3. In the _package.py file you should add a "class Package" that holds most
or all of the application startup/execution code not designated to other
modules. Then run the application with the call to "Package()", as in

if __name__ == '__main__':
   Package()

Some other questions I have are:
A. What should go in the package __init__.py file? For example, a doc
describing the program usage seems helpful, but maybe it should have info
about your modules only? Assuming the __init__.py code gets executed when
you import the module, you could place part or all of the application code
here as well. I'm guessing this is not a good idea, but not really
convinced.

B. How should you import your _package.py module into your /usr/bin script.
Is there a way to use an '__all__' to simplify this? Again this goes back to
question A, should there be any code added to __init__.py?

C. If you have a _package.py file as the application entry, is it worth it
to place most of the application code in a class, described in part 3?

D. When I import a package._package module, I get a lot of junk in my
namespace. I thought an '__all__' define in the module would prevent this,
but it does not seem to work.

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

Re: "indexed properties"...

2008-05-21 Thread pataphor
On Tue, 20 May 2008 10:40:17 -0500
"David C. Ullrich" <[EMAIL PROTECTED]> wrote:

> > > Today's little joke: Long ago I would have solved
> > > this by storing the data as a list of rows and _also_
> > > a list of columns, updating each one any time the
> > > other changed. Just goes to show you things
> > > could always be worse...
> > 
> > Well have I ever ... I only thought about this last week and I
> > actually thought it was a *good* idea. 
> 
> Sorry. If you really want to do this you could keep things
> in sync automatically by writing the appropriate __setitem__
> and resolving never to modify the data except through that...
> 
> def whatever.__setitem__(self, (row,col), value):
>   self.rows[row][col] = value
>   self.cols[col][row] = value
 
Using the trick of encapsulating the values inside single-element lists
one can make a transposition of the matrix and get synchronicity for
the little price of doubling the number of instances. Since the views
share the data this is a lot less expensive than one would think. One
can use the row view or the column view to alter data and the changes
will automatically be visible in the other view, since the views update
the same lists. There is a little notational gotcha, instead of writing
row[0] = [1,2,3] one now must write row[0][:] = [1,2,3] or else
synchronicity is lost.

I found a nice ListMixin class at
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440656

Using that I wrote the following proof of concept:

class Storage(ListMixin):

  def __init__(self, seq=[]):
self.L = [[x] for x in seq] 

  def _constructor(self, iterable):
return Storage(iterable)

  def __len__(self):
return len(self.L)

  def _get_element(self, i):
assert 0 <= i < len(self)
return self.L[i][0]

  def _set_element(self, i, x):
assert 0 <= i < len(self)
self.L[i][0] = x

  def _resize_region(self, start, end, new_size):
assert 0 <= start <= len(self)
assert 0 <= end   <= len(self)
assert start <= end
self.L[start:end] = [[None] for i in range(new_size)]

def test():
n = 3
R = range(n)
it = iter(range(n*n))
MR = [Storage(it.next() for i in R) for i in R]
MC = [Storage() for i in R]
T = zip(*[x.L for x in MR])
for x,y in zip(MC,T):
x.L = y
print MR
print MC
MC[2][:] = 'abc'
print
print MR
print MC

if __name__=='__main__':
test()

Output:

[Storage([0, 1, 2]), Storage([3, 4, 5]), Storage([6, 7, 8])]
[Storage([0, 3, 6]), Storage([1, 4, 7]), Storage([2, 5, 8])]

[Storage([0, 1, 'a']), Storage([3, 4, 'b']), Storage([6, 7, 'c'])]
[Storage([0, 3, 6]), Storage([1, 4, 7]), Storage(['a', 'b', 'c'])]

P.

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


Re: C-like assignment expression?

2008-05-21 Thread Bruno Desthuilliers

[EMAIL PROTECTED] a écrit :

Hello,

I have an if-elif chain in which I'd like to match a string against
several regular expressions. Also I'd like to use the match groups
within the respective elif... block. The C-like idiom that I would
like to use is this:

if (match = my_re1.match(line):
  # use match
elsif (match = my_re2.match(line)):
  # use match
elsif (match = my_re3.match(line))
  # use match



Isn't it the third or fourth time this very same question pops up here ? 
 Starts to look like a FAQ.



The canonical solution is to iterate over a list of expression,function 
pairs, ie:


def use_match1(match):
   # code here

def use_match2(match):
   # code here

def use_match3(match):
   # code here

for exp, func in [
(my_re1, use_match1),
(my_re2, use_match2),
(my_re3, use_match3)
]:
match = exp.match(line)
if match:
   func(match)
   break


The alternate solution is Diez's Test object.

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


Re: Code/test ratio wrt static vs dynamic typing

2008-05-21 Thread Bruno Desthuilliers

Ben Finney a écrit :

greg <[EMAIL PROTECTED]> writes:


Also, I don't think it's valid to equate the size of the tests with
the amount of effort it took to develop them. For instance, the test
suite for Pyrex is currently larger than the Pyrex compiler, but
I've still spent far more time and effort developing the compiler
than writing the tests.


Right. The unit test suite should tend to increase: add tests far more
often than removing them. The application code, though, should tend to
grow less rapidly: 


or even sometimes, at some point, start to shrink, thanks to:


refactor duplication, remove redundant code,


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


Re: Showing the method's class in expection's traceback

2008-05-21 Thread Bruno Desthuilliers

Gabriel Genellina a écrit :

En Sun, 18 May 2008 17:31:44 -0300, Diez B. Roggisch
<[EMAIL PROTECTED]> escribió:

Agustin Villena schrieb:


is there anyway to show the class of a method in an exception's 
traceback?


I want to improve the line File "G:\dev\exceptions\sample.py",
line 3, in foo

to File "G:\dev\exceptions\sample.py", line 3, in Some.foo

Is this improvement feasible

It should be. You can get a dictionary of the locals of an
exception stack frame, of which you could extract the
self-parameter's class.


That by itself is not enough, the method could be inherited; one
should walk the base classes in the MRO to find the right one. And
deal with classmethods and staticmethods. And decorators that don't
preserve meta information... 


And monkeypatches.


Hmmm, I think it isn't so trivial as it
seems.


And not that useful - why would one care about the function being 
defined in class X or Y when one have the exact file and line ?


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


Re: Showing the method's class in expection's traceback

2008-05-21 Thread Richard G Riley
Bruno Desthuilliers <[EMAIL PROTECTED]> writes:

> Gabriel Genellina a écrit :
>> En Sun, 18 May 2008 17:31:44 -0300, Diez B. Roggisch
>> <[EMAIL PROTECTED]> escribió:
>>> Agustin Villena schrieb:
>>
 is there anyway to show the class of a method in an exception's
 traceback?

 I want to improve the line File "G:\dev\exceptions\sample.py",
 line 3, in foo

 to File "G:\dev\exceptions\sample.py", line 3, in Some.foo

 Is this improvement feasible
>>> It should be. You can get a dictionary of the locals of an
>>> exception stack frame, of which you could extract the
>>> self-parameter's class.
>>
>> That by itself is not enough, the method could be inherited; one
>> should walk the base classes in the MRO to find the right one. And
>> deal with classmethods and staticmethods. And decorators that don't
>> preserve meta information... 
>
> And monkeypatches.
>
>> Hmmm, I think it isn't so trivial as it
>> seems.
>
> And not that useful - why would one care about the function being
> defined in class X or Y when one have the exact file and line ?

Very obvious I would think. One can develop ones own interactive class
browser and code navigator. One can not bring up class help from "line 3
in x.py" but one can from "classname : MyClass at line 2 in z.py". With
the class name I can navigate directly to all sorts of class related
information without the need to delve into a physical usage of it e.g
program.py at line 3.


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

Re: Minimal Python installation?

2008-05-21 Thread Paul Boddie
On 21 Mai, 12:07, Thomas Troeger <[EMAIL PROTECTED]>
wrote:
>
> I'd like to put the python library and interpreter on a small embedded
> Linux x86 compatible device where disk space is an issue. I played
> around with the minimal Python interpreters, but was not entirely happy
> with them, so my question is, is there an (preferably easy) way to put
> the interpreter and a cut-down version of the python library/modules
> that ship with regular Python into a new archive that I can safely copy
> and use?

Perhaps there are some projects on the following pages which may help
in some way:

http://wiki.python.org/moin/EmbeddedPython
http://wiki.python.org/moin/Tiny_Python

[...]

> Let's say I want a complete Python install, but without all the batteries :-)

I think there's an overlap between "installer" tools and some of the
projects mentioned on the above pages, especially where retaining only
the critical libraries in the resulting distribution is concerned.

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


Re: Misuse of list comprehensions?

2008-05-21 Thread Bruno Desthuilliers

Simon Forman a écrit :

On May 20, 8:58 am, Paul McGuire <[EMAIL PROTECTED]> wrote:

On May 20, 10:50 am, [EMAIL PROTECTED] wrote:




You don't need all those conditionals. A set differs from a list
precisely in the fact that each element is unique. And since the
function is expecting "s" to be an iterable object, it can be
constructed even without a for loop:
def compress(s):
return list(set(s))
That does the trick.

Only if order does not need to be maintained.  list(set(s)) will not
necessarily keep the unique characters in the order they are seen.
We'll have to check with the OP to see if this is important (I just
assumed that it was because of the use of list comps).

-- Paul



If order is important, you can use sorted() instead of list() like so:

def compress(s):
new = sorted(set(s), key=s.index)
return return ''.join(new)


This won't still preserve the *original* order.

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


problem with import / namespace

2008-05-21 Thread ohad frand
Hi
I have a problem that the solution to it must be very simple but i couldnt
fint it's answer in the internet so far (i searched for couple of days)
the problme is as follows:

i have two directories e.g. "\\1" and "\\2"
in each directory i have two files with the same names e.g. "tmp1.py" and
"tmp2.py"
each tmp2.py file imports tmp1 from its same directory (import tmp1) - thats
the problem
if i execute one file (\\1\tmp2.py) than the execution is ok
but when i try after that to execute the second file (\\2\tmp2.py) than the
tmp1 file from the wrong directory ( - directory 1 in this case) is imported
instead.
i tried many things to try to solve it, i removed the previous path from
sys.path and added the new one, i tried to change current working directory
with os.chdir()
I tried to delete from locals and from globals the name tmp1 before running
the second file but nothing worked.
please help

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

Re: How to transfer files over serial?

2008-05-21 Thread zerge69
On May 21, 4:07 am, RaymondHe <[EMAIL PROTECTED]> wrote:
> I want to transfer files over serial,but PySerial Module does not
> support any protocol such as xmodem/ymodem,and I find nothing about
> these protocol write in python
>
> What should I do?Thank you

Does it have to be over the serial? If not, and what you really want
to do is transfer information between machines, you may want to take a
look at the socket library.
--
http://mail.python.org/mailman/listinfo/python-list


Re: C-like assignment expression?

2008-05-21 Thread Hrvoje Niksic
Bruno Desthuilliers <[EMAIL PROTECTED]>
writes:

> The canonical solution is to iterate over a list of
> expression,function pairs, ie:

Although that solution is pretty, it is not the canonical solution
because it doesn't cover the important case of "if" bodies needing to
access common variables in the enclosing scope.  (This will be easier
in Python 3 with 'nonlocal', though.)  The snippet posted by Diez is
IMHO closer to a canonical solution to this FAQ.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Struct usage and varying sizes of h, l, etc

2008-05-21 Thread John Machin

Robert Kern wrote:

Ethan Furman wrote:

Greetings,

I'm looking at the struct module for binary packing of ints and 
floats.  The documentation refers to C datatypes.  It's been many 
years since I looked at C, but I seem to remember that the data type 
sizes were not fixed -- for example, an int might be two byes on one 
machine, and four bytes on the next.  Can any C programmers verify 
this?  If it is true, does that mean that struct.pack('h', 8001) might 
give me different results depending on the machine it's running on?


Right. I believe (but could be wrong) that "char" is defined to be one 
byte, but that "short", "int", "long", and "long long" are defined as 
"at least as big as the previous type".


In practice, though, on nearly every machine that Python runs on, "char" 
is one byte, "short" is two bytes, and "int" is four bytes. "longs" and 
"long longs" tend to vary substantially, though; never assume sizes for 
them.


Single-precision floats are always four bytes and double-precision 
floats are always eight bytes. "long doubles" vary; they could be twelve 
bytes or sixteen.


If you want to deal with fixed sizes, use struct.calcsize() to test the 
sizes of each of the integer types, assign them to width-specific 
aliases, and always use these aliases.




This is all true if you want to operate in "native" mode; however in 
"standard" mode the sizes are fixed -- otherwise there'd be no easy way 
of reading/writing the fixed-size fields in many common file formats.


As the manual says:
"""
Native size and alignment are determined using the C compiler's sizeof 
expression. This is always combined with native byte order.


Standard size and alignment are as follows: no alignment is required for 
any type (so you have to use pad bytes); short is 2 bytes; int and long 
are 4 bytes; long long (__int64 on Windows) is 8 bytes; float and double 
are 32-bit and 64-bit IEEE floating point numbers, respectively.

"""

If, as I suspect, Ethan's purpose is be able to read/write files in a 
long-established PC file format, he will need to '<' for littleendian 
order, and an appropriate selection from bBhHiI and d will do what he needs.


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


Re: Newbie: Keep TCP socket open

2008-05-21 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 "Alan Wright" <[EMAIL PROTECTED]> wrote:

> Thanks Roy
> 
> Any ideas how to code this child process stuff, as I said I am newbie and 
> not from a coding background

The easiest thing would be to use os.system().  If you wanted to spawn 10 
child processes, you could do:

import os
for i in range(10):
os.system ("./child.py &")

and then have child.py be a script that creates 1000 TCP connections.

Keep in mind that one man's stress test is another man's denial of service 
attack.  If there are any firewalls between you and your target, they may 
restrict the number of connections you get to make (or the rate at which 
they're created).  You may also get a polite phone call from your local IT 
people asking enquiring about your activities.
--
http://mail.python.org/mailman/listinfo/python-list


qrcode in python?

2008-05-21 Thread Michel Albert
I am planning to write a python-module for python as I haven't found
anything on the tubes so far. If anyone has any interesting insight on
this topic, replies are welcome! ;)

Q: What is QR-Code?
A: http://www.denso-wave.com/qrcode/qrstandard-e.html

So far (as of May 21st 2008):

Google  (1 sensible hit): 
http://mail.python.org/pipermail/python-list/2006-May/385258.html
The Cheese shop (nothing): 
http://pypi.python.org/pypi?%3Aaction=search&term=qrcode&submit=search
Sourceforge (1 hit - no files/code): http://sourceforge.net/projects/qrcode/

I was planning to make use of qr-code in a web-application which is
written in python. So far I was not yet lucky to find any existing
module. I just contacted the project lead of 
http://sourceforge.net/projects/qrcode/
on this topic as well. Let's see what he replies.

So. any pointers/ideas ?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Struct usage and varying sizes of h, l, etc

2008-05-21 Thread Matthieu Brucher
>
> This is all true if you want to operate in "native" mode; however in
> "standard" mode the sizes are fixed -- otherwise there'd be no easy way of
> reading/writing the fixed-size fields in many common file formats.
>
> As the manual says:
> """
> Native size and alignment are determined using the C compiler's sizeof
> expression. This is always combined with native byte order.
>
> Standard size and alignment are as follows: no alignment is required for
> any type (so you have to use pad bytes); short is 2 bytes; int and long are
> 4 bytes; long long (__int64 on Windows) is 8 bytes; float and double are
> 32-bit and 64-bit IEEE floating point numbers, respectively.
> """
>
> If, as I suspect, Ethan's purpose is be able to read/write files in a
> long-established PC file format, he will need to '<' for littleendian order,
> and an appropriate selection from bBhHiI and d will do what he needs.
>
> HTH,
> John


On an Ubuntu 64 box :

>>> struct.calcsize('l')
8

not 4.

Matthieu
-- 
French PhD student
Website : http://matthieu-brucher.developpez.com/
Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92
LinkedIn : http://www.linkedin.com/in/matthieubrucher
--
http://mail.python.org/mailman/listinfo/python-list

about python modules

2008-05-21 Thread srinivas
hi friends i am new to python programming.
i am using Python 2.5 and IDLE as editor.
i have developed some functions in python those will be calling
frequently in my main method .
now i want to know how to import my functions folder to python in
sucha way that the functions in functions folder should work like
python library modules .

i have  python in folder C:\python25\..
and functions folder D:\programs\Functions\

pls help me friends how to do that.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Running commands on cisco routers using python

2008-05-21 Thread James Harris
On 19 May, 16:18, SPJ <[EMAIL PROTECTED]> wrote:
> Is it possible to run specific commands on cisco router using Python?
> I have to run command "show access-list" on few hundred cisco routers and get 
> the dump into a file. Please let me know if it is feasible and the best way 
> to achieve this.

Can you access the routers with telnet or do you need to use ssh? I've
written loads of Python to access Cisco routers using a wrapper around
the standard telnetlib. Telnetlib supplies an excellent expect
function which makes this work.

It is telnet, though. If I had to use ssh I would probably add it
under the same wrapper so that higher level code could work unchanged.
There may be a way to route the telnet interractions through openssh
or similar externally but I haven't tried that.
--
http://mail.python.org/mailman/listinfo/python-list


Re: about python modules

2008-05-21 Thread Roy Smith
In article 
<[EMAIL PROTECTED]>,
 srinivas <[EMAIL PROTECTED]> wrote:

> hi friends i am new to python programming.
> i am using Python 2.5 and IDLE as editor.
> i have developed some functions in python those will be calling
> frequently in my main method .
> now i want to know how to import my functions folder to python in
> sucha way that the functions in functions folder should work like
> python library modules .
> 
> i have  python in folder C:\python25\..
> and functions folder D:\programs\Functions\
> 
> pls help me friends how to do that.

You need to either:

1) Put your modules in some directory that's already on your python path.  
To find out what your path is, do:

import sys
print sys.path

It should include a directory which ends in "site-packages".  Just drop 
your modules into that directory.

2) Add the directory where you modules are to your python path.  The 
easiest way to do this is to set PYTHONPATH in your environment.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Misuse of list comprehensions?

2008-05-21 Thread cokofreedom
''.join(seen.add(c) or c for c in s if c not in seen)

>From what I can understand...

.join will be a String of unique 'c' values.

'seen.add(c) or c' will always point to the second statement 'c'
because seen.add(c) returns None.

'if c not in seen' will ensure 'c' being added to both the .join and
seen is unique.

That is really clever! I like it :) (but does require a bit of
knowledge about .add return None and the affect that has on the ..
or .. statement)
--
http://mail.python.org/mailman/listinfo/python-list


Re: about python modules

2008-05-21 Thread bockman
On 21 Mag, 14:31, srinivas <[EMAIL PROTECTED]> wrote:
> hi friends i am new to python programming.
> i am using Python 2.5 and IDLE as editor.
> i have developed some functions in python those will be calling
> frequently in my main method .
> now i want to know how to import my functions folder to python in
> sucha way that the functions in functions folder should work like
> python library modules .
>
> i have  python in folder C:\python25\..
> and functions folder D:\programs\Functions\
>
> pls help me friends how to do that.

You have two choices:

1. In this way you can import single modules (files) in tour folder

import sys
sys.path.append(r'D:\programs\Functions\')
import my_module_1
import my_module_2

and then  use whatever you have in the modules:

my_module_1.my_function()
print my_module_1.my_variable


2.
If you add an empty python module called __init__.py inside the folder
D:\programs\Functions\,
then python will handle the folder as a package (i.e. a group of
modules) and  you can import
them in this way:

sys.path.append(r'D:\programs\')
import Functions # I'm not sure this is needed ...
from Functions import my_module_1, my_module_2

And then use whatever is in your modules as in case 1.

If you put any code in __init__.py, this code will be executed when
the import Functions
statement is executed. This can be handy in some cases, e.g. if you
have subfolders of
Function folder and want to extend sys.path to include all them.

For more details, read the section 6 of Python tutorial.

HTH

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


Re: Database Query Contains Old Data

2008-05-21 Thread Jerry Hill
On Wed, May 21, 2008 at 6:30 AM,  <[EMAIL PROTECTED]> wrote:
> The first time you run a report, everything works as expected but if
> you run it a second time, after modifying data, it seems that the data
> from before the modification is selected on the second report run.

Did you remember to commit your changes before re-running the report?
Python's DB API requires that any auto-commit feature of the
underlying database be turned off by default, so you are required to
commit changes yourself.  If you're used to having auto-commit turned
on, this can be confusing.

See http://www.python.org/dev/peps/pep-0249/ for more details of
python's DB API.

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


Re: C-like assignment expression?

2008-05-21 Thread [EMAIL PROTECTED]
On May 21, 1:47 pm, Hrvoje Niksic <[EMAIL PROTECTED]> wrote:

> Although that solution is pretty, it is not the canonical solution
> because it doesn't cover the important case of "if" bodies needing to
> access common variables in the enclosing scope.  (This will be easier
> in Python 3 with 'nonlocal', though.)  The snippet posted by Diez is
> IMHO closer to a canonical solution to this FAQ.

Hello everybody,

thanks for the various answers. I'm actually pretty puzzled because I
expected to see some obvious solution that I just hadn't found before.
In general I find Python more elegant and syntactically richer than C
(that's where I come from), so I didn't expect the solutions to be a
lot more verbose and/or ugly (no offense) than the original idea which
would have worked if Python's assignment statement would double as
expression, as in C.

Thanks again,
robert

PS: Since I'm testing only three REs, and I only need the match
results from one of them, I just re-evaluate that one.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Database Query Contains Old Data

2008-05-21 Thread giraffeboy
On May 21, 1:49 pm, "Jerry Hill" <[EMAIL PROTECTED]> wrote:

> Did you remember to commit your changes before re-running the report?
> Python's DB API requires that any auto-commit feature of the
> underlying database be turned off by default, so you are required to
> commit changes yourself.  If you're used to having auto-commit turned
> on, this can be confusing.

I did and I confirmed this by modifying the data, selecting it from
the mysql command line client to verify the changes, then running the
report again. If I exit the application and then start it again,
everything works as expected until the second instance of the report
is run. I have a feeling it has something to do with there already
being an instance of the report class, but I can't work out how to
destroy it and aren't really sure how to remove the references to it
either. I added a print statement to the code and it displays a row
that doesn't exist any more. Code, output of print statement and
result from the mysql client shown below.

Andrew


Code:
#Get all the mileages and add them together for the month:
curs.execute('SELECT date, mileage, name FROM mileage, agents WHERE
mileage.agent = agent.rowid AND date >= CAST(%s AS DATE) AND date <
CAST(%s AS DATE) AND mileage.agent=%s ORDER BY date', (fromdate,
todate, agentid))
for row in curs:
   month = str(row[0])[:7]
   print row[1], month

Output:
100.0 2008-03

MySQL Output just prior to running the report:
mysql> select * from mileage;
+---++-+-+---+
| rowid | date   | mileage | vehicle | agent |
+---++-+-+---+
| 1 | 2008-04-28 |  875.63 |   3 | 3 |
| 2 | 2008-04-28 | 1188.13 |   6 | 6 |
| 3 | 2008-04-28 |  676.88 |   4 | 4 |
| 4 | 2008-04-21 | .25 |   6 | 6 |
| 5 | 2008-04-21 | 1126.88 |   3 | 3 |
| 6 | 2008-04-28 | 1029.38 |   7 | 8 |
| 7 | 2008-04-21 |  953.13 |   7 | 8 |
| 8 | 2008-04-21 |  675.63 |   4 | 4 |
| 9 | 2008-04-14 |  891.88 |   3 | 3 |
+---++-+-+---+
9 rows in set (0.00 sec)

As you can see there's no row with a mileage of 100 with the correct
month.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Print HTML from Python

2008-05-21 Thread Mike Driscoll
On May 21, 3:45 am, "Jorgen Bodde" <[EMAIL PROTECTED]> wrote:
> Hi All,
>
> I am at a loss. This is slightly OT because it concerns Windows and
> HTML printing. I would like to print a HTML document from Python, but
> not showing the printing dialog. After numerous searches and trials I
> came to the conclusion that ShellExecute with the "print" command and
> a HTML document simply always shows a print dialog, so that road is a
> dead end (or unless someone can show me a snippet that does work).
>
> I used win32com and I am able to print through he internet explorer
> interface which seems to work, but quite unreliably. When I execute
> the scipt too fast, nothing is printed at all. The method isBusy that
> IE exposes through COM always returns False so there is no way to wait
> reliably on the progress of the printer.
>
> So basically my question is, does someone know a python lib or way to
> print HTML to the default printer (I can get the printer name so even
> that is not really needed) without showing the print dialog?
>
> With regards,
> - Jorgen


Did you try all the methods on Tim Golden's site?

http://timgolden.me.uk/python/win32_how_do_i/print.html

I use the one at the bottom for PDFs. I never see a print dialog, but
it does leave Adobe running. If you're printing from Internet
Explorer, you might look at the PAMIE project.

http://pamie.sourceforge.net/

HTH

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


Re: C-like assignment expression?

2008-05-21 Thread cokofreedom
On May 21, 3:12 pm, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> On May 21, 1:47 pm, Hrvoje Niksic <[EMAIL PROTECTED]> wrote:
>
> > Although that solution is pretty, it is not the canonical solution
> > because it doesn't cover the important case of "if" bodies needing to
> > access common variables in the enclosing scope.  (This will be easier
> > in Python 3 with 'nonlocal', though.)  The snippet posted by Diez is
> > IMHO closer to a canonical solution to this FAQ.
>
> Hello everybody,
>
> thanks for the various answers. I'm actually pretty puzzled because I
> expected to see some obvious solution that I just hadn't found before.
> In general I find Python more elegant and syntactically richer than C
> (that's where I come from), so I didn't expect the solutions to be a
> lot more verbose and/or ugly (no offense) than the original idea which
> would have worked if Python's assignment statement would double as
> expression, as in C.
>
> Thanks again,
> robert
>
> PS: Since I'm testing only three REs, and I only need the match
> results from one of them, I just re-evaluate that one.

Is it really a lot to change to have it

if my_re1.match(line):
  match = my_re1.match(line)
elseif my_re2.match(line):
  match = my_re2.match(line)
elseif my_re3.match(line):
  match = my_re3.match(line)

?

That reads clearly to me...
--
http://mail.python.org/mailman/listinfo/python-list


Re: Publish a program

2008-05-21 Thread TheSaint
On 18:15, mercoledì 21 maggio 2008 alex23 wrote:

> On May 21, 7:52 pm, TheSaint <[EMAIL PROTECTED]> wrote:

> There's also http://python.pastebin.com, which lets you create a new
> paste by modifying an existing one, and keeps them linked for easy
> diff'ing.
> 
> Sample: http://python.pastebin.com/d3964b241

Thank you for the reply :)
In my case, it's rather a set of modules which trying to remove spam from the
mailbox(es) either by POP3 or IMAP4 according regex criteria.
The project is working quiet good, the most advantage is that it downloads
only the header for speed needs. Some time I'm doing it by GPRS in roaming
and volume it _matters_ much.
I simply like that somebody will express some opinion about my job, as
meaning of teaching me better. After all that's what I'm trying to do ;)

Other idea, I'll apreciate somebody to join and put new views on this
project.



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

Re: C-like assignment expression?

2008-05-21 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

> On May 21, 1:47 pm, Hrvoje Niksic <[EMAIL PROTECTED]> wrote:
> 
>> Although that solution is pretty, it is not the canonical solution
>> because it doesn't cover the important case of "if" bodies needing to
>> access common variables in the enclosing scope.  (This will be easier
>> in Python 3 with 'nonlocal', though.)  The snippet posted by Diez is
>> IMHO closer to a canonical solution to this FAQ.
> 
> Hello everybody,
> 
> thanks for the various answers. I'm actually pretty puzzled because I
> expected to see some obvious solution that I just hadn't found before.
> In general I find Python more elegant and syntactically richer than C
> (that's where I come from), so I didn't expect the solutions to be a
> lot more verbose and/or ugly (no offense) than the original idea which
> would have worked if Python's assignment statement would double as
> expression, as in C.

Well, it's a design-decision - and I'm pretty ok with it being a bit verbose
here - as it prevents a *great* deal of programming errors that would
otherwise happen from accidentally writing a = b where a == b was meant.

One could argue that regular expressions - which seem to be THE case where
it bugs people - should offer a standard way that essentially works as my
solution - by keeping state around, making series of tests easier.


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


Re: C-like assignment expression?

2008-05-21 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

> On May 21, 3:12 pm, "[EMAIL PROTECTED]"
> <[EMAIL PROTECTED]> wrote:
>> On May 21, 1:47 pm, Hrvoje Niksic <[EMAIL PROTECTED]> wrote:
>>
>> > Although that solution is pretty, it is not the canonical solution
>> > because it doesn't cover the important case of "if" bodies needing to
>> > access common variables in the enclosing scope.  (This will be easier
>> > in Python 3 with 'nonlocal', though.)  The snippet posted by Diez is
>> > IMHO closer to a canonical solution to this FAQ.
>>
>> Hello everybody,
>>
>> thanks for the various answers. I'm actually pretty puzzled because I
>> expected to see some obvious solution that I just hadn't found before.
>> In general I find Python more elegant and syntactically richer than C
>> (that's where I come from), so I didn't expect the solutions to be a
>> lot more verbose and/or ugly (no offense) than the original idea which
>> would have worked if Python's assignment statement would double as
>> expression, as in C.
>>
>> Thanks again,
>> robert
>>
>> PS: Since I'm testing only three REs, and I only need the match
>> results from one of them, I just re-evaluate that one.
> 
> Is it really a lot to change to have it
> 
> if my_re1.match(line):
>   match = my_re1.match(line)
> elseif my_re2.match(line):
>   match = my_re2.match(line)
> elseif my_re3.match(line):
>   match = my_re3.match(line)
> 
> ?
> 
> That reads clearly to me...

And wastes time. regular expressions can become expensive to match - doing
it twice might be hurtful.

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


Re: C-like assignment expression?

2008-05-21 Thread cokofreedom
>
> And wastes time. regular expressions can become expensive to match - doing
> it twice might be hurtful.
>
> Diez

match = (my_re1.match(line) or my_re2.match(line)) or
my_re3.match(line)

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


Re: problem with import / namespace

2008-05-21 Thread Laszlo Nagy

ohad frand wrote:

Hi
I have a problem that the solution to it must be very simple but i 
couldnt fint it's answer in the internet so far (i searched for couple 
of days)

the problme is as follows:

i have two directories e.g. "\\1" and "\\2"
in each directory i have two files with the same names e.g. "tmp1.py" 
and "tmp2.py"


So this is what you have:

/1/tmp1.py
/1/tmp2.py
/2/tmp1.py
/2/tmp2.py

each tmp2.py file imports tmp1 from its same directory (import tmp1) - 
thats the problem

if i execute one file (\\1\tmp2.py) than the execution is ok
but when i try after that to execute the second file (\\2\tmp2.py) 
than the tmp1 file from the wrong directory ( - directory 1 in this 
case) is imported instead.


When you try to import a module, python starts to search for it. The was 
it does the search is very well defined. It mostly depends on the 
current directory and sys.path. You can read more about this here:


http://docs.python.org/tut/node8.html#searchPath

This is very basic thing - you should read and go through the tutorial 
before asking questions like this. :-)


i tried many things to try to solve it, i removed the previous path 
from sys.path and added the new one, i tried to change current working 
directory with os.chdir()
I tried to delete from locals and from globals the name tmp1 before 
running the second file but nothing worked.

please help
The problem is still not well defined. Python works as expected and 
documented, but apparently you do not know how to import 1/tmp2.py from 
2/tmp1.py.  There are several ways to do it, and we cannot tell which 
one is correct. It depends on what are these modules for.


Here are the solution that you would use (most likely) as a beginner:


#1 first, rename your "1" and "2" directories to "one" and "two". If you 
are creating a package with modules, then you have to define the 
package's name with its directory. Since identifiers cannot begin with 
digits in Python, you need to use an identifier-like name for your 
subdirs. It is a good idea anyway. A package name called "1" would tell 
nothing about what it does?

#2 place your main application in /app/app.py
#3 create /app/one/__init__.py and /app/two/__init__.py files (they can 
be empty)
- inside your app.py file either make sure that the current dir is /app, 
or insert /app in the first place in sys.path



Then for example, inside two/tmp1.py you can do this:


import one.tmp1
import one.tmp2
import two.tmp1

one.tmp1.somefunc()
two.tmp1.somefunc()


You got the idea.

   Laszlo


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


Re: Struct usage and varying sizes of h, l, etc

2008-05-21 Thread Grant Edwards
On 2008-05-20, Robert Kern <[EMAIL PROTECTED]> wrote:

>> I'm looking at the struct module for binary packing of ints
>> and floats.  The documentation refers to C datatypes.  It's
>> been many years since I looked at C, but I seem to remember
>> that the data type sizes were not fixed -- for example, an int
>> might be two byes on one machine, and four bytes on the next.
>> Can any C programmers verify this?  If it is true, does that
>> mean that struct.pack('h', 8001) might give me different 
>> results depending on the machine it's running on?
>
> Right. I believe (but could be wrong) that "char" is defined
> to be one byte,

Yes, C defines "char" to be one byte, but it doesn't define the
size of a "byte" other than it's at least big enough to hold
one character (or something like that).  In practice, a byte is
pretty much guaranteed to be at least 8 bits.  But, on some
targets a "byte" is 16 bits, and on others a byte is 32 bits.

However, I'm not aware of any Python implementations on those
targets...

-- 
Grant Edwards   grante Yow! Clear the laundromat!!
  at   This whirl-o-matic just had
   visi.coma nuclear meltdown!!
--
http://mail.python.org/mailman/listinfo/python-list


Re: C-like assignment expression?

2008-05-21 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

>>
>> And wastes time. regular expressions can become expensive to match -
>> doing it twice might be hurtful.
>>
>> Diez
> 
> match = (my_re1.match(line) or my_re2.match(line)) or
> my_re3.match(line)

How do you know *which* of the three has matched then?

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


Re: Showing the method's class in expection's traceback

2008-05-21 Thread Bruno Desthuilliers

Richard G Riley a écrit :

Bruno Desthuilliers <[EMAIL PROTECTED]> writes:


(snip)


And not that useful - why would one care about the function being
defined in class X or Y when one have the exact file and line ?


Very obvious I would think. One can develop ones own interactive class
browser and code navigator.


From the traceback ?


 One can not bring up class help from "line 3
in x.py" but one can from "classname : MyClass at line 2 in z.py". With
the class name I can navigate directly to all sorts of class related
information without the need to delve into a physical usage of it e.g
program.py at line 3.


Please bear with me, but I'm afraid I still don't get the point : I 
don't need tracebacks to get to some object's info (help etc).


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

Re: Database Query Contains Old Data

2008-05-21 Thread Paul Boddie
On 21 Mai, 15:22, [EMAIL PROTECTED] wrote:
>
> I did and I confirmed this by modifying the data, selecting it from
> the mysql command line client to verify the changes, then running the
> report again. If I exit the application and then start it again,
> everything works as expected until the second instance of the report
> is run.

Note that if you have a connection open in your program, especially if
that connection has already been used to select data, it may be the
case that you then have to perform a rollback or commit before
attempting to access newly added data. The reason for this behaviour
is that the DB-API modules will have begun a transaction on your
behalf, and while that transaction is open, changes committed in other
transactions may be unavailable to your own transaction, depending on
the transaction isolation level.

MySQL appears to use "repeatable read" by default [1] as its
transaction isolation level, whereas PostgreSQL (for example) uses
"read committed" by default [2]. I would guess that if you were using
PostgreSQL, this particular problem would not have occurred, but there
are other reasons to be aware of the effects of long duration
transactions in PostgreSQL, and the practice of periodically
performing a rollback would still be worth considering with that
database system.

Paul

[1] http://dev.mysql.com/doc/refman/5.1/en/innodb-transaction-isolation.html
[2] http://www.postgresql.org/docs/8.1/interactive/transaction-iso.html
--
http://mail.python.org/mailman/listinfo/python-list


Code For Five Threads To Process Multiple Files?

2008-05-21 Thread tdahsu
All,

I'd appreciate any help.  I've got a list of files in a directory, and
I'd like to iterate through that list and process each one.  Rather
than do that serially, I was thinking I should start five threads and
process five files at a time.

Is this a good idea?  I picked the number five at random... I was
thinking that I might check the number of processors and start a
multiple of that, but then I remembered KISS and it seemed that that
was too complicated.

If it's not a horrible idea, would anyone be able to provide some
quick code as to how to do that?  Any and all help would be greatly
appreciated!

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


how to proccess the blank in the path on linux

2008-05-21 Thread zhf
I want ro walk a directory and its sub directory on linux,
to find some shell script file, and run them, but I found some path belong
blank charactor, such as '8000 dir', if I write as follow, I got error
"no such file"
path = '8000 dir'
for root, dirs, files in os.walk(path):
cmd = ' '
cmd = 'cd ' + root
os.system(cmd)

How can I repair it?

thanks, best regards.



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


Re: Showing the method's class in expection's traceback

2008-05-21 Thread Richard G Riley
Bruno Desthuilliers <[EMAIL PROTECTED]> writes:

> Richard G Riley a écrit :
>> Bruno Desthuilliers <[EMAIL PROTECTED]> writes:
>
> (snip)
>
>>> And not that useful - why would one care about the function being
>>> defined in class X or Y when one have the exact file and line ?
>>
>> Very obvious I would think. One can develop ones own interactive class
>> browser and code navigator.
>
> From the traceback ?
>
>>  One can not bring up class help from "line 3
>> in x.py" but one can from "classname : MyClass at line 2 in z.py". With
>> the class name I can navigate directly to all sorts of class related
>> information without the need to delve into a physical usage of it e.g
>> program.py at line 3.
>
> Please bear with me, but I'm afraid I still don't get the point : I
> don't need tracebacks to get to some object's info (help etc).

This is a view quite common to people when they are happy with what they
have. Some like to improve what they have. It is immediately apparent to
me why having a class name and method name in the traceback would be
immediately useful. Having written a few extensions to IDEs in the past
I know it would help me, and I suspect, the original poster. As a recent
"recruit" to Python I am quite surprised as how poor most of the query
like tools in the python shell are. The first thing I did was to move to
iPython. Still, horses for courses.


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

Re: C-like assignment expression?

2008-05-21 Thread cokofreedom
On May 21, 4:09 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
>
> >> And wastes time. regular expressions can become expensive to match -
> >> doing it twice might be hurtful.
>
> >> Diez
>
> > match = (my_re1.match(line) or my_re2.match(line)) or
> > my_re3.match(line)
>
> How do you know *which* of the three has matched then?
>
> Diez

Depends if the OP wants to know that...
--
http://mail.python.org/mailman/listinfo/python-list


Re: problem with import / namespace

2008-05-21 Thread Laszlo Nagy




When you try to import a module, python starts to search for it. The 
was it does the search is very well defined. It mostly depends on the 
current directory and sys.path. You can read more about this here:

"The was it" -> "The way it"
- inside your app.py file either make sure that the current dir is 
/app, or insert /app in the first place in sys.path

Example:

import os,sys
mydir = os.split(os.abspath(__file__)[0]
os.chdir(mydir) # Option 1 - chdir to dir. containing your app
sys.path.insert(0,mydir) # Option 2 - add to your sys.path

Good things to know:

- In Python, it is recommended not to use upper case module/package 
names. It is a convention. However, some 3rd party packages (like 
wxPython or PIL) break this rule.
- Obviously, you should not use numbers, reserved words for module or 
package names. The name should tell what is it for.
- It is good to know the standard library, and avoid overwriting names 
from the standard lib. For example, you can create your own 'os.py' 
module but it would be very silly.


I personally tend to use absolute package names for libraries that are 
not tied to a specific project but it does not need to be that way.


You can find many threads in python-list about how applications and 
packages should be constructed.


Best,

  Laszlo

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


Re: Showing the method's class in expection's traceback

2008-05-21 Thread Bruno Desthuilliers

Richard G Riley a écrit :

Bruno Desthuilliers <[EMAIL PROTECTED]> writes:


Richard G Riley a écrit :

Bruno Desthuilliers <[EMAIL PROTECTED]> writes:

(snip)


And not that useful - why would one care about the function being
defined in class X or Y when one have the exact file and line ?

Very obvious I would think. One can develop ones own interactive class
browser and code navigator.

From the traceback ?


 One can not bring up class help from "line 3
in x.py" but one can from "classname : MyClass at line 2 in z.py". With
the class name I can navigate directly to all sorts of class related
information without the need to delve into a physical usage of it e.g
program.py at line 3.

Please bear with me, but I'm afraid I still don't get the point : I
don't need tracebacks to get to some object's info (help etc).


This is a view quite common to people when they are happy with what they
have. Some like to improve what they have. It is immediately apparent to
me why having a class name and method name in the traceback would be
immediately useful.


Then please explain.


Having written a few extensions to IDEs in the past
I know it would help me,


To do what ?

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

Re: problem with import / namespace

2008-05-21 Thread ohad frand
Hi
Thanks for the answer.
I probably didnt write the problem accurately but it is not as you
described.
(i already read before the section that you pointed and it didnt help me)
the problem is that i dont want to import a file from different directory
but only from the same directory.
\\1\tmp2.py imports \\1\tmp1.py
\\2\tmp2.py imports \\2\tmp2.py
but when i execute the following script in the interpreter i get that the
second tmp2.py file imports not the file from the same directory but the
file that was already imported by the first executed tmp2.py file.
the shell script is:
>>> import os
>>> os.chdir("c:\\1")
>>> execfile("tmp2.py") <- here the executaion is OK
>>> os.chdir("c:\\2")
>>> execfile("tmp2.py") <- here the execution is not ok because tmp2.py file
imports the tmp1.py file from c:\\1 which is not OK

in between those two execfile commands i tried to do a lot of things but
every time python imported the incorrect file for the second execution. (i
am not building a package and those names are just examples for the problem,
i am not really using 1 and 2 names as dirs)

I hope that this time i am more understood

Thanks again
Ohad


On Wed, May 21, 2008 at 4:46 PM, Laszlo Nagy <[EMAIL PROTECTED]> wrote:

> ohad frand wrote:
>
>> Hi
>> I have a problem that the solution to it must be very simple but i couldnt
>> fint it's answer in the internet so far (i searched for couple of days)
>> the problme is as follows:
>>
>> i have two directories e.g. "\\1" and "\\2"
>> in each directory i have two files with the same names e.g. "tmp1.py" and
>> "tmp2.py"
>>
>
> So this is what you have:
>
> /1/tmp1.py
> /1/tmp2.py
> /2/tmp1.py
> /2/tmp2.py
>
>  each tmp2.py file imports tmp1 from its same directory (import tmp1) -
>> thats the problem
>> if i execute one file (\\1\tmp2.py) than the execution is ok
>> but when i try after that to execute the second file (\\2\tmp2.py) than
>> the tmp1 file from the wrong directory ( - directory 1 in this case) is
>> imported instead.
>>
>
> When you try to import a module, python starts to search for it. The was it
> does the search is very well defined. It mostly depends on the current
> directory and sys.path. You can read more about this here:
>
> http://docs.python.org/tut/node8.html#searchPath
>
> This is very basic thing - you should read and go through the tutorial
> before asking questions like this. :-)
>
>  i tried many things to try to solve it, i removed the previous path from
>> sys.path and added the new one, i tried to change current working directory
>> with os.chdir()
>> I tried to delete from locals and from globals the name tmp1 before
>> running the second file but nothing worked.
>> please help
>>
> The problem is still not well defined. Python works as expected and
> documented, but apparently you do not know how to import 1/tmp2.py from
> 2/tmp1.py.  There are several ways to do it, and we cannot tell which one is
> correct. It depends on what are these modules for.
>
> Here are the solution that you would use (most likely) as a beginner:
>
>
> #1 first, rename your "1" and "2" directories to "one" and "two". If you
> are creating a package with modules, then you have to define the package's
> name with its directory. Since identifiers cannot begin with digits in
> Python, you need to use an identifier-like name for your subdirs. It is a
> good idea anyway. A package name called "1" would tell nothing about what it
> does?
> #2 place your main application in /app/app.py
> #3 create /app/one/__init__.py and /app/two/__init__.py files (they can be
> empty)
> - inside your app.py file either make sure that the current dir is /app, or
> insert /app in the first place in sys.path
>
>
> Then for example, inside two/tmp1.py you can do this:
>
>
> import one.tmp1
> import one.tmp2
> import two.tmp1
>
> one.tmp1.somefunc()
> two.tmp1.somefunc()
>
>
> You got the idea.
>
>   Laszlo
>
>
>
--
http://mail.python.org/mailman/listinfo/python-list

Re: about python modules

2008-05-21 Thread inhahe
i always just put most of my python files in the c:\python25 directory. 
including ones i want to import as modules, since they import from there. 
otherwise you can put the file in c:\python25\lib\site-packages

"srinivas" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> hi friends i am new to python programming.
> i am using Python 2.5 and IDLE as editor.
> i have developed some functions in python those will be calling
> frequently in my main method .
> now i want to know how to import my functions folder to python in
> sucha way that the functions in functions folder should work like
> python library modules .
>
> i have  python in folder C:\python25\..
> and functions folder D:\programs\Functions\
>
> pls help me friends how to do that. 


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


Re: Python and Flaming Thunder

2008-05-21 Thread Dave Parker
> Personally (and borrowing from Python), I'd prefer something more
> like:
>
> Write "Fa".
> Repeat 8 times:
> Write "-la".

I actually kind of prefer that, too.  Or

Repeat 8 times write "-la".

I'll think about it.  Thank you for suggesting it.

On May 20, 3:40 pm, MRAB <[EMAIL PROTECTED]> wrote:
> On May 20, 4:20 am, Dave Parker <[EMAIL PROTECTED]> wrote:
>
>
>
> > > > I <[EMAIL PROTECTED]> wrote:
> > > > Plus, me getting paid to work on Flaming Thunder is far more
> > > > motivating than me not getting paid to work on Python.
> > > On May 14, 8:30 pm, John Salerno <[EMAIL PROTECTED]> wrote:
> > > That's truly disappointing.
>
> > I guess I could have stated that better.  Flaming Thunder is a labor
> > of love for me.  I've programmed in almost every language since
> > FORTRAN and Lisp, and Flaming Thunder is the language I've always
> > wished the others were.
>
> > For one example, I've always preferred compiled languages because
> > they're faster.  So Flaming Thunder is compiled.
>
> > For another example, I've always preferred languages that are English-
> > like because it's easier to return to your code after several years
> > and still know what you were doing (and it's easier for someone else
> > to maintain your code).
>
> > For over 5 years I've been working on Flaming Thunder unpaid and on my
> > own, getting the back-end up and running.  8-by-8 shotgun cross
> > compilers written in assembly language, that can fit all of the
> > libraries for both the 32- and 64-bit versions of FreeBSD, Linux, Mac
> > OS X and Windows into a single executable file that's less than 180K,
> > aren't written overnight.
>
> > So now that I've released it, it's extremely gratifying that people
> > think it's cool enough to actually pay $19 for it.  That gives me lots
> > of motivation (and buys enough time) for me to add features to it as
> > fast as possible.
>
> > To whit: you pointed out the awkwardness in Python of having to
> > declare a for-loop variable when you only wanted to loop a specific
> > number of times and didn't need the variable.  Last week, Flaming
> > Thunder had the same awkwardness.  If you wanted to loop 8 times:
>
> > for i from 1 to 8 do 
>
> > you still had to use a variable (in this case, i).  This week, I've
> > added two new for-loop variations that fix that awkwardness, and also
> > allow you to explicitly declare an infinite loop without having to
> > rely on idiomatic constructs such as while-true.  Examples of the two
> > new variations (for-forever and for-expression-times):
>
> > Write "Fa".
> > For 8 times do write "-la".
>
> Personally (and borrowing from Python), I'd prefer something more
> like:
>
> Write "Fa".
> Repeat 8 times:
>     Write "-la".
>
> > For forever do
> >   (
> >   Write "Do you know the definition of insanity? ".
> >   Read response.
> >   ).
>
> Repeat:
>     Write "Do you know the definition of insanity? ".
>     Read response.- Hide quoted text -
>
> - Show quoted text -

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


Re: C-like assignment expression?

2008-05-21 Thread inhahe
one of the few things i miss from C is being able to use assignment in 
expressions.   that's the only thing, really.
also there's no switch/case, you have to use a dictionary of functions 
instead, although i rarely need that, usually i just use elif.

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> On May 21, 1:47 pm, Hrvoje Niksic <[EMAIL PROTECTED]> wrote:
>
>> Although that solution is pretty, it is not the canonical solution
>> because it doesn't cover the important case of "if" bodies needing to
>> access common variables in the enclosing scope.  (This will be easier
>> in Python 3 with 'nonlocal', though.)  The snippet posted by Diez is
>> IMHO closer to a canonical solution to this FAQ.
>
> Hello everybody,
>
> thanks for the various answers. I'm actually pretty puzzled because I
> expected to see some obvious solution that I just hadn't found before.
> In general I find Python more elegant and syntactically richer than C
> (that's where I come from), so I didn't expect the solutions to be a
> lot more verbose and/or ugly (no offense) than the original idea which
> would have worked if Python's assignment statement would double as
> expression, as in C.
>
> Thanks again,
> robert
>
> PS: Since I'm testing only three REs, and I only need the match
> results from one of them, I just re-evaluate that one. 


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


Re: how to proccess the blank in the path on linux

2008-05-21 Thread A.T.Hofkamp
On 2008-05-21, zhf <[EMAIL PROTECTED]> wrote:
> I want ro walk a directory and its sub directory on linux,
> to find some shell script file, and run them, but I found some path belong
> blank charactor, such as '8000 dir', if I write as follow, I got error
> "no such file"
> path = '8000 dir'
> for root, dirs, files in os.walk(path):
> cmd = ' '
> cmd = 'cd ' + root
> os.system(cmd)
>
> How can I repair it?

Escape the space to prevent the shell from interpreting it as a word seperator.
This of course also holds for all other shell meta characters,
such as * [ ] \ > < & and a few others I probably have forgotten.


I am not sure why you execute 'cd' commands in a sub-shell, as it is not very
useful. (that is, you start a new sub-process, in that sub-process you run the
'cd' command (causing the cwd of the sub-process to change directory), and then
the sub-process ends)

You most likely want to change the cwd of the Python process. If so, have a
look at os.chdir(). That function has the added advantage that there is no
shell in between that interprets all those meta characters (that is,
"os.chdir('8000 dir')" will work without further effort).

Sincerely,
Albert
--
http://mail.python.org/mailman/listinfo/python-list


Re: C-like assignment expression?

2008-05-21 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

> On May 21, 4:09 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
>> [EMAIL PROTECTED] wrote:
>>
>> >> And wastes time. regular expressions can become expensive to match -
>> >> doing it twice might be hurtful.
>>
>> >> Diez
>>
>> > match = (my_re1.match(line) or my_re2.match(line)) or
>> > my_re3.match(line)
>>
>> How do you know *which* of the three has matched then?
>>
>> Diez
> 
> Depends if the OP wants to know that...

Well, in *general* one wants that. So as a general-purpose solution this is
certainly *not* the way to go.

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


Re: how to proccess the blank in the path on linux

2008-05-21 Thread Jeremy Sanders
A.T.Hofkamp wrote:

> Escape the space to prevent the shell from interpreting it as a word
> seperator. This of course also holds for all other shell meta characters,
> such as * [ ] \ > < & and a few others I probably have forgotten.

If the command was useful (unlike cd), it might be better to use subprocess
to launch it so that you don't need the escaping:

subprocess.call(['ls', '8000 dir'])

This avoids using the shell.

-- 
Jeremy Sanders
http://www.jeremysanders.net/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Code For Five Threads To Process Multiple Files?

2008-05-21 Thread A.T.Hofkamp
On 2008-05-21, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> I'd appreciate any help.  I've got a list of files in a directory, and
> I'd like to iterate through that list and process each one.  Rather
> than do that serially, I was thinking I should start five threads and
> process five files at a time.
>
> Is this a good idea?  I picked the number five at random... I was

Depends what you are doing.
If you are mainly reading/writing files, there is not much to gain, since 1
process will already push the disk IO system to its limit. If you do a lot of
processing, then more threads than the number of processors is not much use. If
you have more 'burtsy' behavior (first do lot of reading, then lot of
processing, then again reading, etc), then the system may be able to do some
scheduling and keep both the processors and the file system busy.

I cannot really give you advice on threading, I have never done that. You may
want to consider an alternative, namely multi-tasking at OS level. If you can
easily split the files over a number of OS processes (written in Python), you
can make the Python program really simple, and let the OS handle the
task-switching between the programs.

Sincerely,
Albert
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Flaming Thunder

2008-05-21 Thread Dave Parker
> Or just:
>
> If command is "quit" ...

Hmmm.  In Flaming Thunder, I'm using "is" (and "is an", "is a", etc)
for assigning and checking types.  For example, to read data from a
file and check for errors:

 Read data from "input.txt".
 If data is an error then go to ...

Or when assigning a type to an identifier:

 HarmonicMean is a function(x, y) ...
 LoopCount is a variable ...

By using = only for equality and "is" only for types, the Flaming
Thunder compiler can detect when either is being used incorrectly
because the syntax for the two is incompatible.  That avoids the man-
years of wasted debugging time spent on languages that accept
statements that are easily confused, yet syntactically valid (e.g. the
confusion between = and == in C if-statments, or the confusion between
= (equality) and "is" (identity) in Python).

On May 20, 3:41 pm, MRAB <[EMAIL PROTECTED]> wrote:
> On May 20, 4:33 am, Dave Parker <[EMAIL PROTECTED]> wrote:
>
>
>
> > On May 14, 7:59 pm, John Salerno <[EMAIL PROTECTED]> wrote:
>
> > > Would it be valid to say:
>
> > > x = "concrete"
>
> > > or to say:
>
> > > if command (is) set to "quit"
>
> > > ??
>
> > I like the idea of:
>
> > If command is set to "quit" ...
>
> Or just:
>
> If command is "quit" ...
>
>
>
> > I've added it to my list of things to think about, and possibly
> > implement.- Hide quoted text -
>
> - Show quoted text -- Hide quoted text -
>
> - Show quoted text -

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


Re: compressing short strings?

2008-05-21 Thread inhahe
i don't see anybody mentioning huffman encoding.  i think it just works per 
byte, so it's not as tight as gzip or whatever.  but it sounds like it would 
be easy to implement and wouldn't require any corpus-wide compression 
information. except a character frequency count if you wanted to be optimal.



"Paul Rubin"  wrote in message 
news:[EMAIL PROTECTED]
>I have a lot of short English strings I'd like to compress in order to
> reduce the size of a database.  That is, I'd like a compression
> function that takes a string like (for example) "George Washington"
> and returns a shorter string, with luck maybe 6 bytes or so.  One
> obvious idea is take the gzip function, compress some large text
> corpus with it in streaming mode and throw away the output (but
> setting up the internal state to model the statistics of English
> text), then put in "George Washington" and treat the additional output
> as the compressed string.  Obviously to get reasonable speed there
> would have to be a way to save the internal state after initializing
> from the corpus.
>
> Anyone know if this has been done and if there's code around for it?
> Maybe I'm better off with freezing a dynamic Markov model?  I think
> there's DMM code around but am not sure where to look.
>
> Thanks. 


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


Re: C-like assignment expression?

2008-05-21 Thread cokofreedom
On May 21, 4:57 pm, "inhahe" <[EMAIL PROTECTED]> wrote:
> one of the few things i miss from C is being able to use assignment in
> expressions.   that's the only thing, really.
> also there's no switch/case, you have to use a dictionary of functions
> instead, although i rarely need that, usually i just use elif.

One thing I hate from C is the assignment in expressions...Forcing
myself to write
0 == Something
rather than
Something == 0
just to make sure I was mistakenly assigning values in statements is
annoying, it ruins the ease of reading.

I kind of agree with the select:case, but I think a key issue is how
to implement it. Elif is reasonable for now.

Diez, true I guess, but then we haven't seen what these expressions
are, and why there has to be three.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python and Flaming Thunder

2008-05-21 Thread Bruno Desthuilliers

Dave Parker a écrit :

Or just:

If command is "quit" ...


Hmmm.  In Flaming Thunder, I'm using "is" (and "is an", "is a", etc)
for assigning and checking types.  For example, to read data from a
file and check for errors:

 Read data from "input.txt".
 If data is an error then go to ...


Arf ! A goto !


Or when assigning a type to an identifier:

 HarmonicMean is a function(x, y) ...
 LoopCount is a variable ...

By using = only for equality and "is" only for types, the Flaming
Thunder compiler can detect when either is being used incorrectly
because the syntax for the two is incompatible.  That avoids the man-
years of wasted debugging time spent on languages that accept
statements that are easily confused, yet syntactically valid (e.g. the
confusion between = and == in C if-statments, or the confusion between
= (equality) and "is" (identity) in Python).



Actually in Python the equality test is '==', not '='. And since 
Python's types are objects - which is *definitively* a GoodThing(tm) in 
an OOPL -, your point here is moot.


Also, you're overloading the meaning of 'is', which *is* (pun intented) 
confusing too.

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


Re: C-like assignment expression?

2008-05-21 Thread Paul McGuire
On May 21, 9:09 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
>
> >> And wastes time. regular expressions can become expensive to match -
> >> doing it twice might be hurtful.
>
> >> Diez
>
> > match = (my_re1.match(line) or my_re2.match(line)) or
> > my_re3.match(line)
>
> How do you know *which* of the three has matched then?
>
> Diez

Since the OP is processing alternative regexp's, he may be drifting
close to parsing territory.  Here is a pyparsing example showing how
to match one of 'n' alternatives, and then apply functional logic
depending on which expression was matched.  This example actually
shows 4 ways to address this question (in roughly increasing order of
OO-ness):
- explicit if/elif/... test on the name of the specific match to see
which alternative matched
- more Pythonic dispatch using a dict of names and corresponding
expression processing functions
- parse-time processing using pyparsing parse actions
- parse actions invoke class constructors, to return expression-
specific objects

-- Paul


from pyparsing import oneOf, Combine, Optional, Word, \
alphas, nums, alphanums, QuotedString

# define basic expressions
sign = oneOf("+ -")
integer = Combine(Optional(sign) + Word(nums))
real = Combine(Optional(sign) + Word(nums) + "." +
Optional(Word(nums)))
name = Word(alphas,alphanums) | QuotedString("'")

# define alternates with results names
item = real("real") | integer("integer") | name("name")

print "\nUse results names to determine which pattern matched"
for it in item.searchString("abc 123 -3.14 'phase of the moon'"):
if it.getName() == "real":
print "Real:", (float(it[0]))
elif it.getName() == "integer":
print "Int:", (int(it[0]))
else:
print "String:", it[0]


print "\nUse dict to dispatch to type-specific functions " \
   "- more Pythonically canonical"
def processRealItem(it):
print "Real:", (float(it[0]))

def processIntegerItem(it):
print "Int:", (int(it[0]))

def processNameItem(it):
print "String:", it[0]

for it in item.searchString("abc 123 -3.14 'phase of the moon'"):
{"real": processRealItem,
 "integer" : processIntegerItem,
 "name": processNameItem }[it.getName()](it)


print "\nMove expression-specific logic into parse-time parse actions"
def convertInt(t):
return int(t[0])
def convertReal(t):
return float(t[0])
integer.setParseAction(convertInt)
real.setParseAction(convertReal)
item = real("real") | integer("integer") | name("name")

for it in item.searchString("abc 123 -3.14 'phase of the moon'"):
print "%s: %s %s" % (it.getName(), it[0], type(it[0]))


print "\nUse class constructors as parse-time parse actions " \
  "- results names no longer needed"
class IntObject(object):
def __init__(self,t):
self.type, self.value = "Int", int(t[0])
class RealObject(object):
def __init__(self,t):
self.type, self.value = "Real", float(t[0])
class StringObject(object):
def __init__(self,t):
self.type, self.value = "String", t[0]
integer.setParseAction(IntObject)
real.setParseAction(RealObject)
name.setParseAction(StringObject)
item = real | integer | name

for it in item.searchString("abc 123 -3.14 'phase of the moon'"):
print "%s: %s (%s)" % (it[0].type, it[0].value,
it[0].__class__.__name__)


Prints:

Use results names to determine which pattern matched
String: abc
Int: 123
Real: -3.14
String: phase of the moon

Use dict to dispatch to type-specific functions - more Pythonically
canonical
String: abc
Int: 123
Real: -3.14
String: phase of the moon

Move expression-specific logic into parse-time parse actions
name: abc 
integer: 123 
real: -3.14 
name: phase of the moon 

Use class constructors as parse-time parse actions - results names no
longer needed
String: abc (StringObject)
Int: 123 (IntObject)
Real: -3.14 (RealObject)
String: phase of the moon (StringObject)

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


Re: Python and Flaming Thunder

2008-05-21 Thread Dave Parker
On May 20, 7:05 pm, Collin <[EMAIL PROTECTED]> wrote:

> Personally, FT is a bit meh to me. The way you issue your statements I
> always think something is wrong, mainly because when I want to define,
> say, x, in python I'd go:
>
> x = "whatever"
>
> Instantly noting that I defined x. While in Flaming Thunder I'd have to
> type:
>
> Set x to "whatever"
>
> It just feels wrong.

Actually, it felt wrong to me when I first started working on Flaming
Thunder because I've been programming for decades and have had all of
the programming idioms burned into my brain.

But after getting input from children and teachers, etc, it started
feeling right.

For example, consider the two statements:

 x = 8
 x = 10

The reaction from most math teachers (and kids) was "one of those is
wrong because x can't equal 2 different things at the same time".
Many computer languages conflate "equality" with "assignment" and then
go to even more confusing measures to disambiguate them (such as using
== for equality, or := for assignment).

Plus, symbols are more confusing for people to learn about than
words.  There are lots of people who are fluent in English, but
dislike math.

So, I opted for a simple, unambiguous, non-mathematical way of
expressing "assignment" which makes sense even to the non-
mathematically inclined:

 Set x to 8.

That way, = can be reserved unambiguously and unconfusingly for the
mathematical notion of "equality" -- because it's in their math
classes that people learn what = means:

Set QuadraticEquation to a*x^2 + b*x + c = 0.
--
http://mail.python.org/mailman/listinfo/python-list


Possibly pydb 1.23 release around May 30

2008-05-21 Thread R. Bernstein
A release of pydb (1.23) is currently scheduled for around May
30th. If you can and want to help make sure the release is okay, you can try 
out what is currently in CVS: 
   http://sourceforge.net/cvs/?group_id=61395

I've put an interim tar at http://bashdb.sf.net/pydb-1.23cvs.tar.gz

Changes in the upgoming release:

* Show parameters on call

* Some doc fixes.

* add ipython and python commands to go into an ipython or a python shell

* add "save" command to save the current breakpoints and/or 
  most settings to a file. (Suggested at a NYC Python group meeting)

* add set/show "deftrace" to allow stopping at a def (method creation)
  statement.

* pseudo gdb-like "annotate" set/show commands and option.

* Better emacs interactivion via above annotate

* bug when "info local" is run inside a "with" statement

  Fixes for last three items based patches by Alberto Griggio

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


Re: C-like assignment expression?

2008-05-21 Thread Kay Schluehr
On 21 Mai, 11:38, [EMAIL PROTECTED] wrote:
> Hello,
>
> I have an if-elif chain in which I'd like to match a string against
> several regular expressions. Also I'd like to use the match groups
> within the respective elif... block. The C-like idiom that I would
> like to use is this:
>
> if (match = my_re1.match(line):
>   # use match
> elsif (match = my_re2.match(line)):
>   # use match
> elsif (match = my_re3.match(line))
>   # use match
>
> ...buy this is illegal in python. The other way is to open up an else:
> block in each level, do the assignment and then the test. This
> unneccessarily leads to deeper and deeper nesting levels which I find
> ugly. Just as ugly as first testing against the RE in the elif: clause
> and then, if it matches, to re-evaluate the RE to access the match
> groups.
>
> Thanks,
> robert

You are perfectly correct. Pythons design is lacking here IMO. But
what is your question?
--
http://mail.python.org/mailman/listinfo/python-list


Re: getting dir(x), but not as list of strings?

2008-05-21 Thread Gary Herron

[EMAIL PROTECTED] wrote:

I want to iterate over members of a module, something like:

for i in dir(x):
if type(i) == types.FunctionType: ...

but of course dir() returns a list of strings.  If x is a module,
how can I get the list of its members as their actual types?

Many TIA!
Mark

  
Use the builtin vars to get a dictionary of names and associated objects. 


import sys
for name,ob in vars(sys).items():
 print name,type(ob)

Gary Herron



setrecursionlimit 
getfilesystemencoding 
path_importer_cache 
stdout 
version_info 
exc_clear 
prefix 
getrefcount 
byteorder 
...

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


Re: Code For Five Threads To Process Multiple Files?

2008-05-21 Thread tdahsu
On May 21, 11:13 am, "A.T.Hofkamp" <[EMAIL PROTECTED]> wrote:
> On 2008-05-21, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
> > I'd appreciate any help.  I've got a list of files in a directory, and
> > I'd like to iterate through that list and process each one.  Rather
> > than do that serially, I was thinking I should start five threads and
> > process five files at a time.
>
> > Is this a good idea?  I picked the number five at random... I was
>
> Depends what you are doing.
> If you are mainly reading/writing files, there is not much to gain, since 1
> process will already push the disk IO system to its limit. If you do a lot of
> processing, then more threads than the number of processors is not much use. 
> If
> you have more 'burtsy' behavior (first do lot of reading, then lot of
> processing, then again reading, etc), then the system may be able to do some
> scheduling and keep both the processors and the file system busy.
>
> I cannot really give you advice on threading, I have never done that. You may
> want to consider an alternative, namely multi-tasking at OS level. If you can
> easily split the files over a number of OS processes (written in Python), you
> can make the Python program really simple, and let the OS handle the
> task-switching between the programs.
>
> Sincerely,
> Albert

Albert,

Thanks for your response - I appreciate your time!

I am mainly reading and writing files, so it seems like it might not
be a good idea.  What if I read the whole file into memory first, and
operate on it there?  They are not large files...

Either way, I'd hope that someone might respond with an example, as
then I could test and see which is faster!

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


Re: compressing short strings?

2008-05-21 Thread Paul Rubin
"inhahe" <[EMAIL PROTECTED]> writes:
> i don't see anybody mentioning huffman encoding.  i think it just works per 
> byte, so it's not as tight as gzip or whatever.  but it sounds like it would 
> be easy to implement and wouldn't require any corpus-wide compression 
> information. except a character frequency count if you wanted to be optimal.

In principle you could do it over digraphs but I tried that once and
it didn't help much.  Basially -because- it doesn't use any
corpus-wide compression information, it doesn't compress anywhere near
as well as LZ, DMC, or whatever.
--
http://mail.python.org/mailman/listinfo/python-list


[ctypes] convert pointer to string?

2008-05-21 Thread Neal Becker
In an earlier post, I was interested in passing a pointer to a structure to
fcntl.ioctl.

This works:

c = create_string_buffer (...)
args = struct.pack("iP", len(c), cast (pointer (c), c_void_p).value)
err = fcntl.ioctl(eos_fd, request, args)

Now to do the same with ctypes, I have one problem.

class eos_dl_args_t (Structure):
_fields_ = [("length", c_ulong),
("data", c_void_p)]
...
args = eos_dl_args_t()
args_p = cast(pointer(args), c_void_ptr).value
fcntl.ioctl(fd, request, args_p)  <<< May fail here

That last may fail, because .value creates a long int, and ioctl needs a
string.

How can I convert my ctypes structure to a string?  It _cannot_ be a c-style
0-terminate string, because the structure may contain '0' values.

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


issues simply parsing a whitespace-delimited textfile in python script

2008-05-21 Thread Damon Getsman
Okay so I'm writing a script in python right now as a dirty fix for a
problem we're having at work..  Unfortunately this is the first really
non-trivial script that I've had to work with in python and the book
that I have on it really kind of sucks.

I'm having an issue parsing lines of 'last' output that I have stored
in a /tmp file.  The first time it does a .readline() I get the full
line of output, which I'm then able to split() and work with the
individual fields of without any problem.  Unfortunately, the second
time that I do a .readline() on the file, I am only receiving the
first character of the first field.  Looking through the /tmp file
shows that it's not corrupted from the format that it should be in at
all...  Here's the relevant script:


#parse
Lastdump = open('/tmp/esd_tmp', 'r')

#find out what the last day entry is in the wtmp
cur_rec = Lastdump.readline()
work = cur_rec.split()

if debug == 1:
print work
print " is our split record line from /tmp/esd_tmp\n"

startday = work[3]

if debug == 1:
print startday + " is the starting day\n"
print days
print " is our dictionary of days\n"
print days[startday] + " is our ending day\n"

for cur_rec in Lastdump.readline():
work = cur_rec.split()

if debug == 1:
print "Starting table building pass . . .\n"
print work
print " is the contents of our split record line now\n"
print cur_rec + " is the contents of cur_rec\n"

#only go back 2 days

while work[0] != days[startday]:
tmp = work[1]
if table.has_key(work[0]):
continue
elif tmp[0] != ':':
#don't keep it if it isn't a SunRay terminal
identifier
continue
else:
#now we keep it
table[work[0]] = tmp


the first and second sets of debugging output show everything as they
should be...  the third shows that the next working line (in cur_rec),
and thus 'work', as well, only hold the first character of the line.
Here's the output:


Debugging run


Building table . . .

['dgetsman', 'pts/3', ':0.0', 'Wed', 'May', '21', '10:21', 'still',
'logged',
'in']
 is our split record line from /tmp/esd_tmp

Wed is the starting day

{'Wed': 'Mon', 'Sun': 'Fri', 'Fri': 'Wed', 'Thurs': 'Tues', 'Tues':
'Sun',
'Mon': 'Sat', 'Sat': 'Thurs'}
 is our dictionary of days

Mon is our ending day

Starting table building pass . . .

['d']
 is the contents of our split record line now

d is the contents of cur_rec


And thus everything fails when I try to work with the different fields
in subsequent script afterwards.  Does anybody have an idea as to why
this would be happening?

Oh, and if relevant, here's the datafile's first few lines:


dgetsman pts/3:0.0 Wed May 21 10:21   still logged
in
dgetsman pts/2:0.0 Wed May 21 09:04   still logged
in
dgetsman pts/1:0.0 Wed May 21 08:56 - 10:21
(01:24)
dgetsman pts/0:0.0 Wed May 21 08:56   still logged
in

I would really appreciate any pointers or suggestions you can give.

http://www.zoominfo.com/people/Getsman_Damon_-214241.aspx";>
*Damon Getsman
Linux/Solaris System Administrator

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


Re: Python and Flaming Thunder

2008-05-21 Thread Dan Upton
On Wed, May 21, 2008 at 11:34 AM, Dave Parker
<[EMAIL PROTECTED]> wrote:
> For example, consider the two statements:
>
> x = 8
> x = 10
>
> The reaction from most math teachers (and kids) was "one of those is
> wrong because x can't equal 2 different things at the same time".

Sounds to me like the teacher is being difficult, and IIRC,  you've
talked about having elementary school kids write in FT -- I don't
think asking "does this make sense to you" of elementary school kids
is necessarily the best metric for PL syntax/semantics.

> Many computer languages conflate "equality" with "assignment" and then
> go to even more confusing measures to disambiguate them (such as using
> == for equality, or := for assignment).
>
> Plus, symbols are more confusing for people to learn about than
> words.  There are lots of people who are fluent in English, but
> dislike math.

If you can't do, or don't like, math, you probably shouldn't be
programming.  If you don't have any symbolic reasoning skills, you're
largely limited to "Hello, World."

> That way, = can be reserved unambiguously and unconfusingly for the
> mathematical notion of "equality" -- because it's in their math
> classes that people learn what = means:
>
> Set QuadraticEquation to a*x^2 + b*x + c = 0.

You keep trotting out this quadratic equation example, but does FT
actually have any kind of useful equation solver in it?  Or does it
just allow you to do something like

Set QuadraticEquation to a*x^2 + b*x + c = 0.
Set a to 1.
Set b to 0.
Set c to -25.
Set x to 5.
If QuadraticEquation is True then do 
--
http://mail.python.org/mailman/listinfo/python-list


Re: C-like assignment expression?

2008-05-21 Thread inhahe

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> On May 21, 4:57 pm, "inhahe" <[EMAIL PROTECTED]> wrote:
>> one of the few things i miss from C is being able to use assignment in
>> expressions.   that's the only thing, really.
>> also there's no switch/case, you have to use a dictionary of functions
>> instead, although i rarely need that, usually i just use elif.
>
> One thing I hate from C is the assignment in expressions...Forcing
> myself to write
> 0 == Something
> rather than
> Something == 0

interesting trick, i've never thought of that/seen it
although if Python implemented it I think it should default to giving 
warnings when you use = in an expression, that way you don't have to worry.

> just to make sure I was mistakenly assigning values in statements is
> annoying, it ruins the ease of reading.
>
> I kind of agree with the select:case, but I think a key issue is how
> to implement it. Elif is reasonable for now.
>
> Diez, true I guess, but then we haven't seen what these expressions
> are, and why there has to be three. 


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


Re: Python and Flaming Thunder

2008-05-21 Thread Dave Parker
On May 21, 10:00 am, "Dan Upton" <[EMAIL PROTECTED]> wrote:

> Sounds to me like the teacher is being difficult, ...

No, proof-by-contradiction is a common technique in math.  If you can
show that x=8 and x=10, then you have shown that your assumptions were
incorrect.

> If you can't do, or don't like, math, you probably shouldn't be
> programming.

Why not?  Recipes are programs.  I prefer to look at it the other way:
an easy-to-use programming language might encourage more people to
like math.

> You keep trotting out this quadratic equation example, but does FT
> actually have any kind of useful equation solver in it?

Not yet, but it will.  Probably around July.
--
http://mail.python.org/mailman/listinfo/python-list


Re: issues simply parsing a whitespace-delimited textfile in python script

2008-05-21 Thread Damon Getsman
Okay, so I manged to kludge around the issue by not using
the .readline() in my 'for' statement.  Instead, I'm slurping the
whole file into a new list that I put in for that purpose, and
everything seems to be working just fine.  However, I don't know WHY
the other method failed and I'm at a loss for why that didn't work and
this is working.  I'd really like to know the why about this issue so
that I don't have to use crappy coding practice and kludge around it
the next time I have an issue like this.

Any ideas much appreciated.

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


  1   2   3   >