Re: Question

2005-10-07 Thread contact
Hi, this email address does not exist. Please go to the site and use the 
correct form to send your message.

No one has seen this message.

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


Re: question

2005-07-03 Thread [EMAIL PROTECTED]
see the answer on your previous post (
http://groups-beta.google.com/group/comp.lang.python/browse_frm/thread/8e132d9c734907b/87fd1f579a362e71?q=&rnum=2&hl=en#87fd1f579a362e71),
to get an interactive session open a command window and type ' python'

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


RE Question

2005-08-18 Thread Yoav
I don't understand why the two REs produce a different result. I read 
the RE guide but still I can't seem to figure it out.

 >>> t
'echo user=name password=pass path="/ret files"\r\n'
 >>> re.findall(r'(?<=\s)[^=]+=((?:".*")|(?:\S*))(?=\s)', t)
['name', 'pass', '"/ret files"']
 >>> re.findall(r'(?<=\s)[^=]+=((".*")|(\S*))(?=\s)', t)
[('name', '', 'name'), ('pass', '', 'pass'), ('"/ret files"', '"/ret 
files"', '')]


Also, does '|' char (meaning or) produces a pair for each section. I 
don't understand how it works. Can someone please direct me to a place 
which will explain it?

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


Re: Question

2005-08-28 Thread Adam Tomjack
Double clicking python.exe will give you the command line version.  To 
run IDLE, click Start -> Programs -> Python 2.x -> IDLE.

pythonw.exe is useful for running GUI scripts.  In Windows there are two 
types of programs: command line and gui programs.  python.exe is the 
command line version.  Suppose you write a Tk or a wxWindows program 
with python and you save it to a file.  You can still use python.exe to 
run that gui program, but it'll open an extra black window with nothing 
in it.  That's what pythonw.exe is for.  It can't give you a command 
line (which is why it disappears right away when you double click it), 
but it also doesn't open than extra window when you use it to run a gui 
application.

Adam

Beginner/Not Yet Programmer wrote:
> I've never programmed before, so I thought I'd try and learn a bit by
> using some Python tutorials.  I started using the tutorial at
> http://www.honors.montana.edu/~jjc/easytut/easytut/node3.html.  It
> mentioned different forms of Python, specifically Command Line and
> IDLE.  Being inexperienced, I'm not sure how to change from Command
> Line to IDLE, and I'm not sure which one I'm in when I start up the
> program.  In my Python folder, the only applications I have are
> python.exe and pythonw.exe.  Pythonw.exe won't run.  So, I run
> python.exe, and I'm not sure whether it is IDLE, Command Line, or
> neither.  Also, I'm unsure of how to save programs, considering when I
> run python.exe, it opens up a window which does not have the little bar
> with the "File", "Edit", "View" and "Help" buttons on it.  If you can
> help me out at all, thank you.
> 

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


Re: Question

2005-08-29 Thread [EMAIL PROTECTED]
Much more useful stuff for beginners is here:
http://wiki.python.org/moin/BeginnersGuide

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


Re: Question

2006-03-02 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 "Tom Leggio" <[EMAIL PROTECTED]> wrote:

> Do I need this on my computer---Python---can I remove it without hurting 
> anything?
> Thanks Tommy

Tom,

That's a very difficult question to answer without knowing more about your 
computer.  Some systems depend on Python for administrative tasks.  If you 
remove Python on such a system, you could create a mess for yourself.

Why do you want to remove it?  Even if you never use it, it's probably not 
taking up much space and it's not hurting anything.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question

2006-03-03 Thread P Boy
You may want to read up on http://python.org/doc/faq/installed.html

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


Re: Question

2006-03-03 Thread Duncan Booth
Tom Leggio wrote:

> Do I need this on my computer---Python---can I remove it without hurting 
> anything?

Without further information it is hard to answer, you haven't even said 
what operating system you are running, let alone what programs you have 
installed. Your message headers imply you are running some variant of 
Microsoft Windows, so I'll work on that assumption.

Windows itself does not use Python, so if you have Python installed it has 
been installed to run some other software. For example, my parents' 
computer has Python installed because my mum likes playing patience games 
(so it has Pysol installed).

If you uninstall Python then your system won't stop running, but it is 
likely that some other programs on the system will stop working. One option 
is to make sure you record the exact version of Python which you have 
installed, download that version from python.org and save the install file. 
Then uninstall it and if you notice later something no longer works you can 
reinstall it.

Alternatively, search your entire hard disc for files with the extensions 
.pyo, .pyc, .py, .pyw. You'll find a bunch of these in the directory where 
Python is installed (probably c:\python23 or c:\python24), but if you find 
any more elsewhere on your disc that will give you a clue what else is 
using Python. That isn't perfect (some applications use Python but change 
the file extensions), but it might help.
-- 
http://mail.python.org/mailman/listinfo/python-list


re question

2006-11-01 Thread Schüle Daniel
Hello all,

I didn't found more appropriate news group for
this question, please let me know if there is ng with
regular expression as its main topic

I am trying to construct a case where a greedy and
non greedy operation produce different result.
I dont see the difference between 'a??b' and 'a?b'
As far I understand is that ? will first try to match a
(it's greedy) and only if it fails then it step back
and lets a unmatched. The other doesn't match a at first,
only if the pattern fails to match it steps back and match a.

But don't they do eventually the same thing?
Can someone provide an example where 2 patterns yield
different results.

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


Re: Question

2007-02-05 Thread Simon Brunning
On 2/4/07, Magdy Sanad <[EMAIL PROTECTED]> wrote:
> I have certain data in the default file format ( GADGET ) .
>
> I Will be appreciated if you guide me to read these data
>
> under Python ?

You'd probably get more help if you told people what GADGET is. ;-)
Are you talking about this - ?

If so, then a quick Google doesn't reveal anything pre-built. But
then, "gadget" is a pretty appalling product name to Google for - *so*
many hits for that word!

There's a run-down on the file format here, though -
,
so you might be able to write your own using the struct module.

Good luck!

-- 
Cheers,
Simon B
[EMAIL PROTECTED]
http://www.brunningonline.net/simon/blog/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question

2007-02-07 Thread Mohammad Tayseer
> I have certain data in the default file format ( GADGET ) . 

Can you be more specific about the file format? what is the exact name, or the 
format specification?

 
-
It's here! Your new message!
Get new email alerts with the free Yahoo! Toolbar.-- 
http://mail.python.org/mailman/listinfo/python-list

re question

2006-06-23 Thread Daniel Sch
Hello re gurus,

I wrote this pattern trying to get the "name" and the "content" of VHDL 
package
I know that the file is a valid VHDL code, so actually there is no need to 
perform
validation after 'end' token is found, but since it works fine I don't want 
to touch it.

this is the pattern

pattern = 
re.compile(r'^\s*package\s+(?P\w+)\s+is\s+(?P.*?)\s+end(\s+package)?(\s+(?P=name))?\s*;',
 
re.DOTALL | re.MULTILINE | re.IGNORECASE)

and the problem is that
package TEST is xyz end;
works but
package TEST123 is xyz end;
fails

\w is supposed to match [a-zA-Z0-9_] so I don't understand why numbers and 
undescore let the pattern fail?
(there is a slight suspicion that it may be a re bug)

I also tried this pattern with the same results

pattern = 
re.compile(r'^\s*package\s+(?P.+?)\s+is\s+(?P.*?)\s+end(\s+package)?(\s+(?P=name))?\s*;',
 
re.DOTALL | re.MULTILINE | re.IGNORECASE)

something must be wrong with (?P\w+) inside the main pattern

thanks in advance

--
Daniel 


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


re question

2006-07-10 Thread Schüle Daniel
Hello,

consider the following code

 >>> re.search("[a-z](?i)[a-z]","AA")
<_sre.SRE_Match object at 0x40177e20>

this gives a match
if we provide an extra group for the first character it still works

 >>> re.search("([a-z])(?i)[a-z]","AA").group(1)
'A'
 >>>

it doesn't matter where (?i) is placed, right?
the re engine would glance at once on the entire pattern string
analize it (complain if pattern doesn't make sense, eg invalid)
and it would be the same as if the option was given expicitely
as re.IGNORECASE.

Is there a way to switch-off the option resp.
switch-on the option in the middle of the pattern?

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


Re: RE Question

2005-08-18 Thread Jorge Godoy
Yoav wrote:

> I don't understand why the two REs produce a different result. I read
> the RE guide but still I can't seem to figure it out.
> 
>  >>> t
> 'echo user=name password=pass path="/ret files"\r\n'
>  >>> re.findall(r'(?<=\s)[^=]+=((?:".*")|(?:\S*))(?=\s)', t)
> ['name', 'pass', '"/ret files"']
>  >>> re.findall(r'(?<=\s)[^=]+=((".*")|(\S*))(?=\s)', t)
> [('name', '', 'name'), ('pass', '', 'pass'), ('"/ret files"', '"/ret
> files"', '')]

Hi Yoav.

You can see at "sre" documentation (use that instead of the docs for "re")
that using "?:" you're asking for a non-groupping version of the
parenthesis match.  When you use parenthesis, the matched expression is
saved for using later.  Using "?:" you prevent that.  This is what causes
the difference for you.

> Also, does '|' char (meaning or) produces a pair for each section. I
> don't understand how it works. Can someone please direct me to a place
> which will explain it?

I didn't get your second question.  When you use "|" the first match is
used.  It is a short-circuited version of "or".  I mean, it tries the first
regexp, if it matches, the second expression is ignored.  The same is true
for "and", except that the comparisons end on the first false result. 


Be seeing you,
-- 
Jorge Godoy  <[EMAIL PROTECTED]>

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


Re: RE Question

2005-08-18 Thread Yoav
Thanks, it seems like the first answer covers the second as well.

Thank you.

Jorge Godoy wrote:
> Yoav wrote:
> 
> 
>>I don't understand why the two REs produce a different result. I read
>>the RE guide but still I can't seem to figure it out.
>>
>> >>> t
>>'echo user=name password=pass path="/ret files"\r\n'
>> >>> re.findall(r'(?<=\s)[^=]+=((?:".*")|(?:\S*))(?=\s)', t)
>>['name', 'pass', '"/ret files"']
>> >>> re.findall(r'(?<=\s)[^=]+=((".*")|(\S*))(?=\s)', t)
>>[('name', '', 'name'), ('pass', '', 'pass'), ('"/ret files"', '"/ret
>>files"', '')]
> 
> 
> Hi Yoav.
> 
> You can see at "sre" documentation (use that instead of the docs for "re")
> that using "?:" you're asking for a non-groupping version of the
> parenthesis match.  When you use parenthesis, the matched expression is
> saved for using later.  Using "?:" you prevent that.  This is what causes
> the difference for you.
> 
> 
>>Also, does '|' char (meaning or) produces a pair for each section. I
>>don't understand how it works. Can someone please direct me to a place
>>which will explain it?
> 
> 
> I didn't get your second question.  When you use "|" the first match is
> used.  It is a short-circuited version of "or".  I mean, it tries the first
> regexp, if it matches, the second expression is ignored.  The same is true
> for "and", except that the comparisons end on the first false result. 
> 
> 
> Be seeing you,
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: RE Question

2005-08-18 Thread Yoav
What is the difference between the RE module and the SRE one?

 Original Message 
From: Jorge Godoy <[EMAIL PROTECTED]>
To:
Subject: Re:RE Question
Date: 18/8/2005 17:44

> Yoav wrote:
> 
> 
>>I don't understand why the two REs produce a different result. I read
>>the RE guide but still I can't seem to figure it out.
>>
>> >>> t
>>'echo user=name password=pass path="/ret files"\r\n'
>> >>> re.findall(r'(?<=\s)[^=]+=((?:".*")|(?:\S*))(?=\s)', t)
>>['name', 'pass', '"/ret files"']
>> >>> re.findall(r'(?<=\s)[^=]+=((".*")|(\S*))(?=\s)', t)
>>[('name', '', 'name'), ('pass', '', 'pass'), ('"/ret files"', '"/ret
>>files"', '')]
> 
> 
> Hi Yoav.
> 
> You can see at "sre" documentation (use that instead of the docs for "re")
> that using "?:" you're asking for a non-groupping version of the
> parenthesis match.  When you use parenthesis, the matched expression is
> saved for using later.  Using "?:" you prevent that.  This is what causes
> the difference for you.
> 
> 
>>Also, does '|' char (meaning or) produces a pair for each section. I
>>don't understand how it works. Can someone please direct me to a place
>>which will explain it?
> 
> 
> I didn't get your second question.  When you use "|" the first match is
> used.  It is a short-circuited version of "or".  I mean, it tries the first
> regexp, if it matches, the second expression is ignored.  The same is true
> for "and", except that the comparisons end on the first false result. 
> 
> 
> Be seeing you,
-- 
http://mail.python.org/mailman/listinfo/python-list


Newbie RE question

2006-09-22 Thread T
I would like to search for any of the strings in r'/\:*?"<>|' in a
string using RE module.  Can someone tell me how?

Thanks!

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


Re: re question

2006-11-01 Thread Steve Holden
Schüle Daniel wrote:
> Hello all,
> 
> I didn't found more appropriate news group for
> this question, please let me know if there is ng with
> regular expression as its main topic
> 
> I am trying to construct a case where a greedy and
> non greedy operation produce different result.
> I dont see the difference between 'a??b' and 'a?b'
> As far I understand is that ? will first try to match a
> (it's greedy) and only if it fails then it step back
> and lets a unmatched. The other doesn't match a at first,
> only if the pattern fails to match it steps back and match a.
> 
> But don't they do eventually the same thing?
> Can someone provide an example where 2 patterns yield
> different results.
> 
  >>> target = "Sample String"
  >>> greedy = re.compile("<.+>")
  >>> nongreedy = re.compile("<.+?>")
  >>> m1 = greedy.match(target)
  >>> m2 = nongreedy.match(target)
  >>> m1.group(0)
'Sample String'
  >>> m2.group(0)
''
  >>>

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb   http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden

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


Re: re question

2006-11-01 Thread attn . steven . kuo
Schüle Daniel wrote:

(snipped)

> I am trying to construct a case where a greedy and
> non greedy operation produce different result.
> I dont see the difference between 'a??b' and 'a?b'
> As far I understand is that ? will first try to match a
> (it's greedy) and only if it fails then it step back
> and lets a unmatched. The other doesn't match a at first,
> only if the pattern fails to match it steps back and match a.
>
> But don't they do eventually the same thing?
> Can someone provide an example where 2 patterns yield
> different results.
>

Perhaps this sheds some light
on the matter:


>>> import re
>>> string = "aaaba"

>>> one =  re.findall(r'a?b?', string)
>>> two =  re.findall(r'a??b?', string)

>>> print one, two

Yields:

['a', 'a', 'ab', 'a', ''] ['', '', '', 'b', '', '']


-- 
Hope this helps,
Steven

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


newbe's re question

2006-09-19 Thread [EMAIL PROTECTED]
All I am after realy is to change this

 reline = re.line.split('instr', '/d$')

into something that grabs any line with instr in it take all the
numbers and then grab any comment that may or may not be at the end of
the line starting with ; until the end of the line including white
spaces..  this is a corrected version from

http://python-forum.org/py/viewtopic.php?t=1703

thanks in advance the hole routine is down below..






[code]
def extractCsdInstrument (input_File_Name, output_File_Name,
instr_number):

"takes an .csd input file and grabs instr_number instrument and
creates output_File_Name"
f = open (input_File_Name , 'r')#opens file passed
in to read
f2 = open (output_File_Name, 'w')   #opens file passed
in to write
instr_yes = 'false' #set flag to false

for line in f:  #for through all
the lines
  if "instr" in line:   #look for instr in
the file
   if instr_yes == 'true':#check to see if
this ends the instr block
   break#exit the block

   reline = re.line.split('instr', '/d$') #error probily
split instr and /d (decimal number into parts) $ for end of line
   number = int(reline[1])  #convert to a
number maybe not important
if number == instr_number:#check to see if
it is the instr passed to function
instr_yes = "true": #change flag to
true because this is the instr we want
  if instr_yes = "true":#start of code to
copy to another file
   f2.write(f.line) #write line to
output file

f.close #close input file
f2.close  

[/code]

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


Re: re question

2006-06-23 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Daniel Schüle wrote:

> this is the pattern
> 
> pattern = 
> re.compile(r'^\s*package\s+(?P\w+)\s+is\s+(?P.*?)\s+end(\s+package)?(\s+(?P=name))?\s*;',
>  
> re.DOTALL | re.MULTILINE | re.IGNORECASE)
> 
> and the problem is that
> package TEST is xyz end;
> works but
> package TEST123 is xyz end;
> fails

For me both work:

In [11]:pattern = (
t>.*?)\s+end(\s+package)?(\s+(?P=name))?\s*;', )\s+is\s+(?P

In [13]:pattern.match('package TEST123 is xyz end;')
Out[13]:<_sre.SRE_Match object at 0x405b15f8>

I have copy and pasted you code.

For debugging re's in Python you might take a
look at http://kodos.sourceforge.net/

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

Re: re question

2006-06-23 Thread Daniel Sch
Hi

[...]

hm, that's wired
I just tried it in python shell and it works but same code as script file 
fails

for anyone who want to see for himself

# package.vhd file
bash % cat package.vhd
library ieee;
use ieee.std_logic_1164.all;

package TEST123 is
constant BASE
End Package Test;


# parser.py
bash % cat parser.py
#!/usr/bin/env python

import sys, re

reflags = re.DOTALL | re.MULTILINE | re.IGNORECASE

pattern = 
re.compile(r'^\s*package\s+(?P\w+)\s+is\s+(?P.*?)\s+end(\s+package)?(\s+(?P=name))?\s*;',
 
reflags)

class PackageParser(object):
def __init__(self, filename):
self.package = file(filename).read()
def parse(self):
return pattern.search(self.package)

if __name__ == "__main__":
p = PackageParser("package.vhd")
m = p.parse()
if m is None:
print "nothing"
sys.exit(1)
print m.group("content")
print m.group("name")


# testing
bash % ./parser.py
nothing

ps:
>>> sys.version
'2.4.2 (#2, Mar  3 2006, 13:32:59) \n[GCC 3.2.2 20030222 (Red Hat Linux 
3.2.2-5)]'

Regards, Daniel 


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


Re: re question

2006-06-23 Thread Paul McGuire
Shouldn't

End Package Test;

read:

End Package Test123;


-- Paul


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


Re: re question

2006-06-23 Thread Daniel Sch

"Paul McGuire" <[EMAIL PROTECTED]> schrieb im Newsbeitrag 
news:[EMAIL PROTECTED]
> Shouldn't
>
> End Package Test;
>
> read:
>
> End Package Test123;
>
>
> -- Paul

yes it must :)
my mistake

thx 


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


Re: re question

2006-07-10 Thread Jim Segrave
In article <[EMAIL PROTECTED]>,
Schüle Daniel  <[EMAIL PROTECTED]> wrote:
>Hello,
>
>consider the following code
>
> >>> re.search("[a-z](?i)[a-z]","AA")
><_sre.SRE_Match object at 0x40177e20>
>
>this gives a match
>if we provide an extra group for the first character it still works
>
> >>> re.search("([a-z])(?i)[a-z]","AA").group(1)
>'A'
> >>>
>
>it doesn't matter where (?i) is placed, right?
>the re engine would glance at once on the entire pattern string
>analize it (complain if pattern doesn't make sense, eg invalid)
>and it would be the same as if the option was given expicitely
>as re.IGNORECASE.
>
>Is there a way to switch-off the option resp.
>switch-on the option in the middle of the pattern?

The docs say:

(?iLmsux)
(One or more letters from the set "i", "L", "m", "s", "u", "x".)
The group matches the empty string; the letters set the
corresponding flags (re.I, re.L, re.M, re.S, re.U, re.X) for the
 ^^^  
entire regular expression. This is useful if you wish to include
^

the flags as part of the regular expression, instead of passing a
flag argument to the compile() function.


Some regex packages, but not Python's, support (?-) and this
allows turning the flag off and on for parts of the regex.



-- 
Jim Segrave   ([EMAIL PROTECTED])

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

Re: Question on sorting

2004-11-29 Thread wes weston
Lad wrote:
Hi,
I have a file of records of 4 fields each.
Each field is separated by a semicolon. That is
Filed1;Ffield2;Field3;Field4
But there may be also empty records such as

(only semicolons).
For sorting I used
#
lines = file('Config.txt').readlines()# a file I want to sort
lines.sort()
ff=open('ConfigSorted.txt','w')# sorted file
ff.writelines(lines)
ff.close()
###
It was sorted but empty records were first. I need them to be last(at
the end of the file). How can I do that?
Thanks for help
Lad
Lad,
   The sort call can have a function name as an arg. You
could do:
def mycompare(s1,s2):
#return -1 to put s1's at front; 1 to put s1's at back; 0 for a tie
#if s1=="" and s2<>"": return 1
lines.sort(mycompare)
wes
--
http://mail.python.org/mailman/listinfo/python-list


Re: Question of Optionparse

2004-11-30 Thread Peter Otten
Pekka Niiranen wrote:

> How can I STOP Optionparse to process boolean
> value as parameter. See this:
> 
>  >>> parser = optparse.OptionParser()
>  >>> parser.add_option("-x",dest='xxx', action="store_true",help="xxx")
>  >>> parser.add_option("-r",dest='root',help="directory",type="string")
>  >>> args = ["-r", "d:", "-x"]
>  >>> parser.parse_args(args)
> (, [])
> 
> Last line is correct: boolean 'xxx' gets set 'True'
> and parameter 'root' to 'd:'
> 
> However when value is NOT given for '-r' but '-x' exists:
> 
>  >>> args = ["-r", "-x"]
>  >>> parser.parse_args(args)
> (, [])
> 
> This is BS: I expected 'root' to be None and 'xxx' to be 'True'.
> How can I make it so?

I think you need a callback option.

> Another question: Is there a way to store options
> directly into user defined dictionary without assignment
> like this:
> 
> my_environment_values = {}
> (options, args) = parser.parse_args()
> environment_values["xxx"] = options.xxx

environment_values.update(options.__dict__)

Full example:

import optparse

def callback(option, opt, value, parser):
rargs = parser.rargs
if rargs and not rargs[0].startswith("-"):
parser.values.root = rargs.pop(0)
else:
parser.values.root = ""

parser = optparse.OptionParser()
parser.add_option("-x", "--xtra-terrestrial", action="store_true")
parser.add_option("-r", "--root", action="callback", callback=callback)

options, args = parser.parse_args()

environment = {}
environment.update(options.__dict__)

print environment

Peter

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


Re: Question on sorting

2004-11-30 Thread Eddie Corns
wes weston <[EMAIL PROTECTED]> writes:

>Lad wrote:
>> Hi,
>> I have a file of records of 4 fields each.
>> Each field is separated by a semicolon. That is
>> 
>> Filed1;Ffield2;Field3;Field4
>> 
>> But there may be also empty records such as
>> 
>> (only semicolons).
>> 
>> For sorting I used
>> #
>> lines = file('Config.txt').readlines()# a file I want to sort
>> lines.sort()
>> ff=open('ConfigSorted.txt','w')# sorted file
>> ff.writelines(lines)
>> ff.close()
>> ###
>> It was sorted but empty records were first. I need them to be last(at
>> the end of the file). How can I do that?
>> 
>> Thanks for help
>> Lad

>Lad,
>The sort call can have a function name as an arg. You
>could do:

>def mycompare(s1,s2):
>#return -1 to put s1's at front; 1 to put s1's at back; 0 for a tie
>#if s1=="" and s2<>"": return 1

>lines.sort(mycompare)

I can't help feeling that the OP might have really wanted to be sorting on
individual fields rather than whole lines.  In which case I would think of
doing a line.split(';') on each line before sorting.  It would still need
either to use a function to make empty fields go later or alternatively use
DSU (google!) and convert '' to say '~' and back again. This also solves the
problem of what to expect when only some of the fields are blank rather than
all of them.

Eddie

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


Re: Question on sorting

2004-12-01 Thread Lad
wes weston <[EMAIL PROTECTED]> wrote in message news:<[EMAIL PROTECTED]>...
> Lad wrote:
> > Hi,
> > I have a file of records of 4 fields each.
> > Each field is separated by a semicolon. That is
> > 
> > Filed1;Ffield2;Field3;Field4
> > 
> > But there may be also empty records such as
> > 
> > (only semicolons).
> > 
> > For sorting I used
> > #
> > lines = file('Config.txt').readlines()# a file I want to sort
> > lines.sort()
> > ff=open('ConfigSorted.txt','w')# sorted file
> > ff.writelines(lines)
> > ff.close()
> > ###
> > It was sorted but empty records were first. I need them to be last(at
> > the end of the file). How can I do that?
> > 
> > Thanks for help
> > Lad
> 
> Lad,
> The sort call can have a function name as an arg. You
> could do:
> 
> def mycompare(s1,s2):
> #return -1 to put s1's at front; 1 to put s1's at back; 0 for a tie
> #if s1=="" and s2<>"": return 1
> 
> lines.sort(mycompare)
> 
Wes,
Thank you for reply. But I do not understand mycompare function. Can
you please explain to me how it should work? Thanks

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


Re: Question on sorting

2004-12-01 Thread Peter Otten
Lad wrote:

> wes weston <[EMAIL PROTECTED]> wrote in message
> news:<[EMAIL PROTECTED]>...
>> Lad wrote:
>> > Hi,
>> > I have a file of records of 4 fields each.
>> > Each field is separated by a semicolon. That is
>> > 
>> > Filed1;Ffield2;Field3;Field4
>> > 
>> > But there may be also empty records such as
>> > 
>> > (only semicolons).
>> > 
>> > For sorting I used
>> > #
>> > lines = file('Config.txt').readlines()# a file I want to sort
>> > lines.sort()
>> > ff=open('ConfigSorted.txt','w')# sorted file
>> > ff.writelines(lines)
>> > ff.close()
>> > ###
>> > It was sorted but empty records were first. I need them to be last(at
>> > the end of the file). How can I do that?
>> > 
>> > Thanks for help
>> > Lad
>> 
>> Lad,
>> The sort call can have a function name as an arg. You
>> could do:
>> 
>> def mycompare(s1,s2):
>> #return -1 to put s1's at front; 1 to put s1's at back; 0 for a tie
>> #if s1=="" and s2<>"": return 1
>> 
>> lines.sort(mycompare)
>> 
> Wes,
> Thank you for reply. But I do not understand mycompare function. Can
> you please explain to me how it should work? Thanks

compare(a, b) is just a function for comparing two items/lines. I must
return -1 if ab, and 0 if a==b. For example the following
compare moves the "" records to the end and keeps the order of others
unaffected:

>>> items = ["", ";a;b;;", ";b;a;;", "a;b;c;d;e", "a;;;d;e"]
>>> def compare(a, b):
... return cmp(a == "", b == "") or cmp(a, b)
...
>>> items.sort(compare)
>>> items
[';a;b;;', ';b;a;;', 'a;;;d;e', 'a;b;c;d;e', '']

As Eddie Corns pointed out, you left some doubt whether that is really what
you want. Here is a more complex compare() that handles the lines as
columns split by ";" and puts empty columns last in the sorting order:

>>> def key(row):
... return [(not col, col) for col in row.split(";")]
...
>>> def compare(a, b):
... return cmp(key(a), key(b))
...
>>> items.sort(compare)
>>> items
['a;b;c;d;e', 'a;;;d;e', ';a;b;;', ';b;a;;', '']

If you are on Python 2.4, you don't need the compare() detour and can use
key() directly:

>>> items.sort(key=key)
>>> items
['a;b;c;d;e', 'a;;;d;e', ';a;b;;', ';b;a;;', '']

Finally, the "" lines don't seem to carry any information - why not
filter them out completely?

>>> items = [line[:-1] for line in file("cfg.txt", "U") if line != "\n"]


Peter

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


Re: Question on sorting

2004-12-01 Thread Lad
Peter Otten <[EMAIL PROTECTED]> wrote in message news:<[EMAIL PROTECTED]>...
> Lad wrote:
> 
> > wes weston <[EMAIL PROTECTED]> wrote in message
> > news:<[EMAIL PROTECTED]>...
> >> Lad wrote:
> >> > Hi,
> >> > I have a file of records of 4 fields each.
> >> > Each field is separated by a semicolon. That is
> >> > 
> >> > Filed1;Ffield2;Field3;Field4
> >> > 
> >> > But there may be also empty records such as
> >> > 
> >> > (only semicolons).
> >> > 
> >> > For sorting I used
> >> > #
> >> > lines = file('Config.txt').readlines()# a file I want to sort
> >> > lines.sort()
> >> > ff=open('ConfigSorted.txt','w')# sorted file
> >> > ff.writelines(lines)
> >> > ff.close()
> >> > ###
> >> > It was sorted but empty records were first. I need them to be last(at
> >> > the end of the file). How can I do that?
> >> > 
> >> > Thanks for help
> >> > Lad
> >> 
> >> Lad,
> >> The sort call can have a function name as an arg. You
> >> could do:
> >> 
> >> def mycompare(s1,s2):
> >> #return -1 to put s1's at front; 1 to put s1's at back; 0 for a tie
> >> #if s1=="" and s2<>"": return 1
> >> 
> >> lines.sort(mycompare)
> >> 
> > Wes,
> > Thank you for reply. But I do not understand mycompare function. Can
> > you please explain to me how it should work? Thanks
> 
> compare(a, b) is just a function for comparing two items/lines. I must
> return -1 if ab, and 0 if a==b. For example the following
> compare moves the "" records to the end and keeps the order of others
> unaffected:
> 
> >>> items = ["", ";a;b;;", ";b;a;;", "a;b;c;d;e", "a;;;d;e"]
> >>> def compare(a, b):
> ... return cmp(a == "", b == "") or cmp(a, b)
> ...
> >>> items.sort(compare)
> >>> items
> [';a;b;;', ';b;a;;', 'a;;;d;e', 'a;b;c;d;e', '']
> 
Petr,
thank you for help and explanation.
It works
Lad
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question about modules

2004-12-10 Thread Jon
Hi Jeff,

That makes sense -- thanks.  However now when I use "re.capwords (sentence)"
I get a different error message:

AttributeError: 'module' object has no attribute 'capwords'

Each of the other two suggested implimentations produce a similar error
message.  Is there something even more basic that I am failing to do?  I'm
using the IDLE GUI in WinXP, Python release 2.4...

Thanks!
Jon


"Jeffrey Maitland" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Jon writes:
>
> > Hi,
> >
> > The following four lines of code:
> >
> > import sys, os, re
> > sentence = raw_input("Enter a sentence:  ")
> > capwords (sentence)
> > print sentence
> >
> > gives me the following error:  NameError: name 'capwords' is not defined
> >
> > As far as I can tell from the online docs, "capwords" should be defined
in
> > the built-in "regex" module.  Why is it telling me that capwords is not
> > defined?
> >
> > I am completely new to Python so my apologies for such a basic question!
> >
> > Thanks,
> > Jon
> >
> >
> > -- 
> > http://mail.python.org/mailman/listinfo/python-list
>
> Hello Jon,
>
> The reason for that is you only imported the module(class/object) now to
use
> its methodes you need to call the object.
>
> in this case to fix the problem you are having you would have to do it
> either one of these methodes (unless there are more that I am not aware
of)
> 1/
> import sys, os, re
> sentence = raw_input("Enter a sentence:  ")
> re.capwords (sentence) # <-- notice the re.capwords this
>   # calling the capword method of the re module.
> print sentence
>
> 2/
> import sys, os
> from re import * # < import all methods of re and allow them to be
> #   used locally
> sentence = raw_input("Enter a sentence:  ")
> capwords (sentence)
> print sentence
> # this imports all the methodes in the re module so they can be used
> # localy.
>
> or
> import sys, os
> from re import capwords  # < import only capwords method of re
> sentence = raw_input("Enter a sentence:  ")
> capwords (sentence)
> print sentence
> # this import only imports the capwords methode of the re module
>
>
> I hope this helps you some and if i used the incorrect terminology I am
> sorry and I hope someone points it out to me.
>
> Jeff Maitland


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


Re: question about modules

2004-12-10 Thread Jeffrey Maitland
Jon writes: 

Hi, 

The following four lines of code: 

import sys, os, re
sentence = raw_input("Enter a sentence:  ")
capwords (sentence)
print sentence 

gives me the following error:  NameError: name 'capwords' is not defined 

As far as I can tell from the online docs, "capwords" should be defined in
the built-in "regex" module.  Why is it telling me that capwords is not
defined? 

I am completely new to Python so my apologies for such a basic question! 

Thanks,
Jon 

--
http://mail.python.org/mailman/listinfo/python-list
Hello Jon, 

The reason for that is you only imported the module(class/object) now to use 
its methodes you need to call the object. 

in this case to fix the problem you are having you would have to do it 
either one of these methodes (unless there are more that I am not aware of)
1/
import sys, os, re
sentence = raw_input("Enter a sentence:  ")
re.capwords (sentence) # <-- notice the re.capwords this
 # calling the capword method of the re module.
print sentence 

2/
import sys, os
from re import * # < import all methods of re and allow them to be
   #   used locally
sentence = raw_input("Enter a sentence:  ")
capwords (sentence)
print sentence
# this imports all the methodes in the re module so they can be used
# localy. 

or
import sys, os
from re import capwords  # < import only capwords method of re
sentence = raw_input("Enter a sentence:  ")
capwords (sentence)
print sentence
# this import only imports the capwords methode of the re module 

I hope this helps you some and if i used the incorrect terminology I am 
sorry and I hope someone points it out to me. 

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


Re: question about modules

2004-12-10 Thread Reinhold Birkenfeld
Jon wrote:
> Hi Jeff,
> 
> That makes sense -- thanks.  However now when I use "re.capwords (sentence)"
> I get a different error message:
> 
> AttributeError: 'module' object has no attribute 'capwords'
> 
> Each of the other two suggested implimentations produce a similar error
> message.  Is there something even more basic that I am failing to do?  I'm
> using the IDLE GUI in WinXP, Python release 2.4...

The 'capwords' function seems to be defined in the "string" module, not
the "re" module.

Reinhold

-- 
[Windows ist wie] die Bahn: Man muss sich um nichts kuemmern, zahlt fuer
jede Kleinigkeit einen Aufpreis, der Service ist mies, Fremde koennen
jederzeit einsteigen, es ist unflexibel und zu allen anderen Verkehrs-
mitteln inkompatibel.   -- Florian Diesch in dcoulm
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question Regarding SocketServer

2005-01-25 Thread [EMAIL PROTECTED]
you are missing quotes in "socketserver.py". Make sure the comments at
the top are quoted out. In "IDLE" they should be green.

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


Re: Question Regarding SocketServer

2005-01-25 Thread [EMAIL PROTECTED]
I tried to reply earlier... basically your "SocketServer.py" file is
messed up. That line "AF_INET{,6}: IP (Internet Protocol) sockets
(default)" should be commented out.  It should be part of a block of
lines that are all commented out.

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


Re: Question Regarding SocketServer

2005-01-25 Thread missiplicity

[EMAIL PROTECTED] wrote:
> I tried to reply earlier... basically your "SocketServer.py" file is
> messed up. That line "AF_INET{,6}: IP (Internet Protocol) sockets
> (default)" should be commented out.  It should be part of a block of
> lines that are all commented out.

Thanks for your quick response. I am suprised that "SocketServer.py" is
messed up because I just installed Python and didnt touch any files in
Python's installation folder. Anyway I removed the comments at the top
and I still get the error

File "C:\Python24\lib\SocketServer.py", line 8, in ?

AttributeError: 'module' object has no attribute 'StreamRequestHandler'






If it is of any help here are the first few lines in SocketServer.py


__version__ = "0.4"


import socket
import sys
import os

__all__ =
["TCPServer","UDPServer","ForkingUDPServer","ForkingTCPServer",

"ThreadingUDPServer","ThreadingTCPServer","BaseRequestHandler",
"StreamRequestHandler","DatagramRequestHandler",
"ThreadingMixIn", "ForkingMixIn"]
if hasattr(socket, "AF_UNIX"):
__all__.extend(["UnixStreamServer","UnixDatagramServer",
"ThreadingUnixStreamServer",
"ThreadingUnixDatagramServer"])


I opened the SocketServer.py in the IDE and it seems normal. Is there a
way I can check if the module is corrupted in the IDE?

Thanks,
Kris

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


Re: Question Regarding SocketServer

2005-01-25 Thread missiplicity
I figured out my problem. I initially had named my program
SocketServer.py and then compiled it. It created a file
SocketServer.pyc
Then I changed the name of the program to TestServer3.py
but when I imported SocketServer, it was importing from the compiled
file left in the current folder (SocketServer.pyc) I guess.  I deleted
it and everything worked. Please bear with my ignorance.
Thanks once again for the help,
Kris

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


Re: Question Regarding SocketServer

2005-01-26 Thread [EMAIL PROTECTED]
I am glad you were able to figure it out. It's strange that the pyc
file didn't get updated... it should have automatically fixed itself.
*shrug* that's one of those problems that aggrivate you to death...

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


Re: Question about 'None'

2005-01-27 Thread Fredrik Lundh
"flamesrock" <[EMAIL PROTECTED]> wrote:

> The statement (1 > None) is false (or any other value above 0). Why is
> this?

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

"The operators <, >, ==, >=, <=, and != compare the values of
two objects. The objects need not have the same type. If both
are numbers, they are converted to a common type. Otherwise,
objects of different types always compare unequal, and are
ordered consistently but arbitrarily.

(This unusual definition of comparison was used to simplify the
definition of operations like sorting and the in and not in
operators. In the future, the comparison rules for objects of
different types are likely to change.)"

 



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


Re: Question about 'None'

2005-01-27 Thread Steven Bethard
flamesrock wrote:
The statement (1 > None) is false (or any other value above 0). Why is
this?
What code are you executing?  I don't get this behavior at all:
py> 100 > None
True
py> 1 > None
True
py> 0 > None
True
py> -1 > None
True
py> -100 > None
True
(The reason I ask is sortof unrelated. I wanted to use None as a
variable for which any integer, including negative ones have a greater
value so that I wouldn't need to implement any tests or initializations
for a loop that finds the maximum of a polynomial between certain x
values. Anything is greater than nothing, no?)
Yup, that's the behavior I get with None.
Steve
--
http://mail.python.org/mailman/listinfo/python-list


Re: Question about 'None'

2005-01-27 Thread Francis Girard
Le jeudi 27 Janvier 2005 20:16, Steven Bethard a écrit :
> flamesrock wrote:
> > The statement (1 > None) is false (or any other value above 0). Why is
> > this?
>
> What code are you executing?  I don't get this behavior at all:
>
> py> 100 > None
> True
> py> 1 > None
> True
> py> 0 > None
> True
> py> -1 > None
> True
> py> -100 > None
> True
>

Wow ! What is it that are compared ? I think it's the references (i.e. the 
adresses) that are compared. The "None" reference may map to the physical 0x0 
adress whereas 100 is internally interpreted as an object for which the 
reference (i.e. address) exists and therefore greater than 0x0.

Am I interpreting correctly ?

> > (The reason I ask is sortof unrelated. I wanted to use None as a
> > variable for which any integer, including negative ones have a greater
> > value so that I wouldn't need to implement any tests or initializations
> > for a loop that finds the maximum of a polynomial between certain x
> > values. Anything is greater than nothing, no?)
>
> Yup, that's the behavior I get with None.
>
> Steve

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


Re: Question about 'None'

2005-01-27 Thread Steven Bethard
Francis Girard wrote:
Le jeudi 27 Janvier 2005 20:16, Steven Bethard a écrit :
flamesrock wrote:
The statement (1 > None) is false (or any other value above 0). Why is
this?
What code are you executing?  I don't get this behavior at all:
py> 100 > None
True
py> 1 > None
True
py> 0 > None
True
py> -1 > None
True
py> -100 > None
True

Wow ! What is it that are compared ? I think it's the references (i.e. the 
adresses) that are compared. The "None" reference may map to the physical 0x0 
adress whereas 100 is internally interpreted as an object for which the 
reference (i.e. address) exists and therefore greater than 0x0.

Am I interpreting correctly ?
Actually, I believe None is special-cased to work like this.  From object.c:
static int
default_3way_compare(PyObject *v, PyObject *w)
{
...
if (v->ob_type == w->ob_type) {
...
Py_uintptr_t vv = (Py_uintptr_t)v;
Py_uintptr_t ww = (Py_uintptr_t)w;
return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
}
...
/* None is smaller than anything */
if (v == Py_None)
return -1;
if (w == Py_None)
return 1;
...
}
So None being smaller than anything (except itself) is hard-coded into 
Python's compare routine.  My suspicion is that even if/when objects of 
different types are no longer comparable by default (as has been 
suggested for Python 3.0), None will still compare as smaller than 
anything...

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


Re: Question about 'None'

2005-01-27 Thread jfj
Francis Girard wrote:
Wow ! What is it that are compared ? I think it's the references (i.e. the 
adresses) that are compared. The "None" reference may map to the physical 0x0 
adress whereas 100 is internally interpreted as an object for which the 
reference (i.e. address) exists and therefore greater than 0x0.

Am I interpreting correctly ?

Not really. If objects of different types are compared (like compare a
string with a list), then no matter what, all strings but be "smaller"
than all lists. Or the oposite.
So the fast way to accomplish this is to compare the addresses of the
object's method table. Something which is common for all objects of
the same type.
G.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Question about 'None'

2005-01-27 Thread Fredrik Lundh
Steven Bethard wrote:

> So None being smaller than anything (except itself) is hard-coded into 
> Python's compare routine. 
> My suspicion is that even if/when objects of different types are no longer 
> comparable by default 
> (as has been suggested for Python 3.0), None will still compare as smaller 
> than anything...

from the change log for Python 2.1:

"An implementation detail changed in 2.1a1 such that None now compares
less than any other object.  Code relying on this new behavior (like code
that relied on the previous behavior) does so at its own risk."

the documentation (which I quoted earlier) still applies.

 



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


Re: Question about 'None'

2005-01-27 Thread Francis Girard
Le jeudi 27 Janvier 2005 21:29, Steven Bethard a écrit :
> Francis Girard wrote:
> > Le jeudi 27 Janvier 2005 20:16, Steven Bethard a écrit :
> >>flamesrock wrote:
> >>>The statement (1 > None) is false (or any other value above 0). Why is
> >>>this?
> >>
> >>What code are you executing?  I don't get this behavior at all:
> >>
> >>py> 100 > None
> >>True
> >>py> 1 > None
> >>True
> >>py> 0 > None
> >>True
> >>py> -1 > None
> >>True
> >>py> -100 > None
> >>True
> >
> > Wow ! What is it that are compared ? I think it's the references (i.e.
> > the adresses) that are compared. The "None" reference may map to the
> > physical 0x0 adress whereas 100 is internally interpreted as an object
> > for which the reference (i.e. address) exists and therefore greater than
> > 0x0.
> >
> > Am I interpreting correctly ?
>
> Actually, I believe None is special-cased to work like this.  From
> object.c:
>
> static int
> default_3way_compare(PyObject *v, PyObject *w)
> {
>   ...
>   if (v->ob_type == w->ob_type) {
>   ...
>   Py_uintptr_t vv = (Py_uintptr_t)v;
>   Py_uintptr_t ww = (Py_uintptr_t)w;
>   return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
>   }
>   ...
>   /* None is smaller than anything */
>   if (v == Py_None)
>   return -1;
>   if (w == Py_None)
>   return 1;
>   ...
> }
>
> So None being smaller than anything (except itself) is hard-coded into
> Python's compare routine.  My suspicion is that even if/when objects of
> different types are no longer comparable by default (as has been
> suggested for Python 3.0), None will still compare as smaller than
> anything...
>

Well, here's python doesn't seem to confirm what you're saying :

>>> a = "10"
>>> b = 10
>>> a > b
True
>>> b > a
False
>>> id(a)
1077467584
>>> id(b)
134536516

It really looks like the addresses are compared when objects are of different 
types if there is no __cmp__ or __lt__ user made specification to compare 
objects of different types.

If this is case then it is dreadfully dangerous. You end up never really 
knowing for sure if you're comparing the references or the values.

What would be the use to compare references anyway in language like Python. I 
think the code should raise a big bad exception for such cases.

Francis Girard



> Steve

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


Re: Question about 'None'

2005-01-27 Thread Fredrik Lundh
Francis Girard wrote:

> Wow ! What is it that are compared ? I think it's the references (i.e. the
> adresses) that are compared. The "None" reference may map to the physical 0x0
> adress whereas 100 is internally interpreted as an object for which the
> reference (i.e. address) exists and therefore greater than 0x0.
>
> Am I interpreting correctly ?

your hypothesis might match the observations, but it doesn't match the
implementation.  nor the documentation:

" ... objects of different types always compare unequal, and are
ordered consistently but arbitrarily."

(see my others posts in this thread for more details)

 



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


Re: Question about 'None'

2005-01-27 Thread Francis Girard
Oops, I misunderstood what you said. I understood that it was now the case 
that objects of different types are not comparable by default whereas you 
meant it as a planned feature for version 3.

I really hope that it will indeed be the case for version 3.

Francis Girard

Le jeudi 27 Janvier 2005 21:29, Steven Bethard a écrit :
> Francis Girard wrote:
> > Le jeudi 27 Janvier 2005 20:16, Steven Bethard a écrit :
> >>flamesrock wrote:
> >>>The statement (1 > None) is false (or any other value above 0). Why is
> >>>this?
> >>
> >>What code are you executing?  I don't get this behavior at all:
> >>
> >>py> 100 > None
> >>True
> >>py> 1 > None
> >>True
> >>py> 0 > None
> >>True
> >>py> -1 > None
> >>True
> >>py> -100 > None
> >>True
> >
> > Wow ! What is it that are compared ? I think it's the references (i.e.
> > the adresses) that are compared. The "None" reference may map to the
> > physical 0x0 adress whereas 100 is internally interpreted as an object
> > for which the reference (i.e. address) exists and therefore greater than
> > 0x0.
> >
> > Am I interpreting correctly ?
>
> Actually, I believe None is special-cased to work like this.  From
> object.c:
>
> static int
> default_3way_compare(PyObject *v, PyObject *w)
> {
>   ...
>   if (v->ob_type == w->ob_type) {
>   ...
>   Py_uintptr_t vv = (Py_uintptr_t)v;
>   Py_uintptr_t ww = (Py_uintptr_t)w;
>   return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
>   }
>   ...
>   /* None is smaller than anything */
>   if (v == Py_None)
>   return -1;
>   if (w == Py_None)
>   return 1;
>   ...
> }
>
> So None being smaller than anything (except itself) is hard-coded into
> Python's compare routine.  My suspicion is that even if/when objects of
> different types are no longer comparable by default (as has been
> suggested for Python 3.0), None will still compare as smaller than
> anything...
>
> Steve

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


Re: Question about 'None'

2005-01-27 Thread Francis Girard
Le vendredi 28 Janvier 2005 07:49, jfj a écrit :
> Francis Girard wrote:
> > Wow ! What is it that are compared ? I think it's the references (i.e.
> > the adresses) that are compared. The "None" reference may map to the
> > physical 0x0 adress whereas 100 is internally interpreted as an object
> > for which the reference (i.e. address) exists and therefore greater than
> > 0x0.
> >
> > Am I interpreting correctly ?
>
> Not really. If objects of different types are compared (like compare a
> string with a list), then no matter what, all strings but be "smaller"
> than all lists. Or the oposite.
>
> So the fast way to accomplish this is to compare the addresses of the
> object's method table. Something which is common for all objects of
> the same type.
>
>
> G.

I see. There is some rule stating that all the strings are greater than ints 
and smaller than lists, etc.

What was the goal behind this rule ?

Francis Girard

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


Re: Question about 'None'

2005-01-27 Thread Steven Bethard
Francis Girard wrote:
Le jeudi 27 Janvier 2005 21:29, Steven Bethard a écrit :
So None being smaller than anything (except itself) is hard-coded into
Python's compare routine.  My suspicion is that even if/when objects of
different types are no longer comparable by default (as has been
suggested for Python 3.0), None will still compare as smaller than
anything...
Well, here's python doesn't seem to confirm what you're saying :

a = "10"
b = 10
a > b
True
b > a
False
id(a)
1077467584
id(b)
134536516
Actually, this code doesn't contradict what I said at all.  I said that 
None (and only None) was special-cased.

It really looks like the addresses are compared when objects are of different 
types if there is no __cmp__ or __lt__ user made specification to compare 
objects of different types.
Use the source Luke! ;)  Download it from CVS and take a look.  The end 
of default_3way_compare:

static int
default_3way_compare(PyObject *v, PyObject *w)
{
...
/* None is smaller than anything */
if (v == Py_None)
return -1;
if (w == Py_None)
return 1;
/* different type: compare type names; numbers are smaller */
if (PyNumber_Check(v))
vname = "";
else
vname = v->ob_type->tp_name;
if (PyNumber_Check(w))
wname = "";
else
wname = w->ob_type->tp_name;
c = strcmp(vname, wname);
if (c < 0)
return -1;
if (c > 0)
return 1;
/* Same type name, or (more likely) incomparable numeric types */
return ((Py_uintptr_t)(v->ob_type) < (
Py_uintptr_t)(w->ob_type)) ? -1 : 1;
}
So it looks like Python uses the type name.  Testing this:
py> A = type('A', (object,), {})
py> Z = type('Z', (object,), {})
py> lst = [str('a'), dict(b=2), tuple(), Z(), A()]
py> [type(o).__name__ for o in lst]
['str', 'dict', 'tuple', 'Z', 'A']
py> sorted(type(o).__name__ for o in lst)
['A', 'Z', 'dict', 'str', 'tuple']
py> sorted(lst)
[<__main__.A object at 0x011E29D0>, <__main__.Z object at 0x011E29F0>, 
{'b': 2}, 'a', ()]

Yup.  Looks about right.  (Note that the source code also special-cases 
numbers...)

So, the order is consistent, but arbitrary, just as Fredrik Lundh 
pointed out in the documentation.

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


Re: Question about 'None'

2005-01-27 Thread Francis Girard
Le jeudi 27 Janvier 2005 22:07, Steven Bethard a écrit :
> Francis Girard wrote:
> > Le jeudi 27 Janvier 2005 21:29, Steven Bethard a écrit :
> >>So None being smaller than anything (except itself) is hard-coded into
> >>Python's compare routine.  My suspicion is that even if/when objects of
> >>different types are no longer comparable by default (as has been
> >>suggested for Python 3.0), None will still compare as smaller than
> >>anything...
> >
> > Well, here's python doesn't seem to confirm what you're saying :
> a = "10"
> b = 10
> a > b
> >
> > True
> >
> b > a
> >
> > False
> >
> id(a)
> >
> > 1077467584
> >
> id(b)
> >
> > 134536516
>
> Actually, this code doesn't contradict what I said at all.  I said that
> None (and only None) was special-cased.
>

You're right. I just posted too soon.
Sorry.

> > It really looks like the addresses are compared when objects are of
> > different types if there is no __cmp__ or __lt__ user made specification
> > to compare objects of different types.
>
> Use the source Luke! ;)  Download it from CVS and take a look.  The end
> of default_3way_compare:
>

Just want to know the specifications. No matter how it had been implemented.

> static int
> default_3way_compare(PyObject *v, PyObject *w)
> {
>   ...
>   /* None is smaller than anything */
>   if (v == Py_None)
>   return -1;
>   if (w == Py_None)
>   return 1;
>
>   /* different type: compare type names; numbers are smaller */
>   if (PyNumber_Check(v))
>   vname = "";
>   else
>   vname = v->ob_type->tp_name;
>   if (PyNumber_Check(w))
>   wname = "";
>   else
>   wname = w->ob_type->tp_name;
>   c = strcmp(vname, wname);
>   if (c < 0)
>   return -1;
>   if (c > 0)
>   return 1;
>   /* Same type name, or (more likely) incomparable numeric types */
>   return ((Py_uintptr_t)(v->ob_type) < (
>   Py_uintptr_t)(w->ob_type)) ? -1 : 1;
> }
>
> So it looks like Python uses the type name.  Testing this:
>
> py> A = type('A', (object,), {})
> py> Z = type('Z', (object,), {})
> py> lst = [str('a'), dict(b=2), tuple(), Z(), A()]
> py> [type(o).__name__ for o in lst]
> ['str', 'dict', 'tuple', 'Z', 'A']
> py> sorted(type(o).__name__ for o in lst)
> ['A', 'Z', 'dict', 'str', 'tuple']
> py> sorted(lst)
> [<__main__.A object at 0x011E29D0>, <__main__.Z object at 0x011E29F0>,
> {'b': 2}, 'a', ()]
>
> Yup.  Looks about right.  (Note that the source code also special-cases
> numbers...)
>
> So, the order is consistent, but arbitrary, just as Fredrik Lundh
> pointed out in the documentation.
>

Ok. Thank you,

Francis Girard


> Steve

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


Re: Question about 'None'

2005-01-27 Thread Steven Bethard
Francis Girard wrote:
I see. There is some rule stating that all the strings are greater than ints 
and smaller than lists, etc.
Yes, that rule being to compare objects of different types by their type 
names (falling back to the address of the type object if the type names 
are the same, I believe).  Of course, this is arbitrary, and Python does 
not guarantee you this ordering -- it would not raise backwards 
compatibility concerns to, say, change the ordering in Python 2.5.

What was the goal behind this rule ?
I believe at the time, people thought that comparison should be defined 
for all Python objects.  Guido has since said that he wishes the 
decision hadn't been made this way, and has suggested that in Python 
3.0, objects of unequal types will not have a default comparison.

Probably this means ripping the end off of default_3way_compare and 
raising an exception.  As Fredrik Lundh pointed out, they could, if they 
wanted to, also rip out the code that special-cases None too.

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


Re: Question about 'None'

2005-01-27 Thread Francis Girard
Very complete explanation.
Thank you

Francis Girard

Le jeudi 27 Janvier 2005 22:15, Steven Bethard a écrit :
> Francis Girard wrote:
> > I see. There is some rule stating that all the strings are greater than
> > ints and smaller than lists, etc.
>
> Yes, that rule being to compare objects of different types by their type
> names (falling back to the address of the type object if the type names
> are the same, I believe).  Of course, this is arbitrary, and Python does
> not guarantee you this ordering -- it would not raise backwards
> compatibility concerns to, say, change the ordering in Python 2.5.
>
> > What was the goal behind this rule ?
>
> I believe at the time, people thought that comparison should be defined
> for all Python objects.  Guido has since said that he wishes the
> decision hadn't been made this way, and has suggested that in Python
> 3.0, objects of unequal types will not have a default comparison.
>
> Probably this means ripping the end off of default_3way_compare and
> raising an exception.  As Fredrik Lundh pointed out, they could, if they
> wanted to, also rip out the code that special-cases None too.
>
> Steve

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


Re: Question about 'None'

2005-01-27 Thread Steven Bethard
Francis Girard wrote:
a = "10"
b = 10
a > b
True
b > a
False
id(a)
1077467584
id(b)
134536516
Just to thoroughly explain this example, the current CPython 
implementation says that numbers are smaller than everything but None. 
The reason you get such a small id for 'b' is that there is only one 10 
object (for efficiency reasons):

py> 10 is 5 + 5
True
py> 99 is 50 + 49
True
py> 100 is 50 + 50
False
Note that there may be many different instances of integers 100 and 
above (again, in the current CPython implementation).  So to get an 
integer id above a string id, your integer must be at least 100:

py> a = "100"
py> b = 100
py> id(a), id(b)
(18755392, 18925912)
py> a > b
True
py> b > a
False
So, even though b's id is higher than a's, b still compares as smaller 
because the current CPython implementation special-cases the comparison 
to guarantee that numbers are always smaller than all other non-None 
objects.

Again, these are *all* implementation details of the current CPython, 
and depending on these details might run you into troubles if they 
change in a future version of CPython, or if you use a different 
implementation (e.g. Jython or IronPython).

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


Re: Question about 'None'

2005-01-27 Thread flamesrock
Wow! Thanks for all the replies. I'll have to reread everything to
absorb it.

The test code is pretty simple:
if 2 > None:
print 'true'
else:
print 'false'

It prints false every time. I should also mention that I'm using
version 2.0.1 (schools retro solaris machines :( )
At home (version 2.3.4) it prints out 'True' for the above code block.

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


Re: Question about 'None'

2005-01-27 Thread Jeff Shannon
flamesrock wrote:
I should also mention that I'm using
version 2.0.1 (schools retro solaris machines :( )
At home (version 2.3.4) it prints out 'True' for the above code block.
That would explain it -- as /F mentioned previously, the special case 
for None was added in 2.1.

Jeff Shannon
Technician/Programmer
Credit International
--
http://mail.python.org/mailman/listinfo/python-list


Re: Question about 'None'

2005-01-28 Thread Alex Martelli
flamesrock <[EMAIL PROTECTED]> wrote:
   ...
> (The reason I ask is sortof unrelated. I wanted to use None as a
> variable for which any integer, including negative ones have a greater
> value so that I wouldn't need to implement any tests or initializations
> for a loop that finds the maximum of a polynomial between certain x
> values. Anything is greater than nothing, no?)

To have this work reliably across versions of Python (and you mentioned
you need it to work on 2.0 as well as 2.3...) you have to make your own
sentinel class, such as:

class MinusInfinity:
def __cmp__(self, other):
if isinstance(other, MinusInfinity): return 0
else: return -1
minusInfinity = MinusInfinity()

Now, you should be able to use this 'minusInfinity" as ``a variable for
which any integer ... has a greater value'', as you wished to use None.

(Untested code, as I don't have any 2.0 on which to test it anyway).


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


Re: Question about 'None'

2005-01-28 Thread jfj
Francis Girard wrote:
What was the goal behind this rule ?
If you have a list which contains integers, strings, tuples, lists and
dicts and you sort it and print it, it will be easier to detect what
you're looking for:)
G.

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


Re: Question about 'None'

2005-01-28 Thread Francis Girard
Le vendredi 28 Janvier 2005 22:54, jfj a écrit :
> Francis Girard wrote:
> > What was the goal behind this rule ?
>
> If you have a list which contains integers, strings, tuples, lists and
> dicts and you sort it and print it, it will be easier to detect what
> you're looking for:)
>
>
> G.

Mmm. Certainly not one of my top requirements.

Anyway, it would be better to separately provide a compare function that 
orders elements according to their types instead of making the comparison 
operators default semantics somewhat obscure (and dangerous).

Thank you
Francis Girard

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


Re: question about functions

2005-04-14 Thread James Stroud
Just pass a list. E.g.:

# start of ascript

def my_funk(alist):
  print "the first argument: %s" % alist[1]
  print "the second argument: %s" % alist[2]

mylist = ['wuzzup,','g?']

my_funk(mylist)

# end of ascript


Here is the output you expect:

the first argument: wuzzup,
the second argument: g?

On Thursday 14 April 2005 09:44 pm, chris patton wrote:
> Hi everyone.
>
> I have a question about passing arguments to python functions. Is there
> any way to make this job act like Perl?
>
> sub my_funk {
>
> print "the first argument: $_[0]\n";
> print "the second argument: $_[1]\n";  }
>
> In other words, can I call the arguments from a list?

-- 
James Stroud, Ph.D.
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

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


Re: question about functions

2005-04-14 Thread James Stroud
Oops, I messed up the indices on the previous post.
Also, maybe you are thinking a bit more perlish:

# start of ascript

def my_funk(*alist):
  print "the first argument: %s" % alist[0]
  print "the second argument: %s" % alist[1]

my_funk('wuzzup,','g?')

# end of ascript

On Thursday 14 April 2005 09:44 pm, chris patton wrote:
> Hi everyone.
>
> I have a question about passing arguments to python functions. Is there
> any way to make this job act like Perl?
>
> sub my_funk {
>
> print "the first argument: $_[0]\n";
> print "the second argument: $_[1]\n";  }
>
> In other words, can I call the arguments from a list?

-- 
James Stroud, Ph.D.
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

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


Re: question about functions

2005-04-14 Thread Heiko Wundram
Am Freitag, 15. April 2005 06:44 schrieb chris patton:
> In other words, can I call the arguments from a list?

Yes.

>>> def testfunc(*args):
...   print args[0]
...   print args[1]
...
>>> testfunc("this is","a test")
this is
a test

Read up on positional and keyword arguments (the latter are something that'd 
make me choose python over anything else instantly) in the Python tutorial 
and documentation.

-- 
--- Heiko.
listening to: Pearl Jam - Given To Fly
  see you at: http://www.stud.mh-hannover.de/~hwundram/wordpress/


pgpJHTrjaYbYA.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: question about functions

2005-04-14 Thread Donn Cave
Quoth "chris patton" <[EMAIL PROTECTED]>:
| Hi everyone.
|
| I have a question about passing arguments to python functions. Is there
| any way to make this job act like Perl?
|
| sub my_funk {
|
| print "the first argument: $_[0]\n";
| print "the second argument: $_[1]\n";  }
|
| In other words, can I call the arguments from a list?


def my_funk(*a):
print 'first', a[0]
print 'second', a[1]

my_funk('one', 'two')

You can mix this with normal argument usage, and there is a
similar way to pass parameters to a function from a tuple.

Donn Cave, [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question on metaclasses

2005-04-24 Thread Diez B. Roggisch
Steffen Glückselig wrote:

> Hello,
> 
> I've been experimenting with metaclasses a bit (even though I am quite
> a newbie to python) and stumpled over the following problem in my code:
> 
> class Meta(type):
>   def __init__(cls, name, bases, dct):
> for attr, value in dct.items():
>   if callable(value):
> dct[attr] = wrapper(value)
> 
> wrapper adds debugging-information to methods of the class (at least
> that is my plan).
> 
> Using dct[attr] = wrapper(value) does not result in wrapped methods,
> though. Using setattr(cls, attr, wrapper(value)) creates the desired
> effect, though.
> 
> Why are the changes to dct not visible in the instantiated class? Is
> dct not the namespace of the class currently instantiated?

You don't use metaclasses correctly I believe. Usage should look like this:

class Foo(type):
def __new__(cls, name, bases, dict):

for k,v in [(k, v) for k,v in dict.items() if callable(v)]:
cls.wrap(k,v,cls.get_directives(v), dict)

return super(Foo, self).__new__(self, name, bases, dict)

Notice the __new__ instead of __init__, and the call to (actually, through
super) type.__new__

-- 
Regards,

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


Re: Question on metaclasses

2005-04-24 Thread Diez B. Roggisch
> class Foo(type):
> def __new__(cls, name, bases, dict):
> 
> for k,v in [(k, v) for k,v in dict.items() if callable(v)]:
> cls.wrap(k,v,cls.get_directives(v), dict)
> 
> return super(Foo, self).__new__(self, name, bases, dict)

There is a confusion of self and cls above - rename self with cls.
-- 
Regards,

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


Re: Question on metaclasses

2005-04-24 Thread Reinhold Birkenfeld
Diez B. Roggisch wrote:
>> class Foo(type):
>> def __new__(cls, name, bases, dict):
>> 
>> for k,v in [(k, v) for k,v in dict.items() if callable(v)]:
>> cls.wrap(k,v,cls.get_directives(v), dict)
>> 
>> return super(Foo, self).__new__(self, name, bases, dict)
> 
> There is a confusion of self and cls above - rename self with cls.

And remove the first argument to __new__.

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


Re: Question on metaclasses

2005-04-24 Thread Steffen Glückselig
Are wrap and get_directives somehow built-in? I couldn't find
references to them.

I've noticed, too, that using __new__ I can manipulate the dictionary
resulting in the behavior I intented.

I'd rather like to know: Why does it work in __new__ but not in
__init__?

And, stimulated by your response: Why is using __new__ superior to
__init__?


best regards
Steffen

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


Re: Question on metaclasses

2005-04-24 Thread Reinhold Birkenfeld
Steffen Glückselig wrote:
> Are wrap and get_directives somehow built-in? I couldn't find
> references to them.
> 
> I've noticed, too, that using __new__ I can manipulate the dictionary
> resulting in the behavior I intented.
> 
> I'd rather like to know: Why does it work in __new__ but not in
> __init__?
> 
> And, stimulated by your response: Why is using __new__ superior to
> __init__?

At short, __new__ is called on the class and must return the instance; that
means that the instance isn't created yet.

__init__, on the other hand, is called on the instance which is already created
at that point. So changing dct in __init__ is pointless, because the instance
(which is a class actually) is already created.

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


Re: Question on metaclasses

2005-04-24 Thread Diez B. Roggisch
Reinhold Birkenfeld wrote:

> Diez B. Roggisch wrote:
>>> class Foo(type):
>>> def __new__(cls, name, bases, dict):
>>> 
>>> for k,v in [(k, v) for k,v in dict.items() if callable(v)]:
>>> cls.wrap(k,v,cls.get_directives(v), dict)
>>> 
>>> return super(Foo, self).__new__(self, name, bases, dict)
>> 
>> There is a confusion of self and cls above - rename self with cls.
> 
> And remove the first argument to __new__.

Ehm, no, I don't think so. The code was copied and pasted from a working
metaclass (at least I hope so...), and in the original code a underscore
was used for the first argument. I've been following that bad habit for a
while but recently started to be more following to the established
conventions. So I rewrote that code on the fly. 

This is the full metaclass:

class TransactionAware(type):
TAS_REX = re.compile("tas::([^, ]+(, *[^, ]+)*)")


WRAPPERS = {
"create" : w_create,
"active" : w_active,
"bind" : w_bind,
"sync" : w_sync,
"autocommit" : w_autocommit,
}
def __new__(_, name, bases, dict):

for k,v in [(k, v) for k,v in dict.items() if callable(v)]:
_.wrap(k,v,_.get_directives(v), dict)

return super(TransactionAware, _).__new__(_, name, bases, dict)

def wrap(_, name, fun, ds, dict, level=0):
if ds:
d, rest = ds[0], ds[1:]
key = "_taw_%s_%i" % (name, level)
try:
w_fun = _.WRAPPERS[d](key)
dict[key] = fun
_.wrap(name, w_fun, rest, dict, level+1)
except KeyError, e:
print "No transaction aware property named %s" % d
raise e
else:

dict[name] = fun

wrap = classmethod(wrap)

def get_directives(_, v):
try:
doc = v.__doc__
res = []
if doc:
for l in doc.split("\n"):
m = _.TAS_REX.match(l.strip())
if m:
res += [s.strip() for s in m.group(1 ).split(",")]
res.reverse()
return res
except KeyError:
return []
get_directives = classmethod(get_directives)



-- 
Regards,

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


Re: Question on metaclasses

2005-04-24 Thread Steffen Glückselig
So dct is something like a template rather than the __dict__ of the
actual class?

I'd assume that changing the content of a dict would be possible even
after it has been assigned to some object (here, a class).


thanks and best regards
Steffen

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


Re: Question on metaclasses

2005-04-24 Thread Reinhold Birkenfeld
Diez B. Roggisch wrote:
> Reinhold Birkenfeld wrote:
> 
>> Diez B. Roggisch wrote:
 class Foo(type):
 def __new__(cls, name, bases, dict):
 
 for k,v in [(k, v) for k,v in dict.items() if callable(v)]:
 cls.wrap(k,v,cls.get_directives(v), dict)
 
 return super(Foo, self).__new__(self, name, bases, dict)
>>> 
>>> There is a confusion of self and cls above - rename self with cls.
>> 
>> And remove the first argument to __new__.
> 
> Ehm, no, I don't think so. The code was copied and pasted from a working
> metaclass (at least I hope so...), and in the original code a underscore
> was used for the first argument. I've been following that bad habit for a
> while but recently started to be more following to the established
> conventions. So I rewrote that code on the fly. 

Oh yes. I forgot that __new__ is a staticmethod anyhow.

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


Re: Question about mutexes

2005-06-01 Thread Reinhold Birkenfeld
Jan Danielsson wrote:
> In OS/2 C, I would do this:
> 
> main()
> {
> ...
> DosCreateMutexSem(NULL, &hmtx, 0UL, FALSE);
> ...
> }
> 
> thread()
> {
> ...
> DosRequestMutexSem(hmtx);
> 
> Locked!
> 
> DosReleaseMutexSem(hmtx);
> ...
> }
> 
> How would I go about doing that in Python?

I think you will want to create a threading.Lock object.

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


Re: Question about mutexes

2005-06-01 Thread Jan Danielsson
Reinhold Birkenfeld wrote:
[---]
>>How would I go about doing that in Python?
> 
> I think you will want to create a threading.Lock object.

It would seem so. Thanks for the tip!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question about smtplib

2005-10-03 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> Hey there,
> 
> i am using the smtplib module in python 2.3
> 
> my question is, this works:
> 
> server = smtplib.SMTP(localhost)
> 
> then server.sendmail(to address, from address, message)
> 
> 
> what i want to know is, how does the connection work?
> 
> when i do server.sendmail, does it connect then ? or did it connect
> when
> i made the object ?
> 
> the reason i need to know is i need to send several emails out at once
> and would be best to only connect once, i think.
> 
> i know that i can call server.close(), i just dont know when it was
> opened.
> thanks
> 
If you provide the host name the server is connected immediately. You 
can use that connection to send several emails, terminating the 
connection when you call the object's quit() method.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: question about smtplib

2005-10-03 Thread nephish
cool. so this line
server = smtplib.SMTP(localhost)
is when i connect ?

i had my syntax wrong anyway, i was using server.close()
instead of server.quit()

thanks much

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


Re: question about smtplib

2005-10-03 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> cool. so this line
> server = smtplib.SMTP(localhost)
> is when i connect ?

http://www.python.org/doc/lib/module-smtplib.html

 "If the optional host and port parameters are given, the
SMTP connect() method is called with those parameters
during initialization."

"For normal use, you should only require the initialization/
connect, sendmail(), and quit() methods. An example is
included below."





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


Re: question about smtplib

2005-10-03 Thread Tim Roberts
[EMAIL PROTECTED] wrote:

>cool. so this line
>server = smtplib.SMTP(localhost)
>is when i connect ?

Use the source, Luke.  Source code for every standard module is included on
your hard disk.  If you look in the __init__ for "class SMTP", your
question will be answered.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question about smtplib

2005-10-04 Thread Piet van Oostrum
> Tim Roberts <[EMAIL PROTECTED]> (TR) wrote:

>TR> [EMAIL PROTECTED] wrote:
>>> cool. so this line
>>> server = smtplib.SMTP(localhost)
>>> is when i connect ?

>TR> Use the source, Luke.  Source code for every standard module is included on
>TR> your hard disk.  If you look in the __init__ for "class SMTP", your
>TR> question will be answered.

The documentation should be the ultimate reference for the API. The source
is just implementation detail which may change in the future.
-- 
Piet van Oostrum <[EMAIL PROTECTED]>
URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4]
Private email: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question about smtplib

2005-10-04 Thread nephish
thanks for all the help,
got it working ok now, connecting once, sending many.

thanks for the link too. 

cheers,
sk

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


Re: question about output

2005-10-05 Thread Java and Swing
doh!  nevermind, my original output had e and d in it.

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


Re: question about output

2005-10-05 Thread Steven D'Aprano
On Wed, 05 Oct 2005 07:24:31 -0700, Java and Swing wrote:

> i have printed out some numbers and they look like
> 
> 10944800e
> 10952560d

They don't look like numbers to me. They have letters at the end. What are
they? What does the letter mean?


> ...if i want to later assign this type of number to variable how can i
> do it?
> 
> for example i can't do...
> 
>>> x = 10944800e
> 
> ..since it says "invalid token" on the "e".

How did you get the "numbers"? If you just typed them in by hand, then
leave the "e" off and you have a number.

If they are supposed to be hex numbers, then you can use:

x = int("10944800e", 16)  # note the quote marks
print x

-> 4450451470

If you don't care about the numeric value, then you just put quote marks
around the number+letter:

x = "10944800e"

but then x will be a string, not a number. 

If none of these answers is what you need, you will need to explain your
problem a little better.


-- 
Steven.

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


Re: question about output

2005-10-05 Thread utabintarbo
Given that the format is consistent (and the last char is not part of
the number you want), you can probably do something like this:

x = int('10944800e'[:-1])

Disclaimer: I am a n00b. YMMV ;-)

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


Re: question about smtplib

2005-10-05 Thread Tim Roberts
Piet van Oostrum <[EMAIL PROTECTED]> wrote:

>> Tim Roberts <[EMAIL PROTECTED]> (TR) wrote:
>
>>TR> [EMAIL PROTECTED] wrote:
 cool. so this line
 server = smtplib.SMTP(localhost)
 is when i connect ?
>
>>TR> Use the source, Luke.  Source code for every standard module is included 
>>on
>>TR> your hard disk.  If you look in the __init__ for "class SMTP", your
>>TR> question will be answered.
>
>The documentation should be the ultimate reference for the API. The source
>is just implementation detail which may change in the future.

I won't argue with that, but the question of "exactly when does the
connection occur" is in itself an implementation detail.  I wouldn't expect
it to be answered in the documentation.
-- 
- Tim Roberts, [EMAIL PROTECTED]
  Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about StringIO

2005-10-09 Thread Steve Holden
Frank Millman wrote:
> Hi all
> 
> I understand that StringIO creates a file-like object in memory.
> 
> Is it possible to invoke another program, using os.system() or
> os.popen(), and use the < redirect operator, so that the other program
> reads my StringIO object as its input?
> 
> I will provide more details if required, but hopefully this is enough
> for a simple yes or no answer, and if so, how.
> 
> BTW, I have tried using popen2() and passing my data via stdin, but the
> other program (psql) does not react well to this - again, I will give
> more info if necessary.
> 
Unfortunately the StringIO module only creates instances inside the 
process they are called: these objects have no existence to the 
operating system or to other processes, and so can't be used for 
inter-process communication.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: Question about StringIO

2005-10-09 Thread Diez B. Roggisch
Frank Millman wrote:
> Hi all
> 
> I understand that StringIO creates a file-like object in memory.
> 
> Is it possible to invoke another program, using os.system() or
> os.popen(), and use the < redirect operator, so that the other program
> reads my StringIO object as its input?

No. Processes don't share memory - thus you have to either use a temp 
file, or pipes.

> BTW, I have tried using popen2() and passing my data via stdin, but the
> other program (psql) does not react well to this - again, I will give
> more info if necessary.

Better do so :)

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


Re: Question about StringIO

2005-10-10 Thread Frank Millman

Diez B. Roggisch wrote:
> Frank Millman wrote:
> > Hi all
> >
> > I understand that StringIO creates a file-like object in memory.
> >
> > Is it possible to invoke another program, using os.system() or
> > os.popen(), and use the < redirect operator, so that the other program
> > reads my StringIO object as its input?
>
> No. Processes don't share memory - thus you have to either use a temp
> file, or pipes.
>
> > BTW, I have tried using popen2() and passing my data via stdin, but the
> > other program (psql) does not react well to this - again, I will give
> > more info if necessary.
>
> Better do so :)
>
> Diez

