I'd like to have a Python program start listening on port 80, but after that execute without root permissions. Is there a way to drop root or to get port 80 without it?
I retrieved the data encoded in big5 from database,and I want to send the data as email of html content, the code is like this:
html += """<tr><td>"""
html += """unicode(rs[0], 'big5')""" # rs[0] is data encoded in big5
I run the script, but the error raised: UnicodeDecodeError: 'ascii' codec can't decode byte......
However, I tried the code in interactive python command line, there are no errors raised, could you give me the clue?
I am just getting into Python development and would like to know which single IDE or editor is the best.
I mainly use Linux, but don't let that stop you if you think the best one is Win/Mac only.
Can you help me understand of the behaviour and implications of the python __init__ constructor. It seems like when there is an optional parameter and you try and set an existing object to a new object the optional value of the existing object is preserved and copied. Ok that was confusing... so look at an example I concocted below.
In the code below I am trying to make a tree structure with nodes and possibly many children . In the first class NodeBad, the constructor has two parameters, the value and any possible children. The second class NodeGood only takes the value of the node as a parameter. Both have an addchild method to add a child to a node.
When creating a tree with the NodeGood class, it works as expected. However, when doing the same thing with the NodeBad class, it seems as though a child can only be added once!
The code below will result in the following output:
Good Tree
1
2
3
[< 3 >]
Bad Tree
1
2
2
[< 2 >, < 3 >]
Que Pasa?
Here is the Example:
#!/usr/bin/python
class NodeBad:
def __init__(self, value, c=[]):
self.value = value
self.children = c
def addchild(self, node):
self.children.append(node)
def __str__(self):
return '< %s >' % self.value
def __repr__(self):
return '< %s >' % self.value
class NodeGood:
def __init__(self, value):
self.value = value
self.children = []
def addchild(self, node):
self.children.append(node)
def __str__(self):
return '< %s >' % self.value
def __repr__(self):
return '< %s >' % self.value
if __name__ == '__main__':
print 'Good Tree'
ng = NodeGood(1) # Root Node
rootgood = ng
ng.addchild(NodeGood(2)) # 1nd Child
ng = ng.children[0]
ng.addchild(NodeGood(3)) # 2nd Child
print rootgood.value
print rootgood.children[0].value
print rootgood.children[0].children[0].value
print rootgood.children[0].children
print 'Bad Tree'
nb = NodeBad(1) # Root Node
rootbad = nb
nb.addchild(NodeBad(2)) # 1st Child
nb = nb.children[0]
nb.addchild(NodeBad(3)) # 2nd Child
print rootbad.value
print rootbad.children[0].value
print rootbad.children[0].children[0].value
print rootbad.children[0].children
Can python retrieve the name of the user that owns a windows service?
I've had a fiddle with win32serviceutil but to no avail, nor can I find much documentation on it beyond starting and stopping services.
Thanks!
I want to configure my Python logger in such a way so that each instance of logger should log in a file having the same name as the name of the logger itself.
e.g.:
log_hm = logging.getLogger('healthmonitor')
log_hm.info("Testing Log") # Should log to /some/path/healthmonitor.log
log_sc = logging.getLogger('scripts')
log_sc.debug("Testing Scripts") # Should log to /some/path/scripts.log
log_cr = logging.getLogger('cron')
log_cr.info("Testing cron") # Should log to /some/path/cron.log
I want to keep it generic and dont want to hardcode all kind of logger names I can have. Is that possible?
Hi.
I'm implementing a RESTful web service in python and would like to add some QOS logging functionality by intercepting function calls and logging their execution time and so on.
Basically i thought of a class from which all other services can inherit, that automatically overrides the default method implementations and wraps them in a logger function. What's the best way to achieve this?
Let's imagine a situation: I have two Python programs. The first one will write some data (str) to computer memory, and then exit. I will then start the second program which will read the in-memory data saved by the first program.
Is this possible?
Hi all,
Is there a cross-platform way of getting the path to the temp directory in Python 2.6?
For example, under Linux that would be /tmp, while under XP C:\Documents and settings\\[user]\Application settings\Temp.
Thanks!
I am attempting to write some tests using webtest to test out my python GAE application. The problem I am running into is that the application is listening on port 8080 but I cannot configure webtest to hit that port.
For example, I want to use app.get('/getreport') to hit http://localhost:8080/getreport. Obviously, it hits just thits http:// localhost/getreport.
Is there a way to set up webtest to hit a particular port?
I'm just getting started on building a Python app for Google App Engine. In the localhost environment I'm trying to send debug info to the GoogleAppEngineLauncher Log Console via logging.debug(), but it isn't showing up. However, anything sent through, say, logging.info() or logging.error() does show up. I've tried a logging.basicConfig(level=logging.DEBUG) before the logging.debug(), but to no avail.
What am I missing?
I have a SimpleXMLRPCServer server (Python).
How can I get the IP address of the client in the request handler?
This information appears in the log. However, I am not sure how to access this information from within the request handler.
I was told that 95% of all loops in Python are "for" loops. Since "while" loops are clearly more "dangerous" than "for" loops, I would like to know if there are situations in which the use of a "while" loop is essential. For teaching purposes it would be useful to know if there is a systematic way of transforming "while" loops into "for" loops.
Hi,
I need a memory efficient int-int dict in Python that would support the following operations in O(log n) time:
d[k] = v # replace if present
v = d[k] # None or a negative number if not present
I need to hold ~250M pairs, so it really has to be tight.
Do you happen to know a suitable implementation (Python 2.7)?
EDIT Removed impossible requirement and other nonsense. Thanks, Craig and Kylotan!
To rephrase. Here's a trivial int-int dictionary with 1M pairs:
>>> import random, sys
>>> from guppy import hpy
>>> h = hpy()
>>> h.setrelheap()
>>> d = {}
>>> for _ in xrange(1000000):
... d[random.randint(0, sys.maxint)] = random.randint(0, sys.maxint)
...
>>> h.heap()
Partition of a set of 1999530 objects. Total size = 49161112 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 1 0 25165960 51 25165960 51 dict (no owner)
1 1999521 100 23994252 49 49160212 100 int
On average, a pair of integers uses 49 bytes.
Here's an array of 2M integers:
>>> import array, random, sys
>>> from guppy import hpy
>>> h = hpy()
>>> h.setrelheap()
>>> a = array.array('i')
>>> for _ in xrange(2000000):
... a.append(random.randint(0, sys.maxint))
...
>>> h.heap()
Partition of a set of 14 objects. Total size = 8001108 bytes.
Index Count % Size % Cumulative % Kind (class / dict of class)
0 1 7 8000028 100 8000028 100 array.array
On average, a pair of integers uses 8 bytes.
I accept that 8 bytes/pair in a dictionary is rather hard to achieve in general. Rephrased question: is there a memory-efficient implementation of int-int dictionary that uses considerably less than 49 bytes/pair?
In Python I have a list of n lists, each with a variable number of elements. How can I create a single list containing all the possible permutations:
For example
[ [ a, b, c], [d], [e, f] ]
I want
[ [a, d, e] , [a, d, f], [b, d, e], [b, d, f], [c, d, e], [c, d, f] ]
Note I don't know n in advance. I thought itertools.product would be the right approach but it requires me to know the number of arguments in advance
Suppose I have a python object x and a string s, how do I set the attribute s on x? So:
>>> x = SomeObject()
>>> attr = 'myAttr'
>>> # magic goes here
>>> x.myAttr
'magic'
What's the magic? The goal of this, incidentally, is to cache calls to x.__getattr__().
There is function in python called eval that takes string input and evaluates it.
>>> x = 1
>>> print eval('x+1')
2
>>> print eval('12 + 32')
44
>>>
What is Haskell equivalent of eval function?
Is it possible to perform multi-linear regression in Python using NumPy?
The documentation here suggests that it is, but I cannot find any more details on the topic.
I'm looking for a way to prevent multiple hosts from issuing simultaneous commands to a Python XMLRPC listener. The listener is responsible for running scripts to perform tasks on that system that would fail if multiple users tried to issue these commands at the same time. Is there a way I can block all incoming requests until the single instance has completed?
Is there any python module to convert PDF files into text? I tried one piece of code found in Activestate which uses pypdf but the text generated had no space between and was of no use.
Hi folks,
I'm using the timeout parameter within the urllib2's urlopen.
urllib2.urlopen('http://www.example.org', timeout=1)
How do I tell Python that if the timeout expires a custom error should be raised?
Any ideas?
I am using python lxml library to parse html pages:
import lxml.html
# this might run indefinitely
page = lxml.html.parse('http://stackoverflow.com/')
Is there any way to set timeout for parsing?