Re: Get Cliet IP Address
"Fred Atkinson" wrote: What is the function to obtain the client browser's IP address? Do you mean the external public IP to the Internet? When I wanted to log the dynamic IP that my ADSL connection gets, I used whatismyip.com like this: import urllib2 QUERY_URL = 'http://www.whatismyip.com/automation/n09230945.asp' def query(): """Get IP as a string. As per the whatismyip.com automation rules, this function should not be called more ofter than every 5 minutes. """ return urllib2.urlopen(QUERY_URL).read() There's probably a better way, but I'm not very good with networking. :o) -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie thwarted by sys.path on Vista
"Dave Angel" wrote in message news:[email protected]... Michael M Mason wrote: I'm running Python 3.1 on Vista and I can't figure out how to add my own directory to sys.path. Thanks to Jon, Piet, David and Dave for the responses. sys.path gets its values from several places. Ah, I'd misunderstood the docs: I thought it came from just one place (which I couldn't find). Anyway, I'd suggest adding it to PythonPath, and if it's empty, just create it with the directory you need. Thanks--that worked! I'm hoping you know you can also add to sys.path directly during script initialization. It's just a list, and is writeable. Yes, but I'm mainly playing in IDLE and I was getting a bit fed up of repeatedly typing import sys sys.path.append('C:/Users/Michael/Code/Python') import mystuff -- Michael -- http://mail.python.org/mailman/listinfo/python-list
Re: cgi script
On Aug 1, 11:11 pm, golu wrote: > Hi, > i started learning cgi few days ago in python and everything went > fine until i started getting the follwing error > " > The server encountered an internal error and was unable to complete > your request. Either the server is overloaded or there was an error in > a CGI script. Your script has a syntax error. (You forgot a colon or something like that.) If you can, try to run the file directly from a Python interpreter to see where the error is. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Custom namespaces
On Sat, 01 Aug 2009 21:46:35 -0700, Chris Rebert wrote:
>> Is there any way to install a custom type as a namespace?
>
> For classes/objects, yes, using metaclasses. See the __prepare__()
> method in PEP 3115: http://www.python.org/dev/peps/pep-3115/
Looks good, but that's Python 3 only, yes?
At least, I can't get the metaclass to change the __dict__ in Python 2.6.
There's obviously no __prepare__ before 3.0, but I tried the following,
and still __dict__ ends up as a regular dict. Am I missing something?
class VerboseDict(dict):
def __getitem__(self, item):
print ("Looking up key '%s'..." % item)
return super(VerboseDict, self).__getitem__(item)
class Meta(type):
def __new__(cls, name, bases, namespace):
namespace = VerboseDict(namespace)
obj = super(Meta, cls).__new__(cls, name, bases, namespace)
return obj
MyClass = Meta('MyClass', (object,), dict(x=1, y=2))
--
Steven
--
http://mail.python.org/mailman/listinfo/python-list
Re: Custom namespaces
On Sun, Aug 2, 2009 at 12:18 AM, Steven
D'Aprano wrote:
> On Sat, 01 Aug 2009 21:46:35 -0700, Chris Rebert wrote:
>
>>> Is there any way to install a custom type as a namespace?
>>
>> For classes/objects, yes, using metaclasses. See the __prepare__()
>> method in PEP 3115: http://www.python.org/dev/peps/pep-3115/
>
> Looks good, but that's Python 3 only, yes?
Correct.
> At least, I can't get the metaclass to change the __dict__ in Python 2.6.
> There's obviously no __prepare__ before 3.0, but I tried the following,
> and still __dict__ ends up as a regular dict. Am I missing something?
>
>
> class VerboseDict(dict):
> def __getitem__(self, item):
> print ("Looking up key '%s'..." % item)
> return super(VerboseDict, self).__getitem__(item)
>
> class Meta(type):
> def __new__(cls, name, bases, namespace):
> namespace = VerboseDict(namespace)
> obj = super(Meta, cls).__new__(cls, name, bases, namespace)
> return obj
I would /guess/ that type.__new__() is internally doing the equivalent
of dict(namespace). Hence why the addition of __prepare__() was
necessary; it's probably impossible to accomplish what you want in
earlier Python versions.
Cheers,
Chris
--
http://blog.rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list
Generate a new object each time a name is imported
I would like to generate a new object each time I import a name from a module, rather than getting the same object each time. For example, currently I might do something like this: # Module count = 0 def factory(): # Generate a unique object each time this is called global count count += 1 return "Object #%d" % count # Calling module from Module import factory a = factory() # a == "Object #1" b = factory() # b == "Object #2" del factory I'm looking for a way to hide the generation of objects from the caller, so I could do something like this: from Module import factory() as a # a == "Object #1" from Module import factory() as b # b == "Object #2" except of course that syntax is illegal. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Generate a new object each time a name is imported
On Aug 2, 12:35 am, Steven D'Aprano wrote: > > I'm looking for a way to hide the generation of objects from the caller, > so I could do something like this: > > from Module import factory() as a # a == "Object #1" > from Module import factory() as b # b == "Object #2" > Explicit is better than implicit. In other words, I don't see why you need to hide this. Just import the factory function and call it. from Module import factory a = factory() -- http://mail.python.org/mailman/listinfo/python-list
RE: Run pyc file without specifying python path ?
> -Original Message- > From: Dave Angel [mailto:[email protected]] > Sent: Thursday, July 30, 2009 20:08 > To: Barak, Ron > Cc: '[email protected]' > Subject: Re: Run pyc file without specifying python path ? > > Barak, Ron wrote: > > Hi Dave, > > > > On second thoughts, I may have a problem implementing the > wrapper solution, because my actual test_pyc.pyc, needs to > parse its command line. > > Namely, the actual call to test_pyc.pyc looks something like this: > > > > $ python test_pyc.py -U dave -PpasswoRD -C CreateMcGroupOnVolume > > --SVMs_IPs '10.1.1.1 , 10.1.1.2' -n "host1,host2" -g gn -j > jn -s svn > > -t tvn -p pool1 -l -c > > > > And I don't know of a way to add these parameters to the "import > > test_pyc" in wrapper > > > > Is there a way to pass information to an imported module ? > (Sorry if there's an obvious answer, I just cannot figure it out). > > > > Bye, > > Ron. > > > > > >> -Original Message- > >> From: Dave Angel [mailto:[email protected]] > >> Sent: Thursday, July 30, 2009 16:03 > >> To: Barak, Ron > >> Cc: 'Dave Angel'; '[email protected]' > >> Subject: RE: Run pyc file without specifying python path ? > >> > >> Barak, Ron wrote: > >> > -Original Message- > From: Dave Angel [mailto:[email protected]] > Sent: Wednesday, July 29, 2009 21:05 > To: Barak, Ron > Cc: '[email protected]' > Subject: Re: Run pyc file without specifying python path ? > > Barak, Ron wrote: > > > > Hi, > > > > I wanted to make a python byte-code file executable, > > > > > expecting to be able to run it without specifying > "python" on the > (Linux bash) command line. > > > > So, I wrote the following: > > > > [r...@vmlinux1 python]# cat test_pyc.py #!/usr/bin/env python > > > > print "hello" > > [r...@vmlinux1 python]# > > > > and made its pyc file executable: > > > > [r...@vmlinux1 python]# ls -ls test_pyc.pyc > > 4 -rwxr-xr-x 1 root root 106 Jul 29 14:22 test_pyc.pyc > > [r...@vmlinux1 python]# > > > > So, I see: > > > > [r...@vmlinux1 python]# file test_pyc.py* > > test_pyc.py: a python script text executable > > test_pyc.pyc: python 2.3 byte-compiled > > [r...@vmlinux1 python]# > > > > If I try to do the following, no problem: > > > > [r...@vmlinux1 python]# python test_pyc.pyc hello > > [r...@vmlinux1 python]# > > > > However, the following fails: > > > > [r...@vmlinux1 python]# ./test_pyc.pyc > > -bash: ./test_pyc.pyc: cannot execute binary file > > [r...@vmlinux1 python]# > > > > Is there a way to run a pyc file without specifying the > > > > > python path ? > > > > Bye, > > Ron. > > > > > > > > > I don't currently run Unix, but I think I know the problem. > > In a text file, the shell examines the first line, and if > > >> it begins > >> > #! > it's assumed to point to the executable of an > interpreter for that > text file. Presumably the same trick doesn't work for a > .pyc file. > > Why not write a trivial wrapper.py file, don't compile > it, and let > that invoke the main code in the .pyc file? > > Then make wrapper.py executable, and you're ready to go. > > DaveA > > > > > >>> Hi Dave, > >>> Your solution sort of defeats my intended purpose (sorry > >>> > >> for not divulging my 'hidden agenda'). > >> > >>> I wanted my application to "hide" the fact that it's a > >>> > >> python script, and look as much as possible like it's a compiled > >> program. > >> > >>> The reason I don't just give my user a py file, is that I > >>> > >> don't want a cleaver user to change the innards of the script. > >> > >>> On the other hand, I don't want to make a compiled > >>> > >> (freezed?) version of the application, because it'll grow the > >> resulting file significantly, and I don't have the > experience to know > >> how it will run on different Linuxes. > >> > >>> Bye, > >>> Ron. > >>> > >>> > >> Most of the other answers basically paraphrased my suggestion of > >> making a wrapper file, not compiling it, and making it > executable. > >> With that > >> approach, the user just types "wrapper.py" on his command line. > >> > >> And wrapper.py only needs two lines, a shebang, and an > import, no big > >> deal if the user modifies it. The rest of your code can be .pyc > >> files. > >> > >> Steven makes some good points. You have to define what level of > >> clever you're protecting from. A determined hacker will get in no > >> matter what you do, unless you want to ship the program in a > >> proprietary embedded system, encased in epoxy. > >> Further, if you have an extension of .py or .pyc, a knowledgeable > >> hacker will know it's probably python. > >> > >> You imply you want it to run unmodifed on multip
Re: Newbie thwarted by sys.path on Vista
Michael M Mason wrote: "Dave Angel" wrote in message news:[email protected]... Michael M Mason wrote: I'm running Python 3.1 on Vista and I can't figure out how to add my own directory to sys.path. Thanks to Jon, Piet, David and Dave for the responses. sys.path gets its values from several places. Ah, I'd misunderstood the docs: I thought it came from just one place (which I couldn't find). Anyway, I'd suggest adding it to PythonPath, and if it's empty, just create it with the directory you need. Thanks--that worked! Be careful, I'm screwed things up on several occasions by placing a file on PYTHONPATH that overrides a file in the standard library, test.py being my favourite! I'm hoping you know you can also add to sys.path directly during script initialization. It's just a list, and is writeable. Yes, but I'm mainly playing in IDLE and I was getting a bit fed up of repeatedly typing import sys sys.path.append('C:/Users/Michael/Code/Python') import mystuff -- Kindest regards. Mark Lawrence. -- http://mail.python.org/mailman/listinfo/python-list
Re: Generate a new object each time a name is imported
Steven D'Aprano writes: > I'm looking for a way to hide the generation of objects from the caller, > so I could do something like this: > > from Module import factory() as a # a == "Object #1" > from Module import factory() as b # b == "Object #2" > > except of course that syntax is illegal. That sounds reasonable (zen quotes aside), but it's just not possible in current Python. It would require for any use of "a" in subsequent code to not only refer to an object, but also to automagically call it. I know of no mechanism to do that. While Python allows intricate customization of access to objects, simply referring to a name remains fixed in meaning, probably intentionally. (The "cell" mechanism used to implement closures sounds like it could help, but a cell only stores a single value, not a factory, and it doesn't apply to global variables anyway.) -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie thwarted by sys.path on Vista
"Mark Lawrence" wrote in message news:[email protected]... Be careful, I'm screwed things up on several occasions by placing a file on PYTHONPATH that overrides a file in the standard library, test.py being my favourite! Thanks. Sure enough, I've already got my own test.py but I hadn't discovered it was a problem yet... -- Michael -- http://mail.python.org/mailman/listinfo/python-list
Re: Run pyc file without specifying python path ?
Barak, Ron wrote:
Hi Dave,
It seems like I don't understand your solution.
I use the (appatched) soapAPI.py as the wrapper to parsing.pyc.
However, if I do (for instance):
$ python -u parsing.pyc -U aaa
The last line of the output is (as expected):
return_code: 12 ; params: {'username': 'aaa'}
But, if I try the following:
$ soapAPI.py -U aaa
I don't get this line. Only the output to stderr gets printed to the screen.
Bye,
Ron.
Hi Ron,
To make it easier for anybody following this thread, let me post the
minimum equivalent source files, inline.
parsing.py:
--
#!/usr/bin/env python
import sys
def main():
print >> sys.stderr, "This is stderr output"
return 5, sys.argv
if __name__ == "__main__":
return_code, params = main()
print "return_code:",return_code,"; params:",params
sys.exit(return_code)
---
soapapi.py:
---
#!/usr/bin/env python
import sys
import parsing
parsing.main()
--
When I run soapapi.;py, it indeed prints only the stderr output.
The solution is to move (most or all) of the top-level code of
parsing.py into a main() function. Since you already have a main(),
I'll rename that, and make a new one that calls it.
new parsing.py:
---
#!/usr/bin/env python
import sys
def innermain():
print >> sys.stderr, "This is stderr output"
return 5, sys.argv
def main():
return_code, params = innermain()
print "return_code:",return_code,"; params:",params
sys.exit(return_code)
if __name__ == "__main__":
main()
---
The output is now two lines, one from innermain(), and one from main().
And it's the same whether the user runs parsing.py or soapAPI.py
To clarify what happened, realize that when the user invokes
parsing.py, the module is considered a script, and gets a pseudo-name of
"__main__"When that same module is imported by another one, it is
considered a library module, and gets its own name "parsing"
So any logic that explicitly checks for "__main__" has to change,
because we want identical behavior in the two cases.
DaveA
--
http://mail.python.org/mailman/listinfo/python-list
Re: Newbie Question regarding __init__()
Simon wrote: Okay I will fix my code and include "self" and see what happens. I know I tried that before and got another error which I suspect was another newbie error. The idea behind the init_Pre is that I can put custom code here to customize the __init__ instead of creating a new subclass. This kind of hook pattern allows you to flatten your inheritance hierarchy. I can choose in the init_Pre method to execute code before the init_exec (which contains the default __init__ code) and still execute the init_Exec method or I can completely customize the entire __init__ by returning False from init_Pre and prevent the init_Exec from being called. I use this type of pattern with almost all my methods. In this way I can create a less complicated inheritance chain but still have have custom code when needed without sub-classing. I am use to Visual FoxPro which where you can do =is.init_Pre().And.This.init_Exec() and the result is discarded so that is why it looks the way it does. In this form init_Exec has to return a value. However, If self.init_Pre(): self.init_Exec() would work the same and then I could avoid returning a value. Thanks, Simon On Aug 1, 5:52 am, Dave Angel wrote: Nat Williams wrote: As MRAB described, ALL instance methods need to accept 'self' as a first parameter, as that will be passed to them implicitly when they are called. This includes __init__. The name 'self' is just a commonly accepted convention for the name of the instance object passed to methods. You don't have to call it that, but you really should. Take a look athttp://docs.python.org/tutorial/classes.html#class-objects It might help shed some light on how methods and instances work. One other thing. I'm a little confused by the first line of dcObject.__init__: self.init_Pre() and self.init_Exec() I suspect this does not do what you think it does. init_Pre and init_Exec will both be called by this expression (unless init_Pre throws an exception, of course). You're not getting anything here that you wouldn't by just calling each method on a separate line, except just making it harder to read. Read the doc-string for init_Pre() and for init_Exec(). The final version of init_Pre() will return False in some circumstances, and in those circumstances Simon doesn't want init_Exec() to be called. He's deliberately using the short-circuit evaluation of 'and' to accomplish that. On Fri, Jul 31, 2009 at 8:53 PM, Simon wrote: Hi So should the dcObject class include the "self" as well since I have not defined an __init__ method in dcCursor? Simon -- http://mail.python.org/mailman/listinfo/python-list Every one of those methods in both of those classes need a "self" first argument. As others have said, all instance methods need a 'self.' (Please don't top-post. You should put new responses at the end of quoted text, or sometimes inline if that's clearer.) I don't understand your comparison to Foxpro. read on. As your code was last posted, you don't need a return value from init_Exec() Every function that doesn't have an explicit return will return None. And None is interpreted as False in an "and" expression. If you had an "if" around the whole thing, then you'd care. DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Help understanding the decisions *behind* python?
sturlamolden wrote: On 20 Jul, 18:27, Phillip B Oldham wrote: We're not looking to start any arguments or religious wars and we're not asking that python be changed into something its not. We'd simply like to understand the decision behind the lists and tuple structures. We feel that in not "getting" the difference between the two types we may be missing out on using these data structures to their full potential. A crude simplification would be: - A Python programmer will use a tuple where a C programmer will use a struct. - Python and C programmers use lists and arrays similarly. Tuples are used for passing arguments to and from a function. Common use of tuples include multiple return values and optional arguments (*args). It has already been mentioned that tuples are immutable and can be used as dictionary keys. I think collections.namedtuple, introduced in Python 2.6, might help bridge the gap between a traditional tuple and a C struct. -- http://mail.python.org/mailman/listinfo/python-list
Re: Generate a new object each time a name is imported
Steven D'Aprano wrote: > I would like to generate a new object each time I import a name from a > module, rather than getting the same object each time. For example, > currently I might do something like this: > > # Module > count = 0 > def factory(): > # Generate a unique object each time this is called > global count > count += 1 > return "Object #%d" % count > > > # Calling module > from Module import factory > a = factory() # a == "Object #1" > b = factory() # b == "Object #2" > del factory > > > I'm looking for a way to hide the generation of objects from the caller, > so I could do something like this: > > from Module import factory() as a # a == "Object #1" > from Module import factory() as b # b == "Object #2" > > except of course that syntax is illegal. How about >>> class A(object): ... def __init__(self): ... self._n = 0 ... @property ... def a(self): ... try: ... return self._n ... finally: ... self._n += 1 ... >>> import sys >>> sys.modules["yadda"] = A() >>> from yadda import a >>> from yadda import a as b >>> a, b (0, 1) Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Generate a new object each time a name is imported
On Sun, 02 Aug 2009 12:33:03 +0200, Peter Otten wrote: > How about [snip] import sys sys.modules["yadda"] = A() Perfect! That's exactly the sort of thing I'm looking for. Thanks for everyone who answered. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie thwarted by sys.path on Vista
Michael M Mason wrote: "Mark Lawrence" wrote in message news:[email protected]... Be careful, I'm screwed things up on several occasions by placing a file on PYTHONPATH that overrides a file in the standard library, test.py being my favourite! Thanks. Sure enough, I've already got my own test.py but I hadn't discovered it was a problem yet... Typical, tried to reproduce it and can't! Still at least you've been warned. -- Kindest regards. Mark Lawrence. -- http://mail.python.org/mailman/listinfo/python-list
Re: Generate a new object each time a name is imported
Peter Otten <[email protected]> writes: > >>> import sys > >>> sys.modules["yadda"] = A() OMG wow. I bow to you. But I'm not sure whether that's bowing in awe or in terror. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help understanding the decisions *behind* python?
On 8/1/2009 9:31 PM, sturlamolden wrote: - Python and C programmers use lists and arrays similarly. I'm guessing that's because of the brackets... Marcus -- http://mail.python.org/mailman/listinfo/python-list
Re: Generate a new object each time a name is imported
wrote: KNode cannot parse your From-string correctly. Strange. > Peter Otten <[email protected]> writes: >> >>> import sys >> >>> sys.modules["yadda"] = A() > > OMG wow. I bow to you. But I'm not sure whether that's bowing in > awe or in terror. I don't know who invented it, but it's an old trick. It even made it into the standard library (email.LazyImporter). For the record: I don't recommend it. Peter -- http://mail.python.org/mailman/listinfo/python-list
Skipping a superclass
I have a series of subclasses like this: class A(object): def method(self, *args): print "Lots of work gets done here in the base class" class B(A): def method(self, *args): print "A little bit of work gets done in B" super(B, self).method(*args) class C(B): def method(self, *args): print "A little bit of work gets done in C" super(C, self).method(*args) However, the work done in C.method() makes the work done in B.method() obsolete: I want one to run, or the other, but not both. C does need to inherit from B, for the sake of the other methods, so I want C.method() *only* to skip B while still inheriting from A. (All other methods have to inherit from B as normal.) So what I have done is change the call to super in C to super(B, self) instead of super(C, self). It seems to work, but is this safe to do? Or are there strange side-effects I haven't seen yet? -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Seeding the rand() Generator
How does one seed the rand() generator when retrieving random recordings in MySQL? Regards, Fred -- http://mail.python.org/mailman/listinfo/python-list
Re: Skipping a superclass
On Sun, Aug 2, 2009 at 5:36 AM, Steven D'Aprano wrote: > I have a series of subclasses like this: > > class A(object): > def method(self, *args): > print "Lots of work gets done here in the base class" > > class B(A): > def method(self, *args): > print "A little bit of work gets done in B" > super(B, self).method(*args) > > class C(B): > def method(self, *args): > print "A little bit of work gets done in C" > super(C, self).method(*args) > > > However, the work done in C.method() makes the work done in B.method() > obsolete: I want one to run, or the other, but not both. C does need to > inherit from B, for the sake of the other methods, so I want C.method() > *only* to skip B while still inheriting from A. (All other methods have > to inherit from B as normal.) > > So what I have done is change the call to super in C to super(B, self) > instead of super(C, self). It seems to work, but is this safe to do? Or > are there strange side-effects I haven't seen yet? Barring some true weirdness in super(), I don't /think/ so. It obviously works fine in the single-inheritance case, and (after some brute-force testing) the only permitted multiple inheritances involving C and (A or B) always have C ahead of B in the MRO (method resolution order). The fact that you're wanting to bypass a superclass method might suggest however, that your hierarchy could be structured better. Have you considered moving B.method() into another, new class (e.g. newB) which subclasses B? Then C can inherit from B without inheriting the unwanted method, while B's functionality still exists, just under a new name (newB). Cheers, Chris -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie thwarted by sys.path on Vista
Michael M Mason wrote:
I'm running Python 3.1 on Vista and I can't figure out how to add my own
directory to sys.path.
The docs suggest that I can either add it to the PYTHONPATH environment
variable or to the PythonPath key in the registry. However, PYTHONPATH
doesn't exist, and updating the registry key has no effect (and in any case
the contents aren't the same as sys.path).
So where does sys.path get its value from, and how do I change it?
You can use my PEP 370 (http://python.org/dev/peps/pep-0370/) and a .pth
file to extend the search path for modules.
>>> import os
>>> import site
>>> site.USER_SITE
'/home/heimes/.local/lib/python2.6/site-packages'
>>> if not os.path.isdir(site.USER_SITE):
... os.makedirs(site.USER_SITE)
...
>>> pth = open(os.path.join(site.USER_SITE, "michal.pth"), "w")
>>> pth.write("C:/Users/Michael/Code/Python\n")
>>> pth.close()
Restart Python, your custom search path should be in sys.path.
Christian
--
http://mail.python.org/mailman/listinfo/python-list
Re: A Bug By Any Other Name ...
In article ,
J. Cliff Dyer wrote:
>On Fri, 2009-07-17 at 20:53 +, Albert van der Horst wrote:
>> Because unlike in algol 68 in python whitespace is relevant,
>> we could get by with requiring whitespace:
>> x= -q # okay
>> a> 8 ** -2 # okay
>
>This is actually quite thoroughly untrue. In python, *indentation* is
>significant. Whitespace (internal to a line) is not. You can even call
>methods like this if you want:
You totally don't get it. You describe how python is now.
I propose a change to be made to python. Small wonder that that is
different from what it is now.
>
s = 'abc'
s. upper()
>ABC
You prove nothing by giving examples.
You can disprove by giving one counter example,
here it goes.
Whitespace (internal to a line) is significant.
In Python you cannot change
xleftgoing = 12300
to
x left going = 123 000 000
(You can in Algol68)
>Obviously, that's A Bad Idea(tm), but python's parser won't stop you.
What is a bad idea?
Apparently you are not talking about my idea of changing the parser.
("Pythons parser won't stop you from changing the parser" doesn't
make sense.)
>The ++ operator gotcha is so minor that I can't remember anyone actually
>asking about it on the list (who was actually facing it as a
>problem--this thread was started by idle speculation). Can we not
>change the language syntax to address non-issues?
As other languages have an Eleventh Commandment against concatenating
operators, the larger issue is hardly futile.
>
>Practicality beats purity, a.k.a. don't you have something better to do?
I'm having a great time, thank you!
>Cheers,
>Cliff
Groetjes Albert
--
--
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
alb...@spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst
--
http://mail.python.org/mailman/listinfo/python-list
Re: Colour of output text
In article ,
Jean-Michel Pichavant wrote:
>Nobody wrote:
>> On Fri, 10 Jul 2009 09:23:54 +, garabik-news-2005-05 wrote:
>>
>>
> I would like to learn a way of changing the colour of a particular
> part of the output text. I've tried the following
>
On Unix operating systems this would be done through the curses interface:
http://docs.python.org/library/curses.html
>>> Or using ANSI colour codes:
>>>
>>> colours = {
>>> 'none' :"",
>>> 'default':"\033[0m",
>>> 'bold' :"\033[1m",
>>>
>>
>> [snip]
>>
>>
>>> # non-standard attributes, supported by some terminals
>>>
>>
>> This comment should have appeared immediately after "none" ;)
>>
>> Hard-coding control/escape sequences is just lame. Use the curses modules
>> to obtain the correct sequences for the terminal.
>>
>>
>As the OP I'm really interested in doing so. I currently have all my
>colors hard-coded.
>Now It may be lame but as soon as I call curses.initscr(), it's just
>messing up with my terminal, moreover I didn't figure out how to "print
>'hello'" using curses color codes.
>Anyone has an example ? I'm pretty sure it may fit in one line.
In general initscr() ought to work. It fails if it has no/a wrong
idea of what your terminal is.
In the same shell as you run run your program type
set | grep -i term
Now some entry should show up, e.g.
TERM=xterm
infocmp $TERM
should fetch information about your terminal, from the same source
as curses does.
Possible problems are:
- your operating system/configurations lies to curses about the terminal
or your terminal is not specified at all
- curses has not been properly installed and cannot find the database
Groetjes Albert
>
>JM
>
>
--
--
Albert van der Horst, UTRECHT,THE NETHERLANDS
Economic growth -- being exponential -- ultimately falters.
alb...@spe&ar&c.xs4all.nl &=n http://home.hccnet.nl/a.w.m.van.der.horst
--
http://mail.python.org/mailman/listinfo/python-list
IFL 2009: Call for Papers and Participation
Call for Papers and ParticipationIFL 2009Seton Hall UniversitySOUTH ORANGE, NJ, USAhttp://tltc.shu.edu/blogs/projects/IFL2009/Register at: http://tltc.shu.edu/blogs/projects/IFL2009/registration.html* NEW *Registration and talk submission extended to August 23, 2009! ***The 21st International Symposium on Implementation and Application of Functional Languages, IFL 2009, will be held for the first time in the USA. The hosting institution is Seton Hall University in South Orange, NJ, USA and the symposium dates are September 23-25, 2009. It is our goal to make IFL a regular event held in the USA and in Europe. The goal of the IFL symposia is to bring together researchers actively engaged in the implementation and application of functional and function-based programming languages. IFL 2009 will be a venue for researchers to present and discuss new ideas and concepts, work in progress, and publication-ripe results related to the implementation and application of functional languages and function-based programming.Following the IFL tradition, IFL 2009 will use a post-symposium review process to produce a formal proceedings which will be published by Springer in the Lecture Notes in Computer Science series. All participants in IFL 2009 are invited to submit either a draft paper or an extended abstract describing work to be presented at the symposium. These submissions will be screened by the program committee chair to make sure they are within the scope of IFL and will appear in the draft proceedings distributed at the symposium. Submissions appearing in the draft proceedings are not peer-reviewed publications. After the symposium, authors will be given the opportunity to incorporate the feedback from discussions at the symposium and will be invited to submit a revised full arcticle for the formal review process. These revised submissions will be reviewed by the program committee using prevailing academic standards to select the best articles that will appear in the formal proceedings.Invited Speaker: Benjamin C. Pierce University of Pennsylvania Talk Title: How To Build Your Own Bidirectional Programming LanguageTOPICSIFL welcomes submissions describing practical and theoretical work as well as submissions describing applications and tools. If you are not sure if your work is appropriate for IFL 2009, please contact the PC chair at [email protected]. Topics of interest include, but are not limited to: language concepts type checking contracts compilation techniques staged compilation runtime function specialization runtime code generation partial evaluation (abstract) interpretation generic programming techniques automatic program generation array processing concurrent/parallel programming concurrent/parallel program execution functional programming and embedded systems functional programming and web applications functional programming and security novel memory management techniques runtime profiling and performance measurements debugging and tracing virtual/abstract machine architectures validation and verification of functional programs tools and programming techniques FP in EducationPAPER SUBMISSIONSProspective authors are encouraged to submit papers or extended abstracts to be published in the draft proceedings and to present them at the symposium. All contributions must be written in English, conform to the Springer-Verlag LNCS series format and not exceed 16 pages. The draft proceedings will appear as a technical report of the Department of Mathematics and Computer Science of Seton Hall University.IMPORTANT DATESRegistration deadline August 15, 2009Presentation submission deadline August 15, 2009IFL 2009 Symposium September 23-25, 2009Submission for review process deadline November 1, 2009Notification Accept/Reject December 22, 2009Camera ready version February 1, 2010PROGRAM COMMITTEEPeter Achten University of Nijmegen, The NetherlandsJost Berthold Philipps-Universität Marburg, GermanyAndrew Butterfield University of Dublin, IrelandRobby Findler Northwestern University, USAKathleen Fisher AT&T Research, USACormac Flanagan University of California at Santa Cruz, USAMatthew Flatt University of Utah, USAMatthew Fluet Toyota Technological Institute at Chicago, USADaniel Friedman Indiana University, USAAndy Gill University of Kansas, USAClemens Grelck University of Amsterdam/Hertfordshire, The Netherlands/UKJurriaan Hage Utrecht University, The NetherlandsRalf Hinze Oxford University, UKPaul Hudak Yale University, USAJohn Hughes Chalmers University of Technology, SwedenPatricia Johann University of Strathclyde, UKYukiyoshi Kameyama University of Tsukuba, JapanMarco T. Morazán (Chair) Set
Is python buffer overflow proof?
Is a _pure_ python program buffer overflow proof? For example in C++ you can declare a char[9] to hold user input. If the user inputs 10+ chars a buffer overflow occurs. In python, I cannot seem to find a way to define/restrict a string length. This is probably by design and raises the topic in question. Am curious to see the opinions of people who know. TIA. -- http://mail.python.org/mailman/listinfo/python-list
"PAK WEB" "PAK WEB TV" "PAK WEBSITES" "PAK WEB DIRECTORY" "PAK WEB HOSTING" "PAK WEB HOST" "PAK WEB HOSTING" "PAK WEB" "PAK WEB" "PAK WEB" "PAK WEB" "PAK WEB" "PAK WEB" "PAK WEB" on www.pak-web-page
"PAK WEB" www.pak-web-pages.blogspot.com "PAK WEB TV" www.pak-web-pages.blogspot.com "PAK WEBSITES" www.pak-web-pages.blogspot.com "PAK WEB DIRECTORY" www.pak-web-pages.blogspot.com "PAK WEB HOSTING" www.pak-web-pages.blogspot.com "PAK WEB HOST" www.pak-web-pages.blogspot.com "PAK WEB HOSTING" www.pak-web-pages.blogspot.com "PAK WEB" www.pak-web-pages.blogspot.com "PAK WEB" www.pak-web-pages.blogspot.com "PAK WEB" "PAK WEB" "PAK WEB" www.pak-web-pages.blogspot.com "PAK WEB" www.pak-web-pages.blogspot.com "PAK WEB" on www.pak-web-pages.blogspot.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Is python buffer overflow proof?
On 8/2/2009 9:50 AM, Jizzai wrote: Is a _pure_ python program buffer overflow proof? For example in C++ you can declare a char[9] to hold user input. If the user inputs 10+ chars a buffer overflow occurs. In python, I cannot seem to find a way to define/restrict a string length. This is probably by design and raises the topic in question. Am curious to see the opinions of people who know. TIA. I believe that python is buffer overflow proof. In fact, I think that even ctypes is overflow proof... Marcus -- http://mail.python.org/mailman/listinfo/python-list
Re: Seeding the rand() Generator
On 8/2/2009 9:42 AM, Fred Atkinson wrote: How does one seed the rand() generator when retrieving random recordings in MySQL? Regards, Fred something like: import random, time random.seed(time.time()) #not actual record access code: sqlite3.recordaccessfuction(recordid = random.rand()) Marcus -- http://mail.python.org/mailman/listinfo/python-list
Re: Is python buffer overflow proof?
Marcus Wanner wrote: I believe that python is buffer overflow proof. In fact, I think that even ctypes is overflow proof... No, ctypes isn't buffer overflow proof. ctypes can break and crash a Python interpreter easily. Christian -- http://mail.python.org/mailman/listinfo/python-list
Re: Processes not exiting
On 31 July, 11:27, Piet van Oostrum wrote: > > ma3mju (m) wrote: > >m> Hi all, > >m> I'm having trouble with multiprocessing I'm using it to speed up some > >m> simulations, I find for large queues when the process reaches the > >m> poison pill it does not exit whereas for smaller queues it works > >m> without any problems. Has anyone else had this trouble? Can anyone > >m> tell me a way around it? The code is in two files below. > > How do you know it doesn't exit. You haven't shown any of your output. > > I did discover a problem in your code, but it should cause an exception: > > >m> #set off some of the easy workers on the hard work (maybe double > >m> number of hard) > >m> for i in range(0,num_hard_workers): > >m> hard_work_queue.put(None) > >m> hard_workers.append(multiprocessing.Process > >m> (target=GP.RandomWalkGeneralizationErrorParallel,args= > >m> (hard_work_queue,result_queue,))) > >m> #wait for all hard workers to finish > >m> for worker in hard_workers: > >m> worker.join() > > Here you create new hard workers, but you never start them. The join > should then give an exception when it reaches these. > -- > Piet van Oostrum > URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4] > Private email: [email protected] Ok thanks I'll change that In a sec, It never reaches that bit of code because the easy_workers don't exit so it never gets past the join(). As far as running it goes I get the datapt and number of points printed to the list for everything in both queues. When it reaches the end of either queue I get "Poison" on the screen then "here" for each process but I don't get "worker joined" and as expected don't get "this should not appear". If I have a look at the processes running after all queues are supposed to have finished I see all of them running taking little or no resources. This is running on Ubuntu Jaunty at home and the same happens on the Debian machine at uni. The weird thing is that if I run them with less points the processes do manage to exit. Thanks Matt -- http://mail.python.org/mailman/listinfo/python-list
Re: Processes not exiting
On 31 July, 11:34, MRAB wrote: > ma3mju wrote: > > Hi all, > > > I'm having trouble with multiprocessing I'm using it to speed up some > > simulations, I find for large queues when the process reaches the > > poison pill it does not exit whereas for smaller queues it works > > without any problems. Has anyone else had this trouble? Can anyone > > tell me a way around it? The code is in two files below. > > [snip] > > > #get number of cores and set the number on concurrent processes > > num_hard_workers = 2 > > num_workers = multiprocessing.cpu_count()*1.5 > > easy_workers = [] > > hard_workers = [] > > #add poison pill for each worker and create the worker > > for i in range(0,num_workers-num_hard_workers): > > easy_work_queue.put(None) > > easy_workers.append(multiprocessing.Process > > (target=GP.RandomWalkGeneralizationErrorParallel,args= > > (easy_work_queue,result_queue,))) > > for i in range(0,num_hard_workers): > > hard_work_queue.put(None) > > hard_workers.append(multiprocessing.Process > > (target=GP.RandomWalkGeneralizationErrorParallel,args= > > (hard_work_queue,result_queue,))) > > You have 2 hard workers and ceil(CPU_count * 1.5) - 2 easy workers. > What if the number of CPUs was 1? That would give 2 hard and 0 easy! > > Also, I recommend that you put only 1 'poison pill' in each queue and > have the workers put it back when they see it. I'll give that a go in a sec and see if it helps. The processes quit out for smaller queues though so it should in theory be alright. I'm not too fussed about the CPU's it's only there because I change between a uni PC and home one with a different number of cores in each but both greater than one. -- http://mail.python.org/mailman/listinfo/python-list
Re: Predefined Variables
Piet van Oostrum wrote:
Scott David Daniels (SDD) wrote:
SDD> Stephen Cuppett (should have written in this order):
"Fred Atkinson" wrote ...
Is there a pre-defined variable that returns the GET line...
os.environment('QUERY_STRING')
SDD> Maybe you mean:
SDD> os.environ['USER']
Let's take the best of both:
os.environ['QUERY_STRING']
Sorry about that. I was testing expression before posting, and I don't
do that much cgi stuff. I forgot to restore the variable name.
--Scott David Daniels
[email protected]
--
http://mail.python.org/mailman/listinfo/python-list
Re: Is python buffer overflow proof?
On Sun, 02 Aug 2009 13:50:14 +, Jizzai wrote: > Is a _pure_ python program buffer overflow proof? It's supposed to be. > For example in C++ you can declare a char[9] to hold user input. If the > user inputs 10+ chars a buffer overflow occurs. > > In python, I cannot seem to find a way to define/restrict a string > length. This is probably by design and raises the topic in question. That's a separate issue from being buffer overflow proof. You can't specify that a string have a maximum of N characters except by slicing the string after it's formed: s = "x"*1 # Make a big string. s = s[:100] # Limit it to 100 characters. But Python won't overflow any buffers even if you try to create a truly huge string: s = "x"*(1024**4) # Try to create a 1 TB string. Your PC will run slow while Python and the OS tries to allocate 1TB of memory, then it will safely raise MemoryError. Pure Python should never dump core. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Seeding the rand() Generator
Fred Atkinson wrote: How does one seed the rand() generator when retrieving random recordings in MySQL? It is not entirely clear what you are asking. If you are talking about MySQL's random number generator, you are talking in the wrong newsgroup. If you are talking about Python's, does this work? import random random.seed(123542552) I'm not quite sure how you came to believe that Python controls MySQL, as opposed to using its services. --Scott David Daniels [email protected] -- http://mail.python.org/mailman/listinfo/python-list
Re: Processes not exiting
On 2 Aug, 15:48, ma3mju wrote: > On 31 July, 11:34, MRAB wrote: > > > > > ma3mju wrote: > > > Hi all, > > > > I'm having trouble with multiprocessing I'm using it to speed up some > > > simulations, I find for large queues when the process reaches the > > > poison pill it does not exit whereas for smaller queues it works > > > without any problems. Has anyone else had this trouble? Can anyone > > > tell me a way around it? The code is in two files below. > > > [snip] > > > > #get number of cores and set the number on concurrent processes > > > num_hard_workers = 2 > > > num_workers = multiprocessing.cpu_count()*1.5 > > > easy_workers = [] > > > hard_workers = [] > > > #add poison pill for each worker and create the worker > > > for i in range(0,num_workers-num_hard_workers): > > > easy_work_queue.put(None) > > > easy_workers.append(multiprocessing.Process > > > (target=GP.RandomWalkGeneralizationErrorParallel,args= > > > (easy_work_queue,result_queue,))) > > > for i in range(0,num_hard_workers): > > > hard_work_queue.put(None) > > > hard_workers.append(multiprocessing.Process > > > (target=GP.RandomWalkGeneralizationErrorParallel,args= > > > (hard_work_queue,result_queue,))) > > > You have 2 hard workers and ceil(CPU_count * 1.5) - 2 easy workers. > > What if the number of CPUs was 1? That would give 2 hard and 0 easy! > > > Also, I recommend that you put only 1 'poison pill' in each queue and > > have the workers put it back when they see it. > > I'll give that a go in a sec and see if it helps. The processes quit > out for smaller queues though so it should in theory be alright. I'm > not too fussed about the CPU's it's only there because I change > between a uni PC and home one with a different number of cores in each > but both greater than one. Just tried changing the poison pill part to no avail sadly -- http://mail.python.org/mailman/listinfo/python-list
Re: Generate a new object each time a name is imported
Peter Otten wrote: Steven D'Aprano wrote: I'm looking for a way to hide the generation of objects from the caller, so I could do something like this: from Module import factory() as a # a == "Object #1" from Module import factory() as b # b == "Object #2" except of course that syntax is illegal. How about For newbies who do not get how the following works, but would like to know, I am adding some explanation. class A(object): ... def __init__(self): ... self._n = 0 ... @property ... def a(self): ... try: ... return self._n ... finally: ... self._n += 1 The @property decorator turns the 'a' function into the hidden getter function for what looks to the outside world like a simple instance attribute named 'a'. import sys sys.modules["yadda"] = A() sys.modules is a system namespace that normally associates names with modules. It is used by import statements to find existing modules. However, there is no requirement that the associated object actually be a module. A module is simply a collection of objects accessed as attributes. One can get and set attributes of a module, and but hardly anyhing else. Other attribute collection objects will do as well as far as imports are concerned. 'If it quack like a duck (module in this case)...' The above sets the 'module' to an *instance* of class A. from yadda import a This looks for the 'module' named 'yadda'. It finds one - the instance of A. It then requests attribute 'a' (of that instance). That request is routed to the getter function. This import statement could be in any module, not just the one that set A() as a module surrogate. from yadda import a as b a, b (0, 1) As Peter mentioned in his followup, module surrogates were intended for lazy imports of expensive-to-compute attributes that might never be needed, so their creation could be delayed to whenever needed, if ever. Tricks like the above are not recommended for normal usage, but do illstrate some aspects of the language. Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: How to read webpage
Maybe your python2.5 not working good!?
But, I use python 2.6 , and i use this for your problem:
import urllib
html = urllib.urlopen("http://www.rediff.com/";).read()
print html
If you want use authenticate then...
You make working urllib2 and use this
>>>auth = urllib2.Request(auth_uri, authreq_data)
On Aug 1, 4:52 pm, MRAB wrote:
> tarun wrote:
> > Dear All,
> > I want to read a webpage and copy the contents of it in word file. I
> > tried to write following code:
>
> > import urllib2
> > urllib2.urlopen("http://www.rediff.com/";)
>
> > *Error:-*
>
> > urllib2.urlopen("http://www.icicibank.com/";)
> > File "C:\Python25\lib\urllib2.py", line 121, in urlopen
> > return _opener.open(url, data)
> > File "C:\Python25\lib\urllib2.py", line 374, in open
> > response = self._open(req, data)
> > File "C:\Python25\lib\urllib2.py", line 392, in _open
> > '_open', req)
> > File "C:\Python25\lib\urllib2.py", line 353, in _call_chain
> > result = func(*args)
> > File "C:\Python25\lib\urllib2.py", line 1100, in http_open
> > return self.do_open(httplib.HTTPConnection, req)
> > File "C:\Python25\lib\urllib2.py", line 1075, in do_open
> > raise URLError(err)
> > urllib2.URLError:
>
> I've just tried it. I didn't get an exception, so your problem must be
> elsewhere.
--
http://mail.python.org/mailman/listinfo/python-list
Re: Processes not exiting
ma3mju wrote: On 2 Aug, 15:48, ma3mju wrote: On 31 July, 11:34, MRAB wrote: ma3mju wrote: Hi all, I'm having trouble with multiprocessing I'm using it to speed up some simulations, I find for large queues when the process reaches the poison pill it does not exit whereas for smaller queues it works without any problems. Has anyone else had this trouble? Can anyone tell me a way around it? The code is in two files below. [snip] #get number of cores and set the number on concurrent processes num_hard_workers = 2 num_workers = multiprocessing.cpu_count()*1.5 easy_workers = [] hard_workers = [] #add poison pill for each worker and create the worker for i in range(0,num_workers-num_hard_workers): easy_work_queue.put(None) easy_workers.append(multiprocessing.Process (target=GP.RandomWalkGeneralizationErrorParallel,args= (easy_work_queue,result_queue,))) for i in range(0,num_hard_workers): hard_work_queue.put(None) hard_workers.append(multiprocessing.Process (target=GP.RandomWalkGeneralizationErrorParallel,args= (hard_work_queue,result_queue,))) You have 2 hard workers and ceil(CPU_count * 1.5) - 2 easy workers. What if the number of CPUs was 1? That would give 2 hard and 0 easy! Also, I recommend that you put only 1 'poison pill' in each queue and have the workers put it back when they see it. I'll give that a go in a sec and see if it helps. The processes quit out for smaller queues though so it should in theory be alright. I'm not too fussed about the CPU's it's only there because I change between a uni PC and home one with a different number of cores in each but both greater than one. Just tried changing the poison pill part to no avail sadly I wonder whether one of the workers is raising an exception, perhaps due to lack of memory, when there are large number of jobs to process. Another question: why are you distinguishing between easy and hard jobs? Do you actually get a measurable improvement in performance from doing it this way instead of having just a single queue of jobs and a single pool of workers? -- http://mail.python.org/mailman/listinfo/python-list
Re: Get Cliet IP Address
> Fred Atkinson (FA) wrote:
>FA>What is the function to obtain the client browser's IP
>FA> address?
You mean in a web server?
The following should work (and was posted by me not long ago):
from os import getenv
ip = (getenv("HTTP_CLIENT_IP") or
getenv("HTTP_X_FORWARDED_FOR") or
getenv("HTTP_X_FORWARDED_FOR") or
getenv("REMOTE_ADDR") or
"UNKNOWN")
I use getenv() rather than environ[] to avoid exceptions.
--
Piet van Oostrum
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: [email protected]
--
http://mail.python.org/mailman/listinfo/python-list
Re: cgi script
> golu (g) wrote: >g> Hi, >g> i started learning cgi few days ago in python and everything went >g> fine until i started getting the follwing error >g> " >g> The server encountered an internal error and was unable to complete >g> your request. Either the server is overloaded or there was an error in >g> a CGI script. >g> If you think this is a server error, please contact the webmaster. " >g> i am using apache on xampp. plz help Putting the following in your script might help as it will show the exception trace in your browser (if it gets that far, that is). import cgitb cgitb.enable() -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: [email protected] -- http://mail.python.org/mailman/listinfo/python-list
Building / making an application
What is a good way to do this? There are instructions on making modules at: http://docs.python.org/distutils/setupscript.html however, what do you do if you don't want a module? I'm thinking of where I'd like to split the code into several files and have a build / setup script put it together and install it somewhere such as /usr/local/bin. I'm interested in what the standard way of doing this is. Thanks, Pete -- http://www.petezilla.co.uk -- http://mail.python.org/mailman/listinfo/python-list
Re: socket policy flash help
> NighterNet (N) wrote:
>N> Here the full code.
>N> flashpolicy.xml
>N> [[[
>N>
>N>
>N>
>N>
>N> ]]]
>N> flashpolicytest_server3x.py
>N> [[[
>N> #!/usr/local/bin/python
>N> '''
>N> Still under testing...
>N> python version 3.x.x
>N> '''
>N> import socket
>N> import threading
>N> import sys
>N> import os
>N> file_name = 'flashpolicy.xml'
>N> fh = open(file_name, "r")
>N> policy = fh.read(10001)
You never use that variable.
>N> host = ''; #out side network
>N> port = ;
>N> print ("# - Init... - #");
>N> class ClientThread (threading.Thread):
>N> global policy;
>N> allClients = [];
>N> vlock = threading.Lock();
>N> id = 0 # next available thread number
>N> def __init__(self,clientSocket):
>N> threading.Thread.__init__(self)
>N> self.sockfd = clientSocket; #socket client
>N> self.name = '';
>N> ClientThread.id += 1
>N> self.id = ClientThread.id
>N> self.nickName = '';
>N> self.allClients.append(self.sockfd);
>N> def sendAll(self,buff):
>N> for index,clientSock in enumerate(self.allClients):
>N> try:
>N> clientSock.send(buff);
There is no guarantee that send will indeed transmit all of buff. It is
better to use clientSock.sendall(buff). Or you should check the return
value of send and check if it is equal to the length of buff. And repeat
if not. (But sendall is easier).
Also don't use ; at the end of the statement. It's not pythonic.
>N> except (socket.error):
>N> print ('error socket %s\n',index,"| clean");
>N> clientSock.close()
>N> del self.allClients[index]
>N> def run(self):
>N> while True:
>N> buff = self.sockfd.recv(1028);
There is no guarantee that recv will get the whole message. It may even
get as little as 1 byte. So you should check the return value of recv.
The official way is to keep reading until you have enough input or until
you hit end of file.
>N> if not buff:
>N> print ("connect close...(client side)");
>N> self.sockfd.close();
>N> break #incase it loop infinite
>N> if str(buff) == str("b\'\\x00\'"):
What you check here is whether buff contains the byte sequence that starts with
a
b, then a ' ... and ending with the 5 bytes \ x 0 0 ' which is wrong.
Actually it should be:
if buff == b\'\x00':
or
if buff == b\'\0':
>N> print ('policy FOUND >>> sending...')
>N> print(buff)
>N> b = b'version=\"1.0\"?>N> from domain=\"*\" to-ports=\"*\" />'
>N> print (b)
>N> self.sockfd.send(b);
>N> self.sockfd.sendall(b);
Only self.sockfd.sendall; delete the line with self.sockfd.send(b). And
remove the semicolons for esthetical reasons.
>N> Some odd reason I can't send flash policy from python to flash socket
>N> to agrees with the connection.
--
Piet van Oostrum
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: [email protected]
--
http://mail.python.org/mailman/listinfo/python-list
Re: Building / making an application
On Sun, 2009-08-02 at 20:21 +0100, Peter Chant wrote: > What is a good way to do this? There are instructions on making modules at: > > http://docs.python.org/distutils/setupscript.html > > however, what do you do if you don't want a module? I'm thinking of where > I'd like to split the code into several files and have a build / setup > script put it together and install it somewhere such as /usr/local/bin. > I'm interested in what the standard way of doing this is. > Have you considered creating a deb or rpm package for your application? Most of the documentation for deb or rpm will talk about make files. But even a distutil based python package (with a setup.py) can be made into a deb package. Then the your requirement will be satisfied at least for most gnu/linux based distros. happy hacking. Krishnakant. -- http://mail.python.org/mailman/listinfo/python-list
Re: Building / making an application
Krishnakant wrote: > Have you considered creating a deb or rpm package for your application? > Most of the documentation for deb or rpm will talk about make files. > But even a distutil based python package (with a setup.py) can be made > into a deb package. > Then the your requirement will be satisfied at least for most gnu/linux > based distros. I'm a slacker, so what I would do would be to make a slack build, the slackbuild would take the source and build that. The stage I am at is the "how to build the source" stage. Don't really intend to get as far as distribution specific packages. What I could do is create a script in the source root directory (that sounds a bit overblown) that simply concatenates together all the python files in the right order and perhaps copies the result to /usr/local/bin or /usr/bin as appropriate. Is that the right way to go? It looks like distutils is appropriate only for modules. OTOH it might be appropriate to put the bulk of an application in a module and have a function calling it the only part of the main script. Pete -- http://www.petezilla.co.uk -- http://mail.python.org/mailman/listinfo/python-list
Re: Building / making an application
Peter Chant schrieb: Krishnakant wrote: Have you considered creating a deb or rpm package for your application? Most of the documentation for deb or rpm will talk about make files. But even a distutil based python package (with a setup.py) can be made into a deb package. Then the your requirement will be satisfied at least for most gnu/linux based distros. I'm a slacker, so what I would do would be to make a slack build, the slackbuild would take the source and build that. The stage I am at is the "how to build the source" stage. Don't really intend to get as far as distribution specific packages. What I could do is create a script in the source root directory (that sounds a bit overblown) that simply concatenates together all the python files in the right order and perhaps copies the result to /usr/local/bin or /usr/bin as appropriate. Is that the right way to go? It looks like distutils is appropriate only for modules. OTOH it might be appropriate to put the bulk of an application in a module and have a function calling it the only part of the main script. You should consider using setuptools. Then you get an egg that people can install, and you can define "console_scripts"-entry-points which will be installed into /usr/local/bin or similar locations. Diez -- http://mail.python.org/mailman/listinfo/python-list
Re: Help with Regex for domain names
In article , MRAB wrote: >Nobody wrote: >> On Thu, 30 Jul 2009 10:29:09 -0700, rurpy wrote: >> regex = re.compile(r'[\w\-\.]+\.(?:us|au|de)') >>> You might also want to consider that some country >>> codes such as "co" for Columbia might match more than >>> you want, for example: >>> >>> re.match(r'[\w\-\.]+\.(?:us|au|de|co)', 'foo.boo.com') >>> >>> will match. >> >> ... so put \b at the end, i.e.: >> >> regex = re.compile(r'[\w\-\.]+\.(?:us|au|de)\b') >> >It would still match "www.bbc.co.uk", so you might need: > >regex = re.compile(r'[\w\-\.]+\.(?:us|au|de)\b(?!\.\b)') If it's a string containing just the candidate domain, you can do regex = re.compile(r'[\w\-\.]+\.(?:us|au|de)$') -- Aahz ([email protected]) <*> http://www.pythoncraft.com/ "Many customs in this life persist because they ease friction and promote productivity as a result of universal agreement, and whether they are precisely the optimal choices is much less important." --Henry Spencer -- http://mail.python.org/mailman/listinfo/python-list
Re: Seeding the rand() Generator
On Sun, 02 Aug 2009 08:53:50 -0700, Scott David Daniels wrote: >Fred Atkinson wrote: >> How does one seed the rand() generator when retrieving random >> recordings in MySQL? > >It is not entirely clear what you are asking. If you are talking about >MySQL's random number generator, you are talking in the wrong newsgroup. >If you are talking about Python's, does this work? > import random > random.seed(123542552) >I'm not quite sure how you came to believe that Python controls MySQL, >as opposed to using its services. > >--Scott David Daniels >[email protected] I am coding in Python. I am accessing a MySQL database. I have a string to instruct the MySQL database to use the 'rand()' function to randomly choose one of the records in the database. I know how to seed it in PHP. Does anyone know how to see it from with Python? Regards, Fred -- http://mail.python.org/mailman/listinfo/python-list
Re: Predefined Variables
On Sun, 02 Aug 2009 08:11:22 -0700, Scott David Daniels
wrote:
>Piet van Oostrum wrote:
>>> Scott David Daniels (SDD) wrote:
>>> SDD> Stephen Cuppett (should have written in this order):
> "Fred Atkinson" wrote ...
>> Is there a pre-defined variable that returns the GET line...
> os.environment('QUERY_STRING')
>>> SDD> Maybe you mean:
>>> SDD> os.environ['USER']
>> Let's take the best of both:
>> os.environ['QUERY_STRING']
>
>Sorry about that. I was testing expression before posting, and I don't
>do that much cgi stuff. I forgot to restore the variable name.
>
>--Scott David Daniels
>[email protected]
I finally got it to work with x =getenv('QUERY_STRING')
Regards,
Fred
--
http://mail.python.org/mailman/listinfo/python-list
Re: Processes not exiting
> MRAB (M) wrote: >M> I wonder whether one of the workers is raising an exception, perhaps due >M> to lack of memory, when there are large number of jobs to process. But that wouldn't prevent the join. And you would probably get an exception traceback printed. I wonder if something fishy is happening in the multiprocessing infrastructure. Or maybe the Fortran code goes wrong because it has no protection against buffer overruns and similar problems, I think. -- Piet van Oostrum URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4] Private email: [email protected] -- http://mail.python.org/mailman/listinfo/python-list
Get Cliet IP Address
What is the function to obtain the client browser's IP address? Fred -- http://mail.python.org/mailman/listinfo/python-list
Re: Python docs disappointing
In <[email protected]> Carl Banks writes: Thanks. Your remarks at least confirm that my impression was not simply due to my noob ignorance: the keyboard-accessible docs are indeed as poor as they look. kynn -- http://mail.python.org/mailman/listinfo/python-list
RE Question
Hi;
How do I search and replace something like this:
aLine = re.sub('[<]?[p]?[>]?[<]?[b]?[>]?', '', aLine)
where RE *only* looks for the possibility of "" at the beginning of the
string; that is, not the individual components as I have it coded above, but
the entire 3-character block?
TIA,
Victor
--
http://mail.python.org/mailman/listinfo/python-list
Re: Is python buffer overflow proof?
On 8/2/2009 10:43 AM, Christian Heimes wrote: Marcus Wanner wrote: I believe that python is buffer overflow proof. In fact, I think that even ctypes is overflow proof... No, ctypes isn't buffer overflow proof. ctypes can break and crash a Python interpreter easily. Christian I see. I thought that it said "invalid array index" when you try to read/write outside of an array's bounds, though... Marcus -- http://mail.python.org/mailman/listinfo/python-list
Re: Building / making an application
Diez B. Roggisch wrote: > You should consider using setuptools. Then you get an egg that people > can install, and you can define "console_scripts"-entry-points which > will be installed into /usr/local/bin or similar locations. Interesting, I think I need to have a play with that. The cross platform bit could be useful as well. Pete -- http://www.petezilla.co.uk -- http://mail.python.org/mailman/listinfo/python-list
Re: Python docs disappointing
I am a newbie and about a month old with Python. There is a wealth of material about Python and I am really enjoying learning Python. One thing that could have helped Python documentation is that instead of the very "raw" doc string, it could have used something like PythonDoc (java doc style) so that the functions/classes are documented better. At least I am planning to use PythonDoc for the code that I am going to write. Let me know if there is a better one.. -mohan On Fri, Jul 31, 2009 at 1:10 PM, kj wrote: > > > > I'm pretty new to Python, and I like a lot overall, but I find the > documentation for Python rather poor, overall. > > I'm sure that Python experts don't have this problem: they have > internalized some good ways to access the documentation, are > productive with it, and therefore have lost the ability to see why > the Python documentations is deficient for beginners. This explains > why a suboptimal situation can persist like this: those who are > most able fix it are also the least able to perceive it. > > I've heard similar complaints from other experienced programmers > who are trying out Python for the first time: poor documentation. > > Here is an *entirely typical* example: on some Unix, try > > % pydoc urllib > > The displayed documentation mention the optional parameter "data" > in practically every function listed (a few dozen of them). This > parameter is not documented *anywhere* on that page. All that we > are told is that its default value is always None. > > I'm sure that I can find a full description of this parameter if > I fire up Google, and search online. In fact, more likely than > not, I'll find far more documentation than I want. But my point > is that a programmer should not need to do this. The full > documentation should be readily accessible directly through a few > keystrokes. > > I would love to know how experienced Python programmers quickly > zero in on the Python documentation they need. > > TIA! > > kynn > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://mail.python.org/mailman/listinfo/python-list
Re: Python docs disappointing
> On Fri, Jul 31, 2009 at 1:10 PM, kj wrote: >> I'm pretty new to Python, and I like a lot overall, but I find the >> documentation for Python rather poor, overall. >> >> I'm sure that Python experts don't have this problem: they have >> internalized some good ways to access the documentation, are >> productive with it, and therefore have lost the ability to see why >> the Python documentations is deficient for beginners. This explains >> why a suboptimal situation can persist like this: those who are >> most able fix it are also the least able to perceive it. >> >> I've heard similar complaints from other experienced programmers >> who are trying out Python for the first time: poor documentation. >> >> Here is an *entirely typical* example: on some Unix, try >> >> % pydoc urllib >> >> The displayed documentation mention the optional parameter "data" >> in practically every function listed (a few dozen of them). This >> parameter is not documented *anywhere* on that page. All that we >> are told is that its default value is always None. >> >> I'm sure that I can find a full description of this parameter if >> I fire up Google, and search online. In fact, more likely than >> not, I'll find far more documentation than I want. But my point >> is that a programmer should not need to do this. The full >> documentation should be readily accessible directly through a few >> keystrokes. >> >> I would love to know how experienced Python programmers quickly >> zero in on the Python documentation they need. On Sun, Aug 2, 2009 at 4:22 PM, Mohan Parthasarathy wrote: > I am a newbie and about a month old with Python. There is a wealth of > material about Python and I am really enjoying learning Python. > > One thing that could have helped Python documentation is that instead of the > very "raw" doc string, it could have used something like PythonDoc (java doc > style) so that the functions/classes are documented better. At least I am > planning to use PythonDoc for the code that I am going to write. Let me know > if there is a better one.. If you use reStructuredText (http://docutils.sf.net/rst.html), you can leverage Sphinx (http://sphinx.pocoo.org/), which generates the superb-looking official Python docs. Cheers, Chris P.S. Please don't top-post (http://en.wikipedia.org/wiki/Top-post) in the future. -- http://blog.rebertia.com -- http://mail.python.org/mailman/listinfo/python-list
Re: Seeding the rand() Generator
On Aug 2, 2:18 pm, Fred Atkinson wrote: > On Sun, 02 Aug 2009 08:53:50 -0700, Scott David Daniels > > wrote: > >Fred Atkinson wrote: > >> How does one seed the rand() generator when retrieving random > >> recordings in MySQL? > > >It is not entirely clear what you are asking. If you are talking about > >MySQL's random number generator, you are talking in the wrong newsgroup. > >If you are talking about Python's, does this work? > > import random > > random.seed(123542552) > >I'm not quite sure how you came to believe that Python controls MySQL, > >as opposed to using its services. > > >--Scott David Daniels > >[email protected] > > I am coding in Python. > > I am accessing a MySQL database. > > I have a string to instruct the MySQL database to use the > 'rand()' function to randomly choose one of the records in the > database. > > I know how to seed it in PHP. Does anyone know how to see it > from with Python? It sounds like you are using MySQL's rand() function, which means that whatever SQL command you used to seed it in PHP is the same command you would use to seed it in Python. You'll have to give us more information if you want a better answer than that. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list
Re: Python docs disappointing
Mohan Parthasarathy schrieb: I am a newbie and about a month old with Python. There is a wealth of material about Python and I am really enjoying learning Python. One thing that could have helped Python documentation is that instead of the very "raw" doc string, it could have used something like PythonDoc (java doc style) so that the functions/classes are documented better. At least I am planning to use PythonDoc for the code that I am going to write. Let me know if there is a better one.. Several projects are trying to improve the doc strings with an extended syntax. Personally I prefer the epytext syntax from epydoc [1]. It's a JavaDoc like markup language that extends the raw doc strings with useful information. Christian [1] http://epydoc.sourceforge.net/manual-epytext.html -- http://mail.python.org/mailman/listinfo/python-list
Registation is open for the 9th PyWeek game programming challenge!
The ninth PyWeek challenge will run between: Sunday 30th August to Sunday 6th September (00:00UTC to 00:00UTC) The PyWeek challenge invites entrants to write a game in one week from scratch either as an individual or in a team. Entries must be developed in Python, during the challenge, and must incorporate some theme chosen at the start of the challenge. REGISTRATION IS NOW OPEN -- Visit the challenge website to sign up, join discussions in the message board or read the timetable and rules: http://www.pyweek.org/9/ PLANNING FOR THE CHALLENGE -- Make sure you have working versions of the libraries you're going to use. The rules page has a list of libraries and other resources. Make sure you can build packages to submit as your final submission (if you're going to use py2exe, make sure you know how to use it and that it works). If you don't have access to Linux, Windows or a Mac to test on, contact friends, family or other competitors to find someone who is able to test for you. -- http://mail.python.org/mailman/listinfo/python-list
Re: Skipping a superclass
On Aug 2, 2009, at 5:36 AM, Steven D'Aprano wrote: I have a series of subclasses like this: class A(object): def method(self, *args): print "Lots of work gets done here in the base class" class B(A): def method(self, *args): print "A little bit of work gets done in B" super(B, self).method(*args) class C(B): def method(self, *args): print "A little bit of work gets done in C" super(C, self).method(*args) However, the work done in C.method() makes the work done in B.method() obsolete: I want one to run, or the other, but not both. C does need to inherit from B, for the sake of the other methods, so I want C.method() *only* to skip B while still inheriting from A. (All other methods have to inherit from B as normal.) This might not be applicable to the larger problem you're trying to solve, but for this sample, I would write it as: class A(object): def method(self, *args): self._method(*args) print "Lots of work gets done here in the base class" def _method(self, *args): pass # or perhaps raise NotImplemented class B(A): def _method(self, *args): print "A little bit of work gets done in B" class C(B): def _method(self, *args): print "A little bit of work gets done in C" So what I have done is change the call to super in C to super(B, self) instead of super(C, self). It seems to work, but is this safe to do? Or are there strange side-effects I haven't seen yet? In a diamond-inheritance situation, you may end up skipping methods besides just B.method(). -Miles -- http://mail.python.org/mailman/listinfo/python-list
Re: Generate a new object each time a name is imported
On Aug 3, 4:07 am, Terry Reedy wrote: > Peter Otten wrote: > > Steven D'Aprano wrote: [...] Fantastic question, answer & explanation, guys. Well done. -- http://mail.python.org/mailman/listinfo/python-list