Thanks, Steve and Diez, for the replies. I didn't think it was
possible, but it was worth asking :-)

I will try to explain my experience with popen() briefly.

I have some sql scripts to create tables, indexes, procedures, etc. At
present there are about 50 scripts, but this number will grow. I have
been running them manually so far. Now I want to automate the process.

I am supporting PostgreSQL and MS SQL Server, and the syntax is
slightly different in some cases. Rather than maintain two sets of
scripts, I prefix some lines with -pg- or -ms- to indicate the
platform, and then use Python to parse the scripts and generate a
correct output for each platform, passing it to 'psql' and 'osql'
respectively, using popen().

I have had a few problems, but it would take too long to describe them
all, and I just want a working solution, so I will focus on my latest
attempt.

I run through all the scripts and create a StringIO object with the
string I want to pass. It is about 250 000 bytes long. If I run psql
using popen(), and pass it the string via stdin, it works fine, but I
get all the messages on the screen. If I do the same, but end the
command with ' > fjm 2>&1' it works correctly and the messages end up
in the file fjm, which is about 40 000 bytes long. If I run it with
popen4(), it starts ok, but then hangs about 1/4 of the way through.
Exactly the same happens on MSW. It seems to be hitting a limit on the
size of the stdout file - is that possible?

For my purposes, I will be happy to use popen() and a choice of no
redirection, redirect to a file, or redirect to /dev/null. The question
about popen4() is therefore academic, though I would be interested to
know the answer.

