On Jul 3, 9:43 am, Adrian Smith [EMAIL PROTECTED] wrote:
The following (pinched
from Dive Into Python) seems to work perfectly in Idle, but falls at
the final hurdle when run as a cgi script - can anyone suggest
anything I may have overlooked?
request = urllib2.Request(some_URL)
On Jul 3, 11:14 am, Adrian Smith [EMAIL PROTECTED] wrote:
The following (pinched
from Dive Into Python) seems to work perfectly in Idle, but
falls at the final hurdle when run as a cgi script
Put this at the top of your cgi script:
import cgitb; cgitb.enable()
Did you even try this?
I need to be able to read the stdout and stderr streams of an external
program that I launch from my python script. os.system( 'my_prog' +
' err.log' ) and was planning on monitoring err.log and to display
its contents. Is this the best way to do this?
from subprocess import Popen
stdout,
Bryan wrote:
i would like to save an exception and reraise it at a later time.
something similar to this:
exception = None
def foo():
try:
1/0
except Exception, e:
exception = e
if exception: raise exception
with the above code, i'm able to successfully raise
George Young wrote:
I am puzzled that creating large dicts with an explicit iterable of
key,value pairs seems to be slow. I thought to save time by doing:
palettes = dict((w,set(w)) for w in words)
instead of:
palettes={}
for w in words:
palettes[w]=set(w)
where words
[EMAIL PROTECTED] wrote:
Hey, I have the following code that has to send every command it
receives to a list of backends.
snip
I would like to write each method like:
flush = multimethod()
Here's one way, using a metaclass:
class multimethod(object):
def transform(self, attr):
[EMAIL PROTECTED] wrote:
Is it possible to change the value of a variable in the outer function
if you are in a nested inner function?
The typical kludge is to wrap the variable in the outer function inside
a mutable object, then pass it into the inner using a default argument:
def outer():
Jake Emerson wrote:
However, when
the process goes to insert the unique 'char_freq' into a nested
dictionary the value gets put into ALL of the sub-keys
The way you're currently defining your dict:
rain_raw_dict =
dict.fromkeys(distinctID,{'N':-6999,'char_freq':-6999,...})
Is shorthand for:
Matthew Wilson wrote:
The random.jumpahead documentation says this:
Changed in version 2.3: Instead of jumping to a specific state, n steps
ahead, jumpahead(n) jumps to another state likely to be separated by
many steps..
This change was necessary because the random module got a
Laszlo Nagy wrote:
So how can I tell if 'root.item3' COULD BE FOUND IN THE USUAL PLACES, or
if it is something that was calculated by __getattr__ ?
Of course technically, this is possible and I could give a horrible
method that tells this...
But is there an easy, reliable and thread safe way
Ws wrote:
I'm trying to write up a module that *safely* sets sys.stderr and
sys.stdout, and am currently having troubles with the function
verification. I need to assure that the function can indeed be called
as the Python manual specifies that sys.stdout and sys.stderr should be
defined
[EMAIL PROTECTED] wrote:
i'm looking for a way to have a list of number grouped by consecutive
interval, after a search, for example :
[3, 6, 7, 8, 12, 13, 15]
=
[[3, 4], [6,9], [12, 14], [15, 16]]
(6, not following 3, so 3 = [3:4] ; 7, 8 following 6 so 6, 7, 8 =
[6:9], and so on)
i
David Isaac wrote:
2. Is this a good argmax (as long as I know the iterable is finite)?
def argmax(iterable): return max(izip( iterable, count() ))[1]
Other than the subtle difference that Peter Otten pointed out, that's a
good method.
However if the iterable is a list, it's cleaner (and more
A.M wrote:
Is there any built in feature in Python that can format long integer
123456789 to 12,3456,789 ?
The locale module can help you here:
import locale
locale.setlocale(locale.LC_ALL, '')
'English_United States.1252'
locale.format('%d', 123456789, True)
'123,456,789'
Be
John Machin wrote:
A.M wrote:
Hi,
Is there any built in feature in Python that can format long integer
123456789 to 12,3456,789 ?
Sorry about my previous post. It would produce 123,456,789.
12,3456,789 is weird -- whose idea PHB or yours??
If it's not a typo, it's probably a
[EMAIL PROTECTED] wrote:
Lonnie List comprehensions appear to store their temporary result in a
Lonnie variable named _[1] (or presumably _[2], _[3] etc for
Lonnie nested comprehensions)
Known issue. Fixed in generator comprehensions. Dunno about plans to fix
it in list
[EMAIL PROTECTED] wrote:
I'm creating a program to calculate all primes numbers in a range of 0
to n, where n is whatever the user wants it to be. I've worked out the
algorithm and it works perfectly and is pretty fast, but the one thing
seriously slowing down the program is the following
Erik Johnson wrote:
Thanks for your reply, Nick. My first thought was Ahhh, now I see. That's
slick!, but after playing with this a bit...
class Foo:
... def __getattr__(self, attr):
... def intercepted(*args):
... print %s%s % (attr, args)
... return
Paul Rubin wrote:
I tried to code the Sieve of Erastosthenes with generators:
def sieve_all(n = 100):
# yield all primes up to n
stream = iter(xrange(2, n))
while True:
p = stream.next()
yield p
# filter out all multiples of
Lou Pecora wrote:
I want to subclass a base class that is returned from a Standard Library
function (particularly, subclass file which is returned from open). I
would add some extra functionality and keep the base functions, too.
But I am stuck.
E.g.
class myfile(file):
def
[EMAIL PROTECTED] wrote:
I know how to walk a folder/directory using Python, but I'd like to
check the archive bit for each file. Can anyone make suggestions on
how I might do this? Thanks.
Since the archive bit is Windows-specific, your first place to check is
Mark Hammond's Python for
Ben Cartwright wrote:
[EMAIL PROTECTED] wrote:
I know how to walk a folder/directory using Python, but I'd like to
check the archive bit for each file. Can anyone make suggestions on
how I might do this? Thanks.
Since the archive bit is Windows-specific, your first place to check
John Salerno wrote:
So my question is, how can find all occurrences of a pattern in a
string, including overlapping matches? I figure it has something to do
with look-ahead and look-behind, but I've only gotten this far:
import re
string = 'abababababababab'
pattern = re.compile(r'ab(?=a)')
Murali wrote:
Yes, and no extra for loops are needed! You can define groups inside
the lookahead assertion:
import re
re.findall(r'(?=(aba))', 'abababababababab')
['aba', 'aba', 'aba', 'aba', 'aba', 'aba', 'aba']
Wonderful and this works with any regexp, so
import re
def
John Salerno wrote:
John Salerno wrote:
Ok, I've been staring at this and figuring it out for a while. I'm close
to getting it, but I'm confused by the examples:
(?(id/name)yes-pattern|no-pattern)
Will try to match with yes-pattern if the group with given id or name
exists, and with
[EMAIL PROTECTED] wrote:
Is there a good way to splice two lists together without resorting to a
manual loop? Say I had 2 lists:
l1 = [a,b,c]
l2 = [1,2,3]
And I want a list:
[a,1,b,2,c,3] as the result.
Our good friend itertools can help us out here:
from itertools import chain, izip
[EMAIL PROTECTED] wrote:
Thanks, this worked great.
Welcome. :-)
Can you explain the syntax of the '*' on the
return value of izip? I've only ever seen this syntax with respect to
variable number of args.
When used in a function call (as opposed to a function definition), *
is the unpacking
Philippe Martin wrote:
I have something like this:
Class A:
def A_Func(self, p_param):
.
Class B:
def A_Func(self):
.
Class C (A,B):
A.__init__(self)
B.__init__(self)
.
self.A_Func() #HERE I GET AN EXCEPTION ...
Panos Laganakos wrote:
I'd like to know how its possible to pass a data attribute as a method
parameter.
Something in the form of:
class MyClass:
def __init__(self):
self.a = 10
self.b = '20'
def my_method(self, param1=self.a, param2=self.b):
pass
Sean Givan wrote:
def outer():
val = 10
def inner():
print val
val = 20
inner()
print val
outer()
..I expected to print '10', then '20', but instead got an error:
print val
UnboundLocalError: local variable 'val' referenced
Marcelo Urbano Lima wrote:
class abc:
def __init__(self):
name='marcelo'
print x.name
Traceback (most recent call last):
File 1.py, line 12, in ?
print x.name
AttributeError: abc instance has no attribute 'name'
In Python, you explicitly include a reference to an object when
ej wrote:
I'm not seeing how to get at the 'name' attribute of an HTML form element.
form = cgi.FieldStorage()
gives you a dictionary-like object that has keys for the various named
elements *within* the form...
I could easily replicate the form name in a hidden field, but there ought to
Tim Chase wrote:
In [1]: import re
In [2]: aba_re = re.compile('aba')
In [3]: aba_re.findall('abababa')
Out[3]: ['aba', 'aba']
The return is two matches, whereas, I expected three. Why does this
regular expression work this way?
It's just the way regexes work. You may disagree,
Richard Hsu wrote:
code:-
# Internal -- finish processing of end tag
def finish_endtag(self, tag):
if not tag: # i am confused about this
found = len(self.stack) - 1
if found 0:
self.unknown_endtag(tag) # and this
Terry Reedy wrote:
Alexander Myodov [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]
and even list comprehensions:
b1 = [l for l in a1]
print l: %s % l
This will go away in 3.0. For now, del l if you wish.
Or use a generator expression:
b1 = list(l for l in a1)
l
Michele Simionato wrote:
Roy Smith wrote:
snip
That being said, you can indeed have private data in Python. Just prefix
your variable names with two underscores (i.e. __foo), and they effectively
become private. Yes, you can bypass this if you really want to, but then
again, you can
mrdylan wrote:
class TestMe(object):
def get(self):
pass
def set(self, v):
pass
p = property( get, set )
t = TestMe()
type(t.p) #returns NoneType, what???
t.p.__str__ #returns method-wrapper object at XXX
---
What is the
John Zenger wrote:
Your list probably contains several references to the same object,
instead of several different objects. This happens often when you use a
technique like:
list = [ object ] * 100
This is most likely what's going on. To the OP: please post the
relevant code, including how
Michael Ekstrand wrote:
Is there a natural way
to extend this to other things, so that function creation can be
modified? For example:
create tracer fib(x):
# Return appropriate data here
pass
tracer could create a function that logs its entry and exit; behavior
could be
Todd wrote:
I'm trying to run the following in python.
os.system('/usr/bin/gnuclient -batch -l htmlize -eval (htmlize-file
\test.c\)')
Python is interpreting the \s as s before it's being passed to
os.system. Try doubling the backslashes.
print '/usr/bin/gnuclient -batch -l htmlize -eval
John Salerno wrote:
It
is meant to take a number and generate the next number that follows
according to the Morris sequence. It works for a single number, but what
I'd like it to do is either:
1. repeat indefinitely and have the number of times controlled elsewhere
in the program (e.g., use
John Salerno wrote:
Actually I was just thinking about this and it seems like, at least for
my purpose (to simply return a list of numbers), I don't need a
generator.
Yes, if it's just a list of numbers you need, a generator is more
flexibility than you need. A generator would only come in
Caleb Hattingh wrote:
Your code works on some folders but not others. For example, it works
on my /usr/lib/python2.4 (the example you gave), but on other folders
it terminates early with StopIteration exception on the
os.walk().next() step.
I haven't really looked at this closely enough
[EMAIL PROTECTED] wrote:
I like to define a big dictionary in two
files and use it my main file, build.py
I want the definition to go into build_cfg.py and build_cfg_static.py.
build_cfg_static.py:
target_db = {}
target_db['foo'] = 'bar'
build_cfg.py
target_db['xyz'] = 'abc'
In
nigel wrote:
w =Label(root, text=Congratulations you have made it this far,just a few more
questions then i will be asking you some)
The problem i have is where i have started to write some textCongratulations
you have made it this far,just a few more questions then i will be asking you
Caleb Hattingh wrote:
Unless you have a nice tool handy, calculating many folder sizes for
clearing disk space can be a click-fest nightmare. Looking around, I
found Baobab (gui tool); the du linux/unix command-line tool; the
extremely impressive tkdu: http://unpythonic.net/jeff/tkdu/ ; a
Gregory Piñero wrote:
Hey guys,
I don't understand why this isn't working for me. I'd like to be able
to do this. Is there another short alternative to get this
intersection?
[Dbg] set([{'a':1},{'b':2}]).intersection([{'a':1}])
Traceback (most recent call last):
File interactive
Randall Parker wrote:
My problem is that once I parse the file with minidom and a field from
it to another variable as shown with this line:
IPAddr = self.SocketSettingsObj.IPAddress
I get this error:
[...]
if TargetIPAddrList[0] and TargetIPPortList[0]
0:
Dave Hansen wrote:
On 20 Mar 2006 15:45:36 -0800 in comp.lang.python,
[EMAIL PROTECTED] (Aahz) wrote:
Personally, I think it's a Good Idea to stick with the semi-standard
names of *args and **kwargs to make searching easier...
Agreed (though kwargs kinda makes my skin crawl).
John Salerno wrote:
bruno at modulix wrote:
It seems like this can
get out of hand, since modules are separate from one another and not
compiled together. You'd end up with a lot of import statements.
Sorry, but I don't see the correlation between compilation and import
here ?
I
Jonathan Ballet wrote:
The problem is, xmlrpclib eats those carriage return characters when
loading the XMLRPC request, and replace it by \n. So I got bla\n\nbla.
When I sent back those parameters to others Windows clients (they are
doing some kind of synchronisation throught the XMLRPC
Jonathan Ballet wrote:
The problem is, xmlrpclib eats those carriage return characters when
loading the XMLRPC request, and replace it by \n. So I got bla\n\nbla.
When I sent back those parameters to others Windows clients (they are
doing some kind of synchronisation throught the XMLRPC
lars_woetmann wrote:
I have a list I filter using another list and I would like this to be
as fast as possible
right now I do like this:
[x for x in list1 if x not in list2]
i tried using the method filter:
filter(lambda x: x not in list2, list1)
but it didn't make much difference,
[EMAIL PROTECTED] wrote:
I've done this in Scheme, but I'm not sure I can in Python.
I want the equivalent of this:
if a == yes:
answer = go ahead
else:
answer = stop
in this more compact form:
a = (if a == yes: go ahead: stop)
is there such a form in Python? I tried playing
James Stroud wrote:
Try this (I think its called argument expansion, but I really don't
know what its called, so I can't point you to docs):
def Func1():
choice = ('A', 'B', 'C')
output = random.choice(choice)
output2 = random.choice(choice)
return output, output2
def
Mike Ressler wrote:
timeit.Timer(pow(111,111)).timeit()
10.968398094177246
timeit.Timer(111**111).timeit()
10.04007887840271
timeit.Timer(111.**111.).timeit()
0.36576294898986816
The pow and ** on integers take 10 seconds, but the float ** takes only
0.36 seconds. (The pow with floats
Russ wrote:
Ben Cartwright wrote:
Russ wrote:
Does pow(x,2) simply square x, or does it first compute logarithms
(as would be necessary if the exponent were not an integer)?
The former, using binary exponentiation (quite fast), assuming x is an
int or long.
If x is a float
[EMAIL PROTECTED] wrote:
The first named clearbrd() which takes no variables, and will reset the
board to the 'no-queen' position.
(snip)
The Code:
#!/usr/bin/env python
brd = [9,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
def clearbrd():
brd =
Don Taylor wrote:
Is there a way to discover the original string form of the instance that
is represented by self in a method?
For example, if I have:
fred = C()
fred.meth(27)
then I would like meth to be able to print something like:
about to call meth(fred, 27) or
Sakcee wrote:
now in package.module.checkID function, i wnat to know what is the ID
defiend in the calling scriipt
It's almost always a really bad idea to kludge scopes like this. If
you need to access a variable from the caller's scope in a module
function, make it an argument to that
John wrote:
This works but is a bit slow, I guess I'll have to live with it.
Any chance this could be sped up in python?
Sure, to a point. Instead of:
def countoverlap(s1, s2):
return len([1 for i in xrange(len(s1)) if s1[i:].startswith(s2)])
Try this version, which takes smaller
flamesrock wrote:
whats the best way to pop a random item from a list??
import random
def popchoice(seq):
# raises IndexError if seq is empty
return seq.pop(random.randrange(len(seq)))
--Ben
--
http://mail.python.org/mailman/listinfo/python-list
BartlebyScrivener wrote:
What about a console beep? How do you add that?
rpd
Just use ASCII code 007 (BEL/BEEP):
import sys
sys.stdout.write('\007')
Or if you're on Windows, use the winsound standard module.
--Ben
--
http://mail.python.org/mailman/listinfo/python-list
Rob Cowie wrote:
I wish to derive two lists - each containing either tags to be
included, or tags to be excluded. My idea was to take an element,
examine what element precedes it and accordingly, insert it into the
relevant list. However, I have not been successful.
Is there a better way
Tuvas wrote:
Why is the output list [[0, 1], [0, 1]] and not [[0,
1], [0, 0]]? And how can I make it work right?
http://www.python.org/doc/faq/programming.html#how-do-i-create-a-multidimensional-list
--Ben
--
http://mail.python.org/mailman/listinfo/python-list
orangeDinosaur wrote:
I am encountering a behavior I can think of reason for. Sometimes,
when I use the .strip module for strings, it takes away more than what
I've specified. For example:
a = 'TD WIDTH=175FONT SIZE=2Hughes. John/FONT/TD\r\n'
a.strip('TD WIDTH=175FONT SIZE=2')
Ben Cartwright wrote:
orangeDinosaur wrote:
I am encountering a behavior I can think of reason for. Sometimes,
when I use the .strip module for strings, it takes away more than what
I've specified. For example:
a = 'TD WIDTH=175FONT SIZE=2Hughes. John/FONT/TD\r\n'
a.strip
ianaré wrote:
However, i need the sorting done after the walk, due to the way the
application works... should have specified that, sorry.
If your desired output is just a sorted list of files, there is no good
reason that you shouldn't be able sort in place. Unless your app is
doing something
John Salerno wrote:
You can probably tell what I'm doing. Read a list of lines from a file,
and then I want to slice off the '\n' character from each line. But
after this code runs, the \n is still there. I thought it might have
something to do with the fact that strings are immutable, but a
David Pratt wrote:
# Clean mac .DS_Store
if current_file == '.DS_Store':
print 'a DS_Store item encountered'
os.remove(f)
...
I can't figure why
remove is not removing.
It looks like your indentation is off. From what you posted, the
print line is prepended with 9
David Pratt wrote:
Hi Ben. Sorry about the cut and paste job into my email. It is part of a
larger script. It is actually all tabbed. This will give you a better idea:
for f in file_names:
current_file = os.path.basename(f)
print
David Pratt wrote:
OSError: [Errno 2] No such file or directory: '.DS_Store'
Ah. You didn't mention a traceback earlier, so I assumed the code was
executing but you didn't see the file being removed.
for f in file_names:
current_file = os.path.basename(f)
[EMAIL PROTECTED] wrote:
It seems to me that str.count is awfully slow. Is there some reason
for this?
Evidence:
str.count time test
import string
import time
import array
s = string.printable * int(1e5) # 10**7 character string
a = array.array('c', s)
u = unicode(s)
robin wrote:
i have this function inside a while-loop, which i'd like to loop
forever, but i'm not sure about how to change the parameters of my
function once it is running.
what is the best way to do that? do i have to use threading or is there
some simpler way?
Why not just do this inside
Derek Schuff wrote:
I have some code like this:
for line in f:
toks = line.split()
try:
if int(toks[2],16) == qaddrs[i]+0x1000 and toks[0] ==
200: #producer
write
prod = int(toks[3], 16)
John Salerno wrote:
I contacted my domain host about how Python is implemented on their
server, and got this response:
---
Hello John,
Please be informed that the implementation of python in our server is
through mod_python integration with the apache.
These are the steps
[EMAIL PROTECTED] wrote:
How do I get some
sort of macro behavior so I don't have to write the same thing over and
over again, but which is also not neatly rolled up into a function,
such as combining the return statements with a printing of self-name?
Decorators:
kpp9c wrote:
I've been looking at some of the suggested approaches and looked a
little at Michael's bit which works well bisect is a module i
always struggle with (hee hee)
I am intrigued by Ben's solution and Ben's distilled my problem quite
nicely
Thanks!-) Actually, you should use
[EMAIL PROTECTED] wrote:
But i am stuck on how to do a random chooser that works according to my
idea of choosing according to rating system. It seems to me to be a bit
different that just choosing a weighted choice like so:
...
And i am not sure i want to have to go through what will be
79 matches
Mail list logo