instruction
stringlengths 12
148
| input
stringlengths 16
30.2k
| output
stringlengths 11
27.3k
|
|---|---|---|
How do you extract a JAR in a UNIX filesystem with a single command and specify its target directory using the JAR command?
|
I am creating a Python script within which I am executing UNIX system commands. I have a
war archive named Binaries.war which is within an ear archive named Portal.ear
The Portal ear file resides in, say /home/foo/bar/
jar xf /home/foo/bar/Portal.ear Binaries.war
Will extract the Binaries.war file out of the /home/foo/bar/Portal.ear archive into the current directory I am running the script from.
How do you specify a target directory to be extracted to using just one command?
I would like to do something like this to extract Binaries.war into the directory /home/foo/bar/baz
jar xf /home/foo/bar/Portal.ear Binaries.war [into target directory /home/foo/bar/baz]
I searched the the JAR man page for options and can't seem to find a simple way to do this. Of course I can extract the archive into my current directory and then move it using mv but I'd like to do this in one shot and not shuffle directories and files around.
|
If your jar file already has an absolute pathname as shown, it is particularly easy:
cd /where/you/want/it; jar xf /path/to/jarfile.jar
That is, you have the shell executed by Python change directory for you and then run the extraction.
If your jar file does not already have an absolute pathname, then you have to convert the relative name to absolute (by prefixing it with the path of the current directory) so that jar can find it after the change of directory.
The only issues left to worry about are things like blanks in the path names.
|
Why do pythonistas call the current reference "self" and not "this"?
|
Python is the language I know the most, and strangely I still don't know why I'm typing "self" and not "this" like in Java or PHP.
I know that Python is older than Java, but I can't figure out where does this come from. Especially since you can use any name instead of "self": the program will work fine.
So where does this convention come from?
|
Smalltalk-80, released by Xerox in 1980, used self. Objective-C (early 1980s) layers Smalltalk features over C, so it uses self too. Modula-3 (1988), Python (late 1980s), and Ruby (mid 1990s) also follow this tradition.
C++, also dating from the early 1980s, chose this instead of self. Since Java was designed to be familiar to C/C++ developers, it uses this too.
Smalltalk uses the metaphor of objects sending messages to each other, so "self" just indicates that the object is sending a message to itself.
|
Is there a map without result in python?
|
Sometimes, I just want to execute a function for a list of entries -- eg.:
for x in wowList:
installWow(x, 'installed by me')
Sometimes I need this stuff for module initialization, so I don't want to have a footprint like x in global namespace. One solution would be to just use map together with lambda:
map(lambda x: installWow(x, 'installed by me'), wowList)
But this of course creates a nice list [None, None, ...] so my question is, if there is a similar function without a return-list -- since I just don't need it.
(off course I can also use _x and thus not leaving visible footprint -- but the map-solution looks so neat ...)
|
You could make your own "each" function:
def each(fn, items):
for item in items:
fn(item)
# called thus
each(lambda x: installWow(x, 'installed by me'), wowList)
Basically it's just map, but without the results being returned. By using a function you'll ensure that the "item" variable doesn't leak into the current scope.
|
retrieve links from web page using python and BeautifulSoup
|
How can I retrieve the links of a webpage and copy the url address of the links using Python?
|
Here's a short snippet using the SoupStrainer class in BeautifulSoup:
import httplib2
from BeautifulSoup import BeautifulSoup, SoupStrainer
http = httplib2.Http()
status, response = http.request('http://www.nytimes.com')
for link in BeautifulSoup(response, parseOnlyThese=SoupStrainer('a')):
if link.has_attr('href'):
print link['href']
The BeautifulSoup documentation is actually quite good, and covers a number of typical scenarios:
http://www.crummy.com/software/BeautifulSoup/documentation.html
Edit: Note that I used the SoupStrainer class because it's a bit more efficient (memory and speed wise), if you know what you're parsing in advance.
|
In Python, how do you change an instantiated object after a reload?
|
Let's say you have an object that was instantiated from a class inside a module.
Now, you reload that module.
The next thing you'd like to do is make that reload affect that class.
mymodule.py
---
class ClassChange():
def run(self):
print 'one'
myexperiment.py
---
import mymodule
from mymodule import ClassChange # why is this necessary?
myObject = ClassChange()
myObject.run()
>>> one
### later, i changed this file, so that it says print 'two'
reload(mymodule)
# trick to change myObject needed here
myObject.run()
>>> two
Do you have to make a new ClassChange object, copy myObject into that, and delete the old myObject? Or is there a simpler way?
Edit: The run() method seems like a static class style method but that was only for the sake of brevity. I'd like the run() method to operate on data inside the object, so a static module function wouldn't do...
|
To update all instances of a class, it is necessary to keep track somewhere about those instances -- typically via weak references (weak value dict is handiest and general) so the "keeping track" functionality won't stop unneeded instances from going away, of course!
You'd normally want to keep such a container in the class object, but, in this case, since you'll be reloading the module, getting the old class object is not trivial; it's simpler to work at module level.
So, let's say that an "upgradable module" needs to define, at its start, a weak value dict (and an auxiliary "next key to use" int) with, say, conventional names:
import weakref
class _List(list): pass # a weakly-referenceable sequence
_objs = weakref.WeakValueDictionary()
_nextkey = 0
def _register(obj):
_objs[_nextkey] = List((obj, type(obj).__name__))
_nextkey += 1
Each class in the module must have, typically in __init__, a call _register(self) to register new instances.
Now the "reload function" can get the roster of all instances of all classes in this module by getting a copy of _objs before it reloads the module.
If all that's needed is to change the code, then life is reasonably easy:
def reload_all(amodule):
objs = getattr(amodule, '_objs', None)
reload(amodule)
if not objs: return # not an upgraable-module, or no objects
newobjs = getattr(amodule, '_objs', None)
for obj, classname in objs.values():
newclass = getattr(amodule, classname)
obj.__class__ = newclass
if newobjs: newobjs._register(obj)
Alas, one typically does want to give the new class a chance to upgrade an object of the old class to itself more finely, e.g. by a suitable class method. That's not too hard either:
def reload_all(amodule):
objs = getattr(amodule, '_objs', None)
reload(amodule)
if not objs: return # not an upgraable-module, or no objects
newobjs = getattr(amodule, '_objs', None)
for obj, classname in objs:
newclass = getattr(amodule, classname)
upgrade = getattr(newclass, '_upgrade', None)
if upgrade:
upgrade(obj)
else:
obj.__class__ = newclass
if newobjs: newobjs._register(obj)
For example, say the new version of class Zap has renamed an attribute from foo to bar. This could be the code of the new Zap:
class Zap(object):
def __init__(self):
_register(self)
self.bar = 23
@classmethod
def _upgrade(cls, obj):
obj.bar = obj.foo
del obj.foo
obj.__class__ = cls
This is NOT all -- there's a LOT more to say on the subject -- but, it IS the gist, and the answer is WAY long enough already (and I, exhausted enough;-).
|
Changes to Python since Dive into Python
|
I've been teaching myself Python by working through Dive Into Python by Mark Pilgrim. I thoroughly recommend it, as do other Stack Overflow users.
However, the last update to Dive Into Python was five years ago. I look forward to reading the new Dive into Python 3 When I make the switch to 3.x, but for now, using django means I'll stick to 2.x.
I'm interested to know what new features of Python I'm missing out on, if I've used Dive Into Python as my primary resource for learning the language. A couple of examples that I've come across are
itertools
ElementTree
Is there anything else I'm missing out on?
edit: As Bastien points out in his answer, I could just read the What's New in Python pages, but sometimes it's fun to discover a useful tip on Stack Overflow rather than struggle through the complete, comprehensive answer in the official documentation.
|
Check out What's New in Python. It has all the versions in the 2.x series. Per Alex's comments, you'll want to look at all Python 2.x for x > 2.
Highlights for day-to-day coding:
Enumeration: Instead of doing:
for i in xrange(len(sequence)):
val = sequence[i]
pass
You can now more succinctly write:
for i, val in enumerate(iterable):
pass
This is important because it works for non-getitemable iterables (you would otherwise have to use an incrementing index counter alongside value iteration).
Logging: a sane alternative to print-based debugging, standardized in a Log4j-style library module.
Booleans: True and False, added for clarity: return True clearer intention than return 1.
Generators: An expressive form of lazy evaluation
evens = (i for i in xrange(limit) if i % 2 == 0)
Extended slices: Builtins support strides in slices.
assert [1, 2, 3, 4][::2] == [1, 3]
Sets: For O(1) lookup semantics, you no longer have to do:
pseudo_set = {'foo': None, 'bar': None}
assert 'foo' in pseudo_set
You can now do:
set_ = set(['foo', 'bar'])
assert 'foo' in set_
Reverse iteration: reversed(sequence) is more readable than sequence[::-1].
Subprocess: Unifies all the ways you might want to invoke a subprocess -- capturing outputs, feeding input, blocking or non-blocking.
Conditional expressions: There's an issue with the idiom:
a and b or c
Namely, when b is falsy. b if a else c resolves that issue.
Context management: Resource acquisition/release simplified via the with statement.
with open(filename) as file:
print file.read()
# File is closed outside the `with` block.
Better string formatting: Too much to describe -- see Python documentation under str.format().
|
How do you subclass the file type in Python?
|
I'm trying to subclass the built-in file class in Python to add some extra features to stdin and stdout. Here's the code I have so far:
class TeeWithTimestamp(file):
"""
Class used to tee the output of a stream (such as stdout or stderr) into
another stream, and to add a timestamp to each message printed.
"""
def __init__(self, file1, file2):
"""Initializes the TeeWithTimestamp"""
self.file1 = file1
self.file2 = file2
self.at_start_of_line = True
def write(self, text):
"""Writes text to both files, prefixed with a timestamp"""
if len(text):
# Add timestamp if at the start of a line; also add [STDERR]
# for stderr
if self.at_start_of_line:
now = datetime.datetime.now()
prefix = now.strftime('[%H:%M:%S] ')
if self.file1 == sys.__stderr__:
prefix += '[STDERR] '
text = prefix + text
self.file1.write(text)
self.file2.write(text)
self.at_start_of_line = (text[-1] == '\n')
The purpose is to add a timestamp to the beginning of each message, and to log everything to a log file. However, the problem I run into is that if I do this:
# log_file has already been opened
sys.stdout = TeeWithTimestamp(sys.stdout, log_file)
Then when I try to do print 'foo', I get a ValueError: I/O operation on closed file. I can't meaningfully call file.__init__() in my __init__(), since I don't want to open a new file, and I can't assign self.closed = False either, since it's a read-only attribute.
How can I modify this so that I can do print 'foo', and so that it supports all of the standard file attributes and methods?
|
Calling file.__init__ is quite feasible (e.g., on '/dev/null') but no real use because your attempted override of write doesn't "take" for the purposes of print statements -- the latter internally calls the real file.write when it sees that sys.stdout is an actual instance of file (and by inheriting you've made it so).
print doesn't really need any other method except write, so making your class inherit from object instead of file will work.
If you need other file methods (i.e., print is not all you're doing), you're best advised to implement them yourself.
|
Running JSON through Python's eval()?
|
Best practices aside, is there a compelling reason not to do this?
I'm writing a post-commit hook for use with a Google Code project, which provides commit data via a JSON object. GC provides an HMAC authentication token along with the request (outside the JSON data), so by validating that token I gain high confidence that the JSON data is both benign (as there's little point in distrusting Google) and valid.
My own (brief) investigations suggest that JSON happens to be completely valid Python, with the exception of the "\/" escape sequence â which GC doesn't appear to generate.
So, as I'm working with Python 2.4 (i.e. no json module), eval() is looking really tempting.
Edit: For the record, I am very much not asking if this is a good idea. I'm quite aware that it isn't, and I very much doubt I'll ever use this technique for any future projects even if I end up using it for this one. I just wanted to make sure that I know what kind of trouble I'll run into if I do. :-)
|
If you're comfortable with your script working fine for a while, and then randomly failing on some obscure edge case, I would go with eval.
If it's important that your code be robust, I would take the time to add simplejson. You don't need the C portion for speedups, so it really shouldn't be hard to dump a few .py files into a directory somewhere.
As an example of something that might bite you, JSON uses Unicode and simplejson returns Unicode, whereas eval returns str:
>>> simplejson.loads('{"a":1, "b":2}')
{u'a': 1, u'b': 2}
>>> eval('{"a":1, "b":2}')
{'a': 1, 'b': 2}
Edit: a better example of where eval() behaves differently:
>>> simplejson.loads('{"X": "\uabcd"}')
{u'X': u'\uabcd'}
>>> eval('{"X": "\uabcd"}')
{'X': '\\uabcd'}
>>> simplejson.loads('{"X": "\uabcd"}') == eval('{"X": "\uabcd"}')
False
Edit 2: saw yet another problem today pointed out by SilentGhost: eval doesn't handle true -> True, false -> False, null -> None correctly.
>>> simplejson.loads('[false, true, null]')
[False, True, None]
>>> eval('[false, true, null]')
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'false' is not defined
>>>
|
How do I store desktop application data in a cross platform way for python?
|
I have a python desktop application that needs to store user data. On Windows, this is usually in %USERPROFILE%\Application Data\AppName\, on OSX it's usually ~/Library/Application Support/AppName/, and on other *nixes it's usually ~/.appname/.
There exists a function in the standard library, os.path.expanduser that will get me a user's home directory, but I know that on Windows, at least, "Application Data" is localized into the user's language. That might be true for OSX as well.
What is the correct way to get this location?
UPDATE:
Some further research indicates that the correct way to get this on OSX is by using the function NSSearchPathDirectory, but that's Cocoa, so it means calling the PyObjC bridge...
|
Well, I hate to have been the one to answer my own question, but no one else seems to know. I'm leaving the answer for posterity.
APPNAME = "MyApp"
import sys
from os import path, environ
if sys.platform == 'darwin':
from AppKit import NSSearchPathForDirectoriesInDomains
# http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Functions/Reference/reference.html#//apple_ref/c/func/NSSearchPathForDirectoriesInDomains
# NSApplicationSupportDirectory = 14
# NSUserDomainMask = 1
# True for expanding the tilde into a fully qualified path
appdata = path.join(NSSearchPathForDirectoriesInDomains(14, 1, True)[0], APPNAME)
elif sys.platform == 'win32':
appdata = path.join(environ['APPDATA'], APPNAME)
else:
appdata = path.expanduser(path.join("~", "." + APPNAME))
|
Python: How can I import all variables?
|
I'm new to Python and programming in general (a couple of weeks at most).
Concerning Python and using modules, I realise that functions can imported using from a import *.
So instead of typing
a.sayHi()
a.sayBye()
I can say
sayHi()
sayBye()
which I find simplifies things a great deal. Now, say I have a bunch of variables that I want to use across modules and I have them all defined in one python module. How can I, using a similar method as mentioned above or an equally simple one, import these variables. I don't want to use import a and then be required to prefix all my variables with a..
The following situation would by ideal:
a.py
name = "Michael"
age = 15
b.py
some_function
if name == "Michael":
if age == 15:
print("Simple!")
Output:
Simple!
|
You gave the solution yourself: from a import * will work just fine. Python does not differentiate between functions and variables in this respect.
>>> from a import *
>>> if name == "Michael" and age == 15:
... print('Simple!')
...
Simple!
|
What's the simplest way to put a python script into the system tray (Windows)
|
What's the simplest way to put a python script into the system tray?
My target platform is Windows. I don't want to see the 'cmd.exe' window.
|
Those are two questions, actually:
Adding a tray icon can be done with Win32 API. Example: SysTrayIcon.py
Hiding the cmd.exe window is as easy as using pythonw.exe instead of python.exe to run your scripts.
|
Interface for modifying Windows environment variables from Python
|
How can I persistently modify the Windows environment variables from a Python script? (it's the setup.py script)
I'm looking for a standard function or module to use for this. I'm already familiar with the registry way of doing it, but any comments regarding that are also welcome.
|
Using setx has few drawbacks, especially if you're trying to append to environment variables (eg. setx PATH %Path%;C:\mypath) This will repeatedly append to the path every time you run it, which can be a problem. Worse, it doesn't distinguish between the machine path (stored in HKEY_LOCAL_MACHINE), and the user path, (stored in HKEY_CURRENT_USER). The environment variable you see at a command prompt is made up of a concatenation of these two values. Hence, before calling setx:
user PATH == u
machine PATH == m
%PATH% == m;u
> setx PATH %PATH%;new
Calling setx sets the USER path by default, hence now:
user PATH == m;u;new
machine PATH == m
%PATH% == m;m;u;new
The system path is unavoidably duplicated in the %PATH% environment variable every time you call setx to append to PATH. These changes are permanent, never reset by reboots, and so accumulate through the life of the machine.
Trying to compensate for this in DOS is beyond my ability. So I turned to Python. The solution I have come up with today, to set environment variables by tweaking the registry, including appending to PATH without introducing duplicates, is as follows:
from os import system, environ
import win32con
from win32gui import SendMessage
from _winreg import (
CloseKey, OpenKey, QueryValueEx, SetValueEx,
HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE,
KEY_ALL_ACCESS, KEY_READ, REG_EXPAND_SZ, REG_SZ
)
def env_keys(user=True):
if user:
root = HKEY_CURRENT_USER
subkey = 'Environment'
else:
root = HKEY_LOCAL_MACHINE
subkey = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
return root, subkey
def get_env(name, user=True):
root, subkey = env_keys(user)
key = OpenKey(root, subkey, 0, KEY_READ)
try:
value, _ = QueryValueEx(key, name)
except WindowsError:
return ''
return value
def set_env(name, value):
key = OpenKey(HKEY_CURRENT_USER, 'Environment', 0, KEY_ALL_ACCESS)
SetValueEx(key, name, 0, REG_EXPAND_SZ, value)
CloseKey(key)
SendMessage(
win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment')
def remove(paths, value):
while value in paths:
paths.remove(value)
def unique(paths):
unique = []
for value in paths:
if value not in unique:
unique.append(value)
return unique
def prepend_env(name, values):
for value in values:
paths = get_env(name).split(';')
remove(paths, '')
paths = unique(paths)
remove(paths, value)
paths.insert(0, value)
set_env(name, ';'.join(paths))
def prepend_env_pathext(values):
prepend_env('PathExt_User', values)
pathext = ';'.join([
get_env('PathExt_User'),
get_env('PathExt', user=False)
])
set_env('PathExt', pathext)
set_env('Home', '%HomeDrive%%HomePath%')
set_env('Docs', '%HomeDrive%%HomePath%\docs')
set_env('Prompt', '$P$_$G$S')
prepend_env('Path', [
r'%SystemDrive%\cygwin\bin', # Add cygwin binaries to path
r'%HomeDrive%%HomePath%\bin', # shortcuts and 'pass-through' bat files
r'%HomeDrive%%HomePath%\docs\bin\mswin', # copies of standalone executables
])
# allow running of these filetypes without having to type the extension
prepend_env_pathext(['.lnk', '.exe.lnk', '.py'])
It does not affect the current process or the parent shell, but it will affect all cmd windows opened after it is run, without needing a reboot, and can safely be edited and re-run many times without introducing any duplicates.
|
Choosing Java vs Python on Google App Engine
|
Currently Google App Engine supports both Python & Java. Java support is less mature. However, Java seems to have a longer list of libraries and especially support for Java bytecode regardless of the languages used to write that code. Which language will give better performance and more power? Please advise. Thank you!
Edit:
http://groups.google.com/group/google-appengine-java/web/will-it-play-in-app-engine?pli=1
Edit:
By "power" I mean better expandability and inclusion of available libraries outside the framework. Python allows only pure Python libraries, though.
|
I'm biased (being a Python expert but pretty rusty in Java) but I think the Python runtime of GAE is currently more advanced and better developed than the Java runtime -- the former has had one extra year to develop and mature, after all.
How things will proceed going forward is of course hard to predict -- demand is probably stronger on the Java side (especially since it's not just about Java, but other languages perched on top of the JVM too, so it's THE way to run e.g. PHP or Ruby code on App Engine); the Python App Engine team however does have the advantage of having on board Guido van Rossum, the inventor of Python and an amazingly strong engineer.
In terms of flexibility, the Java engine, as already mentioned, does offer the possibility of running JVM bytecode made by different languages, not just Java -- if you're in a multi-language shop that's a pretty large positive. Vice versa, if you loathe Javascript but must execute some code in the user's browser, Java's GWT (generating the Javascript for you from your Java-level coding) is far richer and more advanced than Python-side alternatives (in practice, if you choose Python, you'll be writing some JS yourself for this purpose, while if you choose Java GWT is a usable alternative if you loathe writing JS).
In terms of libraries it's pretty much a wash -- the JVM is restricted enough (no threads, no custom class loaders, no JNI, no relational DB) to hamper the simple reuse of existing Java libraries as much, or more, than existing Python libraries are similarly hampered by the similar restrictions on the Python runtime.
In terms of performance, I think it's a wash, though you should benchmark on tasks of your own -- don't rely on the performance of highly optimized JIT-based JVM implementations discounting their large startup times and memory footprints, because the app engine environment is very different (startup costs will be paid often, as instances of your app are started, stopped, moved to different hosts, etc, all trasparently to you -- such events are typically much cheaper with Python runtime environments than with JVMs).
The XPath/XSLT situation (to be euphemistic...) is not exactly perfect on either side, sigh, though I think it may be a tad less bad in the JVM (where, apparently, substantial subsets of Saxon can be made to run, with some care). I think it's worth opening issues on the Appengine Issues page with XPath and XSLT in their titles -- right now there are only issues asking for specific libraries, and that's myopic: I don't really care HOW a good XPath/XSLT is implemented, for Python and/or for Java, as long as I get to use it. (Specific libraries may ease migration of existing code, but that's less important than being able to perform such tasks as "rapidly apply XSLT transformation" in SOME way!-). I know I'd star such an issue if well phrased (especially in a language-independent way).
Last but not least: remember that you can have different version of your app (using the same datastore) some of which are implemented with the Python runtime, some with the Java runtime, and you can access versions that differ from the "default/active" one with explicit URLs. So you could have both Python and Java code (in different versions of your app) use and modify the same data store, granting you even more flexibility (though only one will have the "nice" URL such as foobar.appspot.com -- which is probably important only for access by interactive users on browsers, I imagine;-).
|
Boolean value of objects in Python
|
As we know, Python has boolean values for objects: If a class has a __len__ method, every instance of it for which __len__() happens to return 0 will be evaluated as a boolean False (for example, the empty list).
In fact, every iterable, empty custom object is evaluated as False if it appears in boolean expression.
Now suppose I have a class foo with attribute bar. How can I define its truth value, so that, say, it will be evaluated to True if bar % 2 == 0 and False otherwise?
For example:
myfoo = foo()
myfoo.bar = 3
def a(myfoo):
if foo:
print "spam"
else:
print "eggs"
so, a(myfoo) should print "eggs".
|
In Python < 3.0 :
You have to use __nonzero__ to achieve what you want. It's a method that is called automatically by Python when evaluating an object in a boolean context. It must return a boolean that will be used as the value to evaluate.
E.G :
class Foo(object):
def __init__(self, bar) :
self.bar = bar
def __nonzero__(self) :
return self.bar % 2 == 0
if __name__ == "__main__":
if (Foo(2)) : print "yess !"
In Python => 3.0 :
Same thing, except the method has been renamed to the much more obvious __bool__.
|
Validate SSL certificates with Python
|
I need to write a script that connects to a bunch of sites on our corporate intranet over HTTPS and verifies that their SSL certificates are valid; that they are not expired, that they are issued for the correct address, etc. We use our own internal corporate Certificate Authority for these sites, so we have the public key of the CA to verify the certificates against.
Python by default just accepts and uses SSL certificates when using HTTPS, so even if a certificate is invalid, Python libraries such as urllib2 and Twisted will just happily use the certificate.
Is there a good library somewhere that will let me connect to a site over HTTPS and verify its certificate in this way?
How do I verify a certificate in Python?
|
I have added a distribution to the Python Package Index which makes the match_hostname() function from the Python 3.2 ssl package available on previous versions of Python.
http://pypi.python.org/pypi/backports.ssl_match_hostname/
You can install it with:
pip install backports.ssl_match_hostname
Or you can make it a dependency listed in your project's setup.py. Either way, it can be used like this:
from backports.ssl_match_hostname import match_hostname, CertificateError
...
sslsock = ssl.wrap_socket(sock, ssl_version=ssl.PROTOCOL_SSLv3,
cert_reqs=ssl.CERT_REQUIRED, ca_certs=...)
try:
match_hostname(sslsock.getpeercert(), hostname)
except CertificateError, ce:
...
|
Use of eval in Python?
|
There is an eval() function in Python I stumbled upon while playing around. I cannot think of a case when this function is needed, except maybe as syntactic sugar. Can anyone give an example?
|
eval and exec are handy quick-and-dirty way to get some source code dynamically, maybe munge it a bit, and then execute it -- but they're hardly ever the best way, especially in production code as opposed to "quick-and-dirty" prototypes &c.
For example, if I had to deal with such dynamic Python sources, I'd reach for the ast module -- ast.literal_eval is MUCH safer than eval (you can call it directly on a string form of the expression, if it's a one-off and relies on simple constants only, or do node = ast.parse(source) first, then keep the node around, perhaps munge it with suitable visitors e.g. for variable lookup, then literal_eval the node) -- or, once having put the node in proper shape and vetted it for security issues, I could compile it (yielding a code object) and build a new function object out of that. Far less simple (except that ast.literal_eval is just as simple as eval for the simplest cases!) but safer and preferable in production-quality code.
For many tasks I've seen people (ab-)use exec and eval for, Python's powerful built-ins, such as getattr and setattr, indexing into globals(), &c, provide preferable and in fact often simpler solutions. For specific uses such as parsing JSON, library modules such as json are better (e.g. see SilentGhost's comment on tinnitus' answer to this very question). Etc, etc...
|
ftplib checking if a file is a folder?
|
How can i check if a file on a remote ftp is a folder or not using ftplib?
Best way i have right now is to do a nlst, and iterate through calling size on each of the files, if the file errors out then it is a folder?
Is there a better way? I cannot parse the output of list, since there is about a dozen different ftp servers(many extremely old.)
What should i do?
|
FTP is quite a rudimentary protocol and there's no built-in protocol query allowing you to get the type (file, dir) of each node, so a heuristic like the one you found is the only solution.
If getting the size of each node doesn't work, perhaps you should consider calling FTP.nlst() on each of those nodes: those that error out will be files rather than dirs.
|
Adding attributes into Django Model's Meta class
|
I'm writing a mixin which will allow my Models to be easily translated into a deep dict of values (kind of like .values(), but traversing relationships). The cleanest place to do the definitions of these seems to be in the models themselves, a la:
class Person(models.Model, DeepValues):
name = models.CharField(blank=True, max_length=100)
tribe = models.ForeignKey('Tribes')
class Meta:
schema = {
'name' : str,
'tribe' : {
'name' : str
}
}
Person.objects.all().deep_values() => {
'name' : 'Andrey Fedorov',
'tribe' : {
'name' : 'Mohicans'
}
}
However, Django complains about my including this in class Meta with:
TypeError: 'class Meta' got invalid attribute(s): schema
(entire stack trace here)
Now, I suppose I could elaborately override this in my mixin, but is there a more elegant way of storing this information?
|
I don't know about elegant, but one pragmatic way is:
import django.db.models.options as options
options.DEFAULT_NAMES = options.DEFAULT_NAMES + ('schema',)
Obviously, this would break if Django ever added a 'schema' attribute of its own. But hey, it's a thought...you could always pick an attribute name which is less likely to clash.
|
Financial Charts / Graphs in Ruby or Python
|
What are my best options for creating a financial open-high-low-close (OHLC) chart in a high level language like Ruby or Python? While there seem to be a lot of options for graphing, I haven't seen any gems or eggs with this kind of chart.
http://en.wikipedia.org/wiki/Open-high-low-close_chart (but I don't need the moving average or Bollinger bands)
JFreeChart can do this in Java, but I'd like to make my codebase as small and simple as possible.
Thanks!
|
You can use matplotlib and the the optional bottom parameter of matplotlib.pyplot.bar. You can then use line plot to indicate the opening and closing prices:
For example:
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import lines
import random
deltas = [4, 6, 13, 18, 15, 14, 10, 13, 9, 6, 15, 9, 6, 1, 1, 2, 4, 4, 4, 4, 10, 11, 16, 17, 12, 10, 12, 15, 17, 16, 11, 10, 9, 9, 7, 10, 7, 16, 8, 12, 10, 14, 10, 15, 15, 16, 12, 8, 15, 16]
bases = [46, 49, 45, 45, 44, 49, 51, 52, 56, 58, 53, 57, 62, 63, 68, 66, 65, 66, 63, 63, 62, 61, 61, 57, 61, 64, 63, 58, 56, 56, 56, 60, 59, 54, 57, 54, 54, 50, 53, 51, 48, 43, 42, 38, 37, 39, 44, 49, 47, 43]
def rand_pt(bases, deltas):
return [random.randint(base, base + delta) for base, delta in zip(bases, deltas)]
# randomly assign opening and closing prices
openings = rand_pt(bases, deltas)
closings = rand_pt(bases, deltas)
# First we draw the bars which show the high and low prices
# bottom holds the low price while deltas holds the difference
# between high and low.
width = 0
ax = plt.axes()
rects1 = ax.bar(np.arange(50), deltas, width, color='r', bottom=bases)
# Now draw the ticks indicating the opening and closing price
for opening, closing, bar in zip(openings, closings, rects1):
x, w = bar.get_x(), 0.2
args = {
}
ax.plot((x - w, x), (opening, opening), **args)
ax.plot((x, x + w), (closing, closing), **args)
plt.show()
creates a plot like this:
Obviously, you'd want to package this up in a function that drew the plot using (open, close, min, max) tuples (and you probably wouldn't want to randomly assign your opening and closing prices).
|
Python: Inflate and Deflate implementations
|
I am interfacing with a server that requires that data sent to it is compressed with Deflate algorithm (Huffman encoding + LZ77) and also sends data that I need to Inflate.
I know that Python includes Zlib, and that the C libraries in Zlib support calls to Inflate and Deflate, but these apparently are not provided by the Python Zlib module. It does provide Compress and Decompress, but when I make a call such as the following:
result_data = zlib.decompress( base64_decoded_compressed_string )
I receive the following error:
Error -3 while decompressing data: incorrect header check
Gzip does no better; when making a call such as:
result_data = gzip.GzipFile( fileobj = StringIO.StringIO( base64_decoded_compressed_string ) ).read()
I receive the error:
IOError: Not a gzipped file
which makes sense as the data is a Deflated file not a true Gzipped file.
Now I know that there is a Deflate implementation available (Pyflate), but I do not know of an Inflate implementation.
It seems that there are a few options:
1. Find an existing implementation (ideal) of Inflate and Deflate in Python
2. Write my own Python extension to the zlib c library that includes Inflate and Deflate
3. Call something else that can be executed from the command line (such as a Ruby script, since Inflate/Deflate calls in zlib are fully wrapped in Ruby)
4. ?
I am seeking a solution, but lacking a solution I will be thankful for insights, constructive opinions, and ideas.
Additional information:
The result of deflating (and encoding) a string should, for the purposes I need, give the same result as the following snippet of C# code, where the input parameter is an array of UTF bytes corresponding to the data to compress:
public static string DeflateAndEncodeBase64(byte[] data)
{
if (null == data || data.Length < 1) return null;
string compressedBase64 = "";
//write into a new memory stream wrapped by a deflate stream
using (MemoryStream ms = new MemoryStream())
{
using (DeflateStream deflateStream = new DeflateStream(ms, CompressionMode.Compress, true))
{
//write byte buffer into memorystream
deflateStream.Write(data, 0, data.Length);
deflateStream.Close();
//rewind memory stream and write to base 64 string
byte[] compressedBytes = new byte[ms.Length];
ms.Seek(0, SeekOrigin.Begin);
ms.Read(compressedBytes, 0, (int)ms.Length);
compressedBase64 = Convert.ToBase64String(compressedBytes);
}
}
return compressedBase64;
}
Running this .NET code for the string "deflate and encode me" gives the result "7b0HYBxJliUmL23Ke39K9UrX4HShCIBgEyTYkEAQ7MGIzeaS7B1pRyMpqyqBymVWZV1mFkDM7Z28995777333nvvvfe6O51OJ/ff/z9cZmQBbPbOStrJniGAqsgfP358Hz8iZvl5mbV5mi1nab6cVrM8XeT/Dw=="
When "deflate and encode me" is run through the Python Zlib.compress() and then base64 encoded, the result is "eJxLSU3LSSxJVUjMS1FIzUvOT0lVyE0FAFXHB6k=".
It is clear that zlib.compress() is not an implementation of the same algorithm as the standard Deflate algorithm.
More Information:
The first 2 bytes of the .NET deflate data ("7b0HY..."), after b64 decoding are 0xEDBD, which does not correspond to Gzip data (0x1f8b), BZip2 (0x425A) data, or Zlib (0x789C) data.
The first 2 bytes of the Python compressed data ("eJxLS..."), after b64 decoding are 0x789C. This is a Zlib header.
SOLVED
To handle the raw deflate and inflate, without header and checksum, the following things needed to happen:
On deflate/compress: strip the first two bytes (header) and the last four bytes (checksum).
On inflate/decompress: there is a second argument for window size. If this value is negative it suppresses headers.
here are my methods currently, including the base64 encoding/decoding - and working properly:
import zlib
import base64
def decode_base64_and_inflate( b64string ):
decoded_data = base64.b64decode( b64string )
return zlib.decompress( decoded_data , -15)
def deflate_and_base64_encode( string_val ):
zlibbed_str = zlib.compress( string_val )
compressed_string = zlibbed_str[2:-4]
return base64.b64encode( compressed_string )
|
You can still use the zlib module to inflate/deflate data. The gzip module uses it internally, but adds a file-header to make it into a gzip-file. Looking at the gzip.py file, something like this could work:
import zlib
def deflate(data, compresslevel=9):
compress = zlib.compressobj(
compresslevel, # level: 0-9
zlib.DEFLATED, # method: must be DEFLATED
-zlib.MAX_WBITS, # window size in bits:
# -15..-8: negate, suppress header
# 8..15: normal
# 16..30: subtract 16, gzip header
zlib.DEF_MEM_LEVEL, # mem level: 1..8/9
0 # strategy:
# 0 = Z_DEFAULT_STRATEGY
# 1 = Z_FILTERED
# 2 = Z_HUFFMAN_ONLY
# 3 = Z_RLE
# 4 = Z_FIXED
)
deflated = compress.compress(data)
deflated += compress.flush()
return deflated
def inflate(data):
decompress = zlib.decompressobj(
-zlib.MAX_WBITS # see above
)
inflated = decompress.decompress(data)
inflated += decompress.flush()
return inflated
I don't know if this corresponds exactly to whatever your server requires, but those two functions are able to round-trip any data I tried.
The parameters maps directly to what is passed to the zlib library functions.
Python ⇒ C
zlib.compressobj(...) ⇒ deflateInit(...)
compressobj.compress(...) ⇒ deflate(...)
zlib.decompressobj(...) ⇒ inflateInit(...)
decompressobj.decompress(...) ⇒ inflate(...)
The constructors create the structure and populate it with default values, and pass it along to the init-functions.
The compress/decompress methods update the structure and pass it to inflate/deflate.
|
Is & faster than % when checking for odd numbers?
|
To check for odd and even integer, is the lowest bit checking more efficient than using the modulo?
>>> def isodd(num):
return num & 1 and True or False
>>> isodd(10)
False
>>> isodd(9)
True
|
Yep. The timeit module in the standard library is how you check on those things. E.g:
AmAir:stko aleax$ python -mtimeit -s'def isodd(x): x & 1' 'isodd(9)'
1000000 loops, best of 3: 0.446 usec per loop
AmAir:stko aleax$ python -mtimeit -s'def isodd(x): x & 1' 'isodd(10)'
1000000 loops, best of 3: 0.443 usec per loop
AmAir:stko aleax$ python -mtimeit -s'def isodd(x): x % 2' 'isodd(10)'
1000000 loops, best of 3: 0.453 usec per loop
AmAir:stko aleax$ python -mtimeit -s'def isodd(x): x % 2' 'isodd(9)'
1000000 loops, best of 3: 0.461 usec per loop
As you see, on my (first-day==old==slow;-) Macbook Air, the & solution is repeatably between 7 and 18 nanoseconds faster than the % solution.
timeit not only tells you what's faster, but by how much (just run the tests a few times), which usually shows how supremely UNimportant it is (do you really care about 10 nanoseconds' difference, when the overhead of calling the function is around 400?!-)...
Convincing programmers that micro-optimizations are essentially irrelevant has proven to be an impossible task -- even though it's been 35 years (over which computers have gotten orders of magnitude faster!) since Knuth wrote
We should forget about small
efficiencies, say about 97% of the
time: premature optimization is the
root of all evil.
which as he explained is a quote from an even older statement from Hoare. I guess everybody's totally convinced that THEIR case falls in the remaining 3%!
So instead of endlessly repeating "it doesn't matter", we (Tim Peters in particular deserves the honors there) put in the standard Python library module timeit, that makes it trivially easy to measure such micro-benchmarks and thereby lets at least some programmers convince themselves that, hmmm, this case DOES fall in the 97% group!-)
|
Any drawbacks to storing an integer as a string in a database?
|
I have id values for products that I need store. Right now they are all integers, but I'm not sure if the data provider in the future will introduce letters or symbols into that mix, so I'm debating whether to store it now as integer or string.
Are there performance or other disadvantages to saving the values as strings?
|
Unless you really need the features of an integer (that is, the ability to do arithmetic), then it is probably better for you to store the product IDs as strings. You will never need to do anything like add two product IDs together, or compute the average of a group of product IDs, so there is no need for an actual numeric type.
It is unlikely that storing product IDs as strings will cause a measurable difference in performance. While there will be a slight increase in storage size, the size of a product ID string is likely to be much smaller than the data in the rest of your database row anyway.
Storing product IDs as strings today will save you much pain in the future if the data provider decides to start using alphabetic or symbol characters. There is no real downside.
|
Event system in Python
|
What event system for Python do you use? I'm already aware of pydispatcher, but I was wondering what else can be found, or is commonly used?
I'm not interested in event managers that are part of large frameworks, I'd rather use a small bare-bones solution that I can easily extend.
|
Wrapping up the various event systems that are mentioned in the answers here:
The most basic style of event system is the 'bag of handler methods', which is a simple implementation of the Observer pattern. Basically, the handler methods (callables) are stored in an array and are each called when the event 'fires'.
zope.event shows the bare bones of how this works (see Lennart's answer). Note: this example does not even support handler arguments.
LongPoke's 'callable list' implementation shows that such an event system can be implemented very minimalistically by subclassing list.
spassig's EventHook (Michael Foord's Event Pattern) is a straightforward implementation.
Josip's Valued Lessons Event class is basically the same, but uses a set instead of a list to store the bag, and implements __call__ which are both reasonable additions.
PyNotify is similar in concept and also provides additional concepts of variables and conditions ('variable changed event').
axel is basically a bag-of-handlers with more features related to threading, error handling, ...
The disadvantage of these event systems is that you can only register the handlers on the actual Event object (or handlers list).
So at registration time the event already needs to exist.
That's why the second style of event systems exists: the publish-subscribe pattern.
Here, the handlers don't register on an event object (or handler list), but on a central dispatcher. Also the notifiers only talk to the dispatcher. What to listen for, or what to publish is determined by 'signal', which is nothing more than a name (string).
blinker has some nifty features such as automatic disconnection and filtering based on sender.
PyPubSub at first sight seems to be pretty straightforward; apparently does not yet support Python3
PyDispatcher seems to emphasize flexibility with regards to many-to-many publication etc.
louie is a reworked PyDispatcher "providing plugin infrastructure including Twisted and PyQt specific support".
django.dispatch is a rewritten PyDispatcher "with a more limited interface, but higher performance".
Qt's Signals and Slots are available from PyQt or PySide. They work as callback when used in the same thread, or as events (using an event loop) between two different threads. Signals and Slots have the limitation that they only work in objects of classes that derive from QObject.
Note: threading.Event is not an 'event system' in the above sense. It's a thread synchronization system where one thread waits until another thread 'signals' the Event object.
|
How do I check what version of Python is running my script?
|
How can I check what version of the Python Interpreter is interpreting my script?
|
This information is available in the sys.version string in the sys module:
>>> import sys
Human readable:
>>> print (sys.version) #parentheses necessary in python 3.
2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)]
For further processing:
>>> sys.version_info
(2, 5, 2, 'final', 0)
# or
>>> sys.hexversion
34014192
To ensure a script runs with a minimal version requirement of the Python interpreter add this to your code:
assert sys.version_info >= (2,5)
This compares major and minor version information. Add micro (=0, 1, etc) and even releaselevel (='alpha','final', etc) to the tuple as you like. Note however, that it is almost always better to "duck" check if a certain feature is there, and if not, workaround (or bail out). Sometimes features go away in newer releases, being replaced by others.
|
pyserial - How to read the last line sent from a serial device
|
I have an Arduino connected to my computer running a loop, sending a value over the serial port back to the computer every 100 ms.
I want to make a Python script that will read from the serial port only every few seconds, so I want it to just see the last thing sent from the Arduino.
How do you do this in Pyserial?
Here's the code I tried which does't work. It reads the lines sequentially.
import serial
import time
ser = serial.Serial('com4',9600,timeout=1)
while 1:
time.sleep(10)
print ser.readline() #How do I get the most recent line sent from the device?
|
Perhaps I'm misunderstanding your question, but as it's a serial line, you'll have to read everything sent from the Arduino sequentially - it'll be buffered up in the Arduino until you read it.
If you want to have a status display which shows the latest thing sent - use a thread which incorporates the code in your question (minus the sleep), and keep the last complete line read as the latest line from the Arduino.
Update: mtasic's example code is quite good, but if the Arduino has sent a partial line when inWaiting() is called, you'll get a truncated line. Instead, what you want to do is to put the last complete line into last_received, and keep the partial line in buffer so that it can be appended to the next time round the loop. Something like this:
def receiving(ser):
global last_received
buffer_string = ''
while True:
buffer_string = buffer_string + ser.read(ser.inWaiting())
if '\n' in buffer_string:
lines = buffer_string.split('\n') # Guaranteed to have at least 2 entries
last_received = lines[-2]
#If the Arduino sends lots of empty lines, you'll lose the
#last filled line, so you could make the above statement conditional
#like so: if lines[-2]: last_received = lines[-2]
buffer_string = lines[-1]
Regarding use of readline(): Here's what the Pyserial documentation has to say (slightly edited for clarity and with a mention to readlines()):
Be careful when using "readline". Do
specify a timeout when opening the
serial port, otherwise it could block
forever if no newline character is
received. Also note that "readlines()"
only works with a timeout. It
depends on having a timeout and
interprets that as EOF (end of file).
which seems quite reasonable to me!
|
Convert a string to integer with decimal in Python
|
I have a string in the format: 'nn.nnnnn' in Python, and I'd like to convert it to an integer.
Direct conversion fails:
>>> s = '23.45678'
>>> i = int(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '23.45678'
I can convert it to a decimal by using:
>>> from decimal import *
>>> d = Decimal(s)
>>> print d
23.45678
I could also split on '.', then subtract the decimal from zero, then add that to the whole number ... yuck.
But I'd prefer to have it as an int, without unnecessary type conversions or maneuvering.
|
How about this?
>>> s = '23.45678'
>>> int(float(s))
23
Or...
>>> int(Decimal(s))
23
Or...
>>> int(s.split('.')[0])
23
I doubt it's going to get much simpler than that, I'm afraid. Just accept it and move on.
|
Reusable library to get human readable version of file size?
|
There are various snippets on the web that would give you a function to return human readable size from bytes size:
>>> human_readable(2048)
'2 kilobytes'
>>>
But is there a Python library that provides this?
|
Addressing the above "too small a task to require a library" issue by a straightforward implementation:
def sizeof_fmt(num, suffix='B'):
for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f%s%s" % (num, 'Yi', suffix)
Supports:
all currently known binary prefixes
negative and positive numbers
numbers larger than 1000 Yobibytes
arbitrary units (maybe you like to count in Gibibits!)
Example:
>>> sizeof_fmt(168963795964)
'157.4GiB'
by Fred Cirera
|
Is there a Python language specification?
|
Is there anything in Python akin to Java's JLS or C#'s spec?
|
There's no specification per se. The closest thing is the Python Language Reference, which details the syntax and semantics of the language.
|
Matrix from Python to MATLAB
|
I'm working with Python and MATLAB right now and I have a 2D array in Python that I need to write to a file and then be able to read it into MATLAB as a matrix. Any ideas on how to do this?
Thanks!
|
If you use numpy/scipy, you can use the scipy.io.savemat function:
import numpy, scipy.io
arr = numpy.arange(10)
arr = arr.reshape((3, 3)) # 2d array of 3x3
scipy.io.savemat('c:/tmp/arrdata.mat', mdict={'arr': arr})
Now, you can load this data into MATLAB using File -> Load Data. Select the file and the arr variable (a 3x3 matrix) will be available in your environment.
Note: I did this on scipy 0.7.0. (scipy 0.6 has savemat in the scipy.io.mio module.) See the latest documentation for more detail
EDIT: updated link thanks to @gnovice.
|
Get __name__ of calling function's module in Python
|
Suppose myapp/foo.py contains:
def info(msg):
caller_name = ????
print '[%s] %s' % (caller_name, msg)
And myapp/bar.py contains:
import foo
foo.info('Hello') # => [myapp.foo] Hello
I want caller_name to be set to the __name__ attribute of the calling functions' module (which is 'myapp.foo') in this case. How can this be done?
|
Check out the inspect module:
inspect.stack() will return the stack information.
Inside a function, inspect.stack()[1] will return your caller's stack. From there, you can get more information about the caller's function name, module, etc.
See the docs for details:
http://docs.python.org/library/inspect.html
Also, Doug Hellmann has a nice writeup of the inspect module in his PyMOTW series:
http://pymotw.com/2/inspect/index.html#module-inspect
EDIT: Here's some code which does what you want, I think:
def info(msg):
frm = inspect.stack()[1]
mod = inspect.getmodule(frm[0])
print '[%s] %s' % (mod.__name__, msg)
|
Does get_or_create() have to save right away? (Django)
|
I need to use something like get_or_create() but the problem is that I have a lot of fields and I don't want to set defaults (which don't make sense anyway), and if I don't set defaults it returns an error, because it saves the object right away apparently.
I can set the fields to null=True, but I don't want null fields.
Is there any other method or any extra parameter that can be sent to get_or_create() so that it instantiates an object but doesn't save it until I call save() on it?
Thanks.
|
You can just do:
try:
obj = Model.objects.get(**kwargs)
except Model.DoesNotExist:
obj = Model(**dict((k,v) for (k,v) in kwargs.items() if '__' not in k))
which is pretty much what get_or_create does, sans commit.
|
where does django install in ubuntu
|
I am looking for the init.py file for django. I tried whereis and find, but I get a lot of dirs.
|
you can just print it out.
>>> import django
>>> print django.__file__
/var/lib/python-support/python2.5/django/__init__.pyc
>>>
or:
import inspect
import django
print inspect.getabsfile(django)
|
Override namespace in Python
|
Say there is a folder, '/home/user/temp/a40bd22344'. The name is completely random and changes in every iteration. I need to be able to import this folder in Python using a fixed name, say 'project'. I know I can add this folder to sys.path to enable import lookup, but is there a way to replace 'a40bd22344' with 'project'?
Maybe some clever hacks in init.py?
Added:
It needs to be global - that is, other scripts loading 'project' via the standard:
import project
Have to work properly, loading a40bd22344 instead.
|
Here's one way to do it, without touching sys.path, using the imp module in Python:
import imp
f, filename, desc = imp.find_module('a40bd22344', ['/home/user/temp/'])
project = imp.load_module('a40bd22344', f, filename, desc)
project.some_func()
Here is a link to some good documentation on the imp module:
imp â Access the import internals
|
How to make urllib2 requests through Tor in Python?
|
I'm trying to crawl websites using a crawler written in Python. I want to integrate Tor with Python meaning I want to crawl the site anonymously using Tor.
I tried doing this. It doesn't seem to work. I checked my IP it is still the same as the one before I used tor. I checked it via python.
import urllib2
proxy_handler = urllib2.ProxyHandler({"tcp":"http://127.0.0.1:9050"})
opener = urllib2.build_opener(proxy_handler)
urllib2.install_opener(opener)
|
You are trying to connect to a SOCKS port - Tor rejects any non-SOCKS traffic. You can connect through a middleman - Privoxy - using Port 8118.
Example:
proxy_support = urllib2.ProxyHandler({"http" : "127.0.0.1:8118"})
opener = urllib2.build_opener(proxy_support)
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
print opener.open('http://www.google.com').read()
Also please note properties passed to ProxyHandler, no http prefixing the ip:port
|
How do I sort unicode strings alphabetically in Python?
|
Python sorts by byte value by default, which means é comes after z and other equally funny things. What is the best way to sort alphabetically in Python?
Is there a library for this? I couldn't find anything. Preferrably sorting should have language support so it understands that åäö should be sorted after z in Swedish, but that ü should be sorted by u, etc. Unicode support is thereby pretty much a requirement.
If there is no library for it, what is the best way to do this? Just make a mapping from letter to a integer value and map the string to a integer list with that?
|
IBM's ICU library does that (and a lot more). It has Python bindings: PyICU.
Update: The core difference in sorting between ICU and locale.strcoll is that ICU uses the full Unicode Collation Algorithm while strcoll uses ISO 14651.
The differences between those two algorithms are briefly summarized here: http://unicode.org/faq/collation.html#13. These are rather exotic special cases, which should rarely matter in practice.
>>> import icu # pip install PyICU
>>> sorted(['a','b','c','ä'])
['a', 'b', 'c', 'ä']
>>> collator = icu.Collator.createInstance(icu.Locale('de_DE.UTF-8'))
>>> sorted(['a','b','c','ä'], key=collator.getSortKey)
['a', 'ä', 'b', 'c']
|
Proper way to use **kwargs in Python
|
What is the proper way to use **kwargs in Python when it comes to default values?
kwargs returns a dictionary, but what is the best way to set default values, or is there one? Should I just access it as a dictionary? Use get function?
class ExampleClass:
def __init__(self, **kwargs):
self.val = kwargs['val']
self.val2 = kwargs.get('val2')
A simple question, but one that I can't find good resources on. People do it different ways in code that I've seen and it's hard to know what to use.
|
You can pass a default value to get() for keys that are not in the dictionary:
self.val2 = kwargs.get('val2',"default value")
However, if you plan on using a particular argument with a particular default value, why not use named arguments in the first place?
def __init__(self, val2="default value", **kwargs):
|
Matching Nested Structures With Regular Expressions in Python
|
I seem to remember that Regular Expressions in DotNet have a special mechanism that allows for the correct matching of nested structures, like the grouping in "( (a ( ( c ) b ) ) ( d ) e )".
What is the python equivalent of this feature? Can this be achieved using regular expressions with some workaround? (Though it seems to be the sort of problem that current implementations of regex aren't designed for)
|
Regular expressions cannot parse nested structures. Nested structures are not regular, by definition. They cannot be constructed by a regular grammar, and they cannot be parsed by a finite state automaton (a regular expression can be seen as a shorthand notation for an FSA).
Today's "regex" engines sometimes support some limited "nesting" constructs, but from a technical standpoint, they shouldn't be called "regular" anymore.
|
Why can't Python find shared objects that are in directories in sys.path?
|
I'm trying to import pycurl:
$ python -c "import pycurl"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: libcurl.so.4: cannot open shared object file: No such file or directory
Now, libcurl.so.4 is in /usr/local/lib. As you can see, this is in sys.path:
$ python -c "import sys; print sys.path"
['', '/usr/local/lib/python2.5/site-packages/setuptools-0.6c9-py2.5.egg',
'/usr/local/lib/python25.zip', '/usr/local/lib/python2.5',
'/usr/local/lib/python2.5/plat-linux2', '/usr/local/lib/python2.5/lib-tk',
'/usr/local/lib/python2.5/lib-dynload',
'/usr/local/lib/python2.5/sitepackages', '/usr/local/lib',
'/usr/local/lib/python2.5/site-packages']
Any help will be greatly appreciated.
|
sys.path is only searched for Python modules. For dynamic linked libraries, the paths searched must be in LD_LIBRARY_PATH. Check if your LD_LIBRARY_PATH includes /usr/local/lib, and if it doesn't, add it and try again.
Some more information (source):
In Linux, the environment variable
LD_LIBRARY_PATH is a colon-separated
set of directories where libraries
should be searched for first, before
the standard set of directories; this
is useful when debugging a new library
or using a nonstandard library for
special purposes. The environment
variable LD_PRELOAD lists shared
libraries with functions that override
the standard set, just as
/etc/ld.so.preload does. These are
implemented by the loader
/lib/ld-linux.so. I should note that,
while LD_LIBRARY_PATH works on many
Unix-like systems, it doesn't work on
all; for example, this functionality
is available on HP-UX but as the
environment variable SHLIB_PATH, and
on AIX this functionality is through
the variable LIBPATH (with the same
syntax, a colon-separated list).
Update: to set LD_LIBRARY_PATH, use one of the following, ideally in your ~/.bashrc
or equivalent file:
export LD_LIBRARY_PATH=/usr/local/lib
or
export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH
Use the first form if it's empty (equivalent to the empty string, or not present at all), and the second form if it isn't. Note the use of export.
|
FFT-based 2D convolution and correlation in Python
|
Is there a FFT-based 2D cross-correlation or convolution function built into scipy (or another popular library)?
There are functions like these:
scipy.signal.correlate2d - "the direct method implemented by convolveND will be
slow for large data"
scipy.ndimage.correlate - "The array is correlated with the given kernel using
exact calculation (i.e. not FFT)."
scipy.fftpack.convolve.convolve, which I don't really understand, but seems wrong
numarray had a correlate2d() function with an fft=True switch, but I guess numarray was folded
into numpy, and I can't find if this function was included.
|
I found scipy.signal.fftconvolve, as also pointed out by magnus, but didn't realize at the time that it's n-dimensional. Since it's built-in and produces the right values, it seems like the ideal solution.
From Example of 2D Convolution:
In [1]: a = asarray([[ 1, 2, 3],
...: [ 4, 5, 6],
...: [ 7, 8, 9]])
In [2]: b = asarray([[-1,-2,-1],
...: [ 0, 0, 0],
...: [ 1, 2, 1]])
In [3]: scipy.signal.fftconvolve(a, b, mode = 'same')
Out[3]:
array([[-13., -20., -17.],
[-18., -24., -18.],
[ 13., 20., 17.]])
Correct! The STSCI version, on the other hand, requires some extra work to make the boundaries correct?
In [4]: stsci.convolve2d(a, b, fft = True)
Out[4]:
array([[-12., -12., -12.],
[-24., -24., -24.],
[-12., -12., -12.]])
(The STSCI method also requires compiling, which I was unsuccessful with (I just commented out the non-python parts), has some bugs like this and modifying the inputs ([1, 2] becomes [[1, 2]]), etc. So I changed my accepted answer to the built-in fftconvolve() function.)
Correlation, of course, is the same thing as convolution, but with one input reversed:
In [5]: a
Out[5]:
array([[3, 0, 0],
[2, 0, 0],
[1, 0, 0]])
In [6]: b
Out[6]:
array([[3, 2, 1],
[0, 0, 0],
[0, 0, 0]])
In [7]: scipy.signal.fftconvolve(a, b[::-1, ::-1])
Out[7]:
array([[ 0., -0., 0., 0., 0.],
[ 0., -0., 0., 0., 0.],
[ 3., 6., 9., 0., 0.],
[ 2., 4., 6., 0., 0.],
[ 1., 2., 3., 0., 0.]])
In [8]: scipy.signal.correlate2d(a, b)
Out[8]:
array([[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[3, 6, 9, 0, 0],
[2, 4, 6, 0, 0],
[1, 2, 3, 0, 0]])
and the latest revision has been sped up by using power-of-two sizes internally (and then I sped it up more by using real FFT for real input and using 5-smooth lengths instead of powers of 2 :D ).
|
Library to read ELF file DWARF debug information
|
Any recommendations for a good cross-platform library for reading ELF file debug information in DWARF format? I'd like to read the DWARF debug info in a Python program.
|
There's a new kid on the block - pyelftools - a pure Python library for parsing the ELF and DWARF formats. Give it a try.
It aims to be feature-complete and is currently in active development, so any problems should be handled quickly and enthusiastically :-)
|
How to parse dates with -0400 timezone string in python?
|
I have a date string of the form '2009/05/13 19:19:30 -0400'. It seems that previous versions of python may have supported a %z format tag in strptime for the trailing timezone specification, but 2.6.x seems to have removed that.
What's the right way to parse this string into a datetime object?
|
You can use the parse function from dateutil:
>>> from dateutil.parser import parse
>>> d = parse('2009/05/13 19:19:30 -0400')
>>> d
datetime.datetime(2009, 5, 13, 19, 19, 30, tzinfo=tzoffset(None, -14400))
This way you obtain a datetime object you can then use.
UPDATE: As answered dateutil2.0 is written for python3.0 and does not work with python2.x. For python2.x dateutil1.5 needs to be used.
|
Tkinter: AttributeError: NoneType object has no attribute get
|
I have seen a couple of other posts on similar error message but couldn't find a solution which would fix it in my case.
I dabbled a bit with TkInter and created a very simple UI. The code follows-
from string import *
from Tkinter import *
import tkMessageBox
root=Tk()
vid = IntVar()
def grabText(event):
if entryBox.get().strip()=="":
tkMessageBox.showerror("Error", "Please enter text")
else:
print entryBox.get().strip()
root.title("My Sample")
root.maxsize(width=550, height=200)
root.minsize(width=550, height=200)
root.resizable(width=NO, height=NO)
label=Label(root, text = "Enter text:").grid(row=2,column=0,sticky=W)
entryBox=Entry(root,width=60).grid(row=2, column=1,sticky=W)
grabBtn=Button(root, text="Grab")
grabBtn.grid(row=8, column=1)
grabBtn.bind('<Button-1>', grabText)
root.mainloop()
I get the UI up and running. When I click on the Grab button, I get the following error on the console:
C:\Python25>python.exe myFiles\testBed.py
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python25\lib\lib-tk\Tkinter.py", line 1403, in __call__
return self.func(*args)
File "myFiles\testBed.py", line 10, in grabText
if entryBox.get().strip()=="":
AttributeError: 'NoneType' object has no attribute 'get'
The error traces back to Tkinter.py.
I'm sure some one might have dealt with this before. Any help is appreciated.
|
The grid (and pack, and place) function of the Entry object (and of all other widgets) returns None. In python when you do a().b(), the result of the expression is whatever b() returns, therefore Entry(...).grid(...) will return None.
You should split that onto two lines, like this:
entryBox = Entry(root, width=60)
entryBox.grid(row=2, column=1, sticky=W)
That way, you get your Entry reference stored in entryBox, and it's laid out like you expect. This has a bonus side effect of making your layout easier to understand and maintain, if you collect all of your grid and/or pack statements in blocks.
|
Should I use Celery or Carrot for a Django project?
|
I'm a little confused as to which one I should use. I think either will work, but is one better or more appropriate than the other?
http://github.com/ask/carrot/tree/master
http://github.com/ask/celery/tree/master
|
If you need to send/receive messages to/from AMQP message queues, use carrot.
If you want to run scheduled tasks on a number of machines, use celery.
If you're making soup, use both ;-)
|
Parse annotations from a pdf
|
I want a python function that takes a pdf and returns a list of the text of the note annotations in the document. I have looked at python-poppler (https://code.launchpad.net/~poppler-python/poppler-python/trunk) but I can not figure out how to get it to give me anything useful.
I found the get_annot_mapping method and modified the demo program provided to call it via self.current_page.get_annot_mapping(), but I have no idea what to do with an AnnotMapping object. It seems to not be fully implemented, providing only the copy method.
If there are any other libraries that provide this function, that's fine as well.
|
Just in case somebody is looking for some working code.
Here is a script I use.
import poppler
import sys
import urllib
import os
def main():
input_filename = sys.argv[1]
# http://blog.hartwork.org/?p=612
document = poppler.document_new_from_file('file://%s' % \
urllib.pathname2url(os.path.abspath(input_filename)), None)
n_pages = document.get_n_pages()
all_annots = 0
for i in range(n_pages):
page = document.get_page(i)
annot_mappings = page.get_annot_mapping ()
num_annots = len(annot_mappings)
if num_annots > 0:
for annot_mapping in annot_mappings:
if annot_mapping.annot.get_annot_type().value_name != 'POPPLER_ANNOT_LINK':
all_annots += 1
print 'page: {0:3}, {1:10}, type: {2:10}, content: {3}'.format(i+1, annot_mapping.annot.get_modified(), annot_mapping.annot.get_annot_type().value_nick, annot_mapping.annot.get_contents())
if all_annots > 0:
print str(all_annots) + " annotation(s) found"
else:
print "no annotations found"
if __name__ == "__main__":
main()
|
Do I have any obligations if I upload an egg to the CheeseShop?
|
Suppose I'd like to upload some eggs on the Cheese Shop. Do I have any obligation? Am I required to provide a license? Am I required to provide tests? Will I have any obligations to the users of this egg ( if any ) ?
I haven't really released anything as open source 'till now, and I'd like to know the process.
|
You have an obligation to register the package with a useful description. Nothing is more frustrating than finding a Package that may be good, but you don't know, because there is no description.
Typical example of Lazy developer: http://pypi.python.org/pypi/gevent/0.9.1
Better: http://pypi.python.org/pypi/itty/0.6.0
Fantastic (even a changelog!): http://pypi.python.org/pypi/jarn.mkrelease/2.0b2
On CheeseShop you can also choose to just register the package, but not upload the code. Instead you can provide your own downloading URL. DO NOT DO THAT! That means that your software gets unavailable when cheeseshop is down or when your server is down. That means that if you want to install a system that uses your software, the chances that it will fail because a server is down somewhere doubles. And with a big system, when you have five different servers involved... Always upload the package to the CheeseShop as well as registering it!
You also have the obligation not to remove the egg (except under exceptional circumstances) as people who starts to depend on a specific version of your software will fail if you remove that version.
If you don't want to support the software anymore, upload a new version, with a big fat "THIS IS NO LONGER SUPPORTED SOFTWARE" or something, on top of the description.
And don't upload development versions, like "0.1dev-r73183".
And although you may not have an "obligation" to License your software, you kinda have to, or the uploading gets pointless. If you are unsure, go with GPL.
That's it as far as I'm concerned. Sorry about the ranting. ;-)
|
Find functions explicitly defined in a module (python)
|
Ok I know you can use the dir() method to list everything in a module, but is there any way to see only the functions that are defined in that module? For example, assume my module looks like this:
from datetime import date, datetime
def test():
return "This is a real method"
Even if i use inspect() to filter out the builtins, I'm still left with anything that was imported. E.g I'll see:
['date', 'datetime', 'test']
Is there any way to exclude imports? Or another way to find out what's defined in a module?
|
Are you looking for something like this?
import sys, inspect
def is_mod_function(mod, func):
return inspect.isfunction(func) and inspect.getmodule(func) == mod
def list_functions(mod):
return [func.__name__ for func in mod.__dict__.itervalues()
if is_mod_function(mod, func)]
print 'functions in current module:\n', list_functions(sys.modules[__name__])
print 'functions in inspect module:\n', list_functions(inspect)
EDIT: Changed variable names from 'meth' to 'func' to avoid confusion (we're dealing with functions, not methods, here).
|
Python Lambda Problems
|
What's going on here? I'm trying to create a list of functions:
def f(a,b):
return a*b
funcs = []
for i in range(0,10):
funcs.append(lambda x:f(i,x))
This isn't doing what I expect. I would expect the list to act like this:
funcs[3](3) = 9
funcs[0](5) = 0
But all the functions in the list seem to be identical, and be setting the fixed value to be 9:
funcs[3](3) = 27
funcs[3](1) = 9
funcs[2](6) = 54
Any ideas?
|
lambdas in python are closures.... the arguments you give it aren't going to be evaluated until the lambda is evaluated. At that time, i=9 regardless, because your iteration is finished.
The behavior you're looking for can be achieved with functools.partial
import functools
def f(a,b):
return a*b
funcs = []
for i in range(0,10):
funcs.append(functools.partial(f,i))
|
How to include a python .egg library that is in a subdirectory (relative location)?
|
How do you import python .egg files that are stored in a relative location to the .py code?
For example,
My Application/
My Application/library1.egg
My Application/libs/library2.egg
My Application/test.py
How do you import and use library1 and library2 from within test.py, while leaving the .egg libraries in-place?
|
An .egg is just a .zip file that acts like a directory from which you can import stuff.
You can use the PYTHONPATH variable to add the .egg to your path, or append a directory to
sys.path. Another option is to use a .pth file pointing to the eggs.
For more info see A Small Introduction to Python eggs, Python Eggs and All about eggs.
For example, if your library1.egg contains a package named foo, and you add library1.egg to PYTHONPATH, you can simply import foo
If you can't set PYTHONPATH, you can write:
import sys
sys.path.append("library1.egg")
import foo
|
How do I read a date in Excel format in Python?
|
How can I convert an Excel date (in a number format) to a proper date in Python?
|
You can use xlrd.
From its documentation, you can read that dates are always stored as numbers; however, you can use xldate_as_tuple to convert it to a python date.
Note: the version on the PyPI seems more up-to-date than the one available on xlrd's website.
|
How to store an IP in mySQL
|
We've got a healthy debate going on in the office this week. We're creating a Db to store proxy information, for the most part we have the schema worked out except for how we should store IPs. One camp wants to use 4 smallints, one for each octet and the other wants to use a 1 big int,INET_ATON.
These tables are going to be huge so performance is key. I am in middle here as I normally use MS SQL and 4 small ints in my world. I don't have enough experience with this type of volume storing IPs.
We'll be using perl and python scripts to access the database to further normalize the data into several other tables for top talkers, interesting traffic etc.
I am sure there are some here in the community that have done something simular to what we are doing and I am interested in hearing about their experiences and which route is best, 1 big int, or 4 small ints for IP addresses.
EDIT - One of our concerns is space, this database is going to be huge like in 500,000,000 records a day. So we are trying to weigh the space issue along with the performance issue.
EDIT 2 Some of the conversation has turned over to the volume of data we are going to store...that's not my question. The question is which is the preferable way to store an IP address and why. Like I've said in my comments, we work for a large fortune 50 company. Our log files contain usage data from our users. This data in turn will be used within a security context to drive some metrics and to drive several security tools.
|
I would suggest looking at what type of queries you will be running to decide which format you adopt.
Only if you need to pull out or compare individual octets would you have to consider splitting them up into separate fields.
Otherwise, store it as an 4 byte integer. That also has the bonus of allowing you to use the MySQL built-in INET_ATON() and INET_NTOA() functions.
EDIT: Updated for:
Performance vs. Space
Storage:
If you are only going to support IPv4 address then your datatype in MySQL can be an UNSIGNED INT which only uses 4 bytes of storage.
To store the individual octets you would only need to use UNSIGNED TINYINT datatypes, not SMALLINTS, which would use up 1 byte each of storage.
Both methods would use similar storage with perhaps slightly more for separate fields for some overhead.
More info:
Numeric Type Overview
Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT
Performance:
Using a single field will yield much better performance, its a single comparison instead of 4. You mentioned that you will only run queries against the whole IP address, so there should be no need to keep the octets seperate. Using the `INET_*? functions of MySQL will do the conversion between the text and integer representations once for the comparison.
|
switch versions of python
|
Story:
One of the app that i have works on python 2.4 and other on 2.6. I tried to do a sym link of python2.4 to python and things started to break loose on ubuntu jaunty.
Now i am downloading every dependency of 2.4 and installing it using python2.4 setup.py install. The dependencies seem to be endless.
Question1: How will i tell any framework that go and use version so and so pf python like day django to use 2.6 and say mjango to use 2.4? Something like we say use database databasename kinda syntax.
Question2: Is there more elegant way to switch between version as my hack of symlinking was a virtual disaster?
Question3: Can I download a deb for say hardy and make jaunty believe its for her?
|
Use Virtualenv.
There is more information here: Working with virtualenv.
Using virtualenv you can create a new virtual python environment with whatever version of Python you want for each project or application. You can then activate the appropriate environment when you need it.
To expand on my answer:
You can install multiple versions of Python on your computer (I have 2.4, 2.5, 2.6 and 3.1 on my machine - I install each from source). I use a Mac, and keep my system Python as whatever OS X sets as the default.
I use *easy_install* to install packages. On ubuntu you can get easy_install like this:
sudo apt-get install python-setuptools
To install virtualenv then do:
easy_install virtualenv
I tend to create a new virtualenv for each project I'm working on and don't give it access to the global site-packages. This keeps all the packages tight together and allows me to have the specific versions of everything I need.
virtualenv -p python2.6 --no-site-packages ~/env/NEW_DJANGO_PROJECT
And then whenever I am doing anything related to this project I activate it:
source ~/env/NEW_DJANGO_PROJECT/bin/activate
If I run python now it uses this new python. If I use easy_install it installs things into my new virtual environment.
So, virtualenv should be able to solve all of your problems.
|
Getting list of pixel values from PIL
|
Guys, I'm looking for a bit of assistance. I'm a newbie programmer and one of the problems I'm having at the minute is trying to convert a black & white .jpg image into a list which I can then modulate into an audio signal. This is part of a lager project to create a python SSTV program.
I have imported the PIL module and am trying to call the built-in function: list(im.getdata()). When I call it, python crashes. Is there some way of breaking down the image (always 320x240) into 240 lines to make the computations easier? Or am I just calling the wrong function.
If anyone has any suggestions please fire away. If anyone has experience of generating modulated audio tones using python I would gladly accept any 'pearls of wisdom' they are willing to impart.
Thanks in advance
|
Python shouldn't crash when you call getdata(). The image might be corrupted or there is something wrong with your PIL installation. Try it with another image or post the image you are using.
This should break down the image the way you want:
from PIL import Image
im = Image.open('um_000000.png')
pixels = list(im.getdata())
width, height = im.size
pixels = [pixels[i * width:(i + 1) * width] for i in xrange(height)]
|
Does python have a sorted list?
|
By which I mean a structure with:
O(log n) complexity for x.push() operations
O(log n) complexity to find an element
O(n) complexity to compute list(x) which will be sorted
I also had a related question about performance of list(...).insert(...) which is now here.
|
The standard Python list is not sorted in any form. The standard heapq module can be used to append in O(log n) and remove the smallest one in O(log n), but isn't a sorted list in your definition.
There are various implementations of balanced trees for Python that meet your requirements, e.g. rbtree, RBTree, or pyavl.
|
What is the most efficent way to store a list in the Django models?
|
Currently I have a lot of python objects in my code similar to the following:
class MyClass():
def __init__(self, name, friends):
self.myName = name
self.myFriends = [str(x) for x in friends]
Now I want to turn this into a Django model, where self.myName is a string field, and self.myFriends is a list of strings.
from django.db import models
class myDjangoModelClass():
myName = models.CharField(max_length=64)
myFriends = ??? # what goes here?
Since the list is such a common data structure in python, I sort of expected there to be a Django model field for it. I know I can use a ManyToMany or OneToMany relationship, but I was hoping to avoid that extra indirection in the code.
Edit:
I added this related question, which people may find useful.
|
"Premature optimization is the root of all evil."
With that firmly in mind, let's do this! Once your apps hit a certain point, denormalizing data is very common. Done correctly, it can save numerous expensive database lookups at the cost of a little more housekeeping.
To return a list of friend names we'll need to create a custom Django Field class that will return a list when accessed.
David Cramer posted a guide to creating a SeperatedValueField on his blog. Here is the code:
from django.db import models
class SeparatedValuesField(models.TextField):
__metaclass__ = models.SubfieldBase
def __init__(self, *args, **kwargs):
self.token = kwargs.pop('token', ',')
super(SeparatedValuesField, self).__init__(*args, **kwargs)
def to_python(self, value):
if not value: return
if isinstance(value, list):
return value
return value.split(self.token)
def get_db_prep_value(self, value):
if not value: return
assert(isinstance(value, list) or isinstance(value, tuple))
return self.token.join([unicode(s) for s in value])
def value_to_string(self, obj):
value = self._get_val_from_obj(obj)
return self.get_db_prep_value(value)
The logic of this code deals with serializing and deserializing values from the database to Python and vice versa. Now you can easily import and use our custom field in the model class:
from django.db import models
from custom.fields import SeparatedValuesField
class Person(models.Model):
name = models.CharField(max_length=64)
friends = SeparatedValuesField()
|
Why does Django's signal handling use weak references for callbacks by default?
|
The Django docs say this on the subject:
Note also that Django stores signal
handlers as weak references by
default, so if your handler is a local
function, it may be garbage collected.
To prevent this, pass weak=False when
you call the signalâs connect().
I haven't been able to find any justification for why this is the default, and I don't understand why you would ever want a signal that you explicitly registered to implicitly disappear. So what is the use-case for weak references here? And why is it the default?
I realize it probably doesn't matter either way in 99% of cases, but clearly there's something I don't understand here, and I want to know if there's any "gotchas" lurking that might bite me someday.
|
Signals handlers are stored as weak references to avoid the object they reference from not being garbage collected (for example after explicit deletion of the signal handler), just because a signal is still flying around.
|
Get time zone information of the system in Python?
|
I want to get the default timezone (PST) of my system from Python. What's the best way to do that? I'd like to avoid forking another process.
|
That should work:
import time
time.tzname
it returns a tuple of two strings: the first is the name of the local non-DST timezone, the second is the name of the local DST timezone.
|
How do I capture SIGINT in Python?
|
I'm working on a python script that starts several processes and database connections. Every now and then I want to kill the script with a Ctrl+C signal, and I'd like to do some cleanup.
In Perl I'd do this:
$SIG{'INT'} = 'exit_gracefully';
sub exit_gracefully {
print "Caught ^C \n";
exit (0);
}
How do I do the analogue of this in Python?
|
Register your handler with signal.signal like this:
#!/usr/bin/env python
import signal
import sys
def signal_handler(signal, frame):
print('You pressed Ctrl+C!')
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C')
signal.pause()
Code adapted from here.
More documentation on signal can be found here.
|
Perl equivalent of (Python-) list comprehension
|
I'm looking for ways to express this Python snippet in Perl:
data = {"A": None, "B": "yes", "C": None}
key_list = [k for k in data if data[k]]
# in this case the same as filter(lambda k: data[k], data) but let's ignore that
So looking at it one way, I just want the keys where the values are None or undef. Looking at it another way, what I want is the concise perl equivalent of a list comprehension with conditional.
|
I think you want grep:
#!/usr/bin/env perl
use strict;
use warnings;
my %data = ( A => undef, B => 'yes', C => undef );
my @keys = grep { defined $data{$_} } keys %data;
print "Key: $_\n" for @keys;
I also think that I type too slowly, and that I should reload the page before posting answers. By the way, either a value of 0 or undef can be a good way to handle null values, but make sure you remember which you're using. A false value and and undefined value aren't the same thing in Perl. To clarify: undef returns false in a boolean test, but so does 0. If 0 is a valid value, then you want to explicitly test for definedness, not simply truth. (I mention it because James went for 0 and I went the other way, and you may or may not know if it matters.)
|
Import python package from local directory into interpreter
|
I'm developing/testing a package in my local directory. I want to import it in the interpreter (v2.5), but sys.path does not include the current directory. Right now I type in sys.path.insert(0,'.'). Is there a better way?
Also,
from . import mypackage
fails with this error:
ValueError: Attempted relative import in non-package
|
You can use relative imports only from in a module that was in turn imported as part of a package -- your script or interactive interpreter wasn't, so of course from . import (which means "import from the same package I got imported from") doesn't work. import mypackage will be fine once you ensure the parent directory of mypackage is in sys.path (how you managed to get your current directory away from sys.path I don't know -- do you have something strange in site.py, or...?)
To get your current directory back into sys.path there is in fact no better way than putting it there;-).
|
What does Ruby have that Python doesn't, and vice versa?
|
There is a lot of discussions of Python vs Ruby, and I all find them completely unhelpful, because they all turn around why feature X sucks in language Y, or that claim language Y doesn't have X, although in fact it does. I also know exactly why I prefer Python, but that's also subjective, and wouldn't help anybody choosing, as they might not have the same tastes in development as I do.
It would therefore be interesting to list the differences, objectively. So no "Python's lambdas sucks". Instead explain what Ruby's lambdas can do that Python's can't. No subjectivity. Example code is good!
Don't have several differences in one answer, please. And vote up the ones you know are correct, and down those you know are incorrect (or are subjective). Also, differences in syntax is not interesting. We know Python does with indentation what Ruby does with brackets and ends, and that @ is called self in Python.
UPDATE: This is now a community wiki, so we can add the big differences here.
Ruby has a class reference in the class body
In Ruby you have a reference to the class (self) already in the class body. In Python you don't have a reference to the class until after the class construction is finished.
An example:
class Kaka
puts self
end
self in this case is the class, and this code would print out "Kaka". There is no way to print out the class name or in other ways access the class from the class definition body in Python (outside method definitions).
All classes are mutable in Ruby
This lets you develop extensions to core classes. Here's an example of a rails extension:
class String
def starts_with?(other)
head = self[0, other.length]
head == other
end
end
Python (imagine there were no ''.startswith method):
def starts_with(s, prefix):
return s[:len(prefix)] == prefix
You could use it on any sequence (not just strings). In order to use it you should import it explicitly e.g., from some_module import starts_with.
Ruby has Perl-like scripting features
Ruby has first class regexps, $-variables, the awk/perl line by line input loop and other features that make it more suited to writing small shell scripts that munge text files or act as glue code for other programs.
Ruby has first class continuations
Thanks to the callcc statement. In Python you can create continuations by various techniques, but there is no support built in to the language.
Ruby has blocks
With the "do" statement you can create a multi-line anonymous function in Ruby, which will be passed in as an argument into the method in front of do, and called from there. In Python you would instead do this either by passing a method or with generators.
Ruby:
amethod { |here|
many=lines+of+code
goes(here)
}
Python (Ruby blocks correspond to different constructs in Python):
with amethod() as here: # `amethod() is a context manager
many=lines+of+code
goes(here)
Or
for here in amethod(): # `amethod()` is an iterable
many=lines+of+code
goes(here)
Or
def function(here):
many=lines+of+code
goes(here)
amethod(function) # `function` is a callback
Interestingly, the convenience statement in Ruby for calling a block is called "yield", which in Python will create a generator.
Ruby:
def themethod
yield 5
end
themethod do |foo|
puts foo
end
Python:
def themethod():
yield 5
for foo in themethod():
print foo
Although the principles are different, the result is strikingly similar.
Ruby supports functional style (pipe-like) programming more easily
myList.map(&:description).reject(&:empty?).join("\n")
Python:
descriptions = (f.description() for f in mylist)
"\n".join(filter(len, descriptions))
Python has built-in generators (which are used like Ruby blocks, as noted above)
Python has support for generators in the language. In Ruby 1.8 you can use the generator module which uses continuations to create a generator from a block. Or, you could just use a block/proc/lambda! Moreover, in Ruby 1.9 Fibers are, and can be used as, generators, and the Enumerator class is a built-in generator 4
docs.python.org has this generator example:
def reverse(data):
for index in range(len(data)-1, -1, -1):
yield data[index]
Contrast this with the above block examples.
Python has flexible name space handling
In Ruby, when you import a file with require, all the things defined in that file will end up in your global namespace. This causes namespace pollution. The solution to that is Rubys modules. But if you create a namespace with a module, then you have to use that namespace to access the contained classes.
In Python, the file is a module, and you can import its contained names with from themodule import *, thereby polluting the namespace if you want. But you can also import just selected names with from themodule import aname, another or you can simply import themodule and then access the names with themodule.aname. If you want more levels in your namespace you can have packages, which are directories with modules and an __init__.py file.
Python has docstrings
Docstrings are strings that are attached to modules, functions and methods and can be
introspected at runtime. This helps for creating such things as the help command and
automatic documentation.
def frobnicate(bar):
"""frobnicate takes a bar and frobnicates it
>>> bar = Bar()
>>> bar.is_frobnicated()
False
>>> frobnicate(bar)
>>> bar.is_frobnicated()
True
"""
Ruby's equivalent are similar to javadocs, and located above the method instead of within it. They can be retrieved at runtime from the files by using 1.9's Method#source_location example use
Python has multiple inheritance
Ruby does not ("on purpose" -- see Ruby's website, see here how it's done in Ruby). It does reuse the module concept as a type of abstract classes.
Python has list/dict comprehensions
Python:
res = [x*x for x in range(1, 10)]
Ruby:
res = (0..9).map { |x| x * x }
Python:
>>> (x*x for x in range(10))
<generator object <genexpr> at 0xb7c1ccd4>
>>> list(_)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Ruby:
p = proc { |x| x * x }
(0..9).map(&p)
Python 2.7+:
>>> {x:str(y*y) for x,y in {1:2, 3:4}.items()}
{1: '4', 3: '16'}
Ruby:
>> Hash[{1=>2, 3=>4}.map{|x,y| [x,(y*y).to_s]}]
=> {1=>"4", 3=>"16"}
Python has decorators
Things similar to decorators can also be created in Ruby, and it can also be argued that they aren't as necessary as in Python.
Syntax differences
Ruby requires "end" or "}" to close all of its scopes, while Python uses white-space only. There have been recent attempts in Ruby to allow for whitespace only indentation http://github.com/michaeledgar/seamless
|
Ruby has the concepts of blocks, which are essentially syntactic sugar around a section of code; they are a way to create closures and pass them to another method which may or may not use the block. A block can be invoked later on through a yield statement.
For example, a simple definition of an each method on Array might be something like:
class Array
def each
for i in self
yield(i) # If a block has been passed, control will be passed here.
end
end
end
Then you can invoke this like so:
# Add five to each element.
[1, 2, 3, 4].each{ |e| puts e + 5 }
> [6, 7, 8, 9]
Python has anonymous functions/closures/lambdas, but it doesn't quite have blocks since it's missing some of the useful syntactic sugar. However, there's at least one way to get it in an ad-hoc fashion. See, for example, here.
|
Cost of len() function
|
What is the cost of len() function for Python built-ins? (list/tuple/string/dictionary)
|
It's O(1) (very fast) on every type you've mentioned, plus set and others such as array.array.
|
Should I use Unicode string by default?
|
Is it considered as a good practice to pick Unicode string over regular string when coding in Python? I mainly work on the Windows platform, where most of the string types are Unicode these days (i.e. .NET String, '_UNICODE' turned on by default on a new c++ project, etc ). Therefore, I tend to think that the case where non-Unicode string objects are used is a sort of rare case. Anyway, I'm curious about what Python practitioners do in real-world projects.
|
From my practice -- use unicode.
At beginning of one project we used usuall strings, however our project was growing, we were implementing new features and using new third-party libraries. In that mess with non-unicode/unicode string some functions started failing. We started spending time localizing this problems and fixing them. However, some third-party modules doesn't supported unicode and started failing after we switched to it (but this is rather exclusion than a rule).
Also I have some experience when we needed to rewrite some third party modules(e.g. SendKeys) cause they were not supporting unicode. If it was done in unicode from beginning it will be better :)
So I think today we should use unicode.
P.S. All that mess upwards is only my hamble opinion :)
|
Set Django IntegerField by choices=... name
|
When you have a model field with a choices option you tend to have some magic values associated with human readable names. Is there in Django a convenient way to set these fields by the human readable name instead of the value?
Consider this model:
class Thing(models.Model):
PRIORITIES = (
(0, 'Low'),
(1, 'Normal'),
(2, 'High'),
)
priority = models.IntegerField(default=0, choices=PRIORITIES)
At some point we have a Thing instance and we want to set its priority. Obviously you could do,
thing.priority = 1
But that forces you to memorize the Value-Name mapping of PRIORITIES. This doesn't work:
thing.priority = 'Normal' # Throws ValueError on .save()
Currently I have this silly workaround:
thing.priority = dict((key,value) for (value,key) in Thing.PRIORITIES)['Normal']
but that's clunky. Given how common this scenario could be I was wondering if anyone had a better solution. Is there some field method for setting fields by choice name which I totally overlooked?
|
Do as seen here. Then you can use a word that represents the proper integer.
Like so:
LOW = 0
NORMAL = 1
HIGH = 2
STATUS_CHOICES = (
(LOW, 'Low'),
(NORMAL, 'Normal'),
(HIGH, 'High'),
)
Then they are still integers in the DB.
Usage would be thing.priority = Thing.NORMAL
|
How Do I Use Raw Socket in Python?
|
I am writing an application to test a network driver for handling corrupted data. And I thought of sending this data using raw socket, so it will not be corrected by the sending machine's TCP-IP stack.
I am writing this application solely on Linux. I have code examples of using raw sockets in system-calls, but I would really like to keep my test as dynamic as possible, and write most if not all of it in Python.
I have googled the web a bit for explanations and examples of the usage of raw sockets in python, but haven't found anything really enlightening. Just a a very old code example that demonstrates the idea, but in no means work.
From what I gathered, Raw Socket usage in Python is nearly identical in semantics to UNIX's raw socket, but without the structs that define the packets structure.
I was wondering if it would even be better not to write the raw socket part of the test in Python, but in C with system-calls, and call it from the main Python code?
|
You do it like this:
First you disable your network card's automatic checksumming:
sudo ethtool -K eth1 tx off
And then send your dodgy frame from python:
#!/usr/bin/env python
from socket import socket, AF_PACKET, SOCK_RAW
s = socket(AF_PACKET, SOCK_RAW)
s.bind(("eth1", 0))
# We're putting together an ethernet frame here,
# but you could have anything you want instead
# Have a look at the 'struct' module for more
# flexible packing/unpacking of binary data
# and 'binascii' for 32 bit CRC
src_addr = "\x01\x02\x03\x04\x05\x06"
dst_addr = "\x01\x02\x03\x04\x05\x06"
payload = ("["*30)+"PAYLOAD"+("]"*30)
checksum = "\x1a\x2b\x3c\x4d"
ethertype = "\x08\x01"
s.send(dst_addr+src_addr+ethertype+payload+checksum)
Done.
|
Most "pythonic" way of organising class attributes, constructor arguments and subclass constructor defaults?
|
Being relatively new to Python 2, I'm uncertain how best to organise my class files in the most 'pythonic' way. I wouldn't be asking this but for the fact that Python seems to have quite a few ways of doing things that are very different to what I have come to expect from the languages I am used to.
Initially, I was just treating classes how I'd usually treat them in C# or PHP, which of course made me trip up all over the place when I eventually discovered the mutable values gotcha:
class Pants(object):
pockets = 2
pocketcontents = []
class CargoPants(Pants):
pockets = 200
p1 = Pants()
p1.pocketcontents.append("Magical ten dollar bill")
p2 = CargoPants()
print p2.pocketcontents
Yikes! Didn't expect that!
I've spent a lot of time searching the web and through some source for other projects for hints on how best to arrange my classes, and one of the things I noticed was that people seem to declare a lot of their instance variables - mutable or otherwise - in the constructor, and also pile the default constructor arguments on quite thickly.
After developing like this for a while, I'm still left scratching my head a bit about the unfamiliarity of it. Considering the lengths to which the python language goes to to make things seem more intuitive and obvious, it seems outright odd to me in the few cases where I've got quite a lot of attributes or a lot of default constructor arguments, especially when I'm subclassing:
class ClassWithLotsOfAttributes(object):
def __init__(self, jeebus, coolness='lots', python='isgoodfun',
pythonic='nebulous', duck='goose', pants=None,
magictenbucks=4, datawad=None, dataload=None,
datacatastrophe=None):
if pants is None: pants = []
if datawad is None: datawad = []
if dataload is None: dataload = []
if datacatastrophe is None: datacatastrophe = []
self.coolness = coolness
self.python = python
self.pythonic = pythonic
self.duck = duck
self.pants = pants
self.magictenbucks = magictenbucks
self.datawad = datawad
self.dataload = dataload
self.datacatastrophe = datacatastrophe
self.bigness = None
self.awesomeitude = None
self.genius = None
self.fatness = None
self.topwise = None
self.brillant = False
self.strangenessfactor = 3
self.noisiness = 12
self.whatever = None
self.yougettheidea = True
class Dog(ClassWithLotsOfAttributes):
def __init__(self, coolness='lots', python='isgoodfun', pythonic='nebulous', duck='goose', pants=None, magictenbucks=4, datawad=None, dataload=None, datacatastrophe=None):
super(ClassWithLotsOfAttributes, self).__init__(coolness, python, pythonic, duck, pants, magictenbucks, datawad, dataload, datacatastrophe)
self.noisiness = 1000000
def quack(self):
print "woof"
Mild silliness aside (I can't really help myself when cooking up these artificial example classes), assuming I have a real-world need for a set of classes with this many attributes, I suppose my questions are:
What is the most, uhh, 'pythonic' way of declaring a class with that many attributes? Is it best to put them against the class if the default is immutable, ala Pants.pockets, or is it better to put them in the constructor, ala ClassWithLotsOfAttributes.noisiness?
Is there a way to eliminate the need to redeclare the defaults for all of the subclass constructor arguments, as in Dog.__init__? Should I even be including this many arguments with defaults anyway?
|
If attributes will vary from instance
to instance make them instance
attribute i.e. create them
inside__init__ using self else if they need to
be shared between class instances
like a constant, put them at class
level.
If your class really need to pass, so
many arguments in __init__, let
derive class use argument list and
keyword arguments e.g.
class Dog(ClassWithLotsOfAttributes):
def __init__(self, *args , **kwargs):
super(ClassWithLotsOfAttributes, self).__init__(*args , **kwargs)
self.coolness = "really cool!!!
No need of passing all variables except few important ones, in
__init__, class can assume some
defaults and user can change them
later on if needed.
Use 4 spaces instead of tab.
if you need to add an extra arg bite, to Dog and keyword arg old too
class CoolDog(ClassWithLotsOfAttributes):
def __init__(self, bite, *args , **kwargs):
self.old = kwargs.pop('old', False) # this way we can access base class args too
super(ClassWithLotsOfAttributes, self).__init__(*args , **kwargs)
self.bite = bite
self.coolness = "really really cool!!!
various ways you useCoolDog
CoolDog(True)
CoolDog(True, old=False)
CoolDog(bite=True, old=True)
CoolDog(old=True, bite=False)
|
How to debug in Django, the good way?
|
So, I started learning to code in Python and later Django. The first times it was hard looking at tracebacks and actually figure out what I did wrong and where the syntax error was. Some time has passed now and some way along the way, I guess I got a routine in debugging my Django code. As this was done early in my coding experience, I sat down and wondered if how I was doing this was ineffective and could be done faster. I usually manage to find and correct the bugs in my code, but I wonder if I should be doing it faster?
I usually just use the debug info Django gives when enabled. When things do end up as I thought it would, I break the code flow a lot with a syntax error, and look at the variables at that point in the flow to figure out, where the code does something other than what I wanted.
But can this be improved? Are there some good tools or better ways to debug your Django code?
|
There are a bunch of ways to do it, but the most straightforward is to simply
use the Python debugger. Just add following line in to a Django view function:
import pdb; pdb.set_trace()
If you try to load that page in your browser, the browser will hang and you get a prompt to carry on debugging on actual executing code.
However there are other options suggested by others (I won't recommend them):
* return HttpResponse({variable to inspect})
* print {variable to inspect}
* raise Exception({variable to inspect})
But the Python Debugger (pdb) is highly recommended for all types of Python code. If you are already into pdb, you'd also want to have a look at IPDB that uses ipython for debugging. Happy Coding.
A useful reference provided by Seafangs : Using the Python debugger in Django
|
Java Python Integration
|
I have a Java app that needs to integrate with a 3rd party library. The library is written in Python, and I don't have any say over that. I'm trying to figure out the best way to integrate with it. I'm trying out JEPP (Java Embedded Python) - has anyone used that before? My other thought is to use JNI to communicate with the C bindings for Python.
Any thoughts on the best way to do this would be appreciated. Thanks.
|
Why not use Jython? The only downside I can immediately think of is if your library uses CPython native extensions.
EDIT: If you can use Jython now but think you may have problems with a later version of the library, I suggest you try to isolate the library from your app (e.g. some sort of adapter interface). Go with the simplest thing that works for the moment, then consider JNI/CPython/etc if and when you ever need to. There's little to be gained by going the (painful) JNI route unless you really have to.
|
Base 62 conversion
|
How would you convert an integer to base 62 (like hexadecimal, but with these digits: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ').
I have been trying to find a good Python library for it, but they all seems to be occupied with converting strings. The Python base64 module only accepts strings and turns a single digit into four characters. I was looking for something akin to what URL shorteners use.
|
There is no standard module for this, but I have written my own functions to achieve that.
BASE62 = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
def encode(num, alphabet=BASE62):
"""Encode a positive number in Base X
Arguments:
- `num`: The number to encode
- `alphabet`: The alphabet to use for encoding
"""
if num == 0:
return alphabet[0]
arr = []
base = len(alphabet)
while num:
num, rem = divmod(num, base)
arr.append(alphabet[rem])
arr.reverse()
return ''.join(arr)
def decode(string, alphabet=BASE62):
"""Decode a Base X encoded string into the number
Arguments:
- `string`: The encoded string
- `alphabet`: The alphabet to use for encoding
"""
base = len(alphabet)
strlen = len(string)
num = 0
idx = 0
for char in string:
power = (strlen - (idx + 1))
num += alphabet.index(char) * (base ** power)
idx += 1
return num
Notice the fact that you can give it any alphabet to use for encoding and decoding. If you leave the alphabet argument out, you are going to get the 62 character alphabet defined on the first line of code, and hence encoding/decoding to/from 62 base.
Hope this helps.
PS - For URL shorteners, I have found that it's better to leave out a few confusing characters like 0Ol1oI etc. Thus I use this alphabet for my URL shortening needs - "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"
Have fun.
|
Disabling Python nosetests
|
When using nosetests for Python it is possible to disable a unit test by setting the test function's __test__ attribute to false. I have implemented this using the following decorator:
def unit_test_disabled():
def wrapper(func):
func.__test__ = False
return func
return wrapper
@unit_test_disabled
def test_my_sample_test()
#code here ...
However, this has the side effect of calling wrapper as the unit test. Wrapper will always pass but it is included in nosetests output. Is there another way of structuring the decorator so that the test will not run and does not appear in nosetests output.
|
Nose already has a builtin decorator for this:
from nose.tools import nottest
@nottest
def test_my_sample_test()
#code here ...
Also check out the other goodies that nose provides: https://nose.readthedocs.org/en/latest/testing_tools.html
|
Does Jython have the GIL?
|
I was sure that it hasn't, but looking for a definite answer on the Interwebs left me in doubt. For example, I got a 2008 post which sort of looked like a joke at first glance but seemed to be serious at looking closer.
Edit:
... and turned out to be a joke after looking even closer. Sorry for the confusion. Actually the comments on that post answer my question, as Nikhil has pointed out correctly.
We realized that CPython is far ahead of us in this area, and that we are lacking in compatibility. After serious brainstorming (and a few glasses of wine), we decided that introducing a Global Interpreter Lock in Jython would solve the entire issue!
Now, what's the status here? The "differences" page on sourceforge doesn't mention the GIL at all. Is there any official source I have overlooked?
Note also that I'm aware of the ongoing discussion whether the GIL matters at all, but I don't care about that for the moment.
|
The quote you found was indeed a joke, here is a demo of Jython's implementation of the GIL:
Jython 2.5.0 (trunk:6550M, Jul 20 2009, 08:40:15)
[Java HotSpot(TM) Client VM (Apple Inc.)] on java1.5.0_19
Type "help", "copyright", "credits" or "license" for more information.
>>> from __future__ import GIL
File "<stdin>", line 1
SyntaxError: Never going to happen!
>>>
|
Using Python to execute a command on every file in a folder
|
I'm trying to create a Python script that would :
Look into the folder "/input"
For each video in that folder, run a mencoder command (to transcode them to something playable on my phone)
Once mencoder has finished his run, delete the original video.
That doesn't seem too hard, but I suck at python :)
Any ideas on what the script should look like ?
Bonus question : Should I use
os.system
or
subprocess.call
?
Subprocess.call seems to allow for a more readable script, since I can write the command like this :
cmdLine = ['mencoder',
sourceVideo,
'-ovc',
'copy',
'-oac',
'copy',
'-ss',
'00:02:54',
'-endpos',
'00:00:54',
'-o',
destinationVideo]
EDIT : Ok, that works :
import os, subprocess
bitrate = '100'
mencoder = 'C:\\Program Files\\_utilitaires\\MPlayer-1.0rc2\\mencoder.exe'
inputdir = 'C:\\Documents and Settings\\Administrator\\Desktop\\input'
outputdir = 'C:\\Documents and Settings\\Administrator\\Desktop\\output'
for fichier in os.listdir(inputdir):
print 'fichier :' + fichier
sourceVideo = inputdir + '\\' + fichier
destinationVideo = outputdir + '\\' + fichier[:-4] + ".mp4"
commande = [mencoder,
'-of',
'lavf',
[...]
'-mc',
'0',
sourceVideo,
'-o',
destinationVideo]
subprocess.call(commande)
os.remove(sourceVideo)
raw_input('Press Enter to exit')
I've removed the mencoder command, for clarity and because I'm still working on it.
Thanks to everyone for your input.
|
To find all the filenames use os.listdir().
Then you loop over the filenames. Like so:
import os
for filename in os.listdir('dirname'):
callthecommandhere(blablahbla, filename, foo)
If you prefer subprocess, use subprocess. :-)
|
Which is better in python, del or delattr?
|
This may be silly, but its been nagging the back of my brain for a while.
Python gives us two built-in ways to delete attributes from objects, the del command word and the delattr built-in function. I prefer delattr because it I think its a bit more explicit:
del foo.bar
delattr(foo, "bar")
But I'm wondering if there might be under-the-hood differences between them.
|
The first is more efficient than the second. del foo.bar compiles to two bytecode instructions:
2 0 LOAD_FAST 0 (foo)
3 DELETE_ATTR 0 (bar)
whereas delattr(foo, "bar") takes five:
2 0 LOAD_GLOBAL 0 (delattr)
3 LOAD_FAST 0 (foo)
6 LOAD_CONST 1 ('bar')
9 CALL_FUNCTION 2
12 POP_TOP
This translates into the first running slightly faster (but it's not a huge difference â .15 μs on my machine).
Like the others have said, you should really only use the second form when the attribute that you're deleting is determined dynamically.
[Edited to show the bytecode instructions generated inside a function, where the compiler can use LOAD_FAST and LOAD_GLOBAL]
|
Does Python have anonymous classes?
|
I'm wondering if Python has anything like the C# anonymous classes feature. To clarify, here's a sample C# snippet:
var foo = new { x = 1, y = 2 };
var bar = new { y = 2, x = 1 };
foo.Equals(bar); // "true"
In Python, I would imagine something like this:
foo = record(x = 1, y = 2)
bar = record(y = 2, x = 1)
foo == bar # true
The specific requirement is being able to create an object with specified fields in expression context (e.g. usable in lambdas and other places where statements aren't allowed), with no additional external declarations, and ability to access individual components by name via the normal member access syntax foo.bar. The created object should also implement structural comparison by component names (not by position, as tuples do).
In particular: tuples isn't it because their components are not named; classes isn't it because they require a declaration; dicts isn't it because they have undesired foo["bar"] syntax to access components.
namedtuple isn't it, because it still requires a name even if you define the type inline, and the comparison is position-based, not name-based. In particular:
def foo(): return namedtuple("Foo", "x y")(x = 1, y = 2)
def bar(): return namedtuple("Foo", "y x")(x = 1, y = 2)
foo() == bar() # False because fields are compared in order, and not by name
# True would be desired instead
I know how to write such a thing in Python if needed. But I would like to know if there's anything like that in the Python standard library, or any popular third-party libraries.
[EDIT]
Just for the sake of it, here's a single-expression solution that combines two very informative answers by Ken and alanlcode, yielding structural equality without any extra outside declarations:
type("", (), { \
"__init__": (lambda self, **kwargs: self.__dict__.update(kwargs)), \
"__eq__": (lambda self, other: self.__dict__ == other.__dict__) } \
)(x = 1, y = 2)
Technically, it satisfies all the requirements of the question, but I sincerely hope that no-one ever uses it (I definitely won't).
|
The pythonic way would be to use a dict:
>>> foo = dict(x=1, y=2)
>>> bar = dict(y=2, x=1)
>>> foo == bar
True
Meets all your requirements except that you still have to do foo['x'] instead of foo.x.
If that's a problem, you could easily define a class such as:
class Bunch(object):
def __init__(self, **kwds):
self.__dict__.update(kwds)
def __eq__(self, other):
return self.__dict__ == other.__dict__
Or, a nice and short one
class Bunch(dict):
__getattr__, __setattr__ = dict.get, dict.__setitem__
(but note that this second one has problems as Alex points out in his comment!)
|
How to lock a critical section in Django?
|
I can't find a good clean way to lock a critical section in Django. I could use a lock or semaphore but the python implementation is for threads only, so if the production server forks then those will not be respected. Does anyone know of a way (I am thinking posix semaphores right now) to guarantee a lock across processes, or barring that a way to stop a Django server from forking.
|
If you use RDBMS, you can use its "LOCK" mechanism.
For example, while one "SELECT FOR UPDATE" transaction locks a row, the other "SELECT FOR UPDATE" transactions with the row must wait.
# You can use any Python DB API.
[SQL] BEGIN;
[SQL] SELECT col_name FROM table_name where id = 1 FOR UPDATE;
[Process some python code]
[SQL] COMMIT;
|
Django: Converting an entire set of a Model's objects into a single dictionary
|
If you came here from Google looking for model to dict, skip my question, and just jump down to the first answer. My question will only confuse you.
Is there a good way in Django to entire set of a Model's objects into a single dictionary? I mean, like this:
class DictModel(models.Model):
key = models.CharField(20)
value = models.CharField(200)
DictModel.objects.all().to_dict()
... with the result being a dictionary with the key/value pairs made up of records in the Model? Has anyone else seen this as being useful for them?
Thanks.
Update
I just wanted to add is that my ultimate goal is to be able to do a simple variable lookup inside a Template. Something like:
{{ DictModel.exampleKey }}
With a result of DictModel.objects.get(key__exact=exampleKey).value
Overall, though, you guys have really surprised me with how helpful allof your responses are, and how different the ways to approach it can be. Thanks a lot.
Update October 2011:
This question is the top result if you Google "django model_to_dict", which is actually pretty awful given that it solves a different problem than what I was asking.
What I wanted was to be able to map all of the instances in a queryset into a single dictionary with a specified model field as the key.
model_to_dict, on the other hand converts a single model instance into a dictionary.
Now, my needs at the time were pretty darn specific, and probably extremely rare (I can't even remember the project I needed it for, or why). So I would be pretty surprised that anyone looking for information about model_to_dict is going to find my question actually useful. Sorry.
model_to_dict seems to be a much more common usage case than I had.
Update Dec 2011:
I changed the title to hopefully better reflect my original intent.
|
You can also rely on django code already written ;).
from django.forms.models import model_to_dict
model_to_dict(instance, fields=[], exclude=[])
|
"select" on multiple Python multiprocessing Queues?
|
What's the best way to wait (without spinning) until something is available in either one of two (multiprocessing) Queues, where both reside on the same system?
|
Actually you can use multiprocessing.Queue objects in select.select. i.e.
que = multiprocessing.Queue()
(input,[],[]) = select.select([que._reader],[],[])
would select que only if it is ready to be read from.
No documentation about it though. I was reading the source code of the multiprocessing.queue library (at linux it's usually sth like /usr/lib/python2.6/multiprocessing/queue.py) to find it out.
With Queue.Queue I didn't have found any smart way to do this (and I would really love to).
|
Django persistent database connection
|
I'm using django with apache and mod_wsgi and PostgreSQL (all on same host), and I need to handle a lot of simple dynamic page requests (hundreds per second). I faced with problem that the bottleneck is that a django don't have persistent database connection and reconnects on each requests (that takes near 5ms).
While doing a benchmark I got that with persistent connection I can handle near 500 r/s while without I get only 50 r/s.
Anyone have any advice? How to modify django to use persistent connection? Or speed up connection from python to DB
Thanks in advance.
|
Try PgBouncer - a lightweight connection pooler for PostgreSQL.
Features:
Several levels of brutality when rotating connections:
Session pooling
Transaction pooling
Statement pooling
Low memory requirements (2k per connection by default).
|
Is it possible to go into ipython from code?
|
For my debugging needs, pdb is pretty good. However, it would be much cooler (and helpful) if I could go into ipython. Is this thing possible?
|
There is an ipdb project which embeds iPython into the standard pdb, so you can just do:
import ipdb; ipdb.set_trace()
It's installable via the usual easy_install ipdb.
ipdb is pretty short, so instead of easy_installing you can also create a file ipdb.py somewhere on your Python path and paste the following into the file:
import sys
from IPython.Debugger import Pdb
from IPython.Shell import IPShell
from IPython import ipapi
shell = IPShell(argv=[''])
def set_trace():
ip = ipapi.get()
def_colors = ip.options.colors
Pdb(def_colors).set_trace(sys._getframe().f_back)
|
How can I make setuptools ignore subversion inventory?
|
When packaging a Python package with a setup.py that uses the setuptools:
from setuptools import setup
...
the source distribution created by:
python setup.py sdist
not only includes, as usual, the files specified in MANIFEST.in, but it also, gratuitously, includes all of the files that Subversion lists as being version controlled beneath the package directory. This is vastly annoying. Not only does it make it difficult to exercise any sort of explicit control over what files get distributed with my package, but it means that when I build my package following an "svn export" instead of an "svn checkout", the contents of my package might be quite different, since without the .svn metadata setuptools will make different choices about what to include.
My question: how can I turn off this terrible behavior, so that "setuptools" treats my project the same way whether I'm using Subversion, or version control it's never heard of, or a bare tree created with "svn export" that I've created at the end of my project to make sure it builds cleanly somewhere besides my working directory?
The best I have managed so far is an ugly monkey-patch:
from setuptools.command import sdist
del sdist.finders[:]
But this is Python, not the jungle, so of course I want a better solution that involves no monkeys at all. How can I tame setuptools, turn off its magic, and have it behave sensibly by looking at the visible, predictable rules in my MANIFEST.py instead?
|
I know you know much of this, Brandon, but I'll try to give as a complete answer as I can (although I'm no setuptools gury) for the benefit of others.
The problem here is that setuptools itself involves quite a lot of black magick, including using an entry point called setuptools.file_finders where you can add plugins to find files to include. I am, however, at a complete loss as to how REMOVE plugins from it...
Quick workaround: svn export your package to a temporary directory and run the setup.py from there. That means you have no svn, so the svn finder finds no files to include. :)
Longer workaround: Do you really need setuptools? Setuptools have a lot of features, so the answer is likely yes, but mainly those features are depdenencies (so your dependencies get installed by easy_install), namespace packages (foo.bar), and entry points. Namespace packages can actually be created without setuptools as well. But if you use none of these you might actually get away with just using distutils.
Ugly workaround: The monkeypatch you gave to sdist in your question, which simply makes the plugin not have any finders, and exit quickly.
So as you see, this answer, although as complete as I can make it, is still embarrassingly incomplete. I can't actually answer your question, though I think the answer is "You can't".
|
Get MD5 hash of big files in Python
|
I have used hashlib (which replaces md5 in Python 2.6/3.0) and it worked fine if I opened a file and put its content in hashlib.md5() function.
The problem is with very big files that their sizes could exceed RAM size.
How to get the MD5 hash of a file without loading the whole file to memory?
|
You need to read the file in chunks of suitable size:
def md5_for_file(f, block_size=2**20):
md5 = hashlib.md5()
while True:
data = f.read(block_size)
if not data:
break
md5.update(data)
return md5.digest()
NOTE: Make sure you open your file with the 'rb' to the open - otherwise you will get the wrong result.
So to do the whole lot in one method - use something like:
def generate_file_md5(rootdir, filename, blocksize=2**20):
m = hashlib.md5()
with open( os.path.join(rootdir, filename) , "rb" ) as f:
while True:
buf = f.read(blocksize)
if not buf:
break
m.update( buf )
return m.hexdigest()
The update above was based on the comments provided by Frerich Raabe - and I tested this and found it to be correct on my Python 2.7.2 windows installation
I cross-checked the results using the 'jacksum' tool.
jacksum -a md5 <filename>
http://www.jonelo.de/java/jacksum/
|
Are Generators Threadsafe?
|
I have a multithreaded program where I create a generator function and then pass it to new threads. I want it to be shared/global in nature so each thread can get the next value from the generator.
Is it safe to use a generator like this, or will I run into problems/conditions accessing the shared generator from multiple threads?
If not, is there a better way to approach the problem? I need something that will cycle through a list and produce the next value for whichever thread calls it.
|
It's not thread-safe; simultaneous calls may interleave, and mess with the local variables.
The common approach is to use the master-slave pattern (now called farmer-worker pattern in PC). Make a third thread which generates data, and add a Queue between the master and the slaves, where slaves will read from the queue, and the master will write to it. The standard queue module provides the necessary thread safety and arranges to block the master until the slaves are ready to read more data.
|
"Least Astonishment" and the Mutable Default Argument
|
Anyone tinkering with Python long enough has been bitten (or torn to pieces) by the following issue:
def foo(a=[]):
a.append(5)
return a
Python novices would expect this function to always return a list with only one element: [5]. The result is instead very different, and very astonishing (for a novice):
>>> foo()
[5]
>>> foo()
[5, 5]
>>> foo()
[5, 5, 5]
>>> foo()
[5, 5, 5, 5]
>>> foo()
A manager of mine once had his first encounter with this feature, and called it "a dramatic design flaw" of the language. I replied that the behavior had an underlying explanation, and it is indeed very puzzling and unexpected if you don't understand the internals. However, I was not able to answer (to myself) the following question: what is the reason for binding the default argument at function definition, and not at function execution? I doubt the experienced behavior has a practical use (who really used static variables in C, without breeding bugs?)
Edit:
Baczek made an interesting example. Together with most of your comments and Utaal's in particular, I elaborated further:
>>> def a():
... print "a executed"
... return []
...
>>>
>>> def b(x=a()):
... x.append(5)
... print x
...
a executed
>>> b()
[5]
>>> b()
[5, 5]
To me, it seems that the design decision was relative to where to put the scope of parameters: inside the function or "together" with it?
Doing the binding inside the function would mean that x is effectively bound to the specified default when the function is called, not defined, something that would present a deep flaw: the def line would be "hybrid" in the sense that part of the binding (of the function object) would happen at definition, and part (assignment of default parameters) at function invocation time.
The actual behavior is more consistent: everything of that line gets evaluated when that line is executed, meaning at function definition.
|
Actually, this is not a design flaw, and it is not because of internals, or performance.
It comes simply from the fact that functions in Python are first-class objects, and not only a piece of code.
As soon as you get to think into this way, then it completely makes sense: a function is an object being evaluated on its definition; default parameters are kind of "member data" and therefore their state may change from one call to the other - exactly as in any other object.
In any case, Effbot has a very nice explanation of the reasons for this behavior in Default Parameter Values in Python.
I found it very clear, and I really suggest reading it for a better knowledge of how function objects work.
|
DateTime in python extracting different bits and pieces
|
I want to extract year from current date using python.
Do something like:
DateTime a = DateTime.Now()
a.Year # (this is in C#)
|
It's in fact almost the same in Python.. :-)
import datetime
year = datetime.date.today().year
Of course, date doesn't have a time associated, so if you care about that too, you can do the same with a complete datetime object:
import datetime
year = datetime.datetime.today().year
(Obviously no different, but you can store datetime.datetime.today() in a variable before you grab the year, of course).
One key thing to note is that the time components can differ between 32-bit and 64-bit pythons in some python versions (2.5.x tree I think). So you will find things like hour/min/sec on some 64-bit platforms, while you get hour/minute/second on 32-bit.
|
PHP equivalent to Python's yield operator
|
In Python (and others), you can incrementally process large volumes of data by using the 'yield' operator in a function. What would be the similar way to do so in PHP?
For example, lets say in Python, if I wanted to read a potentially very large file, I could work on each line one at a time like so (this example is contrived, as it is basically the same thing as 'for line in file_obj'):
def file_lines(fname):
f = open(fname)
for line in f:
yield line
f.close()
for line in file_lines('somefile'):
#process the line
What I'm doing right now (in PHP) is I'm using a private instance variable to keep track of state, and acting accordingly each time the function is called, but it seems like there must be a better way.
|
There is a rfc at https://wiki.php.net/rfc/generators adressing just that, which might be included in PHP 5.5.
In the mean time, check out this proof-of-concept of a poor mans "generator function" implemented in userland.
namespace Functional;
error_reporting(E_ALL|E_STRICT);
const BEFORE = 1;
const NEXT = 2;
const AFTER = 3;
const FORWARD = 4;
const YIELD = 5;
class Generator implements \Iterator {
private $funcs;
private $args;
private $key;
private $result;
public function __construct(array $funcs, array $args) {
$this->funcs = $funcs;
$this->args = $args;
}
public function rewind() {
$this->key = -1;
$this->result = call_user_func_array($this->funcs[BEFORE],
$this->args);
$this->next();
}
public function valid() {
return $this->result[YIELD] !== false;
}
public function current() {
return $this->result[YIELD];
}
public function key() {
return $this->key;
}
public function next() {
$this->result = call_user_func($this->funcs[NEXT],
$this->result[FORWARD]);
if ($this->result[YIELD] === false) {
call_user_func($this->funcs[AFTER], $this->result[FORWARD]);
}
++$this->key;
}
}
function generator($funcs, $args) {
return new Generator($funcs, $args);
}
/**
* A generator function that lazily yields each line in a file.
*/
function get_lines_from_file($file_name) {
$funcs = array(
BEFORE => function($file_name) { return array(FORWARD => fopen($file_name, 'r')); },
NEXT => function($fh) { return array(FORWARD => $fh, YIELD => fgets($fh)); },
AFTER => function($fh) { fclose($fh); },
);
return generator($funcs, array($file_name));
}
// Output content of this file with padded linenumbers.
foreach (get_lines_from_file(__FILE__) as $k => $v) {
echo str_pad($k, 8), $v;
}
echo "\n";
|
How accurate is python's time.sleep()?
|
I can give it floating point numbers, such as
time.sleep(0.5)
but how accurate is it? If i give it
time.sleep(0.05)
will it really sleep about 50 ms?
|
The accuracy of the time.sleep function depends on the accuracy of your underlying OS's sleep accuracy. For non-realtime OS's like a stock Windows the smallest interval you can sleep for is about 10-13ms. I have seen accurate sleeps within several milliseconds of that time when above the minimum 10-13ms.
Update:
Like mentioned in the docs sited below, it's common to do the sleep in a loop that will make sure to go back to sleep if the wakes you up the early.
I should also mention that if you are running Ubuntu you can try out a pseudo real-time kernel (with the RT_PREEMPT patch set) by installing the rt kernel package (at least in Ubuntu 10.04 LTS).
EDIT: Correction non-realtime Linux kernels have minimum sleep interval much closer to 1ms then 10ms but it varies in a non-deterministic manner.
|
Python Exception handling
|
C has perror and errno, which print and store the last error encountered. This is convenient when doing file io as I do not have to fstat() every file that fails as an argument to fopen() to present the user with a reason why the call failed.
I was wondering what is the proper way to grab errno when gracefully handling the IOError exception in python?
In [1]: fp = open("/notthere")
---------------------------------------------------------------------------
IOError Traceback (most recent call last)
/home/mugen/ in ()
IOError: [Errno 2] No such file or directory: '/notthere'
In [2]: fp = open("test/testfile")
---------------------------------------------------------------------------
IOError Traceback (most recent call last)
/home/mugen/ in ()
IOError: [Errno 13] Permission denied: 'test/testfile'
In [5]: try:
...: fp = open("nothere")
...: except IOError:
...: print "This failed for some reason..."
...:
...:
This failed for some reason...
|
Here's how you can do it. Also see the errno module and os.strerror function for some utilities.
import os, errno
try:
f = open('asdfasdf', 'r')
except IOError as ioex:
print 'errno:', ioex.errno
print 'err code:', errno.errorcode[ioex.errno]
print 'err message:', os.strerror(ioex.errno)
http://docs.python.org/library/errno.html
http://docs.python.org/library/os.html
For more information on IOError attributes, see the base class EnvironmentError:
http://docs.python.org/library/exceptions.html?highlight=ioerror#exceptions.EnvironmentError
|
Django required field in model form
|
I have a form where a couple of fields are coming out as required when I don't want them too. Here is the form from models.py
class CircuitForm(ModelForm):
class Meta:
model = Circuit
exclude = ('lastPaged',)
def __init__(self, *args, **kwargs):
super(CircuitForm, self).__init__(*args, **kwargs)
self.fields['begin'].widget = widgets.AdminSplitDateTime()
self.fields['end'].widget = widgets.AdminSplitDateTime()
In the actual Circuit model, the fields are defined like this:
begin = models.DateTimeField('Start Time', null=True, blank=True)
end = models.DateTimeField('Stop Time', null=True, blank=True)
My views.py for this is here:
def addCircuitForm(request):
if request.method == 'POST':
form = CircuitForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/sla/all')
form = CircuitForm()
return render_to_response('sla/add.html', {'form': form})
What can I do so that the two fields aren't required?
|
If you don't want to modify blank setting for your fields inside models (doing so will break normal validation in admin site), you can do the following in your Form class:
def __init__(self, *args, **kwargs):
super(CircuitForm, self).__init__(*args, **kwargs)
for key in self.fields:
self.fields[key].required = False
The redefined constructor won't harm any functionality.
|
increment int object
|
Is there a way in python to increment int object in place, int doesn't seem to implement __iadd__ so += 1 actually returns a new object
>>> n=1
>>> id(n)
9788024
>>> n+=1
>>> id(n)
9788012
What I want is n to remain pointing to same object.
Purpose: I have class derived from int and I want to implement C type '++n' operator for that class
Conclusion: ok as int is immutable there is no way, looks like i will have to write my own class something like this
class Int(object):
def __init__(self, value):
self._decr = False
self.value = value
def __neg__(self):
if self._decr:
self.value -= 1
self._decr = not self._decr
return self
def __str__(self):
return str(self.value)
def __cmp__(self, n):
return cmp(self.value, n)
def __nonzero__(self):
return self.value
n = Int(10)
while --n:
print n
|
ints are immutable, so you'll have to build your own class with all the int's methods if you want a "mutable int"
|
What is an efficent way of inserting thousands of records into an SQLite table using Django?
|
I have to insert 8000+ records into a SQLite database using Django's ORM. This operation needs to be run as a cronjob about once per minute. At the moment I'm using a for loop to iterate through all the items and then insert them one by one.
Example:
for item in items:
entry = Entry(a1=item.a1, a2=item.a2)
entry.save()
What is an efficent way of doing this?
Edit: A little comparison between the two insertion methods.
Without commit_manually decorator (11245 records):
nox@noxdevel marinetraffic]$ time python manage.py insrec
real 1m50.288s
user 0m6.710s
sys 0m23.445s
Using commit_manually decorator (11245 records):
[nox@noxdevel marinetraffic]$ time python manage.py insrec
real 0m18.464s
user 0m5.433s
sys 0m10.163s
Note: The test script also does some other operations besides inserting into the database (downloads a ZIP file, extracts an XML file from the ZIP archive, parses the XML file) so the time needed for execution does not necessarily represent the time needed to insert the records.
|
You want to check out django.db.transaction.commit_manually.
http://docs.djangoproject.com/en/dev/topics/db/transactions/#django-db-transaction-commit-manually
So it would be something like:
from django.db import transaction
@transaction.commit_manually
def viewfunc(request):
...
for item in items:
entry = Entry(a1=item.a1, a2=item.a2)
entry.save()
transaction.commit()
Which will only commit once, instead at each save().
In django 1.3 context managers were introduced.
So now you can use transaction.commit_on_success() in a similar way:
from django.db import transaction
def viewfunc(request):
...
with transaction.commit_on_success():
for item in items:
entry = Entry(a1=item.a1, a2=item.a2)
entry.save()
In django 1.4, bulk_create was added, allowing you to create lists of your model objects and then commit them all at once.
NOTE the save method will not be called when using bulk create.
>>> Entry.objects.bulk_create([
... Entry(headline="Django 1.0 Released"),
... Entry(headline="Django 1.1 Announced"),
... Entry(headline="Breaking: Django is awesome")
... ])
In django 1.6, transaction.atomic was introduced, intended to replace now legacy functions commit_on_success and commit_manually.
from the django documentation on atomic:
atomic is usable both as a decorator:
from django.db import transaction
@transaction.atomic
def viewfunc(request):
# This code executes inside a transaction.
do_stuff()
and as a context manager:
from django.db import transaction
def viewfunc(request):
# This code executes in autocommit mode (Django's default).
do_stuff()
with transaction.atomic():
# This code executes inside a transaction.
do_more_stuff()
|
Inserting a Python datetime.datetime object into MySQL
|
I have a date column in a MySQL table. I want to insert a datetime.datetime() object into this column. What should I be using in the execute statement?
I have tried:
now = datetime.datetime(2009,5,5)
cursor.execute("INSERT INTO table
(name, id, datecolumn) VALUES (%s, %s
, %s)",("name", 4,now))
I am getting an error as: "TypeError: not all arguments converted during string formatting"
What should I use instead of %s?
|
For a time field, use:
import time
time.strftime('%Y-%m-%d %H:%M:%S')
I think strftime also applies to datetime.
|
What does python sys.intern do, and when should it be used?
|
I came across this question about memory management of dictionaries, which mentions the intern function. What exactly does it do, and when would it be used?
To give an example:
If I have a set called seen, that contains tuples in the form (string1,string2), which I use to check for duplicates, would storing (intern(string1),intern(string2)) improve performance w.r.t. memory or speed?
|
From the Python 3 documentation:
sys.intern(string)
Enter string in the table of âinternedâ strings and return the
interned string â which is string itself or a copy. Interning strings
is useful to gain a little performance on dictionary lookup â if the
keys in a dictionary are interned, and the lookup key is interned, the
key comparisons (after hashing) can be done by a pointer compare
instead of a string compare. Normally, the names used in Python
programs are automatically interned, and the dictionaries used to hold
module, class or instance attributes have interned keys.
Interned strings are not immortal; you must keep a reference to the
return value of intern() around to benefit from it.
Clarification:
As the documentation suggests, the sys.intern function is intended to be used for performance optimization.
The sys.intern function maintains a table of interned strings. When you attempt to intern a string, the function looks it up in the table and:
If the string does not exists (hasn't been interned yet) the function saves
it in the table and returns it from the interned strings table.
>>> import sys
>>> a = sys.intern('why do pangolins dream of quiche')
>>> a
'why do pangolins dream of quiche'
In the above example, a holds the interned string. Even though it is not visible, the sys.intern function has saved the 'why do pangolins dream of quiche' string object in the interned strings table.
If the string exists (has been interned) the function returns it from the
interned strings table.
>>> b = sys.intern('why do pangolins dream of quiche')
>>> b
'why do pangolins dream of quiche'
Even though it is not immediately visible, because the string 'why do pangolins dream of quiche' has been interned before, b holds now the same string object as a.
>>> b is a
True
If we create the same string without using intern, we end up with two different string objects that have the same value.
>>> c = 'why do pangolins dream of quiche'
>>> c is a
False
>>> c is b
False
By using sys.intern you ensure that you never create two string objects that have the same valueâwhen you request the creation of a second string object with the same value as an existing string object, you receive a reference to the pre-existing string object. This way, you are saving memory. Also, string objects comparison is now very efficient because it is carried out by comparing the memory addresses of the two string objects instead of their content.
|
What is the correct way to document a **kwargs parameter?
|
I'm using sphinx and the autodoc plugin to generate API documentation for my Python modules. Whilst I can see how to nicely document specific parameters, I cannot find an example of how to document a **kwargs parameter.
Does anyone have a good example of a clear way to document these?
|
I think subprocess-module's docs is a good example. Give an exhaustive list of all parameters for a top/parent class. Then just refer to that list for all other occurrences of **kwargs.
|
Recommended Python cryptographic module?
|
I've been exploring what cryptographic modules are available to Python, and I've found 3: ezPyCrypt, yawPyCrypt and KeyCzar (which actually supports a few languages, but Python is included amongst them). The first two rely on the PyCrypto module.
Are there choices I am missing? Is there a clear front-runner for ease and features or does it simply come down to a manner of one's comfort level?
I'm currently leaning towards KeyCzar, with ezPyCrypt close behind.
I would be using the library for digital signature signing and verification, and potentially for key creation (although I won't cry if I have to make a call to something else for that functionality).
I am using Python 3.x and have access to GPG.
|
If you are in an environment which includes GnuPG and Python >= 2.4, then you could also consider a tool such as python-gnupg. (Disclaimer: I'm the maintainer of this project.) It leaves the heavy lifting to gpg and provides a fairly straightforward API.
Overview of API:
>>> import gnupg
>>> gpg = gnupg.GPG(gnupghome='/path/to/keyring/directory')
>>> gpg.list_keys()
[{
...
'fingerprint': 'F819EE7705497D73E3CCEE65197D5DAC68F1AAB2',
'keyid': '197D5DAC68F1AAB2',
'length': '1024',
'type': 'pub',
'uids': ['', 'Gary Gross (A test user) ']},
{
...
'fingerprint': '37F24DD4B918CC264D4F31D60C5FEFA7A921FC4A',
'keyid': '0C5FEFA7A921FC4A',
'length': '1024',
...
'uids': ['', 'Danny Davis (A test user) ']}]
>>> encrypted = gpg.encrypt("Hello, world!", ['0C5FEFA7A921FC4A'])
>>> str(encrypted)
'-----BEGIN PGP MESSAGE-----\nVersion: GnuPG v1.4.9 (GNU/Linux)\n
\nhQIOA/6NHMDTXUwcEAf
...
-----END PGP MESSAGE-----\n'
>>> decrypted = gpg.decrypt(str(encrypted), passphrase='secret')
>>> str(decrypted)
'Hello, world!'
>>> signed = gpg.sign("Goodbye, world!", passphrase='secret')
>>> verified = verified = gpg.verify(str(signed))
>>> print "Verified" if verified else "Not verified"
'Verified'
|
Python inheritance and calling parent class constructor
|
This is what I'm trying to do in Python:
class BaseClass:
def __init__(self):
print 'The base class constructor ran!'
self.__test = 42
class ChildClass(BaseClass):
def __init__(self):
print 'The child class constructor ran!'
BaseClass.__init__(self)
def doSomething(self):
print 'Test is: ', self.__test
test = ChildClass()
test.doSomething()
Which results in:
AttributeError: ChildClass instance has no attribute '_ChildClass__test'
What gives? Why doesn't this work as I expect?
|
From python documentation:
Private name mangling: When an identifier that textually occurs in a class definition begins with two or more underscore characters and does not end in two or more underscores, it is considered a private name of that class. Private names are transformed to a longer form before code is generated for them. The transformation inserts the class name in front of the name, with leading underscores removed, and a single underscore inserted in front of the class name. For example, the identifier __spam occurring in a class named Ham will be transformed to _Ham__spam. This transformation is independent of the syntactical context in which the identifier is used. If the transformed name is extremely long (longer than 255 characters), implementation defined truncation may happen. If the class name consists only of underscores, no transformation is done.
So your attribute is not named __test but _BaseClass__test.
However you should not depend on that, use self._test instead and most python developers will know that the attribute is an internal part of the class, not the public interface.
|
In Python, how do I obtain the current frame?
|
In other languages I can obtain the current frame via a reflection api to determine what variables are local to the scope that I an currently in.
Is there a way to do this in Python?
|
import sys
sys._getframe(number)
The number being 0 for the current frame and 1 for the frame up and so on up.
The best introduction I have found to frames in python is here
However, look at the inspect module as it does most common things you want to do with frames.
|
Whatâs the best way to get an HTTP response code from a URL?
|
Iâm looking for a quick way to get an HTTP response code from a URL (i.e. 200, 404, etc). Iâm not sure which library to use.
|
Here's a solution that uses httplib instead.
import httplib
def get_status_code(host, path="/"):
""" This function retreives the status code of a website by requesting
HEAD data from the host. This means that it only requests the headers.
If the host cannot be reached or something else goes wrong, it returns
None instead.
"""
try:
conn = httplib.HTTPConnection(host)
conn.request("HEAD", path)
return conn.getresponse().status
except StandardError:
return None
print get_status_code("stackoverflow.com") # prints 200
print get_status_code("stackoverflow.com", "/nonexistant") # prints 404
|
What's a quick one-liner to remove empty lines from a python string?
|
I have some code in a python string that contains extraneous empty lines. I would like to remove all empty lines from the string. What's the most pythonic way to do this?
Note: I'm not looking for a general code re-formatter, just a quick one or two-liner.
Thanks!
|
How about:
text = os.linesep.join([s for s in text.splitlines() if s])
where text is the string with the possible extraneous lines?
|
Name this python/ruby language construct (using array values to satisfy function parameters)
|
What is this language construct called?
In Python I can say:
def a(b,c): return b+c
a(*[4,5])
and get 9. Likewise in Ruby:
def a(b,c) b+c end
a(*[4,5])
What is this called, when one passes a single array to a function which otherwise requires multiple arguments?
What is the name of the * operator?
What other languages support this cool feature?
|
The Python docs call this Unpacking Argument Lists. It's a pretty handy feature. In Python, you can also use a double asterisk (**) to unpack a dictionary (hash) into keyword arguments. They also work in reverse. I can define a function like this:
def sum(*args):
result = 0
for a in args:
result += a
return result
sum(1,2)
sum(9,5,7,8)
sum(1.7,2.3,8.9,3.4)
To pack all arguments into an arbitrarily sized list.
|
Python @property versus method performance - which one to use?
|
I have written some code that uses attributes of an object:
class Foo:
def __init__(self):
self.bar = "baz"
myFoo = Foo()
print (myFoo.bar)
Now I want to do some fancy calculation to return bar. I could use @property to make methods act as the attribute bar, or I could refactor my code to use myFoo.bar().
Should I go back and add parens to all my bar accesses or use @property? Assume my code base is small now but due to entropy it will increase.
|
If it's logically a property/attribute of the object, I'd say keep it as a property. If it's likely to become parametrised, by which I mean you may want to invoke myFoo.bar(someArgs) then bite the bullet now and make it a method.
Under most circumstances, performance is unlikely to be an issue.
|
Django: Why do some model fields clash with each other?
|
I want to create an object that contains 2 links to Users. For example:
class GameClaim(models.Model):
target = models.ForeignKey(User)
claimer = models.ForeignKey(User)
isAccepted = models.BooleanField()
but I am getting the following errors when running the server:
Accessor for field 'target' clashes with related field 'User.gameclaim_set'. Add a related_name argument to the definition for 'target'.
Accessor for field 'claimer' clashes with related field 'User.gameclaim_set'. Add a related_name argument to the definition for 'claimer'.
Can you please explain why I am getting the errors and how to fix them?
|
You have two foreign keys to User. Django automatically creates a reverse relation from User back to GameClaim, which is usually gameclaim_set. However, because you have two FKs, you would have two gameclaim_set attributes, which is obviously impossible. So you need to tell Django what name to use for the reverse relation.
Use the related_name attribute in the FK definition. e.g.
class GameClaim(models.Model):
target = models.ForeignKey(User, related_name='gameclaim_targets')
claimer = models.ForeignKey(User, related_name='gameclaim_users')
isAccepted = models.BooleanField()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.