BTW, is there an equivalent of /dev/null on MSW?

Thanks in advance for any suggestions.

Frank

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


Re: Question about StringIO

2005-10-10 Thread Benjamin Niemann
Frank Millman wrote:

> I will try to explain my experience with popen() briefly.
> 
> I have some sql scripts to create tables, indexes, procedures, etc. At
> present there are about 50 scripts, but this number will grow. I have
> been running them manually so far. Now I want to automate the process.
> 
> I am supporting PostgreSQL and MS SQL Server, and the syntax is
> slightly different in some cases. Rather than maintain two sets of
> scripts, I prefix some lines with -pg- or -ms- to indicate the
> platform, and then use Python to parse the scripts and generate a
> correct output for each platform, passing it to 'psql' and 'osql'
> respectively, using popen().
> 
> I have had a few problems, but it would take too long to describe them
> all, and I just want a working solution, so I will focus on my latest
> attempt.
> 
> I run through all the scripts and create a StringIO object with the
> string I want to pass. It is about 250 000 bytes long. If I run psql
> using popen(), and pass it the string via stdin, it works fine, but I
> get all the messages on the screen. If I do the same, but end the
> command with ' > fjm 2>&1' it works correctly and the messages end up
> in the file fjm, which is about 40 000 bytes long. If I run it with
> popen4(), it starts ok, but then hangs about 1/4 of the way through.
> Exactly the same happens on MSW. It seems to be hitting a limit on the
> size of the stdout file - is that possible?
> 
> For my purposes, I will be happy to use popen() and a choice of no
> redirection, redirect to a file, or redirect to /dev/null. The question
> about popen4() is therefore academic, though I would be interested to
> know the answer.

