title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
Getting the pattern back from a compiled re?
190,967
17
2008-10-10T11:58:40Z
190,975
21
2008-10-10T12:01:41Z
[ "python", "regex" ]
Assume I have created a compiled re: ``` x = re.compile('^\d+$') ``` Is there a way to extract the pattern string (^\d+$) back from the x?
You can get it back with ``` x.pattern ``` from the Python [documentation on Regular Expression Objects](https://docs.python.org/3/library/re.html#re.regex.pattern)
How to get a complete list of object's methods and attributes?
191,010
152
2008-10-10T12:18:32Z
191,029
100
2008-10-10T12:25:22Z
[ "python" ]
``` dir(re.compile(pattern)) ``` does not return pattern as one of the lists's elements. Namely it returns: ``` ['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 'search', 'split', 'sub', 'subn'] ``` According to the manual, it is supposed to contain > the object's attributes' names, the > names of its class's attributes, and > recursively of the attributes of its > class's base classes. It says also that > The list is not necessarily complete. Is there a way to get the **complete** list? I always assumed that dir returns a complete list but apparently it does not... Also: is there a way to list only attributes? Or only methods? *Edit: this is actually a bug in python -> supposedly it is fixed in the 3.0 branch (and perhaps also in 2.6)*
For the **complete** list of attributes, the short answer is: no. The problem is that the attributes are actually defined as the arguments accepted by the `getattr` built-in function. As the user can reimplement `__getattr__`, suddenly allowing any kind of attribute, there is no possible generic way to generate that list. The `dir` function returns the keys in the `__dict__` attribute, i.e. all the attributes accessible if the `__getattr__` method is not reimplemented. For the second question, it does not really make sense. Actually, methods are callable attributes, nothing more. You could though filter callable attributes, and, using the `inspect` module determine the class methods, methods or functions.
How to get a complete list of object's methods and attributes?
191,010
152
2008-10-10T12:18:32Z
191,679
35
2008-10-10T14:46:09Z
[ "python" ]
``` dir(re.compile(pattern)) ``` does not return pattern as one of the lists's elements. Namely it returns: ``` ['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 'search', 'split', 'sub', 'subn'] ``` According to the manual, it is supposed to contain > the object's attributes' names, the > names of its class's attributes, and > recursively of the attributes of its > class's base classes. It says also that > The list is not necessarily complete. Is there a way to get the **complete** list? I always assumed that dir returns a complete list but apparently it does not... Also: is there a way to list only attributes? Or only methods? *Edit: this is actually a bug in python -> supposedly it is fixed in the 3.0 branch (and perhaps also in 2.6)*
That is why the new `__dir__()` method has been added in python 2.6 see: * <http://docs.python.org/whatsnew/2.6.html#other-language-changes> (scroll down a little bit) * <http://bugs.python.org/issue1591665>
How to get a complete list of object's methods and attributes?
191,010
152
2008-10-10T12:18:32Z
10,313,703
15
2012-04-25T10:19:45Z
[ "python" ]
``` dir(re.compile(pattern)) ``` does not return pattern as one of the lists's elements. Namely it returns: ``` ['__copy__', '__deepcopy__', 'findall', 'finditer', 'match', 'scanner', 'search', 'split', 'sub', 'subn'] ``` According to the manual, it is supposed to contain > the object's attributes' names, the > names of its class's attributes, and > recursively of the attributes of its > class's base classes. It says also that > The list is not necessarily complete. Is there a way to get the **complete** list? I always assumed that dir returns a complete list but apparently it does not... Also: is there a way to list only attributes? Or only methods? *Edit: this is actually a bug in python -> supposedly it is fixed in the 3.0 branch (and perhaps also in 2.6)*
Here is a practical addition to the answers of PierreBdR and Moe: -- for Python >= 2.6 *and new-style classes*, dir() seems to be enough; -- *for old-style classes*, we can at least do what a [standard module](http://docs.python.org/library/rlcompleter.html) does to support tab completion: in addition to `dir()`, look for `__class__` -- and then to go for its `__bases__`: ``` # code borrowed from the rlcompleter module # tested under Python 2.6 ( sys.version = '2.6.5 (r265:79063, Apr 16 2010, 13:09:56) \n[GCC 4.4.3]' ) # or: from rlcompleter import get_class_members def get_class_members(klass): ret = dir(klass) if hasattr(klass,'__bases__'): for base in klass.__bases__: ret = ret + get_class_members(base) return ret def uniq( seq ): """ the 'set()' way ( use dict when there's no set ) """ return list(set(seq)) def get_object_attrs( obj ): # code borrowed from the rlcompleter module ( see the code for Completer::attr_matches() ) ret = dir( obj ) ## if "__builtins__" in ret: ## ret.remove("__builtins__") if hasattr( obj, '__class__'): ret.append('__class__') ret.extend( get_class_members(obj.__class__) ) ret = uniq( ret ) return ret ``` ( Test code and output are deleted for brevity, but basically for new-style objects we seem to have the same results for `get_object_attrs()` as for `dir()`, and for old-style classes the main addition to the `dir()` output seem to be the `__class__` attribute ) )
Python Webframework Confusion
191,062
10
2008-10-10T12:40:08Z
191,069
15
2008-10-10T12:43:02Z
[ "python", "pylons", "cherrypy", "web-frameworks", "turbogears" ]
Could someone please explain to me how the current python webframworks fit together? The three I've heard of are CherryPy, TurboGears and Pylons. However I'm confused because TurboGears seems to use CherryPy as the 'Controller' (although isn't CherryPy a framework in in it's own right?), and TurbGears 2 is going to be built on top of Pylons (which I thought did the same thing?).
There are more to it ofcourse. Here's a comprehensive list and details! [**Web Frameworks for Python**](http://wiki.python.org/moin/WebFrameworks) Extract from above link: > ## Popular Full-Stack Frameworks > > A web application may use a > combination of a base HTTP application > server, a storage mechanism such as a > database, a template engine, a request > dispatcher, an authentication module > and an AJAX toolkit. These can be > individual components or be provided > together in a high-level framework. > > These are the most popular high-level > frameworks. Many of them include > components listed on the WebComponents > page. > > [**Django**](http://wiki.python.org/moin/Django) (1.0 Released 2008-09-03) a > high-level Python Web framework that > encourages rapid development and > clean, pragmatic design > > [**Pylons**](http://pylonshq.com/) (0.9.6.2 Released 2008-05-28) a > lightweight Web framework emphasizing > flexibility and rapid development. It > combines the very best ideas from the > worlds of Ruby, Python and Perl, > providing a structured but extremely > flexible Python Web framework. It's > also one of the first projects to > leverage the emerging WSGI standard, > which allows extensive re-use and > flexibility but only if you need it. > Out of the box, Pylons aims to make > Web development fast, flexible and > easy. Pylons is built on top of Paste > (see below). > > [**TurboGears**](http://www.turbogears.org/) (1.0.4.4 Released > 2008-03-07) the rapid Web development > megaframework you've been looking for. > Combines [**CherryPy**](http://wiki.python.org/moin/CherryPy), Kid, SQLObject and > [**MochiKit**](http://wiki.python.org/moin/MochiKit). After reviewing the website > check out: [**QuickStart Manual**](http://lucasmanual.com/mywiki/TurboGears) > > [**web2py**](http://mdp.cti.depaul.edu/) (currently version 1.43) > Everything in one package with no > dependencies. Development, deployment, > debugging, testing, database > administration and maintenance of > applications can be done via the > provided web interface. web2py has no > configuration files, requires no > installation, can run off a USB drive. > web2py uses Python for the Model, the > Views and the Controllers, has a > built-in ticketing system to manage > errors, an internationalization > engine, works with MySQL, PostgreSQL, > SQLite , Oracle, MSSQL and the Google > App Engine via an ORM abstraction > layer. web2py includes libraries to > handle HTML/XML, RSS, ATOM, CSV, RTF, > JSON, AJAX, XMLRPC, WIKI markup. > Production ready, capable of > upload/download of very large files, > and always backward compatible. > > [**Grok**](http://grok.zope.org/) (0.13 Released 2008-06-23) is > built on the existing Zope 3 > libraries, but aims to provide an > easier learning curve and a more agile > development experience. It does this > by placing an emphasis on convention > over configuration and DRY (Don't > Repeat Yourself). > > [**Zope**](http://www.zope.org/) (2.10.4 Released 2007-07-04, > 3.3.1 Released 2007-01-14, Zope 3.4.0c1 Released 2008-01-31) Being the grandaddy of Python web frameworks, > Zope has grown into a family of > frameworks over the years. Zope 1 was > released in 1999. Zope 2 is both a web > framework and a general purpose > application server, today it is > primarily used by > ContentManagementSystems. Zope 3 is > both a standalone framework and a > collection of related libraries, which > are also included with newer releases > of Zope 2. All of the Zope frameworks > include the ZODB, an object database > for Python.
Python Webframework Confusion
191,062
10
2008-10-10T12:40:08Z
191,805
7
2008-10-10T15:15:33Z
[ "python", "pylons", "cherrypy", "web-frameworks", "turbogears" ]
Could someone please explain to me how the current python webframworks fit together? The three I've heard of are CherryPy, TurboGears and Pylons. However I'm confused because TurboGears seems to use CherryPy as the 'Controller' (although isn't CherryPy a framework in in it's own right?), and TurbGears 2 is going to be built on top of Pylons (which I thought did the same thing?).
Give a try to web2py. It is point and click (you do not even need to install Python, comes with it). You develop using a web interface and you can deploy almost everywhere, including iPhone, Oracle and Google App Engine. Before trying web2py, try install some of the other Python frameworks, you will appreciate it even more.
How to convert a file to utf-8 in Python?
191,359
35
2008-10-10T13:50:26Z
191,403
40
2008-10-10T13:59:07Z
[ "python", "encoding", "file", "utf-8" ]
I need to convert a bunch of files to utf-8 in Python, and I have trouble with the "converting the file" part. I'd like to do the equivalent of: ``` iconv -t utf-8 $file > converted/$file # this is shell code ``` Thanks!
You can use the [codecs module](https://docs.python.org/2/library/codecs.html), like this: ``` import codecs BLOCKSIZE = 1048576 # or some other, desired size in bytes with codecs.open(sourceFileName, "r", "your-source-encoding") as sourceFile: with codecs.open(targetFileName, "w", "utf-8") as targetFile: while True: contents = sourceFile.read(BLOCKSIZE) if not contents: break targetFile.write(contents) ``` **EDIT**: added `BLOCKSIZE` parameter to control file chunk size.
How to convert a file to utf-8 in Python?
191,359
35
2008-10-10T13:50:26Z
191,455
20
2008-10-10T14:07:07Z
[ "python", "encoding", "file", "utf-8" ]
I need to convert a bunch of files to utf-8 in Python, and I have trouble with the "converting the file" part. I'd like to do the equivalent of: ``` iconv -t utf-8 $file > converted/$file # this is shell code ``` Thanks!
This worked for me in a small test: ``` sourceEncoding = "iso-8859-1" targetEncoding = "utf-8" source = open("source") target = open("target", "w") target.write(unicode(source.read(), sourceEncoding).encode(targetEncoding)) ```
How to convert a file to utf-8 in Python?
191,359
35
2008-10-10T13:50:26Z
192,086
10
2008-10-10T16:14:45Z
[ "python", "encoding", "file", "utf-8" ]
I need to convert a bunch of files to utf-8 in Python, and I have trouble with the "converting the file" part. I'd like to do the equivalent of: ``` iconv -t utf-8 $file > converted/$file # this is shell code ``` Thanks!
Thanks for the replies, it works! And since the source files are in mixed formats, I added a list of source formats to be tried in sequence (`sourceFormats`), and on `UnicodeDecodeError` I try the next format: ``` from __future__ import with_statement import os import sys import codecs from chardet.universaldetector import UniversalDetector targetFormat = 'utf-8' outputDir = 'converted' detector = UniversalDetector() def get_encoding_type(current_file): detector.reset() for line in file(current_file): detector.feed(line) if detector.done: break detector.close() return detector.result['encoding'] def convertFileBestGuess(filename): sourceFormats = ['ascii', 'iso-8859-1'] for format in sourceFormats: try: with codecs.open(fileName, 'rU', format) as sourceFile: writeConversion(sourceFile) print('Done.') return except UnicodeDecodeError: pass def convertFileWithDetection(fileName): print("Converting '" + fileName + "'...") format=get_encoding_type(fileName) try: with codecs.open(fileName, 'rU', format) as sourceFile: writeConversion(sourceFile) print('Done.') return except UnicodeDecodeError: pass print("Error: failed to convert '" + fileName + "'.") def writeConversion(file): with codecs.open(outputDir + '/' + fileName, 'w', targetFormat) as targetFile: for line in file: targetFile.write(line) # Off topic: get the file list and call convertFile on each file # ... ``` (EDIT by Rudro Badhon: this incorporates the original try multiple formats until you don't get an exception as well as an alternate approach that uses chardet.universaldetector)
Converting XML to JSON using Python?
191,536
82
2008-10-10T14:19:44Z
191,617
35
2008-10-10T14:34:55Z
[ "python", "xml", "json" ]
I've seen a fair share of ungainly XML->JSON code on the web, and having interacted with Stack's users for a bit, I'm convinced that this crowd can help more than the first few pages of Google results can. So, we're parsing a weather feed, and we need to populate weather widgets on a multitude of web sites. We're looking now into Python-based solutions. This public [weather.com RSS feed](http://rss.weather.com/weather/rss/local/14607?cm_ven=LWO&cm_cat=rss&par=LWO_rss) is a good example of what we'd be parsing (*our actual weather.com feed contains additional information because of a partnership w/them*). In a nutshell, how should we convert XML to JSON using Python?
There is no "one-to-one" mapping between XML and JSON, so converting one to the other necessarily requires some understanding of what you want to *do* with the results. That being said, Python's standard library has [several modules for parsing XML](http://docs.python.org/2/library/xml.html) (including DOM, SAX, and ElementTree). As of Python 2.6, support for converting Python data structures to and from JSON is included in the [`json` module](http://docs.python.org/2/library/json.html). So the infrastructure is there.
Converting XML to JSON using Python?
191,536
82
2008-10-10T14:19:44Z
10,201,405
169
2012-04-18T01:06:05Z
[ "python", "xml", "json" ]
I've seen a fair share of ungainly XML->JSON code on the web, and having interacted with Stack's users for a bit, I'm convinced that this crowd can help more than the first few pages of Google results can. So, we're parsing a weather feed, and we need to populate weather widgets on a multitude of web sites. We're looking now into Python-based solutions. This public [weather.com RSS feed](http://rss.weather.com/weather/rss/local/14607?cm_ven=LWO&cm_cat=rss&par=LWO_rss) is a good example of what we'd be parsing (*our actual weather.com feed contains additional information because of a partnership w/them*). In a nutshell, how should we convert XML to JSON using Python?
[xmltodict](https://github.com/martinblech/xmltodict) (full disclosure: I wrote it) can help you convert your XML to a dict+list+string structure, following this ["standard"](http://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html). It is [Expat](http://docs.python.org/library/pyexpat.html)-based, so it's very fast and doesn't need to load the whole XML tree in memory. Once you have that data structure, you can serialize it to JSON: ``` import xmltodict, json o = xmltodict.parse('<e> <a>text</a> <a>text</a> </e>') json.dumps(o) # '{"e": {"a": ["text", "text"]}}' ```
Configuring python
191,700
2
2008-10-10T14:52:04Z
191,744
11
2008-10-10T15:02:11Z
[ "python", "memory" ]
I am new to python and struggling to find how to control the amount of memory a python process can take? I am running python on a Cento OS machine with more than 2 GB of main memory size. Python is taking up only 128mb of this and I want to allocate it more. I tried to search all over the internet on this for last half an hour and found absolutely nothing! Why is it so difficult to find information on python related stuff :( I would be happy if someone could throw some light on how to configure python for various things like allowed memory size, number of threads etc. A link to a site where most controllable parameters of python are described would be appreciated well.
Forget all that, python just allocates more memory as needed, there is not a myriad of comandline arguments for the VM as in java, just let it run. For all comandline switches you can just run python -h or read man python.
Is there a function in Python to print all the current properties and values of an object?
192,109
446
2008-10-10T16:19:27Z
192,116
9
2008-10-10T16:20:40Z
[ "python", "debugging", "introspection", "pretty-print", "python-datamodel" ]
So what I'm looking for here is something like [PHP's print\_r](http://us2.php.net/print_r) function. This is so I can debug my scripts by seeing what's the state of the object in question.
You can use the "dir()" function to do this. ``` >>> import sys >>> dir(sys) ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdo t__', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder , 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'exc_clear', 'exc_info' 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'getcheckinterval', 'getdefault ncoding', 'getfilesystemencoding', 'getrecursionlimit', 'getrefcount', 'getwindowsversion', 'he version', 'maxint', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_ ache', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setprofile', 'setrecursionlimit , 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoption ', 'winver'] >>> ``` Another useful feature is help. ``` >>> help(sys) Help on built-in module sys: NAME sys FILE (built-in) MODULE DOCS http://www.python.org/doc/current/lib/module-sys.html DESCRIPTION This module provides access to some objects used or maintained by the interpreter and to functions that interact strongly with the interpreter. Dynamic objects: argv -- command line arguments; argv[0] is the script pathname if known ```
Is there a function in Python to print all the current properties and values of an object?
192,109
446
2008-10-10T16:19:27Z
192,184
85
2008-10-10T16:36:28Z
[ "python", "debugging", "introspection", "pretty-print", "python-datamodel" ]
So what I'm looking for here is something like [PHP's print\_r](http://us2.php.net/print_r) function. This is so I can debug my scripts by seeing what's the state of the object in question.
``` def dump(obj): for attr in dir(obj): print "obj.%s = %s" % (attr, getattr(obj, attr)) ``` There are many 3rd-party functions out there that add things like exception handling, national/special character printing, recursing into nested objects etc. according to their authors' preferences. But they all basically boil down to this.
Is there a function in Python to print all the current properties and values of an object?
192,109
446
2008-10-10T16:19:27Z
192,207
26
2008-10-10T16:44:50Z
[ "python", "debugging", "introspection", "pretty-print", "python-datamodel" ]
So what I'm looking for here is something like [PHP's print\_r](http://us2.php.net/print_r) function. This is so I can debug my scripts by seeing what's the state of the object in question.
*dir* has been mentioned, but that'll only give you the attributes' names. If you want their values as well try \_\_dict\_\_. ``` class O: def __init__ (self): self.value = 3 o = O() ``` >>> o.\_\_dict\_\_ {'value': 3}
Is there a function in Python to print all the current properties and values of an object?
192,109
446
2008-10-10T16:19:27Z
192,365
263
2008-10-10T17:27:06Z
[ "python", "debugging", "introspection", "pretty-print", "python-datamodel" ]
So what I'm looking for here is something like [PHP's print\_r](http://us2.php.net/print_r) function. This is so I can debug my scripts by seeing what's the state of the object in question.
You are really mixing together two different things. Use [`dir()`](https://docs.python.org/3/library/functions.html#dir), [`vars()`](https://docs.python.org/3/library/functions.html#vars) or the [`inspect`](https://docs.python.org/3/library/inspect.html) module to get what you are interested in (I use `__builtins__` as an example; you can use any object instead). ``` >>> l = dir(__builtins__) >>> d = __builtins__.__dict__ ``` Print that dictionary however fancy you like: ``` >>> print l ['ArithmeticError', 'AssertionError', 'AttributeError',... ``` or ``` >>> from pprint import pprint >>> pprint(l) ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'DeprecationWarning', ... >>> pprint(d, indent=2) { 'ArithmeticError': <type 'exceptions.ArithmeticError'>, 'AssertionError': <type 'exceptions.AssertionError'>, 'AttributeError': <type 'exceptions.AttributeError'>, ... '_': [ 'ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'DeprecationWarning', ... ```
Is there a function in Python to print all the current properties and values of an object?
192,109
446
2008-10-10T16:19:27Z
193,539
485
2008-10-11T01:16:32Z
[ "python", "debugging", "introspection", "pretty-print", "python-datamodel" ]
So what I'm looking for here is something like [PHP's print\_r](http://us2.php.net/print_r) function. This is so I can debug my scripts by seeing what's the state of the object in question.
You want vars() mixed with pprint: ``` from pprint import pprint pprint (vars(your_object)) ```
Is there a function in Python to print all the current properties and values of an object?
192,109
446
2008-10-10T16:19:27Z
193,808
15
2008-10-11T07:29:09Z
[ "python", "debugging", "introspection", "pretty-print", "python-datamodel" ]
So what I'm looking for here is something like [PHP's print\_r](http://us2.php.net/print_r) function. This is so I can debug my scripts by seeing what's the state of the object in question.
To print the current state of the object you might: ``` >>> obj # in an interpreter ``` or ``` print repr(obj) # in a script ``` or ``` print obj ``` For your classes define `__str__` or `__repr__` methods. From the [Python documentation](http://www.python.org/doc/2.5.2/ref/customization.html): > `__repr__(self)` Called by the `repr()` built-in function and by string > conversions (reverse quotes) to > compute the "official" string > representation of an object. If at all > possible, this should look like a > valid Python expression that could be > used to recreate an object with the > same value (given an appropriate > environment). If this is not possible, > a string of the form "<...some useful > description...>" should be returned. > The return value must be a string > object. If a class defines **repr**() > but not `__str__()`, then `__repr__()` is > also used when an "informal" string > representation of instances of that > class is required. This is typically > used for debugging, so it is important > that the representation is > information-rich and unambiguous. > > `__str__(self)` Called by the `str()` built-in function and by the print > statement to compute the "informal" > string representation of an object. > This differs from `__repr__()` in that > it does not have to be a valid Python > expression: a more convenient or > concise representation may be used > instead. The return value must be a > string object.
Is there a function in Python to print all the current properties and values of an object?
192,109
446
2008-10-10T16:19:27Z
13,391,460
8
2012-11-15T04:11:48Z
[ "python", "debugging", "introspection", "pretty-print", "python-datamodel" ]
So what I'm looking for here is something like [PHP's print\_r](http://us2.php.net/print_r) function. This is so I can debug my scripts by seeing what's the state of the object in question.
Might be worth checking out -- [Is there a Python equivalent to Perl's Data::Dumper?](http://stackoverflow.com/questions/2540567/is-there-a-python-equivalent-to-perls-datadumper) My recommendation is this -- <https://gist.github.com/1071857> Note that perl has a module called Data::Dumper which translates object data back to perl source code (NB: it does NOT translate code back to source, and almost always you don't want to the object method functions in the output). This can be used for persistence, but the common purpose is for debugging. There are a number of things standard python pprint fails to achieve, in particular it just stops descending when it sees an instance of an object and gives you the internal hex pointer of the object (errr, that pointer is not a whole lot of use by the way). So in a nutshell, python is all about this great object oriented paradigm, but the tools you get out of the box are designed for working with something other than objects. The perl Data::Dumper allows you to control how deep you want to go, and also detects circular linked structures (that's really important). This process is fundamentally easier to achieve in perl because objects have no particular magic beyond their blessing (a universally well defined process).
How do I log an exception at warning- or info-level with trace back using the python logging framework?
192,261
24
2008-10-10T17:02:08Z
193,153
32
2008-10-10T21:49:50Z
[ "python", "exception", "logging" ]
Using something like this: ``` try: #Something... except BaseException, excep: logger = logging.getLogger("componet") logger.warning("something raised an exception: " + excep) logger.info("something raised an exception: " + excep) ``` I would rather not have it on the error-level cause in my special case it is not an error. At least not in that python-process.
From The [logging documentation](http://docs.python.org/library/logging.html#logging.Logger.debug): > There are two keyword arguments in > kwargs which are inspected: exc\_info > which, if it does not evaluate as > false, causes exception information to > be added to the logging message. If an > exception tuple (in the format > returned by sys.exc\_info()) is > provided, it is used; otherwise, > sys.exc\_info() is called to get the > exception information. So do: ``` logger.warning("something raised an exception: " + excep,exc_info=True) ```
In Django how do I notify a parent when a child is saved in a foreign key relationship?
192,367
14
2008-10-10T17:27:35Z
192,525
17
2008-10-10T18:18:56Z
[ "python", "django", "django-models" ]
I have the following two models: ``` class Activity(models.Model): name = models.CharField(max_length=50, help_text='Some help.') entity = models.ForeignKey(CancellationEntity) ... class Cancellation(models.Model): activity = models.ForeignKey(Activity) date = models.DateField(default=datetime.now().date()) description = models.CharField(max_length=250) ... ``` I would like the Activity model to be aware when a Cancellation related to it is saved (both inserted or updated). What is the best way to go about this? Thanks in advance.
What you want to look into is [Django's signals](http://docs.djangoproject.com/en/dev/ref/signals/) (check out [this page](http://docs.djangoproject.com/en/dev/topics/signals/) too), specifically the model signals--more specifically, the **post\_save** signal. Signals are Django's version of a plugin/hook system. The post\_save signal gets sent every time a model is saved, whether it's updated or created (and it'll let you know if it was created). This is how you'd use signals to get notified when an Activity has a Cancellation ``` from django.db.models.signals import post_save class Activity(models.Model): name = models.CharField(max_length=50, help_text='Some help.') entity = models.ForeignKey(CancellationEntity) @classmethod def cancellation_occurred (sender, instance, created, raw): # grab the current instance of Activity self = instance.activity_set.all()[0] # do something ... class Cancellation(models.Model): activity = models.ForeignKey(Activity) date = models.DateField(default=datetime.now().date()) description = models.CharField(max_length=250) ... post_save.connect(Activity.cancellation_occurred, sender=Cancellation) ```
TFS Webservice Documentation
192,579
11
2008-10-10T18:36:02Z
192,792
13
2008-10-10T19:43:39Z
[ "python", "web-services", "api", "tfs" ]
We use a lot of of python to do much of our deployment and would be handy to connect to our TFS server to get information on iteration paths, tickets etc. I can see the webservice but unable to find any documentation. Just wondering if anyone knew of anything?
The web services are not documented by Microsoft as it is not an officially supported route to talk to TFS. The officially supported route is to use their [.NET API](http://msdn.microsoft.com/en-us/library/bb130146(VS.80).aspx). In the case of your sort of application, the course of action I usually recommend is to create your own web service shim that lives on the TFS server (or another server) and uses their API to talk to the server but allows you to present the data in a nice way to your application. Their object model simplifies the interactions a great deal (depending on what you want to do) and so it actually means less code over-all - but better tested and testable code and also you can work around things such as the NTLM auth used by the TFS web services. Hope that helps, Martin.
Can you monkey patch methods on core types in python?
192,649
39
2008-10-10T18:56:12Z
192,703
33
2008-10-10T19:15:42Z
[ "python", "ruby", "programming-languages", "fluent-interface" ]
Ruby can add methods to the Number class and other core types to get effects like: ``` 1.should_equal(1) ``` But it seems like python cannot do this. Is this true? And if so, why? Does it have something to do with the fact that *type* can't be modified? *Update: Rather than talking about different definitions of monkey patching, I would like to just focus on the example above. I have already concluded that it cannot be done as a few of you have answered. But I would like a more detailed explanation of why it cannot be done, and maybe what feature, if available in python, would allow this.* To answer some of you: The reason I *might* want to do this is simply aesthetics/readability. ``` item.price.should_equal(19.99) ``` reads more like English and clearly indicates which is the tested value and which is the expected value, as supposed to: ``` should_equal(item.price, 19.99) ``` This concept is what [Rspec](http://rspec.info/) and some other Ruby frameworks are based on.
What exactly do you mean by Monkey Patch here? There are [several slightly different definitions](http://wikipedia.org/wiki/Monkey_patch). If you mean, "can you change a class's methods at runtime?", then the answer is emphatically yes: ``` class Foo: pass # dummy class Foo.bar = lambda self: 42 x = Foo() print x.bar() ``` If you mean, "can you change a class's methods at runtime and **make all of the instances of that class change after-the-fact**?" then the answer is yes as well. Just change the order slightly: ``` class Foo: pass # dummy class x = Foo() Foo.bar = lambda self: 42 print x.bar() ``` But you can't do this for certain built-in classes, like `int` or `float`. These classes' methods are implemented in C and there are certain abstractions sacrificed in order to make the implementation easier and more efficient. I'm not really clear on **why** you would want to alter the behavior of the built-in numeric classes anyway. If you need to alter their behavior, subclass them!!
Can you monkey patch methods on core types in python?
192,649
39
2008-10-10T18:56:12Z
192,857
55
2008-10-10T20:01:31Z
[ "python", "ruby", "programming-languages", "fluent-interface" ]
Ruby can add methods to the Number class and other core types to get effects like: ``` 1.should_equal(1) ``` But it seems like python cannot do this. Is this true? And if so, why? Does it have something to do with the fact that *type* can't be modified? *Update: Rather than talking about different definitions of monkey patching, I would like to just focus on the example above. I have already concluded that it cannot be done as a few of you have answered. But I would like a more detailed explanation of why it cannot be done, and maybe what feature, if available in python, would allow this.* To answer some of you: The reason I *might* want to do this is simply aesthetics/readability. ``` item.price.should_equal(19.99) ``` reads more like English and clearly indicates which is the tested value and which is the expected value, as supposed to: ``` should_equal(item.price, 19.99) ``` This concept is what [Rspec](http://rspec.info/) and some other Ruby frameworks are based on.
No, you cannot. In Python, all data (classes, methods, functions, etc) defined in C extension modules (including builtins) are immutable. This is because C modules are shared between multiple interpreters in the same process, so monkeypatching them would also affect unrelated interpreters in the same process. However, classes defined in Python code may be monkeypatched because they are local to that interpreter.
Can you monkey patch methods on core types in python?
192,649
39
2008-10-10T18:56:12Z
193,660
13
2008-10-11T04:50:58Z
[ "python", "ruby", "programming-languages", "fluent-interface" ]
Ruby can add methods to the Number class and other core types to get effects like: ``` 1.should_equal(1) ``` But it seems like python cannot do this. Is this true? And if so, why? Does it have something to do with the fact that *type* can't be modified? *Update: Rather than talking about different definitions of monkey patching, I would like to just focus on the example above. I have already concluded that it cannot be done as a few of you have answered. But I would like a more detailed explanation of why it cannot be done, and maybe what feature, if available in python, would allow this.* To answer some of you: The reason I *might* want to do this is simply aesthetics/readability. ``` item.price.should_equal(19.99) ``` reads more like English and clearly indicates which is the tested value and which is the expected value, as supposed to: ``` should_equal(item.price, 19.99) ``` This concept is what [Rspec](http://rspec.info/) and some other Ruby frameworks are based on.
Python's core types are immutable by design, as other users have pointed out: ``` >>> int.frobnicate = lambda self: whatever() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can't set attributes of built-in/extension type 'int' ``` You certainly *could* achieve the effect you describe by making a subclass, since user-defined types in Python are mutable by default. ``` >>> class MyInt(int): ... def frobnicate(self): ... print 'frobnicating %r' % self ... >>> five = MyInt(5) >>> five.frobnicate() frobnicating 5 >>> five + 8 13 ``` There's no need to make the `MyInt` subclass public, either; one could just as well define it inline directly in the function or method that constructs the instance. There are certainly a few situations where Python programmers who are fluent in the idiom consider this sort of subclassing the right thing to do. For instance, `os.stat()` returns a `tuple` subclass that adds named members, precisely in order to address the sort of readability concern you refer to in your example. ``` >>> import os >>> st = os.stat('.') >>> st (16877, 34996226, 65024L, 69, 1000, 1000, 4096, 1223697425, 1223699268, 1223699268) >>> st[6] 4096 >>> st.st_size 4096 ``` That said, in the specific example you give, I don't believe that subclassing `float` in `item.price` (or elsewhere) would be very likely to be considered the Pythonic thing to do. I *can* easily imagine somebody deciding to add a `price_should_equal()` method to `item` if that were the primary use case; if one were looking for something more general, perhaps it might make more sense to use named arguments to make the intended meaning clearer, as in ``` should_equal(observed=item.price, expected=19.99) ``` or something along those lines. It's a bit verbose, but no doubt it could be improved upon. A possible advantage to such an approach over Ruby-style monkey-patching is that `should_equal()` could easily perform its comparison on any type, not just `int` or `float`. But perhaps I'm getting too caught up in the details of the particular example that you happened to provide.
Can you monkey patch methods on core types in python?
192,649
39
2008-10-10T18:56:12Z
4,025,310
20
2010-10-26T15:37:39Z
[ "python", "ruby", "programming-languages", "fluent-interface" ]
Ruby can add methods to the Number class and other core types to get effects like: ``` 1.should_equal(1) ``` But it seems like python cannot do this. Is this true? And if so, why? Does it have something to do with the fact that *type* can't be modified? *Update: Rather than talking about different definitions of monkey patching, I would like to just focus on the example above. I have already concluded that it cannot be done as a few of you have answered. But I would like a more detailed explanation of why it cannot be done, and maybe what feature, if available in python, would allow this.* To answer some of you: The reason I *might* want to do this is simply aesthetics/readability. ``` item.price.should_equal(19.99) ``` reads more like English and clearly indicates which is the tested value and which is the expected value, as supposed to: ``` should_equal(item.price, 19.99) ``` This concept is what [Rspec](http://rspec.info/) and some other Ruby frameworks are based on.
``` def should_equal_def(self, value): if self != value: raise ValueError, "%r should equal %r" % (self, value) class MyPatchedInt(int): should_equal=should_equal_def class MyPatchedStr(str): should_equal=should_equal_def import __builtin__ __builtin__.str = MyPatchedStr __builtin__.int = MyPatchedInt int(1).should_equal(1) str("44").should_equal("44") ``` Have fun ;)
Can you monkey patch methods on core types in python?
192,649
39
2008-10-10T18:56:12Z
17,246,179
17
2013-06-22T00:33:56Z
[ "python", "ruby", "programming-languages", "fluent-interface" ]
Ruby can add methods to the Number class and other core types to get effects like: ``` 1.should_equal(1) ``` But it seems like python cannot do this. Is this true? And if so, why? Does it have something to do with the fact that *type* can't be modified? *Update: Rather than talking about different definitions of monkey patching, I would like to just focus on the example above. I have already concluded that it cannot be done as a few of you have answered. But I would like a more detailed explanation of why it cannot be done, and maybe what feature, if available in python, would allow this.* To answer some of you: The reason I *might* want to do this is simply aesthetics/readability. ``` item.price.should_equal(19.99) ``` reads more like English and clearly indicates which is the tested value and which is the expected value, as supposed to: ``` should_equal(item.price, 19.99) ``` This concept is what [Rspec](http://rspec.info/) and some other Ruby frameworks are based on.
You can do this, but it takes a little bit of hacking. Fortunately, there's a module now called "Forbidden Fruit" that gives you the power to patch methods of built-in types very simply. You can find it at <http://clarete.github.io/forbiddenfruit/?goback=.gde_50788_member_228887816> or <https://pypi.python.org/pypi/forbiddenfruit/0.1.0> With the original question example, after you write the "should\_equal" function, you'd just do ``` from forbiddenfruit import curse curse(int, "should_equal", should_equal) ``` and you're good to go! There's also a "reverse" function to remove a patched method.
XML parsing - ElementTree vs SAX and DOM
192,907
54
2008-10-10T20:22:24Z
192,913
7
2008-10-10T20:25:05Z
[ "python", "xml", "dom", "sax", "elementtree" ]
Python has several ways to parse XML... I understand the very basics of parsing with **SAX**. It functions as a stream parser, with an event-driven API. I understand the **DOM** parser also. It reads the XML into memory and coverts it to objects that can be accessed with Python. Generally speaking, it was easy to choose between the 2 depending on what you needed to do, memory constraints, performance, etc. (hopefully I'm correct so far). Since Python 2.5, we also have **ElementTree**. How does this compare to DOM and SAX? Which is it more similar to? Why is it better than the previous parsers?
ElementTree's parse() is like DOM, whereas iterparse() is like SAX. In my opinion, ElementTree is better than DOM and SAX in that it provides API easier to work with.
XML parsing - ElementTree vs SAX and DOM
192,907
54
2008-10-10T20:22:24Z
194,248
52
2008-10-11T16:02:41Z
[ "python", "xml", "dom", "sax", "elementtree" ]
Python has several ways to parse XML... I understand the very basics of parsing with **SAX**. It functions as a stream parser, with an event-driven API. I understand the **DOM** parser also. It reads the XML into memory and coverts it to objects that can be accessed with Python. Generally speaking, it was easy to choose between the 2 depending on what you needed to do, memory constraints, performance, etc. (hopefully I'm correct so far). Since Python 2.5, we also have **ElementTree**. How does this compare to DOM and SAX? Which is it more similar to? Why is it better than the previous parsers?
ElementTree is much easier to use, because it represents an XML tree (basically) as a structure of lists, and attributes are represented as dictionaries. ElementTree needs much less memory for XML trees than DOM (and thus is faster), and the parsing overhead via `iterparse` is comparable to SAX. Additionally, `iterparse` returns partial structures, and you can keep memory usage constant during parsing by discarding the structures as soon as you process them. ElementTree, as in Python 2.5, has only a small feature set compared to full-blown XML libraries, but it's enough for many applications. If you need a validating parser or complete XPath support, lxml is the way to go. For a long time, it used to be quite unstable, but I haven't had any problems with it since 2.1. ElementTree deviates from DOM, where nodes have access to their parent and siblings. Handling actual documents rather than data stores is also a bit cumbersome, because text nodes aren't treated as actual nodes. In the XML snippet ``` <a>This is <b>a</b> test</a> ``` The string `test` will be the so-called `tail` of element `b`. In general, I recommend ElementTree as the default for all XML processing with Python, and DOM or SAX as the solutions for specific problems.
XML parsing - ElementTree vs SAX and DOM
192,907
54
2008-10-10T20:22:24Z
15,452,402
10
2013-03-16T17:33:15Z
[ "python", "xml", "dom", "sax", "elementtree" ]
Python has several ways to parse XML... I understand the very basics of parsing with **SAX**. It functions as a stream parser, with an event-driven API. I understand the **DOM** parser also. It reads the XML into memory and coverts it to objects that can be accessed with Python. Generally speaking, it was easy to choose between the 2 depending on what you needed to do, memory constraints, performance, etc. (hopefully I'm correct so far). Since Python 2.5, we also have **ElementTree**. How does this compare to DOM and SAX? Which is it more similar to? Why is it better than the previous parsers?
# Minimal DOM implementation: Link: <http://docs.python.org/2/library/xml.dom.minidom.html#module-xml.dom.minidom> Python supplies a full, W3C-standard implementation of XML DOM (*xml.dom*) and a minimal one, *xml.dom.minidom*. This latter one is simpler and smaller than the full implementation. However, from a "parsing perspective", it has all the pros and cons of the standard DOM - i.e. it loads everything in memory. Considering a basic XML file: ``` <?xml version="1.0"?> <catalog> <book isdn="xxx-1"> <author>A1</author> <title>T1</title> </book> <book isdn="xxx-2"> <author>A2</author> <title>T2</title> </book> </catalog> ``` A possible Python parser using *minidom* is: ``` import os from xml.dom import minidom from xml.parsers.expat import ExpatError #-------- Select the XML file: --------# #Current file name and directory: curpath = os.path.dirname( os.path.realpath(__file__) ) filename = os.path.join(curpath, "sample.xml") #print "Filename: %s" % (filename) #-------- Parse the XML file: --------# try: #Parse the given XML file: xmldoc = minidom.parse(filepath) except ExpatError as e: print "[XML] Error (line %d): %d" % (e.lineno, e.code) print "[XML] Offset: %d" % (e.offset) raise e except IOError as e: print "[IO] I/O Error %d: %s" % (e.errno, e.strerror) raise e else: catalog = xmldoc.documentElement books = catalog.getElementsByTagName("book") for book in books: print book.getAttribute('isdn') print book.getElementsByTagName('author')[0].firstChild.data print book.getElementsByTagName('title')[0].firstChild.data ``` Note that *xml.parsers.expat* is a Python interface to the Expat non-validating XML parser (docs.python.org/2/library/pyexpat.html). The *xml.dom* package supplies also the exception class *DOMException*, but it is not supperted in *minidom*! # The ElementTree XML API: Link: <http://docs.python.org/2/library/xml.etree.elementtree.html> *ElementTree* is much easier to use and it requires less memory than XML DOM. Furthermore, a C implementation is available (*xml.etree.cElementTree*). A possible Python parser using *ElementTree* is: ``` import os from xml.etree import cElementTree # C implementation of xml.etree.ElementTree from xml.parsers.expat import ExpatError # XML formatting errors #-------- Select the XML file: --------# #Current file name and directory: curpath = os.path.dirname( os.path.realpath(__file__) ) filename = os.path.join(curpath, "sample.xml") #print "Filename: %s" % (filename) #-------- Parse the XML file: --------# try: #Parse the given XML file: tree = cElementTree.parse(filename) except ExpatError as e: print "[XML] Error (line %d): %d" % (e.lineno, e.code) print "[XML] Offset: %d" % (e.offset) raise e except IOError as e: print "[XML] I/O Error %d: %s" % (e.errno, e.strerror) raise e else: catalogue = tree.getroot() for book in catalogue: print book.attrib.get("isdn") print book.find('author').text print book.find('title').text ```
Standalone Python applications in Linux
193,077
27
2008-10-10T21:26:26Z
193,101
7
2008-10-10T21:34:01Z
[ "python", "linux" ]
How can I distribute a standalone Python application in Linux? I think I can take for granted the presence of a recent Python interpreter in any modern distribution. The problem is dealing with those libraries that do not belong to the standard library, i.e. wxPython, scipy, python cryptographic toolkit, reportlab, and so on. Is there a working Linux counterpart to, say, py2exe (which, by the way, I have never tried)? Is there a free, opensource one?
You can't easily do it in a distribution-neutral format. The only reliable dependency tracking mechanisms are built into the package management systems on the distributions and will vary from distribution to distribution. You'll effectively have to do rpm for fedora, debs for ubuntu and debian etc. Py2exe works fine on Windows. It builds a distribution with all of the necessary DLL's and a wrapper for the python interpreter that starts your program. It's fairly straightforward to install - just drop it in a directory - so making a msi file for it is trivial.
Standalone Python applications in Linux
193,077
27
2008-10-10T21:26:26Z
193,135
9
2008-10-10T21:44:11Z
[ "python", "linux" ]
How can I distribute a standalone Python application in Linux? I think I can take for granted the presence of a recent Python interpreter in any modern distribution. The problem is dealing with those libraries that do not belong to the standard library, i.e. wxPython, scipy, python cryptographic toolkit, reportlab, and so on. Is there a working Linux counterpart to, say, py2exe (which, by the way, I have never tried)? Is there a free, opensource one?
You might want to look at the dependency declarations in [setuptools](http://peak.telecommunity.com/DevCenter/setuptools?action=highlight&value=EasyInstall#declaring-dependencies). This might provide a way to assure that the right packages are either available in the environment or can be installed by someone with appropriate privileges.
Standalone Python applications in Linux
193,077
27
2008-10-10T21:26:26Z
193,963
21
2008-10-11T11:05:10Z
[ "python", "linux" ]
How can I distribute a standalone Python application in Linux? I think I can take for granted the presence of a recent Python interpreter in any modern distribution. The problem is dealing with those libraries that do not belong to the standard library, i.e. wxPython, scipy, python cryptographic toolkit, reportlab, and so on. Is there a working Linux counterpart to, say, py2exe (which, by the way, I have never tried)? Is there a free, opensource one?
Create a deb (for everything Debian-derived) and an rpm (for Fedora/SuSE). Add the right dependencies to the packaging and you can be reasonably sure that it will work.
Standalone Python applications in Linux
193,077
27
2008-10-10T21:26:26Z
909,055
10
2009-05-26T05:32:13Z
[ "python", "linux" ]
How can I distribute a standalone Python application in Linux? I think I can take for granted the presence of a recent Python interpreter in any modern distribution. The problem is dealing with those libraries that do not belong to the standard library, i.e. wxPython, scipy, python cryptographic toolkit, reportlab, and so on. Is there a working Linux counterpart to, say, py2exe (which, by the way, I have never tried)? Is there a free, opensource one?
You can use [cx\_Freeze](http://cx-freeze.sourceforge.net/) to do this. It's just like py2exe (bundles together the interpreter and and startup script and all required libraries and modules), but works on both Linux and Windows. It collects the dependencies from the environment in which it is run, which means that they need to be suitable for the destination as well. If you're doing something like building on 32 bit Debian and deploying on another 32 bit Debian, then that's fine. You can handle 32/64 bit differences by building multiple versions in appropriate environments (e.g. 32 bit and 64 bit chroots) and distributing the appropriate one. If you're wanting something more generic (e.g. build on Debian, deploy on any distribution), then this gets a bit murky, depending on exactly what your dependencies are. If you're doing a fairly straightforward distribution (i.e. you know that your build environment and deploy environments are similar), then this avoids the rather complex rpm/deb/egg/etc step (using cx\_Freeze is very easy, especially if you're familiar with py2exe). If not, then anything from rolling your own dependancy installer to deb/rpm/egg/etc building will work, depending on how much work you want to do, how much flexibility with required versions you want to offer, and what the dependencies are.
What is the best project structure for a Python application?
193,161
405
2008-10-10T21:50:34Z
193,181
212
2008-10-10T22:03:40Z
[ "python", "directory-structure", "project-structure" ]
Imagine that you want to develop a non-trivial end-user desktop (not web) application in Python. What is the best way to structure the project's folder hierarchy? Desirable features are ease of maintenance, IDE-friendliness, suitability for source control branching/merging, and easy generation of install packages. In particular: 1. Where do you put the source? 2. Where do you put application startup scripts? 3. Where do you put the IDE project cruft? 4. Where do you put the unit/acceptance tests? 5. Where do you put non-Python data such as config files? 6. Where do you put non-Python sources such as C++ for pyd/so binary extension modules?
Doesn't too much matter. Whatever makes you happy will work. There aren't a lot of silly rules because Python projects can be simple. * `/scripts` or `/bin` for that kind of command-line interface stuff * `/tests` for your tests * `/lib` for your C-language libraries * `/doc` for most documentation * `/apidoc` for the Epydoc-generated API docs. And the top-level directory can contain README's, Config's and whatnot. The hard choice is whether or not to use a `/src` tree. Python doesn't have a distinction between `/src`, `/lib`, and `/bin` like Java or C has. Since a top-level `/src` directory is seen by some as meaningless, your top-level directory can be the top-level architecture of your application. * `/foo` * `/bar` * `/baz` I recommend putting all of this under the "name-of-my-product" directory. So, if you're writing an application named `quux`, the directory that contains all this stuff is named `/quux`. Another project's `PYTHONPATH`, then, can include `/path/to/quux/foo` to reuse the `QUUX.foo` module. In my case, since I use Komodo Edit, my IDE cuft is a single .KPF file. I actually put that in the top-level `/quux` directory, and omit adding it to SVN.
What is the best project structure for a Python application?
193,161
405
2008-10-10T21:50:34Z
193,280
12
2008-10-10T22:57:39Z
[ "python", "directory-structure", "project-structure" ]
Imagine that you want to develop a non-trivial end-user desktop (not web) application in Python. What is the best way to structure the project's folder hierarchy? Desirable features are ease of maintenance, IDE-friendliness, suitability for source control branching/merging, and easy generation of install packages. In particular: 1. Where do you put the source? 2. Where do you put application startup scripts? 3. Where do you put the IDE project cruft? 4. Where do you put the unit/acceptance tests? 5. Where do you put non-Python data such as config files? 6. Where do you put non-Python sources such as C++ for pyd/so binary extension modules?
In my experience, it's just a matter of iteration. Put your data and code wherever you think they go. Chances are, you'll be wrong anyway. But once you get a better idea of exactly how things are going to shape up, you're in a much better position to make these kinds of guesses. As far as extension sources, we have a Code directory under trunk that contains a directory for python and a directory for various other languages. Personally, I'm more inclined to try putting any extension code into its own repository next time around. With that said, I go back to my initial point: don't make too big a deal out of it. Put it somewhere that seems to work for you. If you find something that doesn't work, it can (and should) be changed.
What is the best project structure for a Python application?
193,161
405
2008-10-10T21:50:34Z
3,419,951
126
2010-08-05T23:29:58Z
[ "python", "directory-structure", "project-structure" ]
Imagine that you want to develop a non-trivial end-user desktop (not web) application in Python. What is the best way to structure the project's folder hierarchy? Desirable features are ease of maintenance, IDE-friendliness, suitability for source control branching/merging, and easy generation of install packages. In particular: 1. Where do you put the source? 2. Where do you put application startup scripts? 3. Where do you put the IDE project cruft? 4. Where do you put the unit/acceptance tests? 5. Where do you put non-Python data such as config files? 6. Where do you put non-Python sources such as C++ for pyd/so binary extension modules?
This [blog post by Jean-Paul Calderone](http://as.ynchrono.us/2007/12/filesystem-structure-of-python-project_21.html) is commonly given as an answer in #python on Freenode. > ## Filesystem structure of a Python project > > Do: > > * name the directory something related to your project. For example, if your project is named "Twisted", name the top-level directory for its source files `Twisted`. When you do releases, you should include a version number suffix: `Twisted-2.5`. > * create a directory `Twisted/bin` and put your executables there, if you have any. Don't give them a `.py` extension, even if they are Python source files. Don't put any code in them except an import of and call to a main function defined somewhere else in your projects. (Slight wrinkle: since on Windows, the interpreter is selected by the file extension, your Windows users actually do want the .py extension. So, when you package for Windows, you may want to add it. Unfortunately there's no easy distutils trick that I know of to automate this process. Considering that on POSIX the .py extension is a only a wart, whereas on Windows the lack is an actual bug, if your userbase includes Windows users, you may want to opt to just have the .py extension everywhere.) > * If your project is expressable as a single Python source file, then put it into the directory and name it something related to your project. For example, `Twisted/twisted.py`. If you need multiple source files, create a package instead (`Twisted/twisted/`, with an empty `Twisted/twisted/__init__.py`) and place your source files in it. For example, `Twisted/twisted/internet.py`. > * put your unit tests in a sub-package of your package (note - this means that the single Python source file option above was a trick - you **always** need at least one other file for your unit tests). For example, `Twisted/twisted/test/`. Of course, make it a package with `Twisted/twisted/test/__init__.py`. Place tests in files like `Twisted/twisted/test/test_internet.py`. > * add `Twisted/README` and `Twisted/setup.py` to explain and install your software, respectively, if you're feeling nice. > > Don't: > > * put your source in a directory called `src` or `lib`. This makes it hard to run without installing. > * put your tests outside of your Python package. This makes it hard to run the tests against an installed version. > * create a package that **only** has a `__init__.py` and then put all your code into `__init__.py`. Just make a module instead of a package, it's simpler. > * try to come up with magical hacks to make Python able to import your module or package without having the user add the directory containing it to their import path (either via PYTHONPATH or some other mechanism). You will **not** correctly handle all cases and users will get angry at you when your software doesn't work in their environment.
What is the best project structure for a Python application?
193,161
405
2008-10-10T21:50:34Z
5,169,006
18
2011-03-02T14:37:19Z
[ "python", "directory-structure", "project-structure" ]
Imagine that you want to develop a non-trivial end-user desktop (not web) application in Python. What is the best way to structure the project's folder hierarchy? Desirable features are ease of maintenance, IDE-friendliness, suitability for source control branching/merging, and easy generation of install packages. In particular: 1. Where do you put the source? 2. Where do you put application startup scripts? 3. Where do you put the IDE project cruft? 4. Where do you put the unit/acceptance tests? 5. Where do you put non-Python data such as config files? 6. Where do you put non-Python sources such as C++ for pyd/so binary extension modules?
It's worth reading through Python's documentation on packaging, too. <http://docs.python.org/tutorial/modules.html#packages> Also make sure you're familiar with the rest of the information on that page.
What is the best project structure for a Python application?
193,161
405
2008-10-10T21:50:34Z
5,998,845
146
2011-05-13T23:49:13Z
[ "python", "directory-structure", "project-structure" ]
Imagine that you want to develop a non-trivial end-user desktop (not web) application in Python. What is the best way to structure the project's folder hierarchy? Desirable features are ease of maintenance, IDE-friendliness, suitability for source control branching/merging, and easy generation of install packages. In particular: 1. Where do you put the source? 2. Where do you put application startup scripts? 3. Where do you put the IDE project cruft? 4. Where do you put the unit/acceptance tests? 5. Where do you put non-Python data such as config files? 6. Where do you put non-Python sources such as C++ for pyd/so binary extension modules?
According to Jean-Paul Calderone's [Filesystem structure of a Python project](http://as.ynchrono.us/2007/12/filesystem-structure-of-python-project_21.html): ``` Project/ |-- bin/ | |-- project | |-- project/ | |-- test/ | | |-- __init__.py | | |-- test_main.py | | | |-- __init__.py | |-- main.py | |-- setup.py |-- README ```
What is the best project structure for a Python application?
193,161
405
2008-10-10T21:50:34Z
19,871,661
69
2013-11-09T02:22:39Z
[ "python", "directory-structure", "project-structure" ]
Imagine that you want to develop a non-trivial end-user desktop (not web) application in Python. What is the best way to structure the project's folder hierarchy? Desirable features are ease of maintenance, IDE-friendliness, suitability for source control branching/merging, and easy generation of install packages. In particular: 1. Where do you put the source? 2. Where do you put application startup scripts? 3. Where do you put the IDE project cruft? 4. Where do you put the unit/acceptance tests? 5. Where do you put non-Python data such as config files? 6. Where do you put non-Python sources such as C++ for pyd/so binary extension modules?
Check out [Open Sourcing a Python Project the Right Way](http://www.jeffknupp.com/blog/2013/08/16/open-sourcing-a-python-project-the-right-way/). Let me excerpt the *project layout* part of that excellent article: > When setting up a project, the layout (or directory structure) is important to get right. A sensible layout means that potential contributors don't have to spend forever hunting for a piece of code; file locations are intuitive. Since we're dealing with an existing project, it means you'll probably need to move some stuff around. > > Let's start at the top. Most projects have a number of top-level files (like setup.py, README.md, requirements.txt, etc). There are then three directories that every project should have: > > * A docs directory containing project documentation > * A directory named with the project's name which stores the actual Python package > * A test directory in one of two places > + Under the package directory containing test code and resources > + As a stand-alone top level directory > To get a better sense of how your files should be organized, here's a simplified snapshot of the layout for one of my projects, sandman: ``` $ pwd ~/code/sandman $ tree . |- LICENSE |- README.md |- TODO.md |- docs | |-- conf.py | |-- generated | |-- index.rst | |-- installation.rst | |-- modules.rst | |-- quickstart.rst | |-- sandman.rst |- requirements.txt |- sandman | |-- __init__.py | |-- exception.py | |-- model.py | |-- sandman.py | |-- test | |-- models.py | |-- test_sandman.py |- setup.py ``` > As you can see, there are some top level files, a docs directory (generated is an empty directory where sphinx will put the generated documentation), a sandman directory, and a test directory under sandman.
What is the best project structure for a Python application?
193,161
405
2008-10-10T21:50:34Z
22,554,594
11
2014-03-21T09:17:46Z
[ "python", "directory-structure", "project-structure" ]
Imagine that you want to develop a non-trivial end-user desktop (not web) application in Python. What is the best way to structure the project's folder hierarchy? Desirable features are ease of maintenance, IDE-friendliness, suitability for source control branching/merging, and easy generation of install packages. In particular: 1. Where do you put the source? 2. Where do you put application startup scripts? 3. Where do you put the IDE project cruft? 4. Where do you put the unit/acceptance tests? 5. Where do you put non-Python data such as config files? 6. Where do you put non-Python sources such as C++ for pyd/so binary extension modules?
Try starting the project using the [python\_boilerplate](https://pypi.python.org/pypi/python_boilerplate_template) template. It largely follows the best practices (e.g. [those here](http://www.jeffknupp.com/blog/2013/08/16/open-sourcing-a-python-project-the-right-way/)), but is better suited in case you find yourself willing to split your project into more than one egg at some point (and believe me, with anything but the simplest projects, you will. One common situation is where you have to use a locally-modified version of someone else's library). * **Where do you put the source?** + For decently large projects it makes sense to split the source into several eggs. Each egg would go as a separate setuptools-layout under `PROJECT_ROOT/src/<egg_name>`. * **Where do you put application startup scripts?** + The ideal option is to have application startup script registered as an `entry_point` in one of the eggs. * **Where do you put the IDE project cruft?** + Depends on the IDE. Many of them keep their stuff in `PROJECT_ROOT/.<something>` in the root of the project, and this is fine. * **Where do you put the unit/acceptance tests?** + Each egg has a separate set of tests, kept in its `PROJECT_ROOT/src/<egg_name>/tests` directory. I personally prefer to use `py.test` to run them. * **Where do you put non-Python data such as config files?** + It depends. There can be different types of non-Python data. - *"Resources"*, i.e. data that must be packaged within an egg. This data goes into the corresponding egg directory, somewhere within package namespace. It can be used via `pkg_resources` package. - *"Config-files"*, i.e. non-Python files that are to be regarded as external to the project source files, but have to be initialized with some values when application starts running. During development I prefer to keep such files in `PROJECT_ROOT/config`. For deployment there can be various options. On Windows one can use `%APP_DATA%/<app-name>/config`, on Linux, `/etc/<app-name>` or `/opt/<app-name>/config`. - *Generated files*, i.e. files that may be created or modified by the application during execution. I would prefer to keep them in `PROJECT_ROOT/var` during development, and under `/var` during Linux deployment. * **Where do you put non-Python sources such as C++ for pyd/so binary extension modules?** + Into `PROJECT_ROOT/src/<egg_name>/native` Documentation would typically go into `PROJECT_ROOT/doc` or `PROJECT_ROOT/src/<egg_name>/doc` (this depends on whether you regard some of the eggs to be a separate large projects). Some additional configuration will be in files like `PROJECT_ROOT/buildout.cfg` and `PROJECT_ROOT/setup.cfg`.
Microphone access in Python
193,789
10
2008-10-11T07:06:48Z
247,349
16
2008-10-29T15:53:36Z
[ "python", "windows", "microphone" ]
Can I access a users microphone in Python? Sorry I forgot not everyone is a mind reader: Windows at minimum XP but Vista support would be VERY good.
I got the job done with [pyaudio](http://people.csail.mit.edu/hubert/pyaudio/) It comes with a binary installer for windows and there's even an example on how to record through the microphone and save to a wave file. Nice! I used it on Windows XP, not sure how it will do on Vista though, sorry.
What are good rules of thumb for Python imports?
193,919
60
2008-10-11T09:59:35Z
193,927
9
2008-10-11T10:10:13Z
[ "python", "python-import" ]
I am a little confused by the multitude of ways in which you can import modules in Python. ``` import X import X as Y from A import B ``` I have been reading up about scoping and namespaces, but I would like some practical advice on what is the best strategy, under which circumstances and why. Should imports happen at a module level or a method/function level? In the `__init__.py` or in the module code itself? My question is not really answered by "[Python packages - import by class, not file](http://stackoverflow.com/questions/45122/python-packages-import-by-class-not-file)" although it is obviously related.
I would normally use `import X` on module level. If you only need a single object from a module, use `from X import Y`. Only use `import X as Y` in case you're otherwise confronted with a name clash. I only use imports on function level to import stuff I need when the module is used as the main module, like: ``` def main(): import sys if len(sys.argv) > 1: pass ``` HTH
What are good rules of thumb for Python imports?
193,919
60
2008-10-11T09:59:35Z
193,931
52
2008-10-11T10:15:40Z
[ "python", "python-import" ]
I am a little confused by the multitude of ways in which you can import modules in Python. ``` import X import X as Y from A import B ``` I have been reading up about scoping and namespaces, but I would like some practical advice on what is the best strategy, under which circumstances and why. Should imports happen at a module level or a method/function level? In the `__init__.py` or in the module code itself? My question is not really answered by "[Python packages - import by class, not file](http://stackoverflow.com/questions/45122/python-packages-import-by-class-not-file)" although it is obviously related.
In production code in our company, we try to follow the following rules. We place imports at the beginning of the file, right after the main file's docstring, e.g.: ``` """ Registry related functionality. """ import wx # ... ``` Now, if we import a class that is one of few in the imported module, we import the name directly, so that in the code we only have to use the last part, e.g.: ``` from RegistryController import RegistryController from ui.windows.lists import ListCtrl, DynamicListCtrl ``` There are modules, however, that contain dozens of classes, e.g. list of all possible exceptions. Then we import the module itself and reference to it in the code: ``` from main.core import Exceptions # ... raise Exceptions.FileNotFound() ``` We use the `import X as Y` as rarely as possible, because it makes searching for usage of a particular module or class difficult. Sometimes, however, you have to use it if you wish to import two classes that have the same name, but exist in different modules, e.g.: ``` from Queue import Queue from main.core.MessageQueue import Queue as MessageQueue ``` As a general rule, we don't do imports inside methods -- they simply make code slower and less readable. Some may find this a good way to easily resolve cyclic imports problem, but a better solution is code reorganization.
What are good rules of thumb for Python imports?
193,919
60
2008-10-11T09:59:35Z
194,422
30
2008-10-11T18:34:42Z
[ "python", "python-import" ]
I am a little confused by the multitude of ways in which you can import modules in Python. ``` import X import X as Y from A import B ``` I have been reading up about scoping and namespaces, but I would like some practical advice on what is the best strategy, under which circumstances and why. Should imports happen at a module level or a method/function level? In the `__init__.py` or in the module code itself? My question is not really answered by "[Python packages - import by class, not file](http://stackoverflow.com/questions/45122/python-packages-import-by-class-not-file)" although it is obviously related.
Let me just paste a part of conversation on django-dev mailing list started by Guido van Rossum: > [...] > For example, it's part of the Google Python style guides[1] that all > imports must import a module, not a class or function from that > module. There are way more classes and functions than there are > modules, so recalling where a particular thing comes from is much > easier if it is prefixed with a module name. Often multiple modules > happen to define things with the same name -- so a reader of the code > doesn't have to go back to the top of the file to see from which > module a given name is imported. **Source:** <http://groups.google.com/group/django-developers/browse_thread/thread/78975372cdfb7d1a> 1: <http://code.google.com/p/soc/wiki/PythonStyleGuide#Module_and_package_imports>
Running a web app in Grails vs Django
195,101
5
2008-10-12T04:36:49Z
195,152
9
2008-10-12T06:23:56Z
[ "python", "django", "grails", "groovy", "web-applications" ]
I'm currently in the planning stage for a web application and I find myself trying to decide on using Grails or Django. From an operation perspective: 1. Which ecosystem is easier to maintain (migrations, backup, disaster recovery etc.)? If using grails it'll probably be a typical tomcat + mysql on linux. If django it'll be apache + mysql on linux. 2. Does django or grails have a better choice of cheap and flexible hosting? Initially it'll probably be low bandwidth requirements. I'm not sure about the exact specs required, but from what I've been reading it seems like django would require far less server resources (even 256MB server is ok) than grails.
You can run grails in 256 megs of ram. Many members of the community are doing so. That being said I would say in either platform you want much more ram than that to make sure your performant. But I might also reccomend checking out www.linode.com. You can get quality hosting for a very reasonable cost and adding a bit of ram for grails will not break your budget. Also if your interested in cloud based solutions Morph is hosting grails apps. <http://developer.mor.ph/grails> I like Django, but I for the maturity of the platform and the amount of quality Java work out there in terms of libaries and frameworks I chose grails. In truth I think they are both good solutions but you cannot deny that your options are much greater with grails.
Running compiled python (py2exe) as administrator in Vista
195,109
7
2008-10-12T04:46:16Z
1,445,547
34
2009-09-18T16:15:43Z
[ "python", "windows-vista", "permissions", "py2exe" ]
Is it possible to programaticly run compiled Python (comiled via py2exe) as administrator in Vista? Some more clarification: I have written a program that modifies the windows hosts file (c:\Windows\system32\drivers\etc\hosts) in Vista the program will not run and will fail with an exception unless you right-click and run as administrator even when the user has administrator privileges, unlike in XP where it will run if the user has administration rights, so I need a way to elevate it to the correct privileges programaticly.
Following the examples from `Python2x\Lib\site-packages\py2exe\samples\user_access_control` just add `uac_info="requireAdministrator"` to console or windows dict: ``` windows = [{ 'script': "admin.py", 'uac_info': "requireAdministrator", },] ```
Python Decimal
195,116
13
2008-10-12T05:03:05Z
195,124
10
2008-10-12T05:11:37Z
[ "python" ]
Does anyone know of a faster decimal implementation in python. As example below demonstrates, standard python decimal is ~100 times slower than float. ``` from timeit import Timer def run(val, the_class): test = the_class(1) for c in xrange(10000): d = the_class(val) d + test d - test d * test d / test d ** test str(d) abs(d) if __name__ == "__main__": a = Timer("run(123.345, float)", "from decimal_benchmark import run") print "FLOAT", a.timeit(1) a = Timer("run('123.345', Decimal)", "from decimal_benchmark import run; from decimal import Decimal") print "DECIMAL", a.timeit(1) FLOAT 0.040635041427 DECIMAL 3.39666790146 ``` Thanks, Maksim
The [GMP](http://gmplib.org) library is one of the best arbitrary precision math libraries around, and there is a Python binding available at [GMPY](http://www.aleax.it/gmpy.html). I would try that method.
Python Decimal
195,116
13
2008-10-12T05:03:05Z
8,192,918
20
2011-11-19T08:47:41Z
[ "python" ]
Does anyone know of a faster decimal implementation in python. As example below demonstrates, standard python decimal is ~100 times slower than float. ``` from timeit import Timer def run(val, the_class): test = the_class(1) for c in xrange(10000): d = the_class(val) d + test d - test d * test d / test d ** test str(d) abs(d) if __name__ == "__main__": a = Timer("run(123.345, float)", "from decimal_benchmark import run") print "FLOAT", a.timeit(1) a = Timer("run('123.345', Decimal)", "from decimal_benchmark import run; from decimal import Decimal") print "DECIMAL", a.timeit(1) FLOAT 0.040635041427 DECIMAL 3.39666790146 ``` Thanks, Maksim
You can try [cdecimal](http://www.bytereef.org/mpdecimal/index.html): ``` from cdecimal import Decimal ```
In production, Apache + mod_wsgi or Nginx + mod_wsgi?
195,534
56
2008-10-12T14:14:19Z
196,039
7
2008-10-12T20:45:41Z
[ "python", "apache", "nginx", "mod-wsgi" ]
What to use for a medium to large python WSGI application, Apache + mod\_wsgi or Nginx + mod\_wsgi? Which combination will need more memory and CPU time? Which one is faster? Which is known for being more stable than the other? I am also thinking to use CherryPy's WSGI server but I hear it's not very suitable for a very high-load application, what do you know about this? ***Note***: I didn't use any Python Web Framework, I just wrote the whole thing from scratch. ***Note'***: Other suggestions are also welcome.
One thing that CherryPy's webserver has going for it is that it's a pure python webserver (AFAIK), which may or may not make deployment easier for you. Plus, I could see the benefits of using it if you're just using a server for WSGI and static content. (shameless plug warning: I wrote the WSGI code that I'm about to mention) [Kamaelia](http://www.kamaelia.org/Home) will have WSGI support coming in the next release. The cool thing is that you'll likely be able to either use the pre-made one or build your own using the existing HTTP and WSGI code. (end shameless plug) With that said, given the current options, I would personally probably go with CherryPy because it seems to be the simplest to configure and I can understand python code moreso than I can understand C code. You may do best to try each of them out and see what the pros and cons of each one are for your specific application though.
In production, Apache + mod_wsgi or Nginx + mod_wsgi?
195,534
56
2008-10-12T14:14:19Z
196,580
13
2008-10-13T02:44:24Z
[ "python", "apache", "nginx", "mod-wsgi" ]
What to use for a medium to large python WSGI application, Apache + mod\_wsgi or Nginx + mod\_wsgi? Which combination will need more memory and CPU time? Which one is faster? Which is known for being more stable than the other? I am also thinking to use CherryPy's WSGI server but I hear it's not very suitable for a very high-load application, what do you know about this? ***Note***: I didn't use any Python Web Framework, I just wrote the whole thing from scratch. ***Note'***: Other suggestions are also welcome.
The main difference is that nginx is built to handle large numbers of connections in a much smaller memory space. This makes it very well suited for apps that are doing comet like connections that can have many idle open connections. This also gives it quite a smaller memory foot print. From a raw performance perspective, nginx is faster, but not so much faster that I would include that as a determining factor. Apache has the advantage in the area of modules available, and the fact that it is pretty much standard. Any web host you go with will have it installed, and most techs are going to be very familiar with it. Also, if you use mod\_wsgi, it is your wsgi server so you don't even need cherrypy. Other than that, the best advice I can give is try setting up your app under both and do some benchmarking, since no matter what any one tells you, your mileage may vary.
In production, Apache + mod_wsgi or Nginx + mod_wsgi?
195,534
56
2008-10-12T14:14:19Z
409,017
16
2009-01-03T13:04:18Z
[ "python", "apache", "nginx", "mod-wsgi" ]
What to use for a medium to large python WSGI application, Apache + mod\_wsgi or Nginx + mod\_wsgi? Which combination will need more memory and CPU time? Which one is faster? Which is known for being more stable than the other? I am also thinking to use CherryPy's WSGI server but I hear it's not very suitable for a very high-load application, what do you know about this? ***Note***: I didn't use any Python Web Framework, I just wrote the whole thing from scratch. ***Note'***: Other suggestions are also welcome.
The author of nginx mod\_wsgi explains some differences to Apache mod\_wsgi [in this mailing list message](http://osdir.com/ml/web.nginx.english/2008-05/msg00451.html).
In production, Apache + mod_wsgi or Nginx + mod_wsgi?
195,534
56
2008-10-12T14:14:19Z
1,038,043
67
2009-06-24T12:26:01Z
[ "python", "apache", "nginx", "mod-wsgi" ]
What to use for a medium to large python WSGI application, Apache + mod\_wsgi or Nginx + mod\_wsgi? Which combination will need more memory and CPU time? Which one is faster? Which is known for being more stable than the other? I am also thinking to use CherryPy's WSGI server but I hear it's not very suitable for a very high-load application, what do you know about this? ***Note***: I didn't use any Python Web Framework, I just wrote the whole thing from scratch. ***Note'***: Other suggestions are also welcome.
For nginx/mod\_wsgi, ensure you read: <http://blog.dscpl.com.au/2009/05/blocking-requests-and-nginx-version-of.html> Because of how nginx is an event driven system underneath, it has behavioural characteristics which are detrimental to blocking applications such as is the case with WSGI based applications. Worse case scenario is that with multiprocess nginx configuration, you can see user requests be blocked even though some nginx worker processes may be idle. Apache/mod\_wsgi doesn't have this issue as Apache processes will only accept requests when it has the resources to actually handle the request. Apache/mod\_wsgi will thus give more predictable and reliable behaviour.
What is the time complexity of popping elements from list in Python?
195,625
16
2008-10-12T15:58:59Z
195,647
13
2008-10-12T16:15:39Z
[ "python" ]
I wonder what is the time complexity of pop method of list objects in Python (in CPython particulary). Also does the value of N for list.pop(N) affects the complexity?
Pop() for the last element ought to be O(1) since you only need to return the element referred to by the last element in the array and update the index of the last element. I would expect pop(N) to be O(N) and require on average N/2 operations since you would need to move any elements beyond the Nth one, one position up in the array of pointers.
What is the time complexity of popping elements from list in Python?
195,625
16
2008-10-12T15:58:59Z
195,839
23
2008-10-12T18:47:42Z
[ "python" ]
I wonder what is the time complexity of pop method of list objects in Python (in CPython particulary). Also does the value of N for list.pop(N) affects the complexity?
Yes, it is O(1) to pop the last element of a Python list, and O(N) to pop an arbitrary element (since the whole rest of the list has to be shifted). Here's a great article on how Python lists are stored and manipulated: <http://effbot.org/zone/python-list.htm>
How to avoid computation every time a python module is reloaded
195,626
6
2008-10-12T15:59:48Z
195,962
17
2008-10-12T20:12:25Z
[ "python", "nltk" ]
I have a python module that makes use of a huge dictionary global variable, currently I put the computation code in the top section, every first time import or reload of the module takes more then one minute which is totally unacceptable. How can I save the computation result somewhere so that the next import/reload doesn't have to compute it? I tried cPickle, but loading the dictionary variable from a file(1.3M) takes approximately the same time as computation. To give more information about my problem, ``` FD = FreqDist(word for word in brown.words()) # this line of code takes 1 min ```
Just to clarify: the code in the body of a module is *not* executed every time the module is imported - it is run only once, after which future imports find the already created module, rather than recreating it. Take a look at sys.modules to see the list of cached modules. However, if your problem is the time it takes for the first import after the program is run, you'll probably need to use some other method than a python dict. Probably best would be to use an on-disk form, for instance a sqlite database, one of the dbm modules. For a minimal change in your interface, the shelve module may be your best option - this puts a pretty transparent interface between the dbm modules that makes them act like an arbitrary python dict, allowing any picklable value to be stored. Here's an example: ``` # Create dict with a million items: import shelve d = shelve.open('path/to/my_persistant_dict') d.update(('key%d' % x, x) for x in xrange(1000000)) d.close() ``` Then in the next process, use it. There should be no large delay, as lookups are only performed for the key requested on the on-disk form, so everything doesn't have to get loaded into memory: ``` >>> d = shelve.open('path/to/my_persistant_dict') >>> print d['key99999'] 99999 ``` It's a bit slower than a real dict, and it **will** still take a long time to load if you do something that requires all the keys (eg. try to print it), but may solve your problem.
How to check if a string in Python is in ASCII?
196,345
120
2008-10-13T00:13:40Z
196,391
189
2008-10-13T00:30:32Z
[ "python", "string", "unicode", "ascii" ]
I want to I check whether a string is in ASCII or not. I am aware of `ord()`, however when I try `ord('é')`, I have `TypeError: ord() expected a character, but string of length 2 found`. I understood it is caused by the way I built Python (as explained in [`ord()`'s documentation](http://docs.python.org/library/functions.html#ord)). Is there another way to check?
I think you are not asking the right question-- A string in python has no property corresponding to 'ascii', utf-8, or any other encoding. The source of your string (whether you read it from a file, input from a keyboard, etc.) may have encoded a unicode string in ascii to produce your string, but that's where you need to go for an answer. Perhaps the question you can ask is: "Is this string the result of encoding a unicode string in ascii?" -- This you can answer by trying: ``` try: mystring.decode('ascii') except UnicodeDecodeError: print "it was not a ascii-encoded unicode string" else: print "It may have been an ascii-encoded unicode string" ```
How to check if a string in Python is in ASCII?
196,345
120
2008-10-13T00:13:40Z
196,392
78
2008-10-13T00:30:43Z
[ "python", "string", "unicode", "ascii" ]
I want to I check whether a string is in ASCII or not. I am aware of `ord()`, however when I try `ord('é')`, I have `TypeError: ord() expected a character, but string of length 2 found`. I understood it is caused by the way I built Python (as explained in [`ord()`'s documentation](http://docs.python.org/library/functions.html#ord)). Is there another way to check?
``` def is_ascii(s): return all(ord(c) < 128 for c in s) ```
How to check if a string in Python is in ASCII?
196,345
120
2008-10-13T00:13:40Z
198,205
10
2008-10-13T16:38:25Z
[ "python", "string", "unicode", "ascii" ]
I want to I check whether a string is in ASCII or not. I am aware of `ord()`, however when I try `ord('é')`, I have `TypeError: ord() expected a character, but string of length 2 found`. I understood it is caused by the way I built Python (as explained in [`ord()`'s documentation](http://docs.python.org/library/functions.html#ord)). Is there another way to check?
How about doing this? ``` import string def isAscii(s): for c in s: if c not in string.ascii_letters: return False return True ```
How to check if a string in Python is in ASCII?
196,345
120
2008-10-13T00:13:40Z
200,267
16
2008-10-14T07:36:59Z
[ "python", "string", "unicode", "ascii" ]
I want to I check whether a string is in ASCII or not. I am aware of `ord()`, however when I try `ord('é')`, I have `TypeError: ord() expected a character, but string of length 2 found`. I understood it is caused by the way I built Python (as explained in [`ord()`'s documentation](http://docs.python.org/library/functions.html#ord)). Is there another way to check?
Your question is incorrect; the error you see is not a result of how you built python, but of a confusion between byte strings and unicode strings. Byte strings (e.g. "foo", or 'bar', in python syntax) are sequences of octets; numbers from 0-255. Unicode strings (e.g. u"foo" or u'bar') are sequences of unicode code points; numbers from 0-1112064. But you appear to be interested in the character é, which (in your terminal) is a multi-byte sequence that represents a single character. Instead of `ord(u'é')`, try this: ``` >>> [ord(x) for x in u'é'] ``` That tells you which sequence of code points "é" represents. It may give you [233], or it may give you [101, 770]. Instead of `chr()` to reverse this, there is `unichr()`: ``` >>> unichr(233) u'\xe9' ``` This character may actually be represented either a single or multiple unicode "code points", which themselves represent either graphemes or characters. It's either "e with an acute accent (i.e., code point 233)", or "e" (code point 101), followed by "an acute accent on the previous character" (code point 770). So this exact same character may be presented as the Python data structure `u'e\u0301'` or `u'\u00e9'`. Most of the time you shouldn't have to care about this, but it can become an issue if you are iterating over a unicode string, as iteration works by code point, not by decomposable character. In other words, `len(u'e\u0301') == 2` and `len(u'\u00e9') == 1`. If this matters to you, you can convert between composed and decomposed forms by using [`unicodedata.normalize`](http://docs.python.org/library/unicodedata.html#unicodedata.normalize). [The Unicode Glossary](http://unicode.org/glossary/) can be a helpful guide to understanding some of these issues, by pointing how how each specific term refers to a different part of the representation of text, which is far more complicated than many programmers realize.
How to check if a string in Python is in ASCII?
196,345
120
2008-10-13T00:13:40Z
6,988,354
16
2011-08-08T20:47:22Z
[ "python", "string", "unicode", "ascii" ]
I want to I check whether a string is in ASCII or not. I am aware of `ord()`, however when I try `ord('é')`, I have `TypeError: ord() expected a character, but string of length 2 found`. I understood it is caused by the way I built Python (as explained in [`ord()`'s documentation](http://docs.python.org/library/functions.html#ord)). Is there another way to check?
Ran into something like this recently - for future reference ``` import chardet encoding = chardet.detect(string) if encoding['encoding'] == 'ascii': print 'string is in ascii' ``` which you could use with: ``` string_ascii = string.decode(encoding['encoding']).encode('ascii') ```
How to check if a string in Python is in ASCII?
196,345
120
2008-10-13T00:13:40Z
12,064,457
7
2012-08-21T23:24:35Z
[ "python", "string", "unicode", "ascii" ]
I want to I check whether a string is in ASCII or not. I am aware of `ord()`, however when I try `ord('é')`, I have `TypeError: ord() expected a character, but string of length 2 found`. I understood it is caused by the way I built Python (as explained in [`ord()`'s documentation](http://docs.python.org/library/functions.html#ord)). Is there another way to check?
I found this question while trying determine how to use/encode/decode a string whose encoding I wasn't sure of (and how to escape/convert special characters in that string). My first step should have been to check the type of the string- I didn't realize there I could get good data about its formatting from type(s). [This answer was very helpful and got to the real root of my issues.](http://stackoverflow.com/a/4987367/727541) If you're getting a rude and persistent > UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 263: ordinal not in range(128) particularly when you're ENCODING, make sure you're not trying to unicode() a string that already IS unicode- for some terrible reason, you get ascii codec errors. (See also the [Python Kitchen recipe](http://packages.python.org/kitchen/unicode-frustrations.html), and the [Python docs](http://docs.python.org/howto/unicode.html) tutorials for better understanding of how terrible this can be.) Eventually I determined that what I wanted to do was this: ``` escaped_string = unicode(original_string.encode('ascii','xmlcharrefreplace')) ``` Also helpful in debugging was setting the default coding in my file to utf-8 (put this at the beginning of your python file): ``` # -*- coding: utf-8 -*- ``` That allows you to test special characters ('àéç') without having to use their unicode escapes (u'\xe0\xe9\xe7'). ``` >>> specials='àéç' >>> specials.decode('latin-1').encode('ascii','xmlcharrefreplace') '&#224;&#233;&#231;' ```
How to check if a string in Python is in ASCII?
196,345
120
2008-10-13T00:13:40Z
18,403,812
31
2013-08-23T13:14:49Z
[ "python", "string", "unicode", "ascii" ]
I want to I check whether a string is in ASCII or not. I am aware of `ord()`, however when I try `ord('é')`, I have `TypeError: ord() expected a character, but string of length 2 found`. I understood it is caused by the way I built Python (as explained in [`ord()`'s documentation](http://docs.python.org/library/functions.html#ord)). Is there another way to check?
Python 3 way: ``` isascii = lambda s: len(s) == len(s.encode()) ```
How do I emulate Python's named printf parameters in Ruby?
196,841
8
2008-10-13T06:25:29Z
12,563,022
14
2012-09-24T10:19:55Z
[ "python", "ruby", "string", "printf" ]
In Python, you can do this: ``` print "Hi! I'm %(name)s, and I'm %(age)d years old." % ({"name":"Brian","age":30}) ``` What's the closest, simplest Ruby idiom to replicate this behavior? (No monkeypatching the String class, please.) **EDIT:** One of the really excellent benefits of this is that you can store the pre-processed string in a variable and use it as a "template", like so: ``` template = "Hi! I'm %(name)s, and I'm %(age)d years old." def greet(template,name,age): print template % ({"name":name,"age":age}) ``` This is obviously a trivial example, but there is a lot of utility in being able to store such a string for later use. Ruby's `"Hi! I'm #{name}"` convention is cursorily similar, but the immediate evaluation makes it less versatile. Please don't downvote answers suggesting the `#{var}` technique, as they came from before this edit. (Random idea kernel: Perhaps answers should be protected from votes if a question author marks them as "outdated"...?)
You can also use ``` printf "1: %<key1>s 2: %<key2>s\n", {:key1 => "value1", :key2 => "value2"} ``` or ``` data = {:key1 => "value1", :key2 => "value2"} printf "1: %<key1>s 2: %<key2>s\n", data ``` or (this needs ruby 1.9, for the other examples I'm not sure) ``` data = {key1: "value1", key2: "value2"} printf "1: %<key1>s 2: %<key2>s\n", data ``` This prints ``` 1: value1 2: value2 ``` Important restriction: The used keys of the hash (*data* in my example) must be symbols. --- A remark on the example above: `printf` takes one format string and optional parameters. But there is also a `String#%`-method. The following four calls have all the same result: ``` printf "1: %<key1>s 2: %<key2>s\n" , {:key1 => "value1", :key2 => "value2"} printf "1: %<key1>s 2: %<key2>s\n" % {:key1 => "value1", :key2 => "value2"} print "1: %<key1>s 2: %<key2>s\n" % {:key1 => "value1", :key2 => "value2"} puts "1: %<key1>s 2: %<key2>s" % {:key1 => "value1", :key2 => "value2"} ``` The second version uses first the `String#%`-method and sends the result to `printf`.
How do I emulate Python's named printf parameters in Ruby?
196,841
8
2008-10-13T06:25:29Z
13,027,855
14
2012-10-23T09:53:41Z
[ "python", "ruby", "string", "printf" ]
In Python, you can do this: ``` print "Hi! I'm %(name)s, and I'm %(age)d years old." % ({"name":"Brian","age":30}) ``` What's the closest, simplest Ruby idiom to replicate this behavior? (No monkeypatching the String class, please.) **EDIT:** One of the really excellent benefits of this is that you can store the pre-processed string in a variable and use it as a "template", like so: ``` template = "Hi! I'm %(name)s, and I'm %(age)d years old." def greet(template,name,age): print template % ({"name":name,"age":age}) ``` This is obviously a trivial example, but there is a lot of utility in being able to store such a string for later use. Ruby's `"Hi! I'm #{name}"` convention is cursorily similar, but the immediate evaluation makes it less versatile. Please don't downvote answers suggesting the `#{var}` technique, as they came from before this edit. (Random idea kernel: Perhaps answers should be protected from votes if a question author marks them as "outdated"...?)
you do it like this: ``` values = {:hello => 'world', :world => 'hello'} puts "%{world} %{hello}" % values ``` Read this for more info: <http://ruby.runpaint.org/strings#sprintf-hash> If you need something more sophisticated, read about ERB, and google template engines. If you need to generate web pages, emails etc. you'll find that using template engines is a more robust solution.
How to ensure user submit only english text
196,924
9
2008-10-13T07:32:12Z
196,950
7
2008-10-13T07:47:57Z
[ "javascript", "python", "nlp" ]
I am building a project involving natural language processing, since the nlp module currently only deal with english text, so I have to make sure the user submitted content (not long, only several words) is in english. Are there established ways to achieve this? Python or Javascript way preferred.
If the content is long enough I would suggest some [frequency analysis](http://en.wikipedia.org/wiki/Frequency_analysis) on the letters. But for a few words I think your best bet is to compare them to an English dictionary and accept the input if half of them match.
How to check if OS is Vista in Python?
196,930
24
2008-10-13T07:35:14Z
196,931
8
2008-10-13T07:35:25Z
[ "python", "windows", "windows-vista", "wxpython", "pywin32" ]
How, in the simplest possible way, distinguish between Windows XP and Windows Vista, using Python and [pywin32](http://python.net/crew/mhammond/win32/Downloads.html) or [wxPython](http://www.wxpython.org/)? Essentially, I need a function that called will return True iff current OS is Vista: ``` >>> isWindowsVista() True ```
The simplest solution I found is this one: ``` import sys def isWindowsVista(): '''Return True iff current OS is Windows Vista.''' if sys.platform != "win32": return False import win32api VER_NT_WORKSTATION = 1 version = win32api.GetVersionEx(1) if not version or len(version) < 9: return False return ((version[0] == 6) and (version[1] == 0) and (version[8] == VER_NT_WORKSTATION)) ```
How to check if OS is Vista in Python?
196,930
24
2008-10-13T07:35:14Z
196,962
8
2008-10-13T07:55:47Z
[ "python", "windows", "windows-vista", "wxpython", "pywin32" ]
How, in the simplest possible way, distinguish between Windows XP and Windows Vista, using Python and [pywin32](http://python.net/crew/mhammond/win32/Downloads.html) or [wxPython](http://www.wxpython.org/)? Essentially, I need a function that called will return True iff current OS is Vista: ``` >>> isWindowsVista() True ```
The solution used in Twisted, which doesn't need pywin32: ``` def isVista(): if getattr(sys, "getwindowsversion", None) is not None: return sys.getwindowsversion()[0] == 6 else: return False ``` Note that it will also match Windows Server 2008.
How to check if OS is Vista in Python?
196,930
24
2008-10-13T07:35:14Z
200,148
39
2008-10-14T06:10:23Z
[ "python", "windows", "windows-vista", "wxpython", "pywin32" ]
How, in the simplest possible way, distinguish between Windows XP and Windows Vista, using Python and [pywin32](http://python.net/crew/mhammond/win32/Downloads.html) or [wxPython](http://www.wxpython.org/)? Essentially, I need a function that called will return True iff current OS is Vista: ``` >>> isWindowsVista() True ```
Python has the lovely 'platform' module to help you out. ``` >>> import platform >>> platform.win32_ver() ('XP', '5.1.2600', 'SP2', 'Multiprocessor Free') >>> platform.system() 'Windows' >>> platform.version() '5.1.2600' >>> platform.release() 'XP' ``` NOTE: As mentioned in the comments proper values may not be returned when using older versions of python.
Can you list the keyword arguments a Python function receives?
196,960
64
2008-10-13T07:55:18Z
196,978
25
2008-10-13T08:09:15Z
[ "python", "arguments", "introspection" ]
I have a dict, which I need to pass key/values as keyword arguments.. For example.. ``` d_args = {'kw1': 'value1', 'kw2': 'value2'} example(**d_args) ``` This works fine, *but* if there are values in the d\_args dict that are not accepted by the `example` function, it obviously dies.. Say, if the example function is defined as `def example(kw2):` This is a problem since I don't control either the generation of the `d_args`, or the `example` function.. They both come from external modules, and `example` only accepts some of the keyword-arguments from the dict.. Ideally I would just do ``` parsed_kwargs = feedparser.parse(the_url) valid_kwargs = get_valid_kwargs(parsed_kwargs, valid_for = PyRSS2Gen.RSS2) PyRSS2Gen.RSS2(**valid_kwargs) ``` I will probably just filter the dict, from a list of valid keyword-arguments, but I was wondering: **Is there a way to programatically list the keyword arguments the a specific function takes?**
This will print names of all passable arguments, keyword and non-keyword ones: ``` def func(one, two="value"): y = one, two return y print func.func_code.co_varnames[:func.func_code.co_argcount] ``` This is because first `co_varnames` are always parameters (next are local variables, like `y` in the example above). So now you could have a function: ``` def getValidArgs(func, argsDict): '''Return dictionary without invalid function arguments.''' validArgs = func.func_code.co_varnames[:func.func_code.co_argcount] return dict((key, value) for key, value in argsDict.iteritems() if key in validArgs) ``` Which you then could use like this: ``` >>> func(**getValidArgs(func, args)) ``` --- **EDIT**: A small addition: if you **really need only keyword arguments** of a function, you can use the `func_defaults` attribute to extract them: ``` def getValidKwargs(func, argsDict): validArgs = func.func_code.co_varnames[:func.func_code.co_argcount] kwargsLen = len(func.func_defaults) # number of keyword arguments validKwargs = validArgs[-kwargsLen:] # because kwargs are last return dict((key, value) for key, value in argsDict.iteritems() if key in validKwargs) ``` You could now call your function with known args, but extracted kwargs, e.g.: ``` func(param1, param2, **getValidKwargs(func, kwargsDict)) ``` This assumes that `func` uses no `*args` or `**kwargs` magic in its signature.
Can you list the keyword arguments a Python function receives?
196,960
64
2008-10-13T07:55:18Z
197,053
98
2008-10-13T09:02:23Z
[ "python", "arguments", "introspection" ]
I have a dict, which I need to pass key/values as keyword arguments.. For example.. ``` d_args = {'kw1': 'value1', 'kw2': 'value2'} example(**d_args) ``` This works fine, *but* if there are values in the d\_args dict that are not accepted by the `example` function, it obviously dies.. Say, if the example function is defined as `def example(kw2):` This is a problem since I don't control either the generation of the `d_args`, or the `example` function.. They both come from external modules, and `example` only accepts some of the keyword-arguments from the dict.. Ideally I would just do ``` parsed_kwargs = feedparser.parse(the_url) valid_kwargs = get_valid_kwargs(parsed_kwargs, valid_for = PyRSS2Gen.RSS2) PyRSS2Gen.RSS2(**valid_kwargs) ``` I will probably just filter the dict, from a list of valid keyword-arguments, but I was wondering: **Is there a way to programatically list the keyword arguments the a specific function takes?**
A little nicer than inspecting the code object directly and working out the variables is to use the inspect module. ``` >>> import inspect >>> def func(a,b,c=42, *args, **kwargs): pass >>> inspect.getargspec(func) (['a', 'b', 'c'], 'args', 'kwargs', (42,)) ``` If you want to know if its callable with a particular set of args, you need the args without a default already specified. These can be got by: ``` def getRequiredArgs(func): args, varargs, varkw, defaults = inspect.getargspec(func) if defaults: args = args[:-len(defaults)] return args # *args and **kwargs are not required, so ignore them. ``` Then a function to tell what you are missing from your particular dict is: ``` def missingArgs(func, argdict): return set(getRequiredArgs(func)).difference(argdict) ``` Similarly, to check for invalid args, use: ``` def invalidArgs(func, argdict): args, varargs, varkw, defaults = inspect.getargspec(func) if varkw: return set() # All accepted return set(argdict) - set(args) ``` And so a full test if it is callable is : ``` def isCallableWithArgs(func, argdict): return not missingArgs(func, argdict) and not invalidArgs(func, argdict) ``` (This is good only as far as python's arg parsing. Any runtime checks for invalid values in kwargs obviously can't be detected.)
Docstrings for data?
197,387
20
2008-10-13T12:24:04Z
197,499
13
2008-10-13T12:55:53Z
[ "python", "docstring" ]
Is there a way to describe the module's data in a similar way that a docstring describes a module or a funcion? ``` class MyClass(object): def my_function(): """This docstring works!""" return True my_list = [] """This docstring does not work!""" ```
To my knowledge, it is not possible to assign docstrings to module data members. [PEP 224](http://www.python.org/dev/peps/pep-0224/) suggests this feature, but the PEP was rejected. I suggest you document the data members of a module in the module's docstring: ``` # module.py: """About the module. module.data: contains the word "spam" """ data = "spam" ```
Docstrings for data?
197,387
20
2008-10-13T12:24:04Z
197,566
9
2008-10-13T13:23:42Z
[ "python", "docstring" ]
Is there a way to describe the module's data in a similar way that a docstring describes a module or a funcion? ``` class MyClass(object): def my_function(): """This docstring works!""" return True my_list = [] """This docstring does not work!""" ```
It **is** possible to make documentation of module's data, with use of [epydoc](http://epydoc.sourceforge.net/) syntax. Epydoc is one of the most frequently used documentation tools for Python. The syntax for documenting is `#:` above the variable initialization line, like this: ``` # module.py: #: Very important data. #: Use with caution. #: @type: C{str} data = "important data" ``` Now when you generate your documentation, `data` will be described as module variable with given description and type `str`. You can omit the `@type` line.
Docstrings for data?
197,387
20
2008-10-13T12:24:04Z
199,179
10
2008-10-13T22:08:20Z
[ "python", "docstring" ]
Is there a way to describe the module's data in a similar way that a docstring describes a module or a funcion? ``` class MyClass(object): def my_function(): """This docstring works!""" return True my_list = [] """This docstring does not work!""" ```
As codeape explains, it's not possible to document general data members. However, it *is* possible to document `property` data members: ``` class Foo: def get_foo(self): ... def set_foo(self, val): ... def del_foo(self): ... foo = property(get_foo, set_foo, del_foo, '''Doc string here''') ``` This will give a docstring to the `foo` attribute, obviously.
Dealing with a string containing multiple character encodings
197,759
9
2008-10-13T14:26:10Z
197,990
7
2008-10-13T15:29:10Z
[ "python", "string", "unicode", "encoding" ]
I'm not exactly sure how to ask this question really, and I'm no where close to finding an answer, so I hope someone can help me. I'm writing a Python app that connects to a remote host and receives back byte data, which I unpack using Python's built-in struct module. My problem is with the strings, as they include multiple character encodings. Here is an example of such a string: "^LThis is an example ^Gstring with multiple ^Jcharacter encodings" Where the different encoding starts and ends is marked using special escape chars: * ^L - Latin1 * ^E - Central Europe * ^T - Turkish * ^B - Baltic * ^J - Japanese * ^C - Cyrillic * ^G - Greek And so on... I need a way to convert this sort of string into Unicode, but I'm really not sure how to do it. I've read up on Python's codecs and string.encode/decode, but I'm none the wiser really. I should mention as well, that I have no control over how the strings are outputted by the host. I hope someone can help me with how to get started on this.
Here's a relatively simple example of how do it... ``` # -*- coding: utf-8 -*- import re # Test Data ENCODING_RAW_DATA = ( ('latin_1', 'L', u'Hello'), # Latin 1 ('iso8859_2', 'E', u'dobrý večer'), # Central Europe ('iso8859_9', 'T', u'İyi akşamlar'), # Turkish ('iso8859_13', 'B', u'Į sveikatą!'), # Baltic ('shift_jis', 'J', u'今日は'), # Japanese ('iso8859_5', 'C', u'Здравствуйте'), # Cyrillic ('iso8859_7', 'G', u'Γειά σου'), # Greek ) CODE_TO_ENCODING = dict([(chr(ord(code)-64), encoding) for encoding, code, text in ENCODING_RAW_DATA]) EXPECTED_RESULT = u''.join([line[2] for line in ENCODING_RAW_DATA]) ENCODED_DATA = ''.join([chr(ord(code)-64) + text.encode(encoding) for encoding, code, text in ENCODING_RAW_DATA]) FIND_RE = re.compile('[\x00-\x1A][^\x00-\x1A]*') def decode_single(bytes): return bytes[1:].decode(CODE_TO_ENCODING[bytes[0]]) result = u''.join([decode_single(bytes) for bytes in FIND_RE.findall(ENCODED_DATA)]) assert result==EXPECTED_RESULT, u"Expected %s, but got %s" % (EXPECTED_RESULT, result) ```
Can I pickle a python dictionary into a sqlite3 text field?
198,692
25
2008-10-13T19:11:13Z
198,748
13
2008-10-13T19:31:36Z
[ "python", "sqlite", "pickle" ]
Any gotchas I should be aware of? Can I store it in a text field, or do I need to use a blob? (I'm not overly familiar with either pickle or sqlite, so I wanted to make sure I'm barking up the right tree with some of my high-level design ideas.)
If you want to store a pickled object, you'll need to use a blob, since it is binary data. However, you can, say, base64 encode the pickled object to get a string that can be stored in a text field. Generally, though, doing this sort of thing is indicative of bad design, since you're storing opaque data you lose the ability to use SQL to do any useful manipulation on that data. Although without knowing what you're actually doing, I can't really make a moral call on it.
Can I pickle a python dictionary into a sqlite3 text field?
198,692
25
2008-10-13T19:11:13Z
2,340,858
35
2010-02-26T10:23:14Z
[ "python", "sqlite", "pickle" ]
Any gotchas I should be aware of? Can I store it in a text field, or do I need to use a blob? (I'm not overly familiar with either pickle or sqlite, so I wanted to make sure I'm barking up the right tree with some of my high-level design ideas.)
I needed to achieve the same thing too. I turns out it caused me quite a headache before I finally figured out, [thanks to this post](http://coding.derkeiler.com/Archive/Python/comp.lang.python/2008-12/msg00352.html), how to actually make it work in a binary format. ### To insert/update: ``` pdata = cPickle.dumps(data, cPickle.HIGHEST_PROTOCOL) curr.execute("insert into table (data) values (:data)", sqlite3.Binary(pdata)) ``` You must specify the second argument to dumps to force a binary pickling. Also note the **sqlite3.Binary** to make it fit in the BLOB field. ### To retrieve data: ``` curr.execute("select data from table limit 1") for row in curr: data = cPickle.loads(str(row['data'])) ``` When retrieving a BLOB field, sqlite3 gets a 'buffer' python type, that needs to be strinyfied using **str** before being passed to the loads method.
I'm looking for a pythonic way to insert a space before capital letters
199,059
8
2008-10-13T21:16:40Z
199,075
16
2008-10-13T21:20:55Z
[ "python", "regex", "text-files" ]
I've got a file whose format I'm altering via a python script. I have several camel cased strings in this file where I just want to insert a single space before the capital letter - so "WordWordWord" becomes "Word Word Word". My limited regex experience just stalled out on me - can someone think of a decent regex to do this, or (better yet) is there a more pythonic way to do this that I'm missing?
You could try: ``` >>> re.sub(r"(\w)([A-Z])", r"\1 \2", "WordWordWord") 'Word Word Word' ```
I'm looking for a pythonic way to insert a space before capital letters
199,059
8
2008-10-13T21:16:40Z
199,120
22
2008-10-13T21:37:39Z
[ "python", "regex", "text-files" ]
I've got a file whose format I'm altering via a python script. I have several camel cased strings in this file where I just want to insert a single space before the capital letter - so "WordWordWord" becomes "Word Word Word". My limited regex experience just stalled out on me - can someone think of a decent regex to do this, or (better yet) is there a more pythonic way to do this that I'm missing?
If there are consecutive capitals, then Gregs result could not be what you look for, since the \w consumes the caracter in front of the captial letter to be replaced. ``` >>> re.sub(r"(\w)([A-Z])", r"\1 \2", "WordWordWWWWWWWord") 'Word Word WW WW WW Word' ``` A look-behind would solve this: ``` >>> re.sub(r"(?<=\w)([A-Z])", r" \1", "WordWordWWWWWWWord") 'Word Word W W W W W W Word' ```
How can I port a legacy Java/J2EE website to a modern scripting language (PHP,Python/Django, etc)?
199,556
4
2008-10-14T00:23:28Z
199,607
7
2008-10-14T00:45:59Z
[ "java", "php", "python", "django", "java-ee" ]
I want to move a legacy Java web application (J2EE) to a scripting language - any scripting language - in order to improve programming efficiency. What is the easiest way to do this? Are there any automated tools that can convert the bulk of the business logic?
If you already have a large amount of business logic implemented in Java, then I see two possibilities for you. The first is to use a high level language that runs within the JVM and has a web framework, such as [Groovy](http://groovy.codehaus.org/)/[Grails](http://grails.org/) or [JRuby](http://jruby.codehaus.org/) and [Rails](http://rads.stackoverflow.com/amzn/click/1590598814). This allows you to directly leverage all of the business logic you've implemented in Java without having to re-architect the entire site. You should be able to take advantage of the framework's improved productivity with respect to the web development and still leverage your existing business logic. An alternative approach is to turn your business logic layer into a set of services available over a standard RPC mechanisim - REST, SOAP, XML-RPC or some other simple XML (YAML or JSON) over HTTP protocol (see also [DWR](https://dwr.dev.java.net/)) so that the front end can make these RPC calls to your business logic. The first approach, using a high level language on the JVM is probably less re-architecture than the second. If your goal is a complete migration off of Java, then either of these approaches allow you to do so in smaller steps - you may find that this kind of hybrid is better than whole sale deprecation - the JVM has a lot of libraries and integrates well into a lot of other systems.
How can I port a legacy Java/J2EE website to a modern scripting language (PHP,Python/Django, etc)?
199,556
4
2008-10-14T00:23:28Z
199,736
11
2008-10-14T01:43:21Z
[ "java", "php", "python", "django", "java-ee" ]
I want to move a legacy Java web application (J2EE) to a scripting language - any scripting language - in order to improve programming efficiency. What is the easiest way to do this? Are there any automated tools that can convert the bulk of the business logic?
Here's what you have to do. First, be sure you can walk before you run. Build something simple, possibly tangentially related to your main project. **DO NOT** build a piece of the final project and hope it will "evolve" into the final project. This never works out well. Why? You'll make dumb mistakes. But you can't delete or rework them because you're supposed to evolve that mistake into the final project. Next, pick a a framework. What? Second? Yes. Second. Until you actually do something with some scripting languages and frameworks, you have no real useful concept of what you're doing. Once you've built something, you now have an informed opinion. "Wait," you say. "To do step 1 I had to pick a framework." True. Step 1, however, contains decisions you're allowed to revoke. Pick the wrong framework for step 1 has no long-term bad effects. It was just learning. Third, with your strategic framework, and some experience, break down your existing site into pieces you can build with your new framework. Prioritize those pieces from most important to least important. **DO NOT** plan the entire conversion as one massive project. It never works. It makes a big job more complex than necessary. We'll use Django as the example framework. You'll have templates, view functions, model definitions, URL mapping and other details. For each build, do the following: 1. Convert your existing model to a Django model. This won't ever fit your legacy SQL. You'll have to rethink your model, fix old mistakes, correct old bugs that you've always wanted to correct. 2. Write unit tests. 3. Build a conversion utility to export old data and import into the new model. 4. Build Django admin pages to touch and feel the new data. 5. Pick representative pages and rework them into the appropriate templates. You might make use of some legacy JSP pages. However, don't waste too much time with this. Use the HTML to create Django templates. 6. Plan your URL's and view functions. Sometimes, these view functions will leverage legacy action classes. Don't "convert". Rewrite from scratch. Use your new language and framework. The only thing that's worth preserving is the data and the operational concept. Don't try to preserve or convert the code. It's misleading. You might convert unittests from JUnit to Python unittest. --- I gave this advice a few months ago. I had to do some coaching and review during the processing. The revised site is up and running. No conversion from the old technology; they did the suggested rewrite from scratch. Developer happy. Site works well.
Get last answer
200,020
87
2008-10-14T04:31:49Z
200,027
130
2008-10-14T04:35:08Z
[ "python" ]
In many symbolic math systems, such as Matlab or Mathematica, you can use a variable like `Ans` or `%` to retrieve the last computed value. Is there a similar facility in the Python shell?
Underscore. ``` >>> 5+5 10 >>> _ 10 >>> _ + 5 15 >>> _ 15 ```
Get last answer
200,020
87
2008-10-14T04:31:49Z
200,045
41
2008-10-14T04:53:38Z
[ "python" ]
In many symbolic math systems, such as Matlab or Mathematica, you can use a variable like `Ans` or `%` to retrieve the last computed value. Is there a similar facility in the Python shell?
Just for the record, ipython takes this one step further and you can access every result with \_ and its numeric value ``` In [1]: 10 Out[1]: 10 In [2]: 32 Out[2]: 32 In [3]: _ Out[3]: 32 In [4]: _1 Out[4]: 10 In [5]: _2 Out[5]: 32 In [6]: _1 + _2 Out[6]: 42 In [7]: _6 Out[7]: 42 ``` And it is possible to edit ranges of lines with the %ed macro too: ``` In [1]: def foo(): ...: print "bar" ...: ...: In [2]: foo() bar In [3]: %ed 1-2 ```
How do I remove a cookie that I've set on someone's computer?
200,250
5
2008-10-14T07:27:21Z
200,265
7
2008-10-14T07:35:43Z
[ "python", "apache", "http", "cookies" ]
I've got a web system where users log in, and it stores a cookie of their session. When they log in as someone else or log out I want to remove that original cookie that I stored. What's the best way to do that? I'm using Python and Apache, though I suppose the answer will remain the same for most languages.
Set the cookie again, as if you hadn't set it the first time, but specify an expiration date that is in the past.
Store simple user settings in Python
200,599
7
2008-10-14T10:04:46Z
200,611
7
2008-10-14T10:10:11Z
[ "python", "database", "website", "settings" ]
I am programming a website in which users will have a number of settings, such as their choice of colour scheme, etc. I'm happy to store these as plain text files, and security is not an issue. The way I currently see it is: there is a dictionary, where all the keys are users and the values are dictionaries with the users' settings in them. For example, userdb["bob"]["colour\_scheme"] would have the value "blue". What is the best way to store it on file? Pickling the dictionary? Are there better ways of doing what I am trying to do?
Using [cPickle](http://www.python.org/doc/2.5.2/lib/module-cPickle.html) on the dictionary would be my choice. Dictionaries are a natural fit for these kind of data, so given your requirements I see no reason not to use them. That, unless you are thinking about reading them from non-python applications, in which case you'd have to use a language neutral text format. And even here you could get away with the pickle plus an export tool.
Store simple user settings in Python
200,599
7
2008-10-14T10:04:46Z
202,988
8
2008-10-14T21:50:29Z
[ "python", "database", "website", "settings" ]
I am programming a website in which users will have a number of settings, such as their choice of colour scheme, etc. I'm happy to store these as plain text files, and security is not an issue. The way I currently see it is: there is a dictionary, where all the keys are users and the values are dictionaries with the users' settings in them. For example, userdb["bob"]["colour\_scheme"] would have the value "blue". What is the best way to store it on file? Pickling the dictionary? Are there better ways of doing what I am trying to do?
I would use the [ConfigParser](http://www.python.org/doc/2.5.2/lib/module-ConfigParser.html) module, which produces some pretty readable and user-editable output for your example: ``` [bob] colour_scheme: blue british: yes [joe] color_scheme: that's 'color', silly! british: no ``` The following code would produce the config file above, and then print it out: ``` import sys from ConfigParser import * c = ConfigParser() c.add_section("bob") c.set("bob", "colour_scheme", "blue") c.set("bob", "british", str(True)) c.add_section("joe") c.set("joe", "color_scheme", "that's 'color', silly!") c.set("joe", "british", str(False)) c.write(sys.stdout) # this outputs the configuration to stdout # you could put a file-handle here instead for section in c.sections(): # this is how you read the options back in print section for option in c.options(section): print "\t", option, "=", c.get(section, option) print c.get("bob", "british") # To access the "british" attribute for bob directly ``` Note that ConfigParser only supports strings, so you'll have to convert as I have above for the Booleans. See [effbot](http://effbot.org/librarybook/configparser.htm) for a good run-down of the basics.
How can I unpack binary hex formatted data in Python?
200,738
5
2008-10-14T11:08:07Z
200,761
8
2008-10-14T11:17:11Z
[ "php", "python", "binary", "hex" ]
Using the PHP [pack()](http://www.php.net/pack) function, I have converted a string into a binary hex representation: ``` $string = md5(time); // 32 character length $packed = pack('H*', $string); ``` The H\* formatting means "Hex string, high nibble first". To unpack this in PHP, I would simply use the [unpack()](http://www.php.net/unpack) function with the H\* format flag. How would I unpack this data in Python?
In Python you use the [struct](http://www.python.org/doc/2.5.2/lib/module-struct.html) module for this. ``` >>> from struct import * >>> pack('hhl', 1, 2, 3) '\x00\x01\x00\x02\x00\x00\x00\x03' >>> unpack('hhl', '\x00\x01\x00\x02\x00\x00\x00\x03') (1, 2, 3) >>> calcsize('hhl') 8 ``` HTH
How can I unpack binary hex formatted data in Python?
200,738
5
2008-10-14T11:08:07Z
200,861
10
2008-10-14T11:59:32Z
[ "php", "python", "binary", "hex" ]
Using the PHP [pack()](http://www.php.net/pack) function, I have converted a string into a binary hex representation: ``` $string = md5(time); // 32 character length $packed = pack('H*', $string); ``` The H\* formatting means "Hex string, high nibble first". To unpack this in PHP, I would simply use the [unpack()](http://www.php.net/unpack) function with the H\* format flag. How would I unpack this data in Python?
There's no corresponding "hex nibble" code for struct.pack, so you'll either need to manually pack into bytes first, like: ``` hex_string = 'abcdef12' hexdigits = [int(x, 16) for x in hex_string] data = ''.join(struct.pack('B', (high <<4) + low) for high, low in zip(hexdigits[::2], hexdigits[1::2])) ``` Or better, you can just use the hex codec. ie. ``` >>> data = hex_string.decode('hex') >>> data '\xab\xcd\xef\x12' ``` To unpack, you can encode the result back to hex similarly ``` >>> data.encode('hex') 'abcdef12' ``` However, note that for your example, there's probably no need to take the round-trip through a hex representation at all when encoding. Just use the md5 binary digest directly. ie. ``` >>> x = md5.md5('some string') >>> x.digest() 'Z\xc7I\xfb\xee\xc96\x07\xfc(\xd6f\xbe\x85\xe7:' ``` This is equivalent to your pack()ed representation. To get the hex representation, use the same unpack method above: ``` >>> x.digest().decode('hex') 'acbd18db4cc2f85cedef654fccc4a4d8' >>> x.hexdigest() 'acbd18db4cc2f85cedef654fccc4a4d8' ``` [Edit]: Updated to use better method (hex codec)
How can I unpack binary hex formatted data in Python?
200,738
5
2008-10-14T11:08:07Z
201,325
10
2008-10-14T14:15:26Z
[ "php", "python", "binary", "hex" ]
Using the PHP [pack()](http://www.php.net/pack) function, I have converted a string into a binary hex representation: ``` $string = md5(time); // 32 character length $packed = pack('H*', $string); ``` The H\* formatting means "Hex string, high nibble first". To unpack this in PHP, I would simply use the [unpack()](http://www.php.net/unpack) function with the H\* format flag. How would I unpack this data in Python?
There's an easy way to do this with the `binascii` module: ``` >>> import binascii >>> print binascii.hexlify("ABCZ") '4142435a' ``` Unless I'm misunderstanding something about the nibble ordering (high-nibble first is the default), that should be perfectly sufficient! Furthermore, Python's `hashlib.md5` objects have a `hexdigest()` method to automatically convert the MD5 digest to an ASCII hex string, so that this method isn't even necessary for MD5 digests. Hope that helps.
Shortest Sudoku Solver in Python - How does it work?
201,461
70
2008-10-14T14:46:15Z
201,550
8
2008-10-14T15:05:37Z
[ "python", "algorithm" ]
I was playing around with my own Sudoku solver and was looking for some pointers to good and fast design when I came across this: ``` def r(a):i=a.find('0');~i or exit(a);[m in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for j in range(81)]or r(a[:i]+m+a[i+1:])for m in'%d'%5**18] from sys import*;r(argv[1]) ``` My own implementation solves Sudokus the same way I solve them in my head but how does this cryptic algorithm work? <http://scottkirkwood.blogspot.com/2006/07/shortest-sudoku-solver-in-python.html>
unobfuscating it: ``` def r(a): i = a.find('0') # returns -1 on fail, index otherwise ~i or exit(a) # ~(-1) == 0, anthing else is not 0 # thus: if i == -1: exit(a) inner_lexp = [ (i-j)%9*(i/9 ^ j/9)*(i/27 ^ j/27 | i%9/3 ^ j%9/3) or a[j] for j in range(81)] # r appears to be a string of 81 # characters with 0 for empty and 1-9 # otherwise [m in inner_lexp or r(a[:i]+m+a[i+1:]) for m in'%d'%5**18] # recurse # trying all possible digits for that empty field # if m is not in the inner lexp from sys import * r(argv[1]) # thus, a is some string ``` So, we just need to work out the inner list expression. I know it collects the digits set in the line -- otherwise, the code around it makes no sense. However, I have no real clue how it does that (and Im too tired to work out that binary fancyness right now, sorry)
Shortest Sudoku Solver in Python - How does it work?
201,461
70
2008-10-14T14:46:15Z
201,771
205
2008-10-14T16:00:21Z
[ "python", "algorithm" ]
I was playing around with my own Sudoku solver and was looking for some pointers to good and fast design when I came across this: ``` def r(a):i=a.find('0');~i or exit(a);[m in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for j in range(81)]or r(a[:i]+m+a[i+1:])for m in'%d'%5**18] from sys import*;r(argv[1]) ``` My own implementation solves Sudokus the same way I solve them in my head but how does this cryptic algorithm work? <http://scottkirkwood.blogspot.com/2006/07/shortest-sudoku-solver-in-python.html>
Well, you can make things a little easier by fixing up the syntax: ``` def r(a): i = a.find('0') ~i or exit(a) [m in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for j in range(81)] or r(a[:i]+m+a[i+1:])for m in'%d'%5**18] from sys import * r(argv[1]) ``` Cleaning up a little: ``` from sys import exit, argv def r(a): i = a.find('0') if i == -1: exit(a) for m in '%d' % 5**18: m in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3) or a[j] for j in range(81)] or r(a[:i]+m+a[i+1:]) r(argv[1]) ``` Okay, so this script expects a command-line argument, and calls the function r on it. If there are no zeros in that string, r exits and prints out its argument. > (If another type of object is passed, > None is equivalent to passing zero, > and any other object is printed to > sys.stderr and results in an exit > code of 1. In particular, > sys.exit("some error message") is a > quick way to exit a program when an > error occurs. See > <http://www.python.org/doc/2.5.2/lib/module-sys.html>) I guess this means that zeros correspond to open spaces, and a puzzle with no zeros is solved. Then there's that nasty recursive expression. The loop is interesting: `for m in'%d'%5**18` Why 5\*\*18? It turns out that `'%d'%5**18` evaluates to `'3814697265625'`. This is a string that has each digit 1-9 at least once, so maybe it's trying to place each of them. In fact, it looks like this is what `r(a[:i]+m+a[i+1:])` is doing: recursively calling r, with the first blank filled in by a digit from that string. But this only happens if the earlier expression is false. Let's look at that: `m in [(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3) or a[j] for j in range(81)]` So the placement is done only if m is not in that monster list. Each element is either a number (if the first expression is nonzero) or a character (if the first expression is zero). m is ruled out as a possible substitution if it appears as a character, which can only happen if the first expression is zero. When is the expression zero? It has three parts that are multiplied: * `(i-j)%9` which is zero if i and j are a multiple of 9 apart, i.e. the same column. * `(i/9^j/9)` which is zero if i/9 == j/9, i.e. the same row. * `(i/27^j/27|i%9/3^j%9/3)` which is zero if both of these are zero: * + `i/27^j^27` which is zero if i/27 == j/27, i.e. the same block of three rows * + `i%9/3^j%9/3` which is zero if i%9/3 == j%9/3, i.e. the same block of three columns If any of these three parts is zero, the entire expression is zero. In other words, if i and j share a row, column, or 3x3 block, then the value of j can't be used as a candidate for the blank at i. Aha! ``` from sys import exit, argv def r(a): i = a.find('0') if i == -1: exit(a) for m in '3814697265625': okay = True for j in range(81): if (i-j)%9 == 0 or (i/9 == j/9) or (i/27 == j/27 and i%9/3 == j%9/3): if a[j] == m: okay = False break if okay: # At this point, m is not excluded by any row, column, or block, so let's place it and recurse r(a[:i]+m+a[i+1:]) r(argv[1]) ``` Note that if none of the placements work out, r will return and back up to the point where something else can be chosen, so it's a basic depth first algorithm. Not using any heuristics, it's not particularly efficient. I took this puzzle from Wikipedia (<http://en.wikipedia.org/wiki/Sudoku>): ``` $ time python sudoku.py 530070000600195000098000060800060003400803001700020006060000280000419005000080079 534678912672195348198342567859761423426853791713924856961537284287419635345286179 real 0m47.881s user 0m47.223s sys 0m0.137s ``` Addendum: How I would rewrite it as a maintenance programmer (this version has about a 93x speedup :) ``` import sys def same_row(i,j): return (i/9 == j/9) def same_col(i,j): return (i-j) % 9 == 0 def same_block(i,j): return (i/27 == j/27 and i%9/3 == j%9/3) def r(a): i = a.find('0') if i == -1: sys.exit(a) excluded_numbers = set() for j in range(81): if same_row(i,j) or same_col(i,j) or same_block(i,j): excluded_numbers.add(a[j]) for m in '123456789': if m not in excluded_numbers: # At this point, m is not excluded by any row, column, or block, so let's place it and recurse r(a[:i]+m+a[i+1:]) if __name__ == '__main__': if len(sys.argv) == 2 and len(sys.argv[1]) == 81: r(sys.argv[1]) else: print 'Usage: python sudoku.py puzzle' print ' where puzzle is an 81 character string representing the puzzle read left-to-right, top-to-bottom, and 0 is a blank' ```
urllib.urlopen works but urllib2.urlopen doesn't
201,515
10
2008-10-14T14:57:41Z
201,737
16
2008-10-14T15:49:47Z
[ "python", "urllib2", "urllib" ]
I have a simple website I'm testing. It's running on localhost and I can access it in my web browser. The index page is simply the word "running". `urllib.urlopen` will successfully read the page but `urllib2.urlopen` will not. Here's a script which demonstrates the problem (this is the actual script and not a simplification of a different test script): ``` import urllib, urllib2 print urllib.urlopen("http://127.0.0.1").read() # prints "running" print urllib2.urlopen("http://127.0.0.1").read() # throws an exception ``` Here's the stack trace: ``` Traceback (most recent call last): File "urltest.py", line 5, in <module> print urllib2.urlopen("http://127.0.0.1").read() File "C:\Python25\lib\urllib2.py", line 121, in urlopen return _opener.open(url, data) File "C:\Python25\lib\urllib2.py", line 380, in open response = meth(req, response) File "C:\Python25\lib\urllib2.py", line 491, in http_response 'http', request, response, code, msg, hdrs) File "C:\Python25\lib\urllib2.py", line 412, in error result = self._call_chain(*args) File "C:\Python25\lib\urllib2.py", line 353, in _call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 575, in http_error_302 return self.parent.open(new) File "C:\Python25\lib\urllib2.py", line 380, in open response = meth(req, response) File "C:\Python25\lib\urllib2.py", line 491, in http_response 'http', request, response, code, msg, hdrs) File "C:\Python25\lib\urllib2.py", line 418, in error return self._call_chain(*args) File "C:\Python25\lib\urllib2.py", line 353, in _call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 499, in http_error_default raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) urllib2.HTTPError: HTTP Error 504: Gateway Timeout ``` Any ideas? I might end up needing some of the more advanced features of `urllib2`, so I don't want to just resort to using `urllib`, plus I want to understand this problem.
Sounds like you have proxy settings defined that urllib2 is picking up on. When it tries to proxy "127.0.0.01/", the proxy gives up and returns a 504 error. From [Obscure python urllib2 proxy gotcha](http://kember.net/articles/obscure-python-urllib2-proxy-gotcha): ``` proxy_support = urllib2.ProxyHandler({}) opener = urllib2.build_opener(proxy_support) print opener.open("http://127.0.0.1").read() # Optional - makes this opener default for urlopen etc. urllib2.install_opener(opener) print urllib2.urlopen("http://127.0.0.1").read() ```
python name a file same as a lib
201,846
2
2008-10-14T16:17:23Z
201,891
7
2008-10-14T16:30:44Z
[ "python" ]
i have the following script ``` import getopt, sys opts, args = getopt.getopt(sys.argv[1:], "h:s") for key,value in opts: print key, "=>", value ``` if i name this getopt.py and run it doesn't work as it tries to import itself is there a way around this, so i can keep this filename but specify on import that i want the standard python lib and not this file? Solution based on Vinko's answer: ``` import sys sys.path.reverse() from getopt import getopt opts, args = getopt(sys.argv[1:], "h:s") for key,value in opts: print key, "=>", value ```
You shouldn't name your scripts like existing modules. Especially if standard. That said, you can touch sys.path to modify the library loading order ``` ~# cat getopt.py print "HI" ~# python Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> import getopt HI ~# python Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.path.remove('') >>> import getopt >>> dir(getopt) ['GetoptError', '__all__', '__builtins__', '__doc__', '__file__', '__name__', 'do_longs', 'do_shorts', 'error', 'getopt', 'gnu_getopt', 'long_has_args', 'os', 'short_has_arg'] ``` In addition, you may wish to avoid the full import and do it differently, like this: ``` import sys sys.path.remove('') from getopt import getopt sys.path.insert(0,'') opts, args = getopt(sys.argv[1:], "h:s") for key,value in opts: print key, "=>", value ```
which python framework to use?
202,939
9
2008-10-14T21:35:15Z
202,941
10
2008-10-14T21:37:55Z
[ "python", "frameworks", "web-frameworks" ]
I'm looking for a framework which is appropriate for beginners (in Python and web development). I already found out about Django and web.py. I think that one of the most important things for me is good documentation. Thanks for the help, Dan
I think Django has some of the best documentation of any project I've worked on. That's the reason we chose it over Turbogears two years ago, and it's been the best technology choice we've made.
which python framework to use?
202,939
9
2008-10-14T21:35:15Z
204,778
10
2008-10-15T13:51:45Z
[ "python", "frameworks", "web-frameworks" ]
I'm looking for a framework which is appropriate for beginners (in Python and web development). I already found out about Django and web.py. I think that one of the most important things for me is good documentation. Thanks for the help, Dan
[web.py](http://webpy.org/)? It's extremely simple, and Python'y. A basic hello-world web-application is.. ``` import web urls = ( '/(.*)', 'hello' ) class hello: def GET(self, name): i = web.input(times=1) if not name: name = 'world' for c in range(int(i.times)): print 'Hello,', name+'!' if __name__ == "__main__": web.run(urls, globals()) ``` ..that's it. I found Django forced a *lot* of it's own conventions and code layout, and I could never remember the middleware/shortcuts imports, and all the other "magic" that is pretty much required to write anything. I found it was closer to Ruby on Rails than a Python web-framework. With web.py, you can write an entire, functioning web-application without using any of web.py's helper modules - the only thing you *have* to do is `import web` and setup the URLs, which is rather unavoidable. (the last line in the example runs the development web-server) It has lots of stuff in it, like an database API, form helpers, a templating engine and so on, but it doesn't force them on you - you could do all your HTML output by `print "Using <b>%s</b>" % (" string formating ".strip())` if you wished! Oh, while I have emphasised the simplicity, web.py is what <http://reddit.com> is written in, so it's also proven very capable/reliable. Also, [this post](http://www.aaronsw.com/weblog/rewritingreddit) by the web.py author is a very good explanation of why I much prefer web.py over Django
Creating self-contained python applications
203,487
19
2008-10-15T02:00:27Z
203,514
20
2008-10-15T02:17:35Z
[ "python", "windows", "executable", "self-contained" ]
I'm trying to create a self-contained version of [pisa](http://www.htmltopdf.org/) (html to pdf converter, [latest version](http://pypi.python.org/pypi/pisa/3.0.27)), but I can't succeed due to several errors. I've tried `py2exe`, `bb-freeze` and `cxfreeze`. This has to be in windows, which makes my life a bit harder. I remember that a couple of months ago the author had a zip file containing the install, but now it's gone, leaving me only with the python dependent way. How would you work this out?
Check out [pyinstaller](http://www.pyinstaller.org/), it makes standalone executables (as in one .EXE file, and that's it).
Does python support multiprocessor/multicore programming?
203,912
60
2008-10-15T06:59:50Z
203,943
23
2008-10-15T07:26:44Z
[ "python", "multicore" ]
What is the difference between multiprocessor programming and multicore programming? preferably show examples in python how to write a small program for multiprogramming & multicore programming
As mentioned in another post Python 2.6 has the [multiprocessing](http://docs.python.org/library/multiprocessing.html) module, which can take advantage of multiple cores/processors (it gets around GIL by starting multiple processes transparently). It offers some primitives similar to the threading module. You'll find some (simple) examples of usage in the documentation pages.
Does python support multiprocessor/multicore programming?
203,912
60
2008-10-15T06:59:50Z
204,150
84
2008-10-15T09:24:52Z
[ "python", "multicore" ]
What is the difference between multiprocessor programming and multicore programming? preferably show examples in python how to write a small program for multiprogramming & multicore programming
There is no such thing as "multiprocessor" or "multicore" programming. The distinction between "multiprocessor" and "multicore" *computers* is probably not relevant to you as an application programmer; it has to do with subtleties of how the cores share access to memory. In order to take advantage of a multicore (or multiprocessor) computer, you need a program written in such a way that it can be run in parallel, and a runtime that will allow the program to actually be executed in parallel on multiple cores (and operating system, although any operating system you can run on your PC will do this). This is really *parallel* programming, although there are different approaches to parallel programming. The ones that are relevant to Python are multiprocessing and multithreading. In languages like C, C++, Java, and C#, you can write parallel programs by executing multiple threads. The global interpreter lock in the CPython and PyPy runtimes preclude this option; but only for those runtimes. (In my personal opinion, multithreading is [dangerous and tricky](http://www.softpanorama.org/People/Ousterhout/Threads/index.shtml) and it is generally a good thing that Python encourages you not to consider it as a way to get a performance advantage.) If you want to write a parallel program which can run on multiple cores in Python, you have a few different options: * Write a multithreaded program using the [`threading`](http://www.python.org/doc/2.5.2/lib/module-threading.html) module and run it in the IronPython or Jython runtime. * Use the [`processing`](http://pypi.python.org/pypi/processing) module, (now included in Python 2.6 as the [`multiprocessing`](https://docs.python.org/2/library/multiprocessing.html) module), to run your code in multiple processes at once. * Use the [`subprocess`](http://www.python.org/doc/2.5.2/lib/module-subprocess.html) module to run multiple python interpreters and communicate between them. * Use [Twisted](http://twistedmatrix.com/) and [Ampoule](https://launchpad.net/ampoule/). This has the advantage of not just running your code across different processes, but (if you don't share access to things like files) potentially across different computers as well. No matter which of these options you choose, you will need to understand how to split the work that your program is doing up into chunks that make sense to separate. Since I'm not sure what kind of programs you are thinking of writing, it would be difficult to provide a useful example.
How do I execute a program from python? os.system fails due to spaces in path
204,017
206
2008-10-15T08:24:28Z
204,049
209
2008-10-15T08:37:39Z
[ "python", "shellexecute" ]
I have a python script that needs to execute an external program, but for some reason fails. If I have the following script: ``` import os; os.system("C:\\Temp\\a b c\\Notepad.exe"); raw_input(); ``` Then it fails with the following error: ``` 'C:\Temp\a' is not recognized as an internal or external command, operable program or batch file. ``` If I escape the program with quotes: ``` import os; os.system('"C:\\Temp\\a b c\\Notepad.exe"'); raw_input(); ``` Then it works. However, if I add a parameter, it stops working again: ``` import os; os.system('"C:\\Temp\\a b c\\Notepad.exe" "C:\\test.txt"'); raw_input(); ``` What is the right way to execute a program and wait for it to complete? I do not need to read output from it, as it is a visual program that does a job and then just exits, but I need to wait for it to complete. Also note, moving the program to a non-spaced path is not an option either. --- **Edit** This does not work either: ``` import os; os.system("'C:\\Temp\\a b c\\Notepad.exe'"); raw_input(); ``` Note the swapped single/double quotes. with or without a parameter to notepad here, it fails with the error message ``` The filename, directory name, or volume label syntax is incorrect. ```
[`subprocess.call`](http://docs.python.org/2/library/subprocess.html#using-the-subprocess-module) will avoid problems with having to deal with quoting conventions of various shells. It accepts a list, rather than a string, so arguments are more easily delimited. i.e. ``` import subprocess subprocess.call(['C:\\Temp\\a b c\\Notepad.exe', 'C:\\test.txt']) ```
How do I execute a program from python? os.system fails due to spaces in path
204,017
206
2008-10-15T08:24:28Z
206,215
50
2008-10-15T20:09:37Z
[ "python", "shellexecute" ]
I have a python script that needs to execute an external program, but for some reason fails. If I have the following script: ``` import os; os.system("C:\\Temp\\a b c\\Notepad.exe"); raw_input(); ``` Then it fails with the following error: ``` 'C:\Temp\a' is not recognized as an internal or external command, operable program or batch file. ``` If I escape the program with quotes: ``` import os; os.system('"C:\\Temp\\a b c\\Notepad.exe"'); raw_input(); ``` Then it works. However, if I add a parameter, it stops working again: ``` import os; os.system('"C:\\Temp\\a b c\\Notepad.exe" "C:\\test.txt"'); raw_input(); ``` What is the right way to execute a program and wait for it to complete? I do not need to read output from it, as it is a visual program that does a job and then just exits, but I need to wait for it to complete. Also note, moving the program to a non-spaced path is not an option either. --- **Edit** This does not work either: ``` import os; os.system("'C:\\Temp\\a b c\\Notepad.exe'"); raw_input(); ``` Note the swapped single/double quotes. with or without a parameter to notepad here, it fails with the error message ``` The filename, directory name, or volume label syntax is incorrect. ```
Here's a different way of doing it. If you're using windows the following acts like double-clicking the file in Explorer, or giving the file name as an argument to the DOS "start" command: the file is opened with whatever application (if any) its extension is associated. ``` filepath = 'textfile.txt' import os os.startfile(filepath) ``` Example: ``` import os os.startfile('textfile.txt') ``` This will open textfile.txt with notepad if notepad is associted with .txt files.