Re: Inexplicable timings
On Aug 2, 12:43 am, MRAB <[EMAIL PROTECTED]> wrote:
> I'm looking at the implementation of regular expressions in Python and
> wrote a script to test my changes. This is the script:
>
> import re
> import time
>
> base = "abc"
> final = "d"
>
> for n in [100, 1000, 1]:
> for f in [final, ""]:
> for r in ["+", "+?"]:
> pattern = "(?:%s)%s%s" % (base, r, final)
> text_format = "(?:%s){%d}%s" % (base, n, f)
> regex = re.compile(pattern)
> text = base * n + f
> start_time = time.clock()
> found = regex.search(text)
> finish_time = time.clock()
> duration = finish_time - start_time
> print "%s\t:: %s\t:: %.3f" % (text_format, pattern,
> duration)
>
> I've found some puzzling behaviour that I can't explain. If I delete
> sre_parse.pyc or sre_compile.pyc before running the script I get
> timings like this:
>
> (?:abc){100}d :: (?:abc)+d :: 0.000
> (?:abc){100}d :: (?:abc)+?d :: 0.000
> (?:abc){100} :: (?:abc)+d :: 0.000
> (?:abc){100} :: (?:abc)+?d :: 0.000
> (?:abc){1000}d :: (?:abc)+d :: 0.000
> (?:abc){1000}d :: (?:abc)+?d :: 0.000
> (?:abc){1000} :: (?:abc)+d :: 0.022
> (?:abc){1000} :: (?:abc)+?d :: 0.020
> (?:abc){1}d :: (?:abc)+d :: 0.001
> (?:abc){1}d :: (?:abc)+?d :: 0.000
> (?:abc){1} :: (?:abc)+d :: 1.961
> (?:abc){1} :: (?:abc)+?d :: 1.756
>
> Subsequent runs give timings like this:
>
> (?:abc){100}d :: (?:abc)+d :: 0.000
> (?:abc){100}d :: (?:abc)+?d :: 0.000
> (?:abc){100} :: (?:abc)+d :: 0.000
> (?:abc){100} :: (?:abc)+?d :: 0.000
> (?:abc){1000}d :: (?:abc)+d :: 0.000
> (?:abc){1000}d :: (?:abc)+?d :: 0.000
> (?:abc){1000} :: (?:abc)+d :: 0.020
> (?:abc){1000} :: (?:abc)+?d :: 0.020
> (?:abc){1}d :: (?:abc)+d :: 0.001
> (?:abc){1}d :: (?:abc)+?d :: 0.000
> (?:abc){1} :: (?:abc)+d :: 3.953
> (?:abc){1} :: (?:abc)+?d :: 1.763
>
> The second-from-last takes twice as long!
>
> This is repeatable.
>
> Python 2.5.2, on the other hand, gives timings like this:
>
> (?:abc){100}d :: (?:abc)+d :: 0.000
> (?:abc){100}d :: (?:abc)+?d :: 0.000
> (?:abc){100} :: (?:abc)+d :: 0.000
> (?:abc){100} :: (?:abc)+?d :: 0.000
> (?:abc){1000}d :: (?:abc)+d :: 0.000
> (?:abc){1000}d :: (?:abc)+?d :: 0.000
> (?:abc){1000} :: (?:abc)+d :: 0.044
> (?:abc){1000} :: (?:abc)+?d :: 0.027
> (?:abc){1}d :: (?:abc)+d :: 0.002
> (?:abc){1}d :: (?:abc)+?d :: 0.002
> (?:abc){1} :: (?:abc)+d :: 4.547
> (?:abc){1} :: (?:abc)+?d :: 2.858
>
> repeatably, irrespective of whether I delete the .pyc files first.
>
> Why is only one timing affected, and why by so much? Python quits
> after each run, so it can't be anything cumulative, surely. I've
> considered things like caching, for example compiling the .pyc files
> on the first run, but can't see why (or how) that would cause what I
> see.
>
> Can anyone suggest a factor that I might be missing? Any suggestions
> welcome!
>
I've found the cause. It's the memory allocation.
For future reference, I think what's happening is that when Python
generates the .pyc files it's using more memory (grabbing it from the
system) so that when my code needs to allocate Python can do it more
quickly; if Python didn't have to generate the .pyc files then it has
to grab more from the system, which takes longer. Or something like
that.
Anyway, it's fixed. :-)
--
http://mail.python.org/mailman/listinfo/python-list
Re: Interconvert a ctypes.Structure to/from a binary string?
On 2 Aug., 08:35, Andrew Lentvorski <[EMAIL PROTECTED]> wrote: > Basically, I'd like to use the ctypes module as a much more descriptive > "struct" module. > > Is there a way to take a ctypes.Structure-based class and convert it > to/from a binary string? > > Thanks, > -a My first idea was : from ctypes import * from pickle import * class T(Structure): pass print dumps(T()) which raises an TypeError, "abstract class". And then I found http://osdir.com/ml/python.ctypes/2006-03/msg9.html Greetings, Uwe -- http://mail.python.org/mailman/listinfo/python-list
Searching for some kind of data type
Hi,
for an FTP server I wrote I'd need to group the FTP commands in one
table that defines the command itself, the syntax string, required
permission, whether it requires authorization, whether it takes
argument and whether there's a need to validate the path from the
argument.
The more obvious way I found to do that is something like this:
class CommandProperty:
def __init__(self, perm, auth_needed, arg_needed, check_path,
syntax):
self.perm = perm
self.auth_needed = auth_needed
self.arg_needed = arg_needed
self.check_path = check_path
self.syntax = syntax
ftp_cmds = {
"ABOR" : CommandProperty(perm=None, auth_needed=True,
arg_needed=False, check_path=False, syntax="ABOR (abort transfer)."),
"APPE" : CommandProperty(perm='a', auth_needed=True,
arg_needed=True, check_path=True, syntax="APPE file-name
(append data to an existent file)."),
"CDUP" : CommandProperty(perm='e',
auth_needed=True,arg_needed=False, check_path=False, syntax="CDUP (go
to parentdirectory)."),
...
...
...
}
...but I find it somewhat redundant and... "ugly".
I was wondering if there was some kind of data type which could better
fit such purpose or if someone could suggest me some other approach to
do this same thing. Maybe using a dictionary is not the better choice
here.
Thanks in advance
--- Giampaolo
http://code.google.com/p/pyftpdlib/
--
http://mail.python.org/mailman/listinfo/python-list
Re:Histogram and \lambda parameter of the laplacian curve.
even i am trying to generate this curve. are you able to generate this curve using matplotlib, because i was thinking to write a library for it. -- Andrew. >Thanks everyone for your earlier help. >I have to plot a histogram of values lets say [0.5,0.6,0.8,0.9].I guess the >histogram would show an exponential decay ie, the laplacian curve. >I need to find the \lambda parameter of this curve . >So please tell me if it be done through >http://matplotlib.sourceforge.net/and are there any other libraries >which can be used. >Thanks in advance. >Aditya -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Concise way to format list/array to custom(hex) string
Hello,
What will be a concise & efficient way to convert a list/array.array of
n elements into a hex string? For e.g. given the bytes
[116, 111, 110, 103, 107, 97]
I would like the formatted string
0x74 0x6f 0x6e 0x67 0x6b 0x61
Is there an approach better than below:
hex = ''
for b in bytes:
hex += ('0x%x '%b)
Thanks
Kurien
Test program:
import array
import sys
bytes = array.array('B')
bytes.fromstring("tongka")
print bytes
hex = ''
for b in bytes:
hex += ('0x%x '%b)
print hex
--
http://mail.python.org/mailman/listinfo/python-list
Multiline text in XML file
Is there any other way to define multiline text in a XML file: -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiline text in XML file
King wrote: > Is there any other way to define multiline text in a XML file: > > > Unless someone has to edit the XML manually (which is bad anyway): first line\nsecond line -- http://mail.python.org/mailman/listinfo/python-list
Re: Concise way to format list/array to custom(hex) string
On Aug 2, 9:53 pm, Kurien Mathew <[EMAIL PROTECTED]> wrote:
> Hello,
>
> What will be a concise & efficient way to convert a list/array.array of
> n elements into a hex string? For e.g. given the bytes
> [116, 111, 110, 103, 107, 97]
> I would like the formatted string
> 0x74 0x6f 0x6e 0x67 0x6b 0x61
>
> Is there an approach better than below:
> hex = ''
> for b in bytes:
> hex += ('0x%x '%b)
>
hex = ' '.join('0x%02x' % b for b in bytes)
--
http://mail.python.org/mailman/listinfo/python-list
Re: Concise way to format list/array to custom(hex) string
Kurien Mathew írta:
> Hello,
>
> What will be a concise & efficient way to convert a list/array.array of
> n elements into a hex string? For e.g. given the bytes
> [116, 111, 110, 103, 107, 97]
> I would like the formatted string
> 0x74 0x6f 0x6e 0x67 0x6b 0x61
>
> Is there an approach better than below:
> hex = ''
> for b in bytes:
> hex += ('0x%x '%b)
>
You should avoid multiple string additions, as each one creates a new
string object (str objects are immutable). Try this:
bytes = [116, 111, 110, 103, 107, 97]
string = ''.join( ['0x%x '%b for b in bytes] )
--
http://mail.python.org/mailman/listinfo/python-list
Profiling weirdness: Timer.timeit(), fibonacci and memoization
I am not clear about the results here.
from timeit import Timer
import Decorators
def fib(n):
a, b = 1, 0
while n:
a, b, n = b, a+b, n-1
return b
@Decorators.memoize
def fibmem(nbr):
if nbr > 1:
return fibmem(nbr-1) + fibmem(nbr-2)
if nbr == 1:
return 1
if nbr == 0:
return 0
s = 100
t1 = Timer('fib(s)', 'from __main__ import fib, s')
t2 = Timer('fibmem(s)', 'from __main__ import fibmem, s')
t1.repeat(number=1)
t2.repeat(number=1)
print t1.timeit()
print t2.timeit()
>>>
35.3092010297
1.6516613145
>>>
So memoization is 20+ times faster than the idiomatic way?
Or am I missing something here?
Ok for fun I added memoization to the idiomatic one:
from timeit import Timer
import Decorators
@Decorators.memoize
def fib(n):
a, b = 1, 0
while n:
a, b, n = b, a+b, n-1
return b
@Decorators.memoize
def fibmem(nbr):
if nbr > 1:
return fibmem(nbr-1) + fibmem(nbr-2)
if nbr == 1:
return 1
if nbr == 0:
return 0
s = 100
t1 = Timer('fib(s)', 'from __main__ import fib, s')
t2 = Timer('fibmem(s)', 'from __main__ import fibmem, s')
t1.repeat(number=1)
t2.repeat(number=1)
print t1.timeit()
print t2.timeit()
didn't think it would make a difference there but it certainly did.
>>>
1.59592657726
1.60179436213
>>> RESTART
>>>
2.66468922726
3.0870236301
>>> RESTART
>>>
1.62921684181
1.51585159566
>>> RESTART
>>>
1.49457319296
1.60948472501
>>> RESTART
>>>
1.48718203012
1.6645559701
>>>
--
http://mail.python.org/mailman/listinfo/python-list
Re: Strong/weak typing
On Fri, 01 Aug 2008 22:47:04 -0400
Mel <[EMAIL PROTECTED]> wrote:
> middle_name = raw_input ('Name?')
> middle_name = middle_name.split()
> middle_name = middle_name[1]
>
> It works, but I don't like it enough to actually use it.
Especially since this works better anyway:
middle_name = raw_input ('Name?').split()[1]
--
D'Arcy J.M. Cain <[EMAIL PROTECTED]> | Democracy is three wolves
http://www.druid.net/darcy/| and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP) | what's for dinner.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Concise way to format list/array to custom(hex) string
On 2008-08-02, Zoltán Nagy <[EMAIL PROTECTED]> wrote:
> Kurien Mathew írta:
>> Hello,
>>
>> What will be a concise & efficient way to convert a list/array.array of
>> n elements into a hex string? For e.g. given the bytes
>> [116, 111, 110, 103, 107, 97]
>> I would like the formatted string
>> 0x74 0x6f 0x6e 0x67 0x6b 0x61
>>
>> Is there an approach better than below:
>> hex = ''
>> for b in bytes:
>> hex += ('0x%x '%b)
>>
>
>
> You should avoid multiple string additions, as each one creates a new
> string object (str objects are immutable). Try this:
>
> bytes = [116, 111, 110, 103, 107, 97]
> string = ''.join( ['0x%x '%b for b in bytes] )
That results in an extra ' ' and the end of the string. Try
this:
string = ' '.join(['0x%02x' % b for b in bytes])
--
Grant Edwards grante Yow! ... Just enough
at time to do my LIBERACE
visi.comimpression...
--
http://mail.python.org/mailman/listinfo/python-list
Re: Strong/weak typing
[EMAIL PROTECTED] schrieb: I'm writing Python as if it were strongly typed, never recycling a name to hold a type other than the original type. Is this good software engineering practice, or am I missing something Pythonic? Others pointed out the wrong wording. As often, this is not a question to be answered with a simple yes or no. Duck-typing is very ptyhonic, and as such it is very common to write e.g. if content_as_string: inf = StringIO.String(content_as_string) else: inf = open(filename) inf has two totally different types now, depending on the path taken. And I personally tend to actually do things like this: if isinstance(foo, str): foo = unicode(str) Or such. But that is more a matter of taste - I personally don't like to many names lying around, but YMMV. Diez -- http://mail.python.org/mailman/listinfo/python-list
Terminology (Re: Strong/weak typing)
On Fri, Aug 01, 2008 at 03:57:10PM +, Alan Franzoni wrote: > [EMAIL PROTECTED] was kind enough to say: > > > I'm writing Python as if it were strongly typed, never recycling a > > name to hold a type other than the original type. [...] > Python *is* strongly typed. That's debatable. It depends on what definition of "strongly typed" you are using, and Martin's usage was not incorrect. There are, unfortunately, lots of them: http://en.wikipedia.org/wiki/Strong_typing On Fri, Aug 01, 2008 at 11:23:31AM -0700, Carl Banks wrote: > The strength of dynamic typing (Pythonistas prefer the terms dynamic > vs static for what you describe, and use weak vs stong for something > else) lies mostly in the freedom it gives you. Pythonistas can be extremely irritating. Some attributes I've observed of (some of) them: - stubborn insistence on their own narrow definitions of terms, and complete refusal to accept that other definitions of those terms exist and are in common usage - stubborn refusal to accept that other terms exist which describe some facet of programming they prefer to call by their own Elite Pythonista name. - A fundamental lack of understanding that not everyone who posts here was born speaking Python - extreme impatience with anyone who does not immediately understand what they are saying - superior/condescending tone leveled at anyone who profers an opinion which differs with the Pythonista hive mind. Is precision in terminology important? Sure, especially when the topic tends to be somewhat complex and/or abstract. But words are just words -- they have meaning that we impart to them, and there is rarely only one to describe a particular concept. There also is rarely only one meaning for each word. Computer Science has evolved increasingly rapidly over the last 40 years or so, and along with it so has its terminology. Each computer language brings with it a unique perspective on programming, and almost out of necessity its own terminology to describe the philosophy behind its design. THIS DOES NOT RENDER WRONG OTHER TERMS OR USAGES. It merely augments the already rich natural language we have to describe what we do. -- Derek D. Martin http://www.pizzashack.org/ GPG Key ID: 0x81CFE75D pgpdANC3vBRJ5.pgp Description: PGP signature -- http://mail.python.org/mailman/listinfo/python-list
Unit testing type comparison
I have a problem where type comparisons don't work in a second module when unit tests in the first module are run. In the example below, class Test is declared in one.py. When one.py is executed, it calls a method in two.py that imports Test from one.py. The problem is that the Test object passed into the run method is in the "__main__" namespace, while the Test class imported from one.py is in the "one" namespace. Comparing type(a) and Test returns False, even though they are both Test objects. How can I tweak these modules so that the type comparison returns True? I suppose one solution is to redesign my solution to not compare types, but I would still appreciate a solution for my personal knowledge. one.py class Test(object): pass if __name__ == '__main__': import two two.run( Test() ) two.py *** *def run( a ): from one import Test print type(a), Test, type(a) == Test * *** Output *** * False -- http://mail.python.org/mailman/listinfo/python-list
Re: Change PC to Win or Windows
On Tue, Jul 22, 2008 at 08:19:05PM +0700, Lie Ryan wrote: > But until the dictionary is rewritten, it is incorrect usage. That's complete nonsense, much like the rest of your argument. People use words all the time that aren't even IN a dictionary. Their absence from any dictionary makes them no less capable of conveying meaning. The dictionary does not define language; humans do, through their every-day use of words. Dictionaries record how words are commonly used, and are written by stubborn, pedantic old men with nothing better to do than sit around their oak desks debating the meaning of words... meanwhile the rest of the just USE words to communicate our ideas. Dictionaries are like technical documentation: written with the best of intentions, and mostly accurate at the time of writing, but out of date by the time they are published. [No offense meant to dictionary writers... I mostly fit that description myself, excepting that I am not quite yet an "old" man.] > FOR DECADES, people used the term PC for all sorts of things, I never said they didn't. That also is completely irrelevant. It's still the case that "PC" is commonly (these days MOST commonly, by far, at least in the US where all this technology was invented and named) used to refer to Intel-compatible hardware running a Microsoft OS. That fact, by itself, justifies the use in this case and any other. This is the very nature of language. > Apple's personal computer is NOT a PC? Aren't you contradicting > yourself? No, of course I'm not. > Just like what Apple, you have just said: "I'm Apple, I'm a > personal computer, but I'm not a personal computer." Completely > nonsense. Yes, I agree: what you wrote is complete nonsense. Only that isn't what I said at all. I said Apple isn't a PC. The term "PC" and the term "personal computer" are separate and distinct. One has only 2 letters, the other has 16 letters in two words. The latter ONLY means a (non-specific) computer designed for personal use. The former can mean that, though that usage is far less common than the one I was using: an Intel compatible personal computer on which Microsoft operating systems run. The software industry has been marketing titles as "For PC" since the creation of the IBM PC, and did not stop doing so when other PC-compatibles arrived on the scene, nor even when IBM stopped making them. So what did they mean by "PC" after IBM stopped making them? They meant, very clearly, that their software was intended for Intel-compatible hardware running a Microsoft OS. Does that mean that PC hardware running Linux is not a PC? Of course not -- except when the term is used in a context where it does mean exactly that. ;-) > Last, probably my strongest argument: "If the folder has been called > WinBuild/WindowsBuild, there is no need for arguments. PC as Windows is > an arguable usage, Windows as Windows is not arguable." There is no need for arguments now! The only reason there are arguments now is because a few stubborn people irrationally refuse to accept the term "PC" as it is most commonly used in modern English, as has been the case for most of my lifetime. Finally, the person who named the build can call it whatever they want... that's one of the perks of creating something: you get to name it. They could have called it "VanillaIceCreamBuild" or "Vinny'sSkankyHoBuild" -- it's their choice what to call it. The name of a thing need not reflect its purpose, orientation, meaning, or any other concrete or abstract property of the thing. It's just a name. Look, I've already said I don't like the term, and in fact I think that eventually, as PC hardware (and the software that runs on it) continues to evolve, it's going to become problematic. Except that it won't: when it becomes a problem, English-speaking humans will invent a new word to describe the class of computers they're discussing. That is how language works. But in the mean time, we have no other word to refer to the class of hardware that is based on Intel chipsets and is designed specifically to be compatible with Microsoft Windows (or indeed running said Windows). We need a word to distinguish this class of machines from Apple computers (which ironically now also use Intel, but are still clearly distinct from PCs, partially because they mainly run Windows), Sun computers, SGI computers, etc. The term "PC" has been relegated to that role, and the fact is that the vast majority of those computers run Windows today. It's also a fact that the overwhelming majority of English-speaking humans commonly use the term "PC" to mean what I've said (and also other similar things). Your complaints and arguments about alternate meanings of "PC" are irrelevant, pointless, and futile. Even if the maintainers are convinced to change the name, it does not change the fact that the term will continue to be used that way by millions of humans, nor that they are not wrong for doing so, since it is
Re: Concise way to format list/array to custom(hex) string
On Aug 2, 9:29 am, Grant Edwards <[EMAIL PROTECTED]> wrote:
> On 2008-08-02, Zoltán Nagy <[EMAIL PROTECTED]> wrote:
>
>
>
>
>
> > Kurien Mathew írta:
> >> Hello,
>
> >> What will be a concise & efficient way to convert a list/array.array of
> >> n elements into a hex string? For e.g. given the bytes
> >> [116, 111, 110, 103, 107, 97]
> >> I would like the formatted string
> >> 0x74 0x6f 0x6e 0x67 0x6b 0x61
>
> >> Is there an approach better than below:
> >> hex = ''
> >> for b in bytes:
> >> hex += ('0x%x '%b)
>
> >
>
> > You should avoid multiple string additions, as each one creates a new
> > string object (str objects are immutable). Try this:
>
> > bytes = [116, 111, 110, 103, 107, 97]
> > string = ''.join( ['0x%x '%b for b in bytes] )
>
> That results in an extra ' ' and the end of the string. Try
> this:
>
> string = ' '.join(['0x%02x' % b for b in bytes])
>
> --
> Grant Edwards grante Yow! ... Just enough
> at time to do my LIBERACE
> visi.com impression...
There is also a built-in hex() method in the Python Standard Library.
So, to make it cleaner:
' '.join(hex(x) for x in bytes)
--
http://mail.python.org/mailman/listinfo/python-list
Re: applescript/python question
[EMAIL PROTECTED] schrieb: I can't seem to figure this out. I just installed Python 2.5.2 a few days ago on my OS X 10.4.11 system. It runs fine and if I type "Python -V" in the Terminal it outputs "Python 2.5.2" which is correct. However, if I try to run a 'do shell script' in AppleScript which I'm wanting to run a Python program, it reverts to using Python 2.3. For example, if I run this code in AppleScript: set p to "#!/usr/bin/python import sys print sys.version[:3]" set x to do shell script "Python -c \"" & p & "\"" return x I get "2.3". Does anyone have any ideas why AppleScript is using the older version of Python? Is there a way to fix this? I guess the shebang is simply ignored - the actual interpreter is fetched from the "Python -c"-line. It's a bit weird that there is Python with a capital P, but what happens if you change that to Python2.5 for example? Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Searching for some kind of data type
Giampaolo Rodola' wrote:
Hi,
for an FTP server I wrote I'd need to group the FTP commands in one
table that defines the command itself, the syntax string, required
permission, whether it requires authorization, whether it takes
argument and whether there's a need to validate the path from the
argument.
The more obvious way I found to do that is something like this:
class CommandProperty:
def __init__(self, perm, auth_needed, arg_needed, check_path,
syntax):
self.perm = perm
self.auth_needed = auth_needed
self.arg_needed = arg_needed
self.check_path = check_path
self.syntax = syntax
ftp_cmds = {
"ABOR" : CommandProperty(perm=None, auth_needed=True,
arg_needed=False, check_path=False, syntax="ABOR (abort transfer)."),
"APPE" : CommandProperty(perm='a', auth_needed=True,
arg_needed=True, check_path=True, syntax="APPE file-name
(append data to an existent file)."),
"CDUP" : CommandProperty(perm='e',
auth_needed=True,arg_needed=False, check_path=False, syntax="CDUP (go
to parentdirectory)."),
...
...
...
}
...but I find it somewhat redundant and... "ugly".
I was wondering if there was some kind of data type which could better
fit such purpose or if someone could suggest me some other approach to
do this same thing. Maybe using a dictionary is not the better choice
here.
Thanks in advance
--- Giampaolo
http://code.google.com/p/pyftpdlib/
Seems completely reasonable to me. You might just consider using keyword
arguments in the __init__ method and eliminate the dictionary altogether.
Not tested, but you will get the idea:
class CommandProperty:
def __init__(self, perm = perm, auth_needed = True, arg_needed = True,
check_path = False, syntax = syntax):
self.perm = perm
self.auth_needed = auth_needed
self.arg_needed = arg_needed
self.check_path = check_path
self.syntax = syntax
ftpCommands = dict(
ABOR = CommandProperty(perm = None, arg_needed = False,
syntax="ABOR (abort transfer)."),
APPE = CommandProperty(perm = 'a', check_path=True,
syntax = "APPE file-name (append data to" \
"an existent file)."),
CDUP = CommandProperty(perm= 'e', arg_needed = False,
syntax="CDUP (go> to parentdirectory)."),
...
...
...
)
IMHO this is a "little" easier to manage because you can take advantage of the
default values for keyword arguments to eliminate some of the arguments.
Hope this helps,
Larry
--
http://mail.python.org/mailman/listinfo/python-list
ANN: pyspread 0.0.8
pyspread 0.0.8 has been released. About: pyspread is a spreadsheet that accepts a pure python expression in each cell. New features: New macro dialog that allows defining python functions, which can be used in the grid. Bug fixes within the copy paste and print code. Highlights: + Numpy high performance arrays for spreadsheet calculation + Full access to python batteries from each cell + No non-python syntax add-ons + 3D grid + Cell access via slicing of numpy array S + X, Y, and Z yield current cell location for relative reference Requires: Python >=2.4, Numpy 1.0.4, and wxPython 2.8.7.1. License: GPL Project page: http://pyspread.sourceforge.net As always, feedback is appreciated. Please also test with wxPython 2.8.8.0. Enjoy Martin -- http://mail.python.org/mailman/listinfo/python-list
embedded python doesn't like socket.accept() and SegFaults
Hi everyone,
I'm practicing with embedding python into C code and i have encountered
a very strange problem: I'm unable to call the "accept" method of a
(correctly created) server socket without receiving a "Segmentation
fault" (inside the PyObject_CallMethod).
My code to be correct (at least it's correct enough for me to
call .getsockname(), .fileno() and other methods without problems), I'm
pretty new to this thing though, therefore I'm confident I'm doing
something very dumb.
Here is the C code:
-- extending.c
#include
PyObject *new_server(long port)
{
PyObject *pName,*pModule;
PyObject *pFunction,*pArg;
PyObject *pTuple,*pValue;
// Import the module
pName = PyString_FromString("extending");
pModule = PyImport_Import(pName);
Py_DECREF(pName);
// Get the function
pFunction = PyObject_GetAttrString(pModule,
"server_socket");
// Module not needed anymore
Py_DECREF(pModule);
// Build the arguments
pArg=PyInt_FromLong(port);
pTuple=PyTuple_New(1);
PyTuple_SET_ITEM(pTuple,0,pArg);
// Call the function
pValue = PyObject_CallObject(pFunction,
pTuple);
// Release the references
Py_DECREF(pFunction);
Py_DECREF(pTuple);
if(pValue==NULL)
printf("Error: server socket not created!\n");
return pValue;
}
PyObject *accept(PyObject *server)
{
PyObject *pValue;
// Code fails here (it does NOT return NULL: just crashes!)
// Note that other calls work fine (e.g. fileno, getsockname ecc)
pValue = PyObject_CallMethod(server,
"accept",
NULL);
return pValue;
}
int main(int argc,char *argv[])
{
PyObject *server,*connection;
// Boot python
Py_Initialize();
PySys_SetArgv(argc, argv);
// Create the server
server=new_server(23000);
// Print it
PyObject_Print(server,stderr,0);
fprintf(stderr,"\n");
// Wait for a connection
connection=accept(server);
// See what we got
PyObject_Print(connection,stderr,0);
fprintf(stderr,"\n");
// We are done, hint the gc.
Py_DECREF(connection);
Py_DECREF(server);
Py_Finalize();
return 0;
}
--
and this is the python script:
-- extending.py
import socket
def server_socket(port):
s=socket.socket()
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,True)
s.bind(("0.0.0.0",port))
s.listen(10)
return s
as already mentioned, replacing the "accept" string with "fileno" or
something else doesn't crash the interpreter.
Another thing worth mentioning, is that even inserting a s.accept() call
in the python script (before the return) makes the bug appear (it
doesn't seems related to my use of the PyObject_CallMethod function, then).
I have tried posting the problem in IRC, searching google (no good
matches) and debugging the code (however I'm afraid i don't have the
python-lib with debugging syms. compiled in, therefore it was quite a
useless attempt...).
Any help about the code would be appreciated (even unrelated to the
issue at hand: im quite new to this "embedding thing" and therefore i
gladly accept hints).
Thank you for your attention,
Riccardo Di Meo
PS: I'm also new to Usenet: is it fine to post the code in the body of
the mail as i did (since it was small, i dared: however I'd like to know
the correct etiquette)?
--
http://mail.python.org/mailman/listinfo/python-list
Re: PIL (etc etc etc) on OS X
In article <[EMAIL PROTECTED]>, Irmen de Jong <[EMAIL PROTECTED]> wrote: > David C. Ullrich wrote: > > Decided to try to install PIL on my Mac (OS X.5). > > > > I know nothing about installing programs on Linux, > > nothing about building C programs, nothing about > > installing libraries, nothing about "fink", nothing > > about anything. Please insert question marks after > > every sentence: > > Not needed. > Just download a precompiled installation package from > http://pythonmac.org/packages/ Lovely - thanks. > I just installed PIL 1.1.6 two days ago, using the Python 2.5 package from > this site :) > (OS X 10.4.11 on a PPC mac mini) > > --irmen -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: Agnostic fetching
Bruce Frederiksen schrieb: On Fri, 01 Aug 2008 17:05:00 -0700, jorpheus wrote: OK, that sounds stupid. Anyway, I've been learning Python for some time now, and am currently having fun with the urllib and urllib2 modules, but have run into a problem(?) - is there any way to fetch (urllib.retrieve) files from a server without knowing the filenames? For instance, there is smth like folder/spam.egg, folder/ unpredictable.egg and so on. If not, perhaps some kind of glob to create a list of existing files? I'd really appreciate some help, since I'm really out of my (newb) depth here. You might try the os.path module and/or the glob module in the standard python library. Not on remote locations. The only work on your local filesystem. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Searching for some kind of data type
Larry Bates wrote:
Giampaolo Rodola' wrote:
Hi,
for an FTP server I wrote I'd need to group the FTP commands in one
table that defines the command itself, the syntax string, required
permission, whether it requires authorization, whether it takes
argument and whether there's a need to validate the path from the
argument.
The more obvious way I found to do that is something like this:
class CommandProperty:
def __init__(self, perm, auth_needed, arg_needed, check_path,
syntax):
self.perm = perm
self.auth_needed = auth_needed
self.arg_needed = arg_needed
self.check_path = check_path
self.syntax = syntax
ftp_cmds = {
"ABOR" : CommandProperty(perm=None, auth_needed=True,
arg_needed=False, check_path=False, syntax="ABOR (abort transfer)."),
"APPE" : CommandProperty(perm='a', auth_needed=True,
arg_needed=True, check_path=True, syntax="APPE file-name
(append data to an existent file)."),
"CDUP" : CommandProperty(perm='e',
auth_needed=True,arg_needed=False, check_path=False, syntax="CDUP (go
to parentdirectory)."),
...
...
...
}
...but I find it somewhat redundant and... "ugly".
I was wondering if there was some kind of data type which could better
fit such purpose or if someone could suggest me some other approach to
do this same thing. Maybe using a dictionary is not the better choice
here.
Thanks in advance
--- Giampaolo
http://code.google.com/p/pyftpdlib/
Seems completely reasonable to me. You might just consider using
keyword arguments in the __init__ method and eliminate the dictionary
altogether.
Not tested, but you will get the idea:
class CommandProperty:
def __init__(self, perm = perm, auth_needed = True, arg_needed =
True,
check_path = False, syntax = syntax):
self.perm = perm
self.auth_needed = auth_needed
self.arg_needed = arg_needed
self.check_path = check_path
self.syntax = syntax
ftpCommands = dict(
ABOR = CommandProperty(perm = None, arg_needed = False,
syntax="ABOR (abort transfer)."),
APPE = CommandProperty(perm = 'a', check_path=True,
syntax = "APPE file-name (append data to" \
"an existent file)."),
CDUP = CommandProperty(perm= 'e', arg_needed = False,
syntax="CDUP (go> to parentdirectory)."),
...
...
...
)
How does this strike you?With care, the comment and the table could
be kept aligned and nicely readable
cmd_data = dict(
# cmd = (perm, auth, arg, path, syntax),
ABOR = (None, False, False, False, "ABOR (abort transfer)."),
APPE = (None, False, False, True, "APPE file-name (append data to"),
...
]
ftpCommands = {}
for cmd,args in cmd_data.iteritems():
ftpCommands[cmd] = CommandProperty(*args)
Gary Herron
IMHO this is a "little" easier to manage because you can take
advantage of the default values for keyword arguments to eliminate
some of the arguments.
Hope this helps,
Larry
--
http://mail.python.org/mailman/listinfo/python-list
--
http://mail.python.org/mailman/listinfo/python-list
Re: PIL (etc etc etc) on OS X
>From the other reply it seems I may not need to worry about any of this. Otoh I've had issues with pythonmac versus OSX versions, etc, in the past. Just in case, also in the spirit of that curious idea that learning things is good: First, it occurred to me that I've got wxPython installed and it includes jpeg support. I don't suppose that means that wxPython has already put a libjpeg somewhere and I just need to tell PIL where it is? Regardless, about your suggestions below (again, any assertions here are really questions): Presumably jibjpeg needs to be unzipped into its own directory, or configure/make etc wouldn't be able to figure out what I want to make. Presumably that happens automatically when I unzip it. Then after I do the configure/make/sudo make install will libjpeg automatically be in some standard place? If not, what's a good choice of standard place to put it, and how do I put it there? (If I start here then it will unzip to there, and then after I make it there it will be installed in this third place, which is where I want it.) Thanks. Sorry to be so dumb - yes, it's perfectly reasonable for eff to assume that people using PIL are programmers. With a "new thing" in, say, Python I'd just try something and then figure out what to try next to make it work - I don't want to take that approach here lest I re-make part of Darwin or something. Once many years ago I learned a new thing: Attempting to run a sufficiently invalid DOS exe could cause physical damage to a hard drive... that wasn't the only thing I learned that day. (Probably won't get back to this til Monday, btw, in case you say something and I don't seem interested.) DU. In article <[EMAIL PROTECTED]>, Kevin Walzer <[EMAIL PROTECTED]> wrote: > David C. Ullrich wrote: > > Decided to try to install PIL on my Mac (OS X.5). > > OK, sounds good. > > > > I know nothing about installing programs on Linux, > > nothing about building C programs, nothing about > > installing libraries, nothing about "fink", nothing > > about anything. Please insert question marks after > > every sentence: > > For the record, OS X isn't Linux--it's a variant of BSD Unix. Similar, > but no identical, to Linux. > > > > > I saw a "BUILDME" with instructions "for lazy programmers". > > I did that. It seems that everything worked except a > > jpg library is missing. > > OK. > > > > > I read that I need to install libjpeg. I read that on OS X > > this is "usually" done using fink. Great: > > > > (i) The idea of installing fink scares me, for no reason > > I could name. There's no way that's going to confuse the > > rest of Darwin, right? > > You don't really need Fink just to install libjpeg. You do need the > developer tools (Xcode) installed, otherwise you can't build any > software at all. > > Libjpeg can be downloaded from http://www.ijg.org/. Download it, > untar/unzip it. Fire up terminal, cd to the libjpeg directory, and type > these commands: > > configure > make > sudo make install > > That should get libjpeg built and installed. > > > > > (ii) When I look at the fink website I see a list of > > supported libraries, not including libjpeg. > > So don't worry about Fink. > > > > > I hate messing with things that I don't understand at _all_... > > Well, that's understandable, but this is your chance to learn something > new. > > > > Thanks for any advice or comments. > > > > DU. > > > --Kevin -- David C. Ullrich -- http://mail.python.org/mailman/listinfo/python-list
Re: How to request data from a lazily-created tree structure ?
On 17 juin, 13:53, méchoui <[EMAIL PROTECTED]> wrote: > On Jun 17, 9:08 am, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: > > > > > > Yes, I need to make sure my requests are properly written so that the > > > generic XPath engine does not need all the structure in memory. > > > > There are quite a few cases where you really don't need to load > > > everything at all. /a/b/*/c/d is an example. But even with an example > > > like /x/z[last()]/t, you don't need to load everything under the > > > every /x/z nodes. You just need to check for the latest one, and make > > > sure there is a t node under it. > > > > Anyway, if I need to make requests that need all the data... that > > > means that the need for lazy instantiation of nodes disappears, > > > right ? > > > Yes. And unless you have memory-constraints I have to admit that I > > really doubt that the parsing overhead isn't by far exceeded by the > > network latency. > > > Diez > > Do you know if there is such XPath engine that can be applied to a DOM- > like structure ? > > One way would be to take an XPath engine from an existing XML engine > (ElementTree, or any other), and see what APIs it calls... and see if > we cannot create a DOM-like structure that has the same API. Duck > typing, really... I have something that works. http://lauploix.blogspot.com/2008/07/xpath-for-my-trees.html It has the pro and cons of the ElementTree 1.3 XPath engine, but it works quite nice. Laurent Ploix -- http://mail.python.org/mailman/listinfo/python-list
Re: PIL (etc etc etc) on OS X
First, it occurred to me that I've got wxPython installed and it includes jpeg support. I don't suppose that means that wxPython has already put a libjpeg somewhere and I just need to tell PIL where it is? I doubt it. You're probably better off building libjpeg yourself. Presumably jibjpeg needs to be unzipped into its own directory, or configure/make etc wouldn't be able to figure out what I want to make. Presumably that happens automatically when I unzip it. Yes. Then after I do the configure/make/sudo make install will libjpeg automatically be in some standard place? If not, what's a good choice of standard place to put it, and how do I put it there? (If I start here then it will unzip to there, and then after I make it there it will be installed in this third place, which is where I want it.) I think, by default, that it installs in /usr/local/lib. You can run configure --help in the libjpeg directory and it will give you a rundown of the various options, including where to install libjepg if you want a different place. Thanks. Sorry to be so dumb - yes, it's perfectly reasonable for eff to assume that people using PIL are programmers. With a "new thing" in, say, Python I'd just try something and then figure out what to try next to make it work - I don't want to take that approach here lest I re-make part of Darwin or something. Once many years ago I learned a new thing: Attempting to run a sufficiently invalid DOS exe could cause physical damage to a hard drive... that wasn't the only thing I learned that day. /usr/local is a good place to install stuff in a way that won't disrupt your system. OS X/Darwin puts its system stuff in /usr/bin, /usr/lib, and so on. --Kevin -- Kevin Walzer Code by Kevin http://www.codebykevin.com -- http://mail.python.org/mailman/listinfo/python-list
Continually check object status
Beginner, so please bare with me. I'm not sure what to call what it is I'm looking for. If I have an object class, let's call it "Creature": class Creature: def __init__(self, status): self.status = "happy" def change_status(self, new_status): self.status = new_status def print_status(self): print self.status I would like to be able to print out the Creature's status every 20 seconds. Let's say I use a script like this: import time while True: time.sleep(20) Creature.print_status() But, while cycling through printing the status, I would like to be able to update Creature.status to something new. I might be approaching this from the wrong direction entirely. Thanks for your input. -- http://mail.python.org/mailman/listinfo/python-list
Re: Continually check object status
[EMAIL PROTECTED] wrote: Beginner, so please bare with me. I'm not sure what to call what it is I'm looking for. If I have an object class, let's call it "Creature": class Creature: def __init__(self, status): self.status = "happy" def change_status(self, new_status): self.status = new_status def print_status(self): print self.status I would like to be able to print out the Creature's status every 20 seconds. Let's say I use a script like this: import time while True: time.sleep(20) Creature.print_status() But, while cycling through printing the status, I would like to be able to update Creature.status to something new. To answer your question, we need to know from where you would derive the directions to change the status. For instance: * time based (random or periodically scheduled) * user mouse/keyboard action * some state external to the program (file content, socket data, phase of the moon, price of tea in China, ...) Each of those possibilities would require a substantially different approach. Gary Herron I might be approaching this from the wrong direction entirely. Thanks for your input. -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list
Help me
The assignment aims at enforcing the encryption and communication techniques. It helps the student in acquiring the necessary knowledge in developing client/server application and in securing data transfer using encryption techniques. Objectives can be summarized as: • Designing and implementing server applications • Designing and implementing client applications • Encrypting and decrypting o Use of DES, RSA o Use of hash techniques ASSIGNMENT DETAILS We need to design and implement a secure mail system simulator. The system should allow sending and receiving encrypted emails with the following criteria: • All messages should be sent encrypted. Only the receiver can read the message. • The sender should sign all messages. The sender can not deny he/she has sent the message and the receiver can be sure the message was not altered. The idea is to build a client/server application whose purpose is to exchange messages between clients through the server. The server will play two roles: 1. It will be the depot of all messages sent by clients 2. It will play the role of the party that assures the client identity (similar to a certification authority (CA)). To achieve the server roles a database should be designed and implemented to hold all the messages sent by clients. Another database should hold all the public keys of the clients with their email addresses. The email address will be considered as the ID of the client. Security is achieved through the encryption of the message before sending it. The encrypted message is saved in the server database. Sending a message by client: Message sending goes as follows: 1. The client gets the signature of the message. 2. The client randomly generate DES key. 3. The client encrypts the message body with the DES key using DES algorithm. 4. The client gets the public key of the receiver from the server. 5. The client encrypts the DES key using the receiver public key and attaches the encrypted key to the message. 6. The client encrypts the message signature with its own private key and attaches the encrypted signature to the message. 7. The client specifies the email address of the receiver and the title of the message and sends the message to server. Receiving an Email by Server: Message post goes as follows: 1. The sender sends the message with the sender ID, the receiver ID and the message title 2. The server receives the message information and saves the message in the receiver Inbox 3. The server sends back a success message to the sender. Receiving a message by client: Message reading goes as follows: 1. The receiver asks the server to send the message with the ID specified. 2. The server checks for the client ID and sends the message back to the client. 3. The receiver gets the encrypted body, the encrypted signature and the encrypted key from the message. 4. The receiver decrypt the encrypted key using its own private key 5. The receiver decrypts the encrypted signature using the sender's public key 6. The receiver decrypts the encrypted message body using the obtained key in 4. 7. If any error encountered, it should be reported. 8. If no errors, the message body is shown, and the message is marked as read. Registration: : 1. The user generates his own private/public RSA keys pair. 2. The user sends its chosen user ID and its public key to the server. 3. The server adds the user ID and public key to the database if user account not found. 4. If successful, the server sends a confirmation message to the client. If not successful, an error message is sent back. The following should be met: 1. Use Python version 2.5 to implement the software 2. Use text file to implement the database 3. Use HTTP to implement the message and data exchange between client and server. 4. Use DES to encrypt the message body. Use pyDES Python library for that. 5. Use MD5 to create message body hash 6. Use RSA to encrypt the DES encryption key 7. Use MS Word 2003 or less to write your documents 1. A WORD document using version MS Office 2003 or less. The document will describe: a. Description of the account creation. b. Description of message sending. c. Description of message reading. d. Description of message listing. e. Description of all needed HTTP response code the system will use and the cases where they are used. f. Short description of the encryption algorithms supported and the features of each one. g. Description of the designed mail server. h. Description of the designed mail client. 2. Mail server Python script A Python script that implements the mail server. It should meet the following requirements: a. Well commented b. Built with sub procedures. Not a whole one procedure script. c. It should be fully configurable. T
Re: Continually check object status
[EMAIL PROTECTED] schrieb: Beginner, so please bare with me. I'm not sure what to call what it is I'm looking for. If I have an object class, let's call it "Creature": class Creature: def __init__(self, status): self.status = "happy" def change_status(self, new_status): self.status = new_status def print_status(self): print self.status I would like to be able to print out the Creature's status every 20 seconds. Let's say I use a script like this: import time while True: time.sleep(20) Creature.print_status() But, while cycling through printing the status, I would like to be able to update Creature.status to something new. I might be approaching this from the wrong direction entirely. Thanks for your input. The "simple", yet possibly dangerous answer is: you need multi-threading. Multi-threading is a technique that allows several (quasi)-parallel paths of execution whilst sharing memory and objects inside that memory. The module in python to achieve this is called "threading". However, concurrent programming is a very advanced topic, ridded with pitfalls for even experienced developers. There are other ways to solve the problem, commonly known as event-loops and timers. These are usually part of frameworks for e.g GUI-creation an such, but you can also roll your own if you like. So, the better answer might be a question: what do you ultimately want to achieve? Given the name of your class, Creature, I assume you are writing on some game or such. Depending on how you plan to do that, you might have a framwork providing you with the needed tools/library calls or whatever. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Help me
Am 02.08.2008, 18:02 Uhr, schrieb <[EMAIL PROTECTED]>: I'll help you by giving some good advice: homework is meant to be homework, so you should get started reading and processing the assignment. If you have any specific questions besides text comprehension, come back to ask. --- Heiko. -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: pyspread 0.0.8
[EMAIL PROTECTED] wrote: pyspread 0.0.8 has been released. About: pyspread is a spreadsheet that accepts a pure python expression in each cell. New features: New macro dialog that allows defining python functions, which can be used in the grid. Bug fixes within the copy paste and print code. Highlights: + Numpy high performance arrays for spreadsheet calculation + Full access to python batteries from each cell + No non-python syntax add-ons + 3D grid + Cell access via slicing of numpy array S + X, Y, and Z yield current cell location for relative reference Requires: Python >=2.4, Numpy 1.0.4, and wxPython 2.8.7.1. License: GPL Project page: http://pyspread.sourceforge.net As always, feedback is appreciated. Please also test with wxPython 2.8.8.0. Enjoy Martin Are you planning any documentation? I've tried: # tpySpread.py print 'start' import pyspread print pyspread.__doc__ Colin W. -- http://mail.python.org/mailman/listinfo/python-list
Re: Continually check object status
On Aug 2, 12:58 pm, Gary Herron <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] wrote: > > Beginner, so please bare with me. I'm not sure what to call what it > > is I'm looking for. > > > If I have an object class, let's call it "Creature": > > > class Creature: > > def __init__(self, status): > > self.status = "happy" > > > def change_status(self, new_status): > > self.status = new_status > > > def print_status(self): > > print self.status > > > I would like to be able to print out the Creature's status every 20 > > seconds. Let's say I use a script like this: > > > import time > > while True: > > time.sleep(20) > > Creature.print_status() > > > But, while cycling through printing the status, I would like to be > > able to update Creature.status to something new. > > To answer your question, we need to know from where you would derive the > directions to change the status. For instance: > * time based (random or periodically scheduled) > * user mouse/keyboard action > * some state external to the program (file content, socket data, phase > of the moon, price of tea in China, ...) > > Each of those possibilities would require a substantially different > approach. > > Gary Herron > > > I might be approaching this from the wrong direction entirely. Thanks > > for your input. > > -- > >http://mail.python.org/mailman/listinfo/python-list > > I was thinking about it taking directions from a GTK event handler, such as a user selecting a button. -- http://mail.python.org/mailman/listinfo/python-list
Re: Continually check object status
On Aug 2, 1:05 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] schrieb: > > > > > Beginner, so please bare with me. I'm not sure what to call what it > > is I'm looking for. > > > If I have an object class, let's call it "Creature": > > > class Creature: > > def __init__(self, status): > > self.status = "happy" > > > def change_status(self, new_status): > > self.status = new_status > > > def print_status(self): > > print self.status > > > I would like to be able to print out the Creature's status every 20 > > seconds. Let's say I use a script like this: > > > import time > > while True: > > time.sleep(20) > > Creature.print_status() > > > But, while cycling through printing the status, I would like to be > > able to update Creature.status to something new. > > > I might be approaching this from the wrong direction entirely. Thanks > > for your input. > > The "simple", yet possibly dangerous answer is: you need > multi-threading. Multi-threading is a technique that allows several > (quasi)-parallel paths of execution whilst sharing memory and objects > inside that memory. The module in python to achieve this is called > "threading". > > However, concurrent programming is a very advanced topic, ridded with > pitfalls for even experienced developers. > > There are other ways to solve the problem, commonly known as event-loops > and timers. These are usually part of frameworks for e.g GUI-creation an > such, but you can also roll your own if you like. > > So, the better answer might be a question: what do you ultimately want > to achieve? Given the name of your class, Creature, I assume you are > writing on some game or such. Depending on how you plan to do that, you > might have a framwork providing you with the needed tools/library calls > or whatever. > > Diez I was afraid that someone was going to mention threading. I have read about it before but not been able to do much with it. My ultimate goal is to create some sort of tamagotchi style virtual pet to interact with. Over time it gets hungry or bored, but the process can be fixed by a user "feeding" or "playing with" it. I wanted to take this opportunity to teach myself some PyGTK coding as well, but I thought that maybe I could build the creature object and looping in such a way that it would be possible to add a GUI to it later. -- http://mail.python.org/mailman/listinfo/python-list
Re: Searching for some kind of data type
On 2 Ago, 18:18, Gary Herron <[EMAIL PROTECTED]> wrote:
> Larry Bates wrote:
> > Giampaolo Rodola' wrote:
> >> Hi,
> >> for an FTP server I wrote I'd need to group the FTP commands in one
> >> table that defines the command itself, the syntax string, required
> >> permission, whether it requires authorization, whether it takes
> >> argument and whether there's a need to validate the path from the
> >> argument.
> >> The more obvious way I found to do that is something like this:
>
> >> class CommandProperty:
> >> def __init__(self, perm, auth_needed, arg_needed, check_path,
> >> syntax):
> >> self.perm = perm
> >> self.auth_needed = auth_needed
> >> self.arg_needed = arg_needed
> >> self.check_path = check_path
> >> self.syntax = syntax
>
> >> ftp_cmds = {
> >> "ABOR" : CommandProperty(perm=None, auth_needed=True,
> >> arg_needed=False, check_path=False, syntax="ABOR (abort transfer)."),
> >> "APPE" : CommandProperty(perm='a', auth_needed=True,
> >> arg_needed=True, check_path=True, syntax="APPE file-name
> >> (append data to an existent file)."),
> >> "CDUP" : CommandProperty(perm='e',
> >> auth_needed=True,arg_needed=False, check_path=False, syntax="CDUP (go
> >> to parentdirectory)."),
> >> ...
> >> ...
> >> ...
> >> }
>
> >> ...but I find it somewhat redundant and... "ugly".
> >> I was wondering if there was some kind of data type which could better
> >> fit such purpose or if someone could suggest me some other approach to
> >> do this same thing. Maybe using a dictionary is not the better choice
> >> here.
>
> >> Thanks in advance
>
> >> --- Giampaolo
> >>http://code.google.com/p/pyftpdlib/
>
> > Seems completely reasonable to me. You might just consider using
> > keyword arguments in the __init__ method and eliminate the dictionary
> > altogether.
>
> > Not tested, but you will get the idea:
>
> > class CommandProperty:
> > def __init__(self, perm = perm, auth_needed = True, arg_needed =
> > True,
> > check_path = False, syntax = syntax):
>
> > self.perm = perm
> > self.auth_needed = auth_needed
> > self.arg_needed = arg_needed
> > self.check_path = check_path
> > self.syntax = syntax
>
> > ftpCommands = dict(
> > ABOR = CommandProperty(perm = None, arg_needed = False,
> > syntax="ABOR (abort transfer)."),
> > APPE = CommandProperty(perm = 'a', check_path=True,
> > syntax = "APPE file-name (append data to" \
> > "an existent file)."),
> > CDUP = CommandProperty(perm= 'e', arg_needed = False,
> > syntax="CDUP (go> to parentdirectory)."),
> > ...
> > ...
> > ...
> > )
>
> How does this strike you? With care, the comment and the table could
> be kept aligned and nicely readable
>
> cmd_data = dict(
> # cmd = (perm, auth, arg, path, syntax),
> ABOR = (None, False, False, False, "ABOR (abort transfer)."),
> APPE = (None, False, False, True, "APPE file-name (append data to"),
> ...
> ]
>
> ftpCommands = {}
> for cmd,args in cmd_data.iteritems():
> ftpCommands[cmd] = CommandProperty(*args)
>
> Gary Herron
>
>
>
>
>
> > IMHO this is a "little" easier to manage because you can take
> > advantage of the default values for keyword arguments to eliminate
> > some of the arguments.
>
> > Hope this helps,
> > Larry
> > --
> >http://mail.python.org/mailman/listinfo/python-list- Nascondi testo citato
>
> - Mostra testo citato -- Nascondi testo citato
>
> - Mostra testo citato -
Thanks, I didnt' know dict() could be used with =.
I think I'm going to use this solution.
--- Giampaolo
http://code.google.com/p/pyftpdlib/
--
http://mail.python.org/mailman/listinfo/python-list
RE: Continually check object status
updated creature running in its own thread will get you started. try it for
yourself, change sleep times per your need.
import os, sys, threading, time
class Creature:
def __init__(self, status):
self.status = status
self.state = 'run'
def start(self):
self.athread = threading.Thread(target=self.print_status)
self.athread.start()
def change_status(self, new_status):
self.status = new_status
def print_status(self):
while self.state == 'run':
print self.status
time.sleep(1)
def stop(self):
self.state = 'stop'
self.athread.join()
#main loop
c = Creature('happy')
c.start()
time.sleep(3) #wait some time
c.change_status('managing')
time.sleep(3) #wait some more time
c.change_status('bye')
time.sleep(1)
c.stop()
concept would be similar with GUI as well
-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED]
On Behalf Of [EMAIL PROTECTED]
Sent: Saturday, August 02, 2008 1:54 PM
To: [email protected]
Subject: Re: Continually check object status
On Aug 2, 1:05 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] schrieb:
>
>
>
> > Beginner, so please bare with me. I'm not sure what to call what it
> > is I'm looking for.
>
> > If I have an object class, let's call it "Creature":
>
> > class Creature:
> > def __init__(self, status):
> > self.status = "happy"
>
> > def change_status(self, new_status):
> > self.status = new_status
>
> > def print_status(self):
> > print self.status
>
> > I would like to be able to print out the Creature's status every 20
> > seconds. Let's say I use a script like this:
>
> > import time
> > while True:
> > time.sleep(20)
> > Creature.print_status()
>
> > But, while cycling through printing the status, I would like to be
> > able to update Creature.status to something new.
>
> > I might be approaching this from the wrong direction entirely. Thanks
> > for your input.
>
> The "simple", yet possibly dangerous answer is: you need
> multi-threading. Multi-threading is a technique that allows several
> (quasi)-parallel paths of execution whilst sharing memory and objects
> inside that memory. The module in python to achieve this is called
> "threading".
>
> However, concurrent programming is a very advanced topic, ridded with
> pitfalls for even experienced developers.
>
> There are other ways to solve the problem, commonly known as event-loops
> and timers. These are usually part of frameworks for e.g GUI-creation an
> such, but you can also roll your own if you like.
>
> So, the better answer might be a question: what do you ultimately want
> to achieve? Given the name of your class, Creature, I assume you are
> writing on some game or such. Depending on how you plan to do that, you
> might have a framwork providing you with the needed tools/library calls
> or whatever.
>
> Diez
I was afraid that someone was going to mention threading. I have read
about it before but not been able to do much with it.
My ultimate goal is to create some sort of tamagotchi style virtual
pet to interact with. Over time it gets hungry or bored, but the
process can be fixed by a user "feeding" or "playing with" it. I
wanted to take this opportunity to teach myself some PyGTK coding as
well, but I thought that maybe I could build the creature object and
looping in such a way that it would be possible to add a GUI to it
later.
--
http://mail.python.org/mailman/listinfo/python-list
The information contained in this message and any attachment may be
proprietary, confidential, and privileged or subject to the work
product doctrine and thus protected from disclosure. If the reader
of this message is not the intended recipient, or an employee or
agent responsible for delivering this message to the intended
recipient, you are hereby notified that any dissemination,
distribution or copying of this communication is strictly prohibited.
If you have received this communication in error, please notify me
immediately by replying to this message and deleting it and all
copies and backups thereof. Thank you.
--
http://mail.python.org/mailman/listinfo/python-list
Re: interpreter vs. compiled
Dennis Lee Bieber <[EMAIL PROTECTED]> wrote: >On Thu, 31 Jul 2008 06:17:59 GMT, Tim Roberts <[EMAIL PROTECTED]> declaimed >the following in comp.lang.python: > >> And again, I never said that it did. CPython is an interpreter. the >> user's code is never translated into machine language. > > Using that definition, the UCSD P-code Pascal and Java are also not >"compilers" -- all three create files containing instructions for a >non-hardware virtual machine. Right. UCSD p-code Pascal was almost always implemented as an interpreter. I would be surprised if anyone argued that it was a compiler. However, I thought Java was usually JIT compiled to machine language. Am I mistaken? -- Tim Roberts, [EMAIL PROTECTED] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Searching for some kind of data type
On Aug 2, 1:12 pm, "Giampaolo Rodola'" <[EMAIL PROTECTED]> wrote:
> Hi,
> for an FTP server I wrote I'd need to group the FTP commands in one
> table that defines the command itself, the syntax string, required
> permission, whether it requires authorization, whether it takes
> argument and whether there's a need to validate the path from the
> argument.
> The more obvious way I found to do that is something like this:
>
> class CommandProperty:
> def __init__(self, perm, auth_needed, arg_needed, check_path,
> syntax):
> self.perm = perm
> self.auth_needed = auth_needed
> self.arg_needed = arg_needed
> self.check_path = check_path
> self.syntax = syntax
>
> ftp_cmds = {
> "ABOR" : CommandProperty(perm=None, auth_needed=True,
> arg_needed=False, check_path=False, syntax="ABOR (abort transfer)."),
> "APPE" : CommandProperty(perm='a', auth_needed=True,
> arg_needed=True, check_path=True, syntax="APPE file-name
> (append data to an existent file)."),
> "CDUP" : CommandProperty(perm='e',
> auth_needed=True,arg_needed=False, check_path=False, syntax="CDUP (go
> to parentdirectory)."),
> ...
> ...
> ...
> }
>
> ...but I find it somewhat redundant and... "ugly".
> I was wondering if there was some kind of data type which could better
> fit such purpose or if someone could suggest me some other approach to
> do this same thing. Maybe using a dictionary is not the better choice
> here.
How about something like this? The idea is to summarize the command
table, then construct the ftp command dictionary programatically from
it.
cmd_table = dict(
ABOR='-AR- (abort transfer)',
APPE='aARP file-name (append data to a file)',
CDUP='eA-- (go to parent directory)',
...
)
The first block of four characters give the options: permission,
whether authentication is needed, whether the argument is required,
and whether the path needs checking. Permission is the permission
letter or - (for none), A or - for authentication, R or - for argument
required, and - or P for path required. Then the help text follows
(with the command name omitted since it's redundant).
Turning these into CommandProperty's is straightforward (untested
code):
ftp_commands = {}
for cmd, descriptor in cmd_table.iteritems():
options, help = descriptor.split(' ', 1)
options = [None if opt == '-' else opt for opt in options]
perm, auth, arg, path = options
assert perm is None or perm in 'ae...'
assert auth is None or auth == 'A'
assert arg is None or arg == 'R'
assert path is None or path == 'P'
ftp_commands[cmd] = CommandProperty(perm=perm, auth_required=auth,
arg_required=arg, check_path=path, syntax = '%s %s' % (cmd, help))
--
Paul Hankin
--
http://mail.python.org/mailman/listinfo/python-list
Re: interpreter vs. compiled
castironpi <[EMAIL PROTECTED]> wrote: > >And furthermore, I think I'm getting >confused about what exactly constitutes an interpreter: it is whether >there is a process that runs product instructions, or the product >instructions can run standalone. I would take 'compiler' to mean, >something that outputs an .EXE executable binary file, and I don't >just mean bundling up the python.exe executable with a file. OK, let me give MY definition. I freely grant that my definition might be different from anyone elses, but perhaps this will help you understand the basis for my arguments. If I run three different CPython programs, the bytes of machine language that get executed are come from the same place: python24.dll. My user programs are just data. That, in my mind, makes the CPython implementation an interpreter. If I compile and run three different C programs, the bytes of machine language will be come from three different places. That, in my mind, makes my C implementation a compiler. If I compile and run three different C# programs, the JIT compiler makes new machine language for each one. The bytes of machine language will come from three different places. That, in my mind, makes the C# implementation a compiler. If I compile and run three different IronPython programs, the JIT compiler makes new machine language for each one. The bytes of machine language will come from three different places. That, in my mind, makes the IronPython implementation a compiler. All four of those scenarios require run-time library support. Even the C progam does not run on its own. Execution starts in the run-time library, which sets up an environment before jumping to "main". The C# and IronPython situations are the same; it's just that there's more processing going on before jumping to "main". -- Tim Roberts, [EMAIL PROTECTED] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Swap memory in Python ? - three questions
John Nagle <[EMAIL PROTECTED]> wrote: >Robert LaMarca wrote: >> >> I am using numpy and wish to create very large arrays. My system is AMD 64 >> x 2 Ubuntu 8.04. Ubuntu should be 64 bit. I have 3gb RAM and a 15 GB swap >> drive. > > Does a full 64-bit version of CPython, one where all pointers >and sizes are 64 bits, even exist? Absolutely. [EMAIL PROTECTED] ~]# uname -a Linux naxier.xx.com 2.6.9-42.0.3.ELsmp #1 SMP Mon Sep 25 17:24:31 EDT 2006 x86_64 x86_64 x86_64 GNU/Linux [EMAIL PROTECTED] ~]# python Python 2.3.4 (#1, Feb 18 2008, 17:16:53) [GCC 3.4.6 20060404 (Red Hat 3.4.6-9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.maxint 9223372036854775807 >>> -- Tim Roberts, [EMAIL PROTECTED] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie Python questions
binaryjesus <[EMAIL PROTECTED]> wrote: > >One great open source GUI package that you left out is GTK ie. pygtk. >i cant compare it with wx as i have never used it but isay its much >better than QT. > >Anyway for ur q if u want to compair qt n wx. QT should be faster coz >it has a better documentation. Holy moly, did you send this from your cell phone? -- Tim Roberts, [EMAIL PROTECTED] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Continually check object status
I was afraid that someone was going to mention threading. I have read about it before but not been able to do much with it. My ultimate goal is to create some sort of tamagotchi style virtual pet to interact with. Over time it gets hungry or bored, but the process can be fixed by a user "feeding" or "playing with" it. I wanted to take this opportunity to teach myself some PyGTK coding as well, but I thought that maybe I could build the creature object and looping in such a way that it would be possible to add a GUI to it later. No, that's not possible. But when you use GTK, there are timer-functions that let you register a timer event which will then invoke a callback in which you can check whatever status you like. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: interpreter vs. compiled
On 2 Aug, 08:33, castironpi <[EMAIL PROTECTED]> wrote: > On Aug 1, 5:24 am, Paul Boddie <[EMAIL PROTECTED]> wrote: > > > a + b # in Python > > > > ...is not sufficiently represented by... > > > > ldr r1, a > > ldr r2, b > > add r3, r1, r2 > > > > ...in some assembly language (and the resulting machine code), mostly > > because the semantics of Python addition are more complicated. > > No, it is not sufficiently represented. Python runs checks before and > after, to check for overflows. It does more than this... >test safeinteger a >test safeinteger b >ldr r1, a >ldr r2, b >add r3, r1, r2 >test not overflow > > However, no implementation of Python can do better, given Python's > specification. In fact, as was probably mentioned before, it does something more like this: get method __add__ on a (if possible) or jump to (1) populate an invocation frame with a and b call the method test the result against the special NotImplemented value if result is not NotImplemented then jump to (3) (1) get method __radd__ on b (if possible) or jump to (2) populate an invocation frame with b and a call the method test the result against the special NotImplemented value if result is not NotImplemented then jump to (3) (2) raise a TypeError exception (3) provide the result to whatever gets evaluated next The instructions that you list, which is based on the really simple case which I mentioned, happens in the method that gets called (eg. __add__), and then only for integers. Note that seemingly trivial things like getting the methods can be quite a few instructions in any low-level code. [...] > Another factor, a and b are known to be and are always integers, in a > given C context. > > int a, b; > ... > a + b > > The C compilation process outputs: > >ldr r1, a >ldr r2, b >add r3, r1, r2 Right. That's why some people want to have type declarations in Python, and others want to be able to generate specialised code at run- time for such cases. > and you are correct. However, for: > > string a, b; > a + b > > performs a concatenation which is not that simple. The point is, C > compilation runs, and you actually have -ldr, ldr, add- lying around > in a file somewhere, which can run as three consecutive instructions > on a processor. It's already in the interpreter in Python, and you > have the -test, test, ldr, ldr, add, test- sequence somewhere in > Python.exe, specifically wherever the object code for ceval.c is > going. Right. The way to think about this is that due to the mechanics of working out what kind of operations should be performed (should it be an integer addition, a string concatentation, something else?), there's a lot of code executed which is really "dancing around" the actual work, and then for short bursts of instructions, the work actually gets done. It's like having to jet around the world, sampling drinks in different locations, rather than just lining the different drinks up at home. Paul -- http://mail.python.org/mailman/listinfo/python-list
I donä't get while-loops
in read2 it never quits when I write quit, why?
def read():
expr = raw_input("Lisp> ")
if expr != "quit":
print parse(expr)
read()
else:
print "Good session!"
def read2():
expr = ""
while expr != "quit":
expr = raw_input("Lisp> ")
print parse(expr)
read2()
print "Good session!"
--
http://mail.python.org/mailman/listinfo/python-list
raw_input on several lines
Hi everybody,
When using raw_input(), the input of the user ends when he types Return on
his keyboard.
How can I change this behavior, so that another action is needed to stop the
input? For example, CTRL-G. It would allow the user to input several lines.
Thanks
Julien
--
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+,\'Z
(55l4('])"
"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list
Re: I donä't get while-loops
def read2():
expr = ""
while expr != "quit":
expr = raw_input("Lisp> ")
print parse(expr)
read2()
^
print "Good session!"
You shouldn't call read2() inside read2()...
just remove that line and retry...
Each time you call read2() recursively, a
new expr is initialized to "", so the condition
never becomes true
--
http://mail.python.org/mailman/listinfo/python-list
Re: I donä't get while-loops
ssecorp wrote:
in read2 it never quits when I write quit, why?
def read():
expr = raw_input("Lisp> ")
if expr != "quit":
print parse(expr)
read()
else:
print "Good session!"
def read2():
expr = ""
while expr != "quit":
expr = raw_input("Lisp> ")
print parse(expr)
read2()
print "Good session!"
That's because read2() is being called recursively making expr be always a blank
string the first time you go through the loop. Delete the call to read2() that
is inside your while loop and try.
-Larry
--
http://mail.python.org/mailman/listinfo/python-list
Re: Profiling weirdness: Timer.timeit(), fibonacci and memoization
Nothing weird about this ... The difference will become larger as your input value becomes larger. You can easily understand why if you try to calculate fib(10) by hand, i.e. work through the algorithm with pencil and paper, then compare the work you have to do to the memoized version which just takes fib(9) and fib(8) from memory and adds them together. Best regards, Stefaan. -- http://mail.python.org/mailman/listinfo/python-list
Re: raw_input on several lines
TP wrote:
Hi everybody,
When using raw_input(), the input of the user ends when he types Return on
his keyboard.
How can I change this behavior, so that another action is needed to stop the
input? For example, CTRL-G. It would allow the user to input several lines.
Thanks
Julien
Just put raw_input() in a loop and check for something. Actually a blank line
would probably work best in that case. Not tested, but you will get the idea:
lines = list()
print 'Enter your text (empty line to quit)'
while 1:
line = raw_input('')
if line.strip() == '':
break
lines.append(line)
-Larry
--
http://mail.python.org/mailman/listinfo/python-list
Re: I donä't get while-loops
oops, embarrassing, I created the while loop not to use recursion then I still did... -- http://mail.python.org/mailman/listinfo/python-list
Re: raw_input on several lines
How can I change this behavior, so that another action is needed to stop the input? For example, CTRL-G. It would allow the user to input several lines. I don't think you can change raw_input's behaviour in this respect, but you could build something yourself that's based on interpretation of raw keyboard scan codes. Google is your friend in this... e.g. on Linux you could use something like urwid e.g. on win32 you could use something like http://code.activestate.com/recipes/197140/ I am not aware of an os independent way to accomplish what you want. -- http://mail.python.org/mailman/listinfo/python-list
Re: raw_input on several lines
TP wrote:
Hi everybody,
When using raw_input(), the input of the user ends when he types Return on
his keyboard.
How can I change this behavior, so that another action is needed to stop the
input? For example, CTRL-G. It would allow the user to input several lines.
Thanks
Julien
How about;
student_scores = {}
name = raw_input("Please enter a student name (q quits): ")
while(name != 'q'):
score = input("Please enter the students score: ")
student_scores[name] = score
name = raw_input("Please enter a student name (q quits): ")
for current_key in student_scores.keys():
print "The current students are:", current_key
--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com
--
http://mail.python.org/mailman/listinfo/python-list
why goes the time change after import statement ?
hi i am working on a S3 project and facing a really weird problem!
take a look at the following import statements and the time output
>>> import time
>>> time.strftime("%a, %d %b %Y %X GMT", time.gmtime())
'Sat, 02 Aug 2008 20:21:56 GMT'
# OK
>>> import pygtk
>>> time.strftime("%a, %d %b %Y %X GMT", time.gmtime())
'Sat, 02 Aug 2008 20:22:04 GMT'
# OK
>>> import gtk
>>> time.strftime("%a, %d %b %Y %X GMT", time.gmtime())
'Sat, 02 Aug 2008 08:22:11 PM GMT'
# HOW THE HELL THIS HAPPEN ??? not DATE_RFC2822 format gmt time !
i have waisted 3 hours trying to locate the source of this strange
problem.
so what i am asking is does anyone know to overwrite or fix the
defaurl behaviour strftime()
--
http://mail.python.org/mailman/listinfo/python-list
Re: why goes the time change after import statement ?
On Aug 2, 10:35 pm, binaryjesus <[EMAIL PROTECTED]> wrote:
> hi i am working on a S3 project and facing a really weird problem!
> take a look at the following import statements and the time output
>
> >>> import time
> >>> time.strftime("%a, %d %b %Y %X GMT", time.gmtime())
>
> 'Sat, 02 Aug 2008 20:21:56 GMT'
>
> # OK
>
> >>> import pygtk
> >>> time.strftime("%a, %d %b %Y %X GMT", time.gmtime())
>
> 'Sat, 02 Aug 2008 20:22:04 GMT'
>
> # OK
>
> >>> import gtk
> >>> time.strftime("%a, %d %b %Y %X GMT", time.gmtime())
>
> 'Sat, 02 Aug 2008 08:22:11 PM GMT'
>
> # HOW THE HELL THIS HAPPEN ??? not DATE_RFC2822 format gmt time !
Reading the manual page for strftime --
http://docs.python.org/lib/module-time.html
-- says that '%X' is the locale's appropriate time representation, so
obviously gtk is adjusting your locale. Perhaps use a formatting
string that doesn't depend on the locale: '%H:%M:%S' instead of '%X'
seems to give your preferred format.
--
Paul Hankin
--
http://mail.python.org/mailman/listinfo/python-list
Re: Profiling weirdness: Timer.timeit(), fibonacci and memoization
Stefaan Himpe wrote in news:[EMAIL PROTECTED] in comp.lang.python: > Nothing weird about this ... > The difference will become larger as your input value becomes larger. > > You can easily understand why if you try to calculate fib(10) by hand, > i.e. work through the algorithm with pencil and paper, > then compare the work you have to do to the memoized version which just > takes fib(9) and fib(8) from memory and adds them together. > I think you missed the point. The problem is that the un-decorated, loop only version takes 35 seconds when called by timeit.Timer. However if you apply the decorator it takes less that a second. In *both* cases the function (fib) only gets called once. Note, I timed the call fib(100) with time.clock() and got a value of less than 1 ms, the memozed version takes about 10 times longer. So the question is: whats going on with timeit.Timer ? Rob. -- http://www.victim-prime.dsl.pipex.com/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Help me
[EMAIL PROTECTED] schrieb: The assignment aims at enforcing the encryption and communication techniques. It helps the student in acquiring the necessary knowledge in developing client/server application and in securing data transfer using encryption techniques. Nice! Finally someone who upfront admits what he wants. Diez -- http://mail.python.org/mailman/listinfo/python-list
SMTP via GMAIL
After reading about and using the smtplib module, I thought code such as below would ignore the 'Cc: ' body line below when sending messages and instead simply use the RECEIVERS list session = smtplib.SMTP(SMTPserver,port) session.set_debuglevel(1) session.ehlo(SMTPuser) # say hello session.starttls() # TLS needed session.ehlo(SMTPuser) # say hello again session.login(SMTPuser, pw) FROM=SENDER RECEIVERS= (TO,CC) BODY= MakeBody(FROM,TO,CC,SUBJECT,MESSAGE) SMTPresult = session.sendmail(SENDER, RECEIVERS, BODY) Here the MakeBody() creates text like below From: FROM To: TO Cc: CC Subject: SUBJECT MESSAGE But when using smtp.gmail.com as the server I learned that any @gmail.com address in the Cc: text block would receive mail even if I changed the code to have the RECEIVERS list to ignore the CC addresses or not include the gmail address in the CC list as below RECEIVERS= (TO,) BODY= MakeBody(FROM,TO,CC,subject,message) SMTPresult = session.sendmail(SENDER, RECEIVERS, BODY) Other @zzz.com CC addresses need to be in the RECEIVERS list however. Also the gmail server changes the 'From: ' text to be the same as SENDER even if this is modified (a case not using FROM=SENDER. I found other servers send mail that displays the BODY specified From: address. Is this gmail specific or a quirk of the smtplib functions? I understand how Google might not want to send mail with FROM not = SENDER, but the CC behavior baffles me. And does anyone have a general routine that lets one also have Bcc: addresses usign SMTP? -- http://mail.python.org/mailman/listinfo/python-list
Re: embedded python doesn't like socket.accept() and SegFaults
Solved (with the help of the guys on #python on freenode). Long story short: i forgot the static in the function definitions and the libc's "accept" got replaced with mine... Riccardo Di Meo wrote: Hi everyone, I'm practicing with embedding python into C code and i have encountered a very strange problem: I'm unable to call the "accept" method of a (correctly created) server socket without receiving a "Segmentation fault" (inside the PyObject_CallMethod). My code to be correct (at least it's correct enough for me to call .getsockname(), .fileno() and other methods without problems), I'm pretty new to this thing though, therefore I'm confident I'm doing something very dumb. -- http://mail.python.org/mailman/listinfo/python-list
Re: Agnostic fetching
jorpheus wrote: > OK, that sounds stupid. Anyway, I've been learning Python for some > time now, and am currently having fun with the urllib and urllib2 > modules, but have run into a problem(?) - is there any way to fetch > (urllib.retrieve) files from a server without knowing the filenames? > For instance, there is smth like folder/spam.egg, folder/ > unpredictable.egg and so on. If not, perhaps some kind of glob to > create a list of existing files? I'd really appreciate some help, > since I'm really out of my (newb) depth here. If you happen to have a URL that simply lists files, then what you have to do is relatively simple. Just fetch the html from the folder url, then parse the html and look for the anchor tags. You can then fetch those anchor urls that interest you. BeautifulSoup can help out with this. Should be able to list all anchor tags in an html string in just one line of code. Combine urllib2 and BeautifulSoup and you'll have a winner. -- http://mail.python.org/mailman/listinfo/python-list
RE: applescript/python question
Hi Diez, Thanks for your reply. I gave this a try too, but it doesn't seem to work either. However, a gentleman just emailed me off-list recommending to use the full path to Python that is in /usr/local/bin. This is where Python 2.5 looks to be installed rather than Python 2.3 which is in /usr/bin. I ran the following code below and it works great! > > set p to "#!/usr/bin/python > import sys > print sys.version[:3]" > set x to do shell script "/usr/local/bin/python -c \"" & p & "\"" > return x > Thank you all again for your thoughts and replies. I really appreciate it!! Jay > I guess the shebang is simply ignored - the actual interpreter is > fetched from the "Python -c"-line. > > It's a bit weird that there is Python with a capital P, but what happens > if you change that to Python2.5 for example? > > Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: current week / weeks in year - best practice
Aljosa Mohorovic <[EMAIL PROTECTED]> wrote: > >what if i know current context week = 20 (example), what would be the >best way to get datetime objects for first and last day of current >context week? >by "current context week" i don't mean current week for current year >but current week when program is iterating all weeks in year. One of the problems is that "current week of the year" is not a well-defined term. Some companies define the first week as the week that contains January 1. Some companies define the first week as the first full week, so that a partial Jan 1 week is actually part of the previous year. And you get the whole "does the week start on Sunday or Monday" debate as well. You need to make sure that the datetime functions match your business rules. -- Tim Roberts, [EMAIL PROTECTED] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: base-96
Kless <[EMAIL PROTECTED]> wrote: > >I think that would be very interesting thay Python would have a module >for working on base 96 too. [1] Well, then, write one. However, I'm not sure I see the point. Base 64 is convenient because 6 bits becomes 8 bits exactly, so 3 bytes translates exactly to 4 characters. With base 96, you would end up doing division instead of just shifting and masking; the conversion isn't as "neat". >As you can see here [2], the printable ASCII characters are 94 >(decimal code range of 33-126). So only left to add another 2 >characters more; the space (code 32), and one not-printable char >(which doesn't create any problem) by last. This leaves some tricky issues. How will you denote the end of a base 96 sequence? If every printable character can be part of the ciphertext, what can you use as an end marker or a padding character? -- Tim Roberts, [EMAIL PROTECTED] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: Interconvert a ctypes.Structure to/from a binary string?
On Aug 1, 11:35 pm, Andrew Lentvorski <[EMAIL PROTECTED]> wrote: > Basically, I'd like to use the ctypes module as a much more descriptive > "struct" module. > > Is there a way to take a ctypes.Structure-based class and convert it > to/from a binary string? > > Thanks, > -a After chugging through the ctypes source code, I found that I can abuse ctypes into doing what I want. Here is how I did it. I can abuse string_at(addressof(SomeCtypesClass), length) to get a binary string out of ctypes while I use: def analyze_elf_header(binaryData): headerSize = ctypes.sizeof(Elf32_Ehdr) header = Elf32_Ehdr() # Abuse ctypes to initialize from a string bb = ctypes.create_string_buffer(binaryData[0:headerSize]) ctypes.memmove(ctypes.addressof(header), ctypes.addressof(bb), headerSize) To jam stuff into a ctypes class. This seems like an oversight in the module though. It would really be better if the class itself had methods to init from/produce to a binary string. However, I would prefer that somebody who actually knows ctypes to weigh in here with comments about what I did. Thanks, -a -- http://mail.python.org/mailman/listinfo/python-list
Re: interpreter vs. compiled
On Aug 2, 2:02 pm, Tim Roberts <[EMAIL PROTECTED]> wrote:
> castironpi <[EMAIL PROTECTED]> wrote:
>
> >And furthermore, I think I'm getting
> >confused about what exactly constitutes an interpreter: it is whether
> >there is a process that runs product instructions, or the product
> >instructions can run standalone. I would take 'compiler' to mean,
> >something that outputs an .EXE executable binary file, and I don't
> >just mean bundling up the python.exe executable with a file.
>
> OK, let me give MY definition. I freely grant that my definition might be
> different from anyone elses, but perhaps this will help you understand the
> basis for my arguments.
I understand that we're having a disagreement about terminology. I
further don't understand exactly what JIT languages are, so I can't
agree on that either.
I will observe the certain amount of corporate hype behind, and worker
base morale riding on, the notion that JIT technology compiles code.
I suspect it's an exaggeration, not outright false, but I can't prove
it until I tell you what instructions run, one right after another, on
a concrete architecture I've held in my hand, like the x86 die. Nor
can I thoroughly believe that it's true either, though, until its
creators have told me what instructions they are. So I'll proclaim
ignorance and await facts... or consistent stories about them.
> If I run three different CPython programs, the bytes of machine language
> that get executed are come from the same place: python24.dll. My user
> programs are just data. That, in my mind, makes the CPython implementation
> an interpreter.
>
> If I compile and run three different C programs, the bytes of machine
> language will be come from three different places. That, in my mind, makes
> my C implementation a compiler.
True. I agree on the facts and the terms.
> If I compile and run three different C# programs, the JIT compiler makes
> new machine language for each one. The bytes of machine language will come
> from three different places. That, in my mind, makes the C# implementation
> a compiler.
>
> If I compile and run three different IronPython programs, the JIT compiler
> makes new machine language for each one. The bytes of machine language
> will come from three different places. That, in my mind, makes the
> IronPython implementation a compiler.
I don't know enough to attest to these for a fact, and you haven't
given enough details to corroborate them as facts. But when you do,
I'll be able to take and learn your terms for them (not that I will,
of course, but I can).
> All four of those scenarios require run-time library support. Even the C
> progam does not run on its own.
I disagree with this, if the C program is statically linked -- the OS
copies the binary (.EXE) from disk into memory, then jumps to a
specific offset in that block / address space. It runs all its own
bytes, then jumps back to an OS-specified point of return of control.
For the other three, though, this is true.
> Execution starts in the run-time library,
> which sets up an environment before jumping to "main". The C# and
> IronPython situations are the same; it's just that there's more processing
> going on before jumping to "main".
I want to give a concrete example of 'generating machine code' per se
(as such).
I run this program:
bin= open( 'abinary.exe', 'w' )
bin.write( '\x09\x0f\x00\x00' )
for x in range( 10 ):
bin.write( '\x04\xA0' + chr( x ) + '\x00' )
bin.write( '\x01\x20\x00\x00' )
It outputs to 'abinary.exe':
\x09\x0f\x00\x00
\x04\xa0\x00\x00
\x04\xa0\x01\x00
\x04\xa0\x02\x00
\x04\xa0\x03\x00
\x04\xa0\x04\x00
\x04\xa0\x05\x00
\x04\xa0\x06\x00
\x04\xa0\x07\x00
\x04\xa0\x08\x00
\x04\xa0\x09\x00
\x01\x20\x00\x00
Which is 12 bytes long and runs in a millisecond. What it does is set
a memory address to successive integers 0..9, then yields. Due to the
nature of program flow control, while it runs its first steps on any
x86 machine, the yield only succeeds if on Windows 98+, and crashes
the machine, or otherwise loses control if not. (That part depends on
those OSses.)
I can try something similar dynamically.
char* mem= alloc( 48 )
setpermission( mem, EXECUTE )
memcpy( mem+ 0, "\x09\x0f\x00\x00", 4 )
for( int x= 0; x< 10; ++x ) {
memcpy( mem+ 4* (x+ 1 ), '\x04\xA0\x00\x00', 4 )
mem[ 4* (x+ 1 )+ 3 ]= (char) x
memcpy( mem+ 44, '\x01\x20\x00\x01', 4 )
setjump
goto mem
Which with some imagination produces the contents of 'abinary.exe'
above (one difference, last word) in a memory block, at address 'mem',
then jumps to it, which then jumps back, and then exits.
I'll compare a C complation to the first example, 'abinary.exe', and a
JIT compilation to the second example, 'char* mem'. If the comparison
isn't accurate, say how, because these are places I can start from...
(yes, that is, instead of just repeating the claims).
When does a JIT do this, and what does it do in the meantime?
--
http://mail.python.org/mailman/listinfo/python
Re: base-96
see http://en.wikipedia.org/wiki/Base-85 for something more practical -- http://mail.python.org/mailman/listinfo/python-list
Re: base-96
Kless <[EMAIL PROTECTED]> wrote: >I think that would be very interesting thay Python would have a module >for working on base 96 too. [1] > >It could be converted to base 96 the digests from hashlib module, and >random bytes used on crypto (to create the salt, the IV, or a key). > >As you can see here [2], the printable ASCII characters are 94 >(decimal code range of 33-126). So only left to add another 2 >characters more; the space (code 32), and one not-printable char >(which doesn't create any problem) by last. Whether it creates problems depends on how you intend to use it. The biggest use for Base64, for instance, is in translating binary files to a form where they can be send via email using only printable characters. If you use a non-printable character, that's a problem for email. With Base64, 3 bytes becomes 4. With Base96, 5 bytes becomes 6. So, you would reduce the conversion penalty from 1.33 down to 1.17. It's not hard to write modules to translate from binary to Base96 and back again, and doing so would be a great exercise to explore the issues in this kind of encoding. -- Tim Roberts, [EMAIL PROTECTED] Providenza & Boekelheide, Inc. -- http://mail.python.org/mailman/listinfo/python-list
Re: ANN: pyspread 0.0.8
On Sat, 02 Aug 2008 13:39:25 -0400
"Colin J. Williams" <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > pyspread 0.0.8 has been released.
> Are you planning any documentation?
Actually, yes.
0.0.10 will feature some docs.
Any help writing and doing the layout is highly appreciated ;-)
> I've tried:
> # tpySpread.py
> print 'start'
> import pyspread
> print pyspread.__doc__
Just launch it with
$ pyspread.py
or when in Windows double click on the pyspread.py file in the Scripts
folder that is in your Python folder.
Alternatively, when in python type:
>>> import pyspread
>>> pyspread.main()
Then the main window should come up.
To make things easier, I post a preliminary tutorial:
--- Tutorial ---
1) One python expression per cell.
In the top left cell (row 0, column 0, table 0) type:
> 2 + 2
The cell text changes to:
4
which is the string representation of the result.
Select the top left cell again. 2 + 2 is displayed in the text field
above the grid. Double-clicking on the cell also changes the content
back to 2 + 2.
>From any other cell, the cell result (that is the resulting object) can
be accessed by entering
> S[0, 0, 0]
This is also possible for other tables. Change to Table 1 in the
icon bar choicebox. and enter S[0,0,0] somewhere.
A value can also be assigned to a global variable. Change back to Table
0 and type into cell 1,0,0:
> myfancystring = " ".join(str(i) for i in xrange(100))
myfancystring can now be accessed from any other cell as a global
variable.
In each cell, upper case X, Y, and Z refer to the cell's position in
the grid. So if you type into the cell directly below the top-left cell
> S[X-1, Y, Z]
The result is identical to S[0, 0, 0]
However, when copying the input with Crtl-C and Ctrl-V, the link stays
relative while the other link is absolute.
2) Python batteries
Library import can be done as follows:
> decimal = __import__("decimal")
in one cell and
> decimal.Decimal(1)
in the next cell. The calculations will be done with the object while
the string representation is displayed in the grid.
Since some functionality should not be done in one-line expression,
functions can be defined in the Macro list.
In the menu, select Macro -> Macro list.
On the lower right side, a code window can be uncovered, in which one
and only one function can be entered, e.g.:
> def mysandwich(spam, eggs, bacon):
> """Add spam, eggs, and bacon."""
> return spam + eggs + bacon
After clicking on Add in the top left of the dialog, the function is
accessible from each cell. The macro form (middle right) allows filling
in the parameters and Ok inserts the function into the selected cell.
When doing changes to the code, Apply alters the current function
including the function name while Add lets you create a new function by
changing the function name.
3) Spreading data
Often, a cell may return a list or a matrix, which is nice for
calculations but bad for export and presentation. Therefore, arrays and
matrices can be spread out into cells using the grid's spread method.
In cell 2,0,0 type:
> [1, 2, 3]
In cell 3,0,0 type:
> S.spread(4, 0, 0, S[2,0,0])
Then in the cells 4,0,0 - 6,0,0, the array will be displayed.
---
I hope that this helps as a quick start.
Best Regards
Martin
--
http://mail.python.org/mailman/listinfo/python-list
Re: I donä't get while-loops
You're actually calling the read2() function from within read2(). This
is called recursion, and it is *not* what you want in this case, since
it unnecessarily fills up your call stack. Remember that a while loop
automatically goes back to the top without you having to re-call your
function. I would just do this:
def read3():
expr = raw_input("Lisp> ")
while expr != "quit":
print parse(expr)
expr = raw_input("Lisp> ")
print "Good session!"
ssecorp wrote:
in read2 it never quits when I write quit, why?
def read():
expr = raw_input("Lisp> ")
if expr != "quit":
print parse(expr)
read()
else:
print "Good session!"
def read2():
expr = ""
while expr != "quit":
expr = raw_input("Lisp> ")
print parse(expr)
read2()
print "Good session!"
--
http://mail.python.org/mailman/listinfo/python-list
Teething troubles with Python on a Mac
I've got a new iMac, have installed Python 2.5.2 on it, and am now trying to run my existing Python programs on it (these are typically number crunching programs that I run from IDLE). Some things work, while others don't, and as this is my first time grappling with Unix and MacOS X, I appreciate some guidance on how to get up and running. Here are details of my setup interspersed with my woes and my questions. Your assistance is greatly appreciated. Item 1. I downloaded and installed 2.5.2 from python.org. Runs fine, it installed a MacPython directory under applications, which has a few icons, including IDLE. However, I have absolutely NO idea where all the Python files are kept. Question 1: How can I locate the Python installation? There a few files under Applications > MacPython 2.5, but this is clearly not the entire installation. Question 2: In Finder, If I click on Search For > Past week, I can see a sequence of folders under the horizontal scroll bar at the bottom of the window, allowing me to determine that some files that were placed under Applications > MacPython 2.5> Extra> Demo. But I do not seem to be able to see the sequence of folders under the horizontal scroll bar in any finder window. What do I need to do to make the folder sequence visible in all Finder Windows? Item 2. I downloaded and installed the SciPy superpack from Macinscience,org. Scipy seems to import correctly into the Python 2.5.1 that comes with the Mac, but i cannot import it into MacPython 2.5.2. Question 3. What do I have to do in order to make SciPy work with both Python 2.5.1 (that comes with the Mac) and 2.5.2 (that I installed myself)? Item 3. I accidentally clicked on something (not sure what) and suddenly found the path to the numpy folder was Macintosh HD > Developer > SDKs > MacOSX10.5.sdk>System> Library>Frameworks>Python.framework>Versions>2.5>extras>lib>Python>numpy. This is insane!!! Where would the superpack have installed SciPy, and how can I find it? Question 4. How do I get MacPython 2.5.2 to see SciPy, NumPy etc. Question 5. How can I find the current value of the PYTHONPATH environment variable, and how can I edit it and add a directory in which I keep my Python programs. Question 6. Apparently there's a Property List Editor that must be used to create a file called ~ /.MacOSX/environment.plist. I can't find a directory called ~/.MacOSX. Is this a hidden directory? Item 4. I opened a terminal window, and typed ipython. Here's what I got: Welcome to IPython. I will try to create a personal configuration directory where you can customize many aspects of IPython's functionality in: /Users/tom/.ipython WARNING: Installation error. IPython's directory was not found. Check the following: The ipython/IPython directory should be in a directory belonging to your PYTHONPATH environment variable (that is, it should be in a directory belonging to sys.path). You can copy it explicitly there or just link to it. IPython will create a minimal default configuration for you. Ipython actually runs once I hit enter, but I do not seem to be able to import and run my programs. Question 7. What is this cryptic message all about? I'm completely confused. I never thought I'd say this, but it actually seemed a lot easier to get Python and any associated programs up and running on Windows! I suspect that a large fraction of my troubles are due to the fact that I am brand new to the Mac and to Unix, but I bought the Mac in part because I thought that using it was effortless. Thank you in advance for your help. Sincerely Thomas Philips -- http://mail.python.org/mailman/listinfo/python-list
Re: Help me
On Sat, 02 Aug 2008 20:02:42 +0300, ahmadoubay_20240 wrote: > The assignment aims at enforcing the encryption and communication > techniques. It helps the student in acquiring the necessary knowledge in > developing client/server application and in securing data transfer using > encryption techniques. This web page will help you a lot. Read it. Study it. Read it again. http://www.catb.org/~esr/faqs/smart-questions.html -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Profiling weirdness: Timer.timeit(), fibonacci and memoization
On Sat, 02 Aug 2008 06:02:02 -0700, ssecorp wrote:
> I am not clear about the results here.
>
>
> from timeit import Timer
> import Decorators
>
> def fib(n):
> a, b = 1, 0
> while n:
> a, b, n = b, a+b, n-1
> return b
[...]
> s = 100
>
> t1 = Timer('fib(s)', 'from __main__ import fib, s')
> t2 = Timer('fibmem(s)', 'from __main__ import fibmem, s')
> t1.repeat(number=1)
> t2.repeat(number=1)
> print t1.timeit()
> print t2.timeit()
>
>
> 35.3092010297
> 1.6516613145
>
> So memoization is 20+ times faster than the idiomatic way? Or am I
> missing something here?
Memoization *can be* faster, not *is* -- memoization requires work, and
if it is more work to look something up than to calculate it, then it
will be a pessimation instead of an optimization. That's probably less of
an issue with high-level languages like Python, but in low level
languages you would need to start thinking about processor caches and all
sorts of complications.
But I digress... in Python, yes, I would expect a significant speedup
with memoization. That's why people use it.
> Ok for fun I added memoization to the idiomatic one:
[...]
> didn't think it would make a difference there but it certainly did.
>
> 1.59592657726
> 1.60179436213
Just curious, but why don't you show the results of the call to repeat()?
It makes me uncomfortable to see somebody showing only half their output.
But yes, with memoization, the lookup to find the Fibonacci number should
decrease the time it takes to calculate the Fibonacci number. I'm not
sure why you are surprised. Regardless of which Fibonacci algorithm you
are using, the Timer object is essentially timing one million lookups,
minus 100 calculations of the Fibonacci number. The 999,900 cache lookups
will dominate the time, far outweighing the 100 calculations, regardless
of which method of calculation you choose. That's why the results are
almost identical.
--
Steven
--
http://mail.python.org/mailman/listinfo/python-list
Re: Profiling weirdness: Timer.timeit(), fibonacci and memoization
On Sat, 02 Aug 2008 16:14:11 -0500, Rob Williscroft wrote:
> Stefaan Himpe wrote in news:[EMAIL PROTECTED] in
> comp.lang.python:
>
>> Nothing weird about this ...
>> The difference will become larger as your input value becomes larger.
>>
>> You can easily understand why if you try to calculate fib(10) by hand,
>> i.e. work through the algorithm with pencil and paper, then compare the
>> work you have to do to the memoized version which just takes fib(9) and
>> fib(8) from memory and adds them together.
>>
>>
> I think you missed the point.
>
> The problem is that the un-decorated, loop only version takes 35 seconds
> when called by timeit.Timer. However if you apply the decorator it
> takes less that a second. In *both* cases the function (fib) only gets
> called once.
I think you are completely misreading the results of the Timeit calls.
That's not correct: you're calling it one million times, not once.
You should apply a "sanity check" to results. At the interactive console,
call the undecorated fib(100) once. Does it take 35 seconds? If so, your
computer is terribly slow -- on mine, it returns instantly.
Note that in your email, you showed only half the output:
[quote]
t1 = Timer('fib(s)', 'from __main__ import fib, s')
t2 = Timer('fibmem(s)', 'from __main__ import fibmem, s')
t1.repeat(number=1)
t2.repeat(number=1)
print t1.timeit()
print t2.timeit()
>>>
35.3092010297
1.6516613145
[end quote]
You had two calls to Timer.repeat() methods, and you didn't show the
output. *They* call the Fibonacci functions once. When I do that, I get
output looking like this:
>>> t1 = Timer('fib(s)', 'from __main__ import fib, s')
>>> t1.repeat(number=1)
[7.9870223999023438e-05, 5.5074691772460938e-05, 5.4121017456054688e-05]
You then call the Timer.timeit() method, which calls the function one
million times by default. That's the output you show: notice that 35s
divided by one million is 3.5e-05s, around what I get using the repeat()
method. There's no mystery.
> Note, I timed the call fib(100) with time.clock() and got a value of
> less than 1 ms, the memozed version takes about 10 times longer.
You shouldn't give much credence to timing results from calling a
function once (unless the function does a *lot* of work). Your operating
system is doing all sorts of work in the background. It can easily
interrupt your process mid-calculation to do something else, and your
timing code will then include that. You'll then wrongly conclude that the
function is slower than it really is.
Also, keep in mind that time.clock() is likely to be significantly less
accurate if you are using Linux. The timeit module automatically choose
the best function to use (time.clock vs time.time) for you.
> So the question is: whats going on with timeit.Timer ?
As far as I can see, nothing. I think you have misunderstood the results
you got.
--
Steven
--
http://mail.python.org/mailman/listinfo/python-list
Re: Teething troubles with Python on a Mac
Thomas Philips wrote: Question 1: How can I locate the Python installation? There a few files under Applications > MacPython 2.5, but this is clearly not the entire installation. Have a look in /Library/Frameworks/Python.framework/Versions/2.5 > But I do not seem to be able to see the sequence of folders under the horizontal scroll bar in any finder window. What do I need to do to make the folder sequence visible in all Finder Windows? You can't -- this feature only exists in the Search window, which is a different kind of window from the normal Finder windows. However, in a normal Finder window, if you click and hold with the Command key on the title displayed in the title bar at the top of the window, you'll get a pop-up menu showing the position of the folder you're looking at in the nesting hierarchy. Item 2. I downloaded and installed the SciPy superpack from Macinscience,org. Scipy seems to import correctly into the Python 2.5.1 that comes with the Mac, but i cannot import it into MacPython 2.5.2. I'm not familiar with SciPy distributions, but if it's some sort of double-clickable installer, it's likely that it's only designed to install into the system Python (i.e. the one that comes installed with MacOSX). See if it has installed anything into /Library/Python/2.5/site-packages If so, you could try moving or copying them into /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages Question 5. How can I find the current value of the PYTHONPATH environment variable, and how can I edit it and add a directory in which I keep my Python programs. To find out its current value, in a Terminal window, echo $PYTHONPATH To have it set each time you open a Terminal window, one way is to put something like this in your ~/.bashrc file: PYTHONPATH=whatever_you_want export PYTHONPATH However, because the filename starts with a dot, it won't show up in the Finder or any Save dialog boxes, making it a bit tricky to edit with a GUI-based text editor. There's some advice here on how to deal with that: http://discussions.apple.com/thread.jspa?threadID=1007602 Question 6. Apparently there's a Property List Editor that must be used to create a file called ~ /.MacOSX/environment.plist. I can't find a directory called ~/.MacOSX. Is this a hidden directory? I've never tried that method myself, but it sounds plausible. You'll have similar difficulties with the name .MacOSX not showing up in the Finder. However, you can get to it using the "Go To Folder..." command under the "Go" menu in the Finder and typing in the full pathname. If there isn't already an environment.plist file there, you may have to save it somewhere else first and then drag it into the .MacOSX folder. The Property List Editor comes with the Developer Tools and lives in /Developer/Applications/Utilities. Item 4. I opened a terminal window, and typed ipython. Here's what I got: /Users/tom/.ipython WARNING: Installation error. IPython's directory was not found. It's quite likely that this will correct itself once you get the relevant files into the right site-packages folder. Also, if this is your only reason for wanting to set PYTHONPATH, you may not have to worry about that either. I never thought I'd say this, but it actually seemed a lot easier to get Python and any associated programs up and running on Windows! I suspect that a large fraction of my troubles are due to the fact that I am brand new to the Mac and to Unix, but I bought the Mac in part because I thought that using it was effortless. It's generally pretty smooth (although different from Windows in many ways, so you do need to learn some new things) as long as you stick to GUI-style applications. Python doesn't quite fit into that way of working, however. You need to know a bit about what's going on underneath, particularly when managing your own Python installation. The way I approach Python on MacOSX is to treat it as a Unix system and use the standard Python method of installing packages, i.e. use Python to run a setup.py file. This ensures that the package will be installed into whichever Python is being used to run the setup.py. Apart from the initial installation of Python itself, I never use an installer to install a Python package if I can avoid it. I wouldn't trust it to install into the right Python version. -- Greg -- http://mail.python.org/mailman/listinfo/python-list
Re: why goes the time change after import statement ?
On Aug 3, 1:46 am, Paul Hankin <[EMAIL PROTECTED]> wrote:
> On Aug 2, 10:35 pm, binaryjesus <[EMAIL PROTECTED]> wrote:
>
>
>
> > hi i am working on a S3 project and facing a really weird problem!
> > take a look at the following import statements and the time output
>
> > >>> import time
> > >>> time.strftime("%a, %d %b %Y %X GMT", time.gmtime())
>
> > 'Sat, 02 Aug 2008 20:21:56 GMT'
>
> > # OK
>
> > >>> import pygtk
> > >>> time.strftime("%a, %d %b %Y %X GMT", time.gmtime())
>
> > 'Sat, 02 Aug 2008 20:22:04 GMT'
>
> > # OK
>
> > >>> import gtk
> > >>> time.strftime("%a, %d %b %Y %X GMT", time.gmtime())
>
> > 'Sat, 02 Aug 2008 08:22:11 PM GMT'
>
> > # HOW THE HELL THIS HAPPEN ??? not DATE_RFC2822 format gmt time !
>
> Reading the manual page for strftime
> --http://docs.python.org/lib/module-time.html
> -- says that '%X' is the locale's appropriate time representation, so
> obviously gtk is adjusting your locale. Perhaps use a formatting
> string that doesn't depend on the locale: '%H:%M:%S' instead of '%X'
> seems to give your preferred format.
>
> --
> Paul Hankin
ok that explain it.
but what command does gtk runs that it sets the default behaviour of
strfime() to that ?
--
http://mail.python.org/mailman/listinfo/python-list
Re: SMTP via GMAIL
i have a lot of experience in gmail. i use it to store 100GB's of server backup on it. the form: field will be equal to the gmail acc u login with. you are not clear with ur cc: so i cant offer any help on it. but u can include multiple addresses in the To: and use Bcc: since python doesnt include bcc in sendmail but there is a hacky method to do that to ='[EMAIL PROTECTED] \n\rBcc: [EMAIL PROTECTED]' snedmail(from,to,mail) this hack is also known as header injection attack On Aug 3, 2:36 am, mmm <[EMAIL PROTECTED]> wrote: > After reading about and using the smtplib module, I thought code such > as below would ignore the 'Cc: ' body line below when sending messages > and instead simply use the RECEIVERS list > > session = smtplib.SMTP(SMTPserver,port) > session.set_debuglevel(1) > session.ehlo(SMTPuser) # say hello > session.starttls() # TLS needed > session.ehlo(SMTPuser) # say hello again > session.login(SMTPuser, pw) > > FROM=SENDER > RECEIVERS= (TO,CC) > > BODY= MakeBody(FROM,TO,CC,SUBJECT,MESSAGE) > SMTPresult = session.sendmail(SENDER, RECEIVERS, BODY) > > Here the MakeBody() creates text like below > > From: FROM > To: TO > Cc: CC > Subject: SUBJECT > > MESSAGE > > But when using smtp.gmail.com as the server I learned that any > @gmail.com address in the Cc: text block would > receive mail even if I changed the code to have the RECEIVERS list to > ignore the CC addresses or not include the gmail address in the CC > list as below > > RECEIVERS= (TO,) > BODY= MakeBody(FROM,TO,CC,subject,message) > SMTPresult = session.sendmail(SENDER, RECEIVERS, BODY) > > Other @zzz.com CC addresses need to be in the RECEIVERS list however. > > Also the gmail server changes the 'From: ' text to be the same as > SENDER even if this is modified (a case not using FROM=SENDER. I > found other servers send mail that displays the BODY specified From: > address. > > Is this gmail specific or a quirk of the smtplib functions? > I understand how Google might not want to send mail with FROM not = > SENDER, but the CC behavior baffles me. > > And does anyone have a general routine that lets one also have Bcc: > addresses usign SMTP? -- http://mail.python.org/mailman/listinfo/python-list
Re: raw_input on several lines
On Sat, 02 Aug 2008 21:58:09 +0200, TP wrote: > Hi everybody, > > When using raw_input(), the input of the user ends when he types Return > on his keyboard. > How can I change this behavior, so that another action is needed to stop > the input? For example, CTRL-G. It would allow the user to input several > lines. > > Thanks > > Julien Well I don't know about using CTRL-G. Now I'm pretty sure you can't change the behavior of raw_input() like this *but* what you do is the following: >>> from sys import stdin >>> user_input = stdin.readlines() this is a multiline test >>> user_input ['this\n', 'is\n', 'a multiline\n', 'test\n'] >>> The end of the input is marked by the "End of Transmission" or "End of File" character(which can be obtained via ctrl+D, at least on linux, I have no idea about win32) This would have the additional bonus of working with something being piped into it as an input -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiline text in XML file
King wrote: > Is there any other way to define multiline text in a XML file: > > > Yes, without the CDATA, for example. XML doesn't treat line ending characters any different from other characters. I have no idea what you are trying to achieve since you didn't tell us (and this newsgroup seems the wrong place to discuss this), but maybe it's this: text of first line text of second line text of third line ... Stefan -- http://mail.python.org/mailman/listinfo/python-list