That's probably a deadlock as described in


> BTW, is there an equivalent of /dev/null on MSW?

Dunno - but as a last resort, you could create a tempfile with a unique name
(to be sure, not to override any existing data), dump your output there and
later os.unlink() it...

-- 
Benjamin Niemann
Email: pink at odahoda dot de
WWW: http://www.odahoda.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about StringIO

2005-10-10 Thread Diez B. Roggisch
> Thanks, Steve and Diez, for the replies. I didn't think it was
> possible, but it was worth asking :-)
> 
> I will try to explain my experience with popen() briefly.
> 
> I have some sql scripts to create tables, indexes, procedures, etc. At
> present there are about 50 scripts, but this number will grow. I have
> been running them manually so far. Now I want to automate the process.
> 
> I am supporting PostgreSQL and MS SQL Server, and the syntax is
> slightly different in some cases. Rather than maintain two sets of
> scripts, I prefix some lines with -pg- or -ms- to indicate the
> platform, and then use Python to parse the scripts and generate a
> correct output for each platform, passing it to 'psql' and 'osql'
> respectively, using popen().

Why don't youn use te python DB-Api instead?


Regards,

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


Re: Question about StringIO

2005-10-11 Thread Frank Millman
Benjamin Niemann wrote:
> Frank Millman wrote:
>
> > I will try to explain my experience with popen() briefly.
> >
> > I run through all the scripts and create a StringIO object with the
> > string I want to pass. It is about 250 000 bytes long. If I run psql
> > using popen(), and pass it the string via stdin, it works fine, but I
> > get all the messages on the screen. If I do the same, but end the
> > command with ' > fjm 2>&1' it works correctly and the messages end up
> > in the file fjm, which is about 40 000 bytes long. If I run it with
> > popen4(), it starts ok, but then hangs about 1/4 of the way through.
> > Exactly the same happens on MSW. It seems to be hitting a limit on the
> > size of the stdout file - is that possible?
> >
>
> That's probably a deadlock as described in
> 
>

Thanks for this pointer. I have read it, but I don't think it applies
to my situation, as it talks about 'reading' from the child's stdout
while the child is 'writing' to stderr. I am not doing that, or at
least not consciously. Here is a code snippet. 's' is a StringIO object
that contains my input. It is about 6000 lines/25 bytes long.

-

sql_stdin,sql_stdout = os.popen4('psql -U %s -d %s' % (user,database))

sql_stdin.writelines(s.readlines())
s.close()
sql_stdin.close()

-

It starts, and then hangs, after processing about 6% of my input.

If I add ' > fjm 2>&1' to the command, it works, so it is definitely
connected with the child writing to stdout/stderr.

I tried storing my input in a list, and passing ''.join(s), but it had
the same result. I also looped over the list and wrote one line at a
time to sql_stdin - same result.

I can work around this, so a solution is not critical. However, it
would be nice to know if this is a limitation of popen4(), or if I am
doing something wrong.

> > BTW, is there an equivalent of /dev/null on MSW?
>
> Dunno - but as a last resort, you could create a tempfile with a unique name
> (to be sure, not to override any existing data), dump your output there and
> later os.unlink() it...
>

A quick google revealed the answer - there is a device called NUL which
achieves the same purpose.

Thanks

Frank

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


Re: Question about StringIO

2005-10-11 Thread Frank Millman
Diez B. Roggisch wrote:
> > Thanks, Steve and Diez, for the replies. I didn't think it was
> > possible, but it was worth asking :-)
> >
> > I will try to explain my experience with popen() briefly.
> >
> > I have some sql scripts to create tables, indexes, procedures, etc. At
> > present there are about 50 scripts, but this number will grow. I have
> > been running them manually so far. Now I want to automate the process.
> >
> > I am supporting PostgreSQL and MS SQL Server, and the syntax is
> > slightly different in some cases. Rather than maintain two sets of
> > scripts, I prefix some lines with -pg- or -ms- to indicate the
> > platform, and then use Python to parse the scripts and generate a
> > correct output for each platform, passing it to 'psql' and 'osql'
> > respectively, using popen().
>
> Why don't youn use te python DB-Api instead?
>
>
> Regards,
>
> Diez

My scripts are used to create the tables in the database. I didn't
think that DB-API covered that. However, even if it did, I don't think
it would handle differences such as the following.

For Unicode support, PostgreSQL uses the character-set specified when
the database is created. SQL Server allows you to specify it for each
column, using the datatype NCHAR and NVARCHAR instead of CHAR and
VARCHAR.

PostgreSQL uses data types called DATE and TIMESTAMP. SQL Server uses
DATETIME (it also uses TIMESTAMP, but that is used for something else).

Both DBMS's have the concept of a column which is automatically
assigned a 'next number' each time a row is created, but the syntax for
defining the column is completely different.

PostgreSQL allows the use of a WHERE clause when creating an INDEX,
which is useful if you only want to index a subset of a table.

SQL Server has the concept of a CLUSTERED INDEX, whereby it stores the
rows physically in index sequence. It defaults to using a clustered
index for the primary key. Often this is not what you want, so it is
desirable to specify the primary key as NONCLUSTERED, and then specify
a CLUSTERED index for a more frequently used column.

These are just a few of the differences, but you get the idea. If there
is a better way to do this in a cross-platform manner, I would love to
know how.

Thanks

Frank

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


Re: Question about StringIO

2005-10-11 Thread Diez B. Roggisch
> Thanks for this pointer. I have read it, but I don't think it applies
> to my situation, as it talks about 'reading' from the child's stdout
> while the child is 'writing' to stderr.

But that is exactly the point: the psql blocks because you don't read 
away the buffered data. Start a thread, read that stdout/stderr and see 
if things go smoothly.

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


Re: Question about StringIO

2005-10-11 Thread Diez B. Roggisch
> My scripts are used to create the tables in the database. I didn't
> think that DB-API covered that. 

The DB-Api covers executin arbirary SQL - either DDL or DML. It is 
surely centered around DML, but that doesn't mean that its not usabel to 
issue "create ..." statements.

 >However, even if it did, I don't think
> it would handle differences such as the following.



All that has nocthing to do with teh API - you'd still need your 
differentiated DDL - but the communication with the programs would go away.

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


Re: Question about StringIO

2005-10-11 Thread Frank Millman

Diez B. Roggisch wrote:
> > Thanks for this pointer. I have read it, but I don't think it applies
> > to my situation, as it talks about 'reading' from the child's stdout
> > while the child is 'writing' to stderr.
>
> But that is exactly the point: the psql blocks because you don't read
> away the buffered data. Start a thread, read that stdout/stderr and see
> if things go smoothly.
>
> Diez

Of course (kicks himself), it is obvious now that you have explained
it. I tried your suggestion and it works perfectly.

Many thanks

Frank

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


Re: Question about StringIO

2005-10-11 Thread Frank Millman

Diez B. Roggisch wrote:
> > My scripts are used to create the tables in the database. I didn't
> > think that DB-API covered that.
>
> The DB-Api covers executin arbirary SQL - either DDL or DML. It is
> surely centered around DML, but that doesn't mean that its not usabel to
> issue "create ..." statements.
>
>  >However, even if it did, I don't think
> > it would handle differences such as the following.
>
> 
>
> All that has nocthing to do with teh API - you'd still need your
> differentiated DDL - but the communication with the programs would go away.
>
> Diez

I understand. It certainly gives me an alternative approach - I will
experiment to see which suits my purpose best.

Many thanks for your assistance.

Frank

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


Re: Question on re.IGNORECASE

2005-10-20 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
> Hi,
> 
> I'm having some problems with basic RE in python. I was wondering
> whether
> somebody could provide a hint on what's going wrong with the following
> script. Comments are included.
> 
> TIA.
> -myself
> 
> 
>>python2.3
> 
> Python 2.3.4 (#1, Nov 18 2004, 13:39:30)
> [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-39)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> 
import re
pattern = re.compile('.*HTTP/(\d\.\d) *(\d*) *(.*)$')
pattern.search("GGHTTP/1.1 200 OK\r\n", re.IGNORECASE)
> 
> <_sre.SRE_Match object at 0xb75c6ed0>
> 
pattern.search("GHTTP/1.1 200 OK\r\n", re.IGNORECASE)
> 
> # this makes no sense to me. Why is the previous line matched

Because the second argument to pattern.search() is the position where the 
search starts, not a flag. re.IGNORECASE == 2 so your search is skipping the 
first two chars.

Try giving the flags as a second argument to re.compile():
 >>> import re
 >>> re.IGNORECASE
2
 >>> pattern = re.compile('.*HTTP/(\d\.\d) *(\d*) *(.*)$', re.IGNORECASE)
 >>> pattern.search("GGHTTP/1.1 200 OK\r\n")
<_sre.SRE_Match object at 0x00965980>
 >>> pattern.search("GHTTP/1.1 200 OK\r\n")
<_sre.SRE_Match object at 0x009659D0>
 >>> pattern.search("Ghttp/1.1 200 OK\r\n")
<_sre.SRE_Match object at 0x009651B0>

Kent


> # and this not?
> 
pattern.search("GHTTP/1.1 200 OK\r\n")
> 
> <_sre.SRE_Match object at 0xb758d020>
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question on re.IGNORECASE

2005-10-20 Thread chemag
OK, I got it.

- The re module search function syntax is:

search( pattern, string[, flags])

where re.IGNORECASE is a valid flag.

- The RE Object search method syntax is:

search( string[, pos[, endpos]])

where "The optional second parameter pos gives an index in the string
where the search is to start; it defaults to 0"

It turns out that re.IGNORECASE has the value
2.

Am I the only person bitten by this?

http://docs.python.org/lib/node115.html
http://docs.python.org/lib/re-objects.html

-myself

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


Re: Question on re.IGNORECASE

2005-10-20 Thread chemag
Thanks for your help. 

-myself

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


Re: Question about inheritance...

2005-10-22 Thread Oliver Andrich
Hi,

22 Oct 2005 14:40:09 -0700, KraftDiner <[EMAIL PROTECTED]>:
> I have a base class called Shape
> And then classes like Circle, Square, Triangle etc, that inherit from
> Shape:
>
> My quesiton is can a method of the Shape class call a method in Circle,
> or Square etc...?

even there would exist a way to accomplish that, I would suggest to
rethink your class hierachy. Such requirements can show serious design
problems.

Best regards,
Oliver

--
Oliver Andrich <[EMAIL PROTECTED]> --- http://roughbook.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about inheritance...

2005-10-22 Thread Mike Meyer
"KraftDiner" <[EMAIL PROTECTED]> writes:

> I have a base class called Shape
> And then classes like Circle, Square, Triangle etc, that inherit from
> Shape:
>
> My quesiton is can a method of the Shape class call a method in Circle,
> or Square etc...?

Yup:

>>> class Shape(object):
...  def commented_draw(self):
...   print "Drawing", self.__class__.__name__
...   self.draw()
... 
>>> class Circle(Shape):
...  def draw(self):
...   print "Drawing a Circle"
... 
>>> c = Circle()
>>> c.commented_draw()
Drawing Circle
Drawing a Circle
>>> 

Or maybe you meant invoking them directly, which a method in Shape
would do by calling Circle.draw(self). The latter is ugly - you should
use self.draw() to invoke the draw routine that's correct for self.

  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about inheritance...

2005-10-22 Thread Ron Adam
KraftDiner wrote:

> I have a base class called Shape
> And then classes like Circle, Square, Triangle etc, that inherit from
> Shape:
> 
> My quesiton is can a method of the Shape class call a method in Circle,
> or Square etc...?


This looks familiar. :-)

Yes, it can if it has references to them.

Could you explain a little better what you are doing.

Since I'm working on the same (or similar) thing maybe we can share our 
results, (or efforts).

Cheers,
Ron


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


  1   2   3   4   5   6   7   8   9   >