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
python: creating excel workbook and dumping csv files as worksheets
5,705,588
12
2011-04-18T15:56:07Z
5,705,925
12
2011-04-18T16:27:36Z
[ "python", "excel", "csv", "xlrd", "xlwt" ]
I have few csv files which I would like to dump as new worksheets in a excel workbook(xls/xlsx). How do I achieve this? Googled and found 'pyXLwriter' but it seems the project was stopped. While Im trying out 'pyXLwriter' would like to know are there any alternatives/suggestions/modules? Many Thanks. [Edit] Here is...
You'll find all you need in this [xlwt tutorial](http://scienceoss.com/write-excel-files-with-python-using-xlwt/). This libraries ([xlrd and xlwt](http://www.python-excel.org/)) are the most popular choices for managing Excel interaction in Python. The downside is that, at the moment, they only support Excel binary for...
python: creating excel workbook and dumping csv files as worksheets
5,705,588
12
2011-04-18T15:56:07Z
5,777,529
18
2011-04-25T10:36:57Z
[ "python", "excel", "csv", "xlrd", "xlwt" ]
I have few csv files which I would like to dump as new worksheets in a excel workbook(xls/xlsx). How do I achieve this? Googled and found 'pyXLwriter' but it seems the project was stopped. While Im trying out 'pyXLwriter' would like to know are there any alternatives/suggestions/modules? Many Thanks. [Edit] Here is...
Not sure what *you* mean by "much leaner, much pythonic" but you certainly could spruce it up a bit: ``` import glob, csv, xlwt, os wb = xlwt.Workbook() for filename in glob.glob("c:/xxx/*.csv"): (f_path, f_name) = os.path.split(filename) (f_short_name, f_extension) = os.path.splitext(f_name) ws = wb.add_s...
Accessing function as attribute in a Python class
5,705,618
28
2011-04-18T15:58:47Z
5,705,691
49
2011-04-18T16:05:28Z
[ "python", "django", "metaprogramming" ]
I'm in a situation where it would be extremely useful (though not strictly necessary) to access a class' instancemethod as an attribute. (it's for an API that uses getattr to set some return values for a dictionary and I don't want to mess the neat little thing up) I remember reading something about an `@attribute` de...
You can use the [`@property`](http://docs.python.org/library/functions.html#property) decorator. ``` class foo(object): bar = "bar" @property def baz(self): return "baz" ```
Accessing function as attribute in a Python class
5,705,618
28
2011-04-18T15:58:47Z
5,705,692
9
2011-04-18T16:05:34Z
[ "python", "django", "metaprogramming" ]
I'm in a situation where it would be extremely useful (though not strictly necessary) to access a class' instancemethod as an attribute. (it's for an API that uses getattr to set some return values for a dictionary and I don't want to mess the neat little thing up) I remember reading something about an `@attribute` de...
Take a look at the decorator form of [property](http://docs.python.org/library/functions.html#property). ``` @property def baz(self): return "baz" ```
How to Detect in Sub Process When Parent Process Has Died?
5,705,659
6
2011-04-18T16:02:52Z
5,705,942
8
2011-04-18T16:28:46Z
[ "python", "subprocess", "orphan" ]
In python, I have a parent process that spawns a handful of child processes. I've run into a situation where, due to an unhandled exception, the parent process was dieing and the child processes where left orphaned. How do I get the child processes to recognize that they've lost their parent? I tried some code that ho...
on UNIX (including Linux): ``` def is_parent_running(): try: os.kill(os.getppid(), 0) return True except OSError: return False ``` Note, that on UNIX, signal 0 is not a real signal. It is used just to test if given process exists. See manual for kill command.
Calling functions by array index in Python
5,707,589
7
2011-04-18T19:04:19Z
5,707,605
21
2011-04-18T19:05:16Z
[ "python", "delegates" ]
I have a bunch of functions in Python out1, out2, out3 etc. and would like to call them based on an integer I pass in. ``` def arryofPointersToFns (value): #call outn where n = value ``` Is there an easy way to do this?
tl;dr: Write an `out(n)` function rather than `out1(), out2(), ..., outN(n)` and don't bother with this hack. I cannot imagine a reasonable scenario where this question would come up in practice. Please reconsider the architecture of the problem; there is likely to be a much better way to do this (because storing them...
Python xlrd read as string
5,707,812
9
2011-04-18T19:26:04Z
5,708,744
8
2011-04-18T20:50:13Z
[ "python", "xlrd" ]
I'm having difficulties in reading a particular cell value from Excel in xlrd. Whatever value I'm reading (date value) is getting converted to a number. I know there are solutions to convert it into a python date format, but can I read directly the string value in xlrd?
xlrd does NOT convert dates to float. Excel stores dates as floats. Quoting from [the xlrd documentation](https://secure.simplistix.co.uk/svn/xlrd/trunk/xlrd/doc/xlrd.html) (scroll down a page): > **Dates in Excel spreadsheets** > > In reality, there are no such things. > What you have are floating point > numbers an...
Jinja2 vs. Smarty
5,708,094
2
2011-04-18T19:50:51Z
5,708,823
11
2011-04-18T20:58:54Z
[ "php", "python", "smarty", "jinja2" ]
I always thought that jinja was better because of template extending.. but them I've found this: <http://www.smarty.net/docs/en/advanced.features.template.inheritance.tpl> Is there's any difference of smarty extendings and jinja2 extendings?
Smarty is an overkill, in my opinion. I prefer Twig: <http://www.twig-project.org/> You should give it a try if you're stuck with php. It's almost the same as jinja2.
Named Entity Recognition for NLTK in Python. Identifying the NE
5,708,352
16
2011-04-18T20:14:16Z
5,708,817
10
2011-04-18T20:58:10Z
[ "python", "nlp", "nltk", "named-entity-recognition" ]
I need to classify words into their parts of speech. Like a verb, a noun, an adverb etc.. I used the ``` nltk.word_tokenize() #to identify word in a sentence nltk.pos_tag() #to identify the parts of speech nltk.ne_chunk() #to identify Named entities. ``` The out put of this is a tree. Eg ``` >>> sentence...
This answer may be off base, and in which case I'll delete it, as I don't have NLTK installed here to try it, but I think you can just do: ``` >>> sent3[2].node 'NE' ``` `sent3[2][0]` returns the first child of the tree, not the node itself **Edit:** I tried this when I got home, and it does indeed work.
How can I elegantly implement version checking in Python without throwing off indentation?
5,708,634
2
2011-04-18T20:40:40Z
5,708,645
7
2011-04-18T20:42:08Z
[ "python" ]
I'd like to very elegantly integrate version checking in Python. I don't want a version checking routine to throw off the indentation of all of my code, however. I.e. ``` if old_version: print 'hey, upgrade.' else: # main body of whole script ``` In the above implementation, the main body of the whole script w...
You can do ``` import sys if old_version: print 'hey, upgrade.' sys.exit(1) # A non-zero code indicates failure, on Unix (sys.exit() exits too, but it returns a 0 [=success] exit code) # main body of whole script ``` This exits the interpreter if the code needs to be upgraded. The reason for returning a n...
What's the difference between these two python shebangs
5,709,616
36
2011-04-18T22:25:12Z
5,709,632
50
2011-04-18T22:28:18Z
[ "python", "shebang" ]
I used to use the shebang ``` #!/usr/bin/env python ``` When is it better to use ``` #!/usr/bin/python ``` What is the exact difference between them? Thanks.
`#!/usr/bin/python` is hardcoded to always run `/usr/bin/python`, while `#!/usr/bin/env python` will run whichever `python` would be default in your current environment (it will take in account for example `$PATH`, you can check which python interpreter will be used with `which python`). The second way ( `#!/usr/bin/e...
How to add space between lines within a single paragraph with Reportlab
5,709,907
2
2011-04-18T23:14:17Z
5,709,999
11
2011-04-18T23:30:23Z
[ "python", "reportlab", "paragraph" ]
I have a block of text that is dynamically pulled from a database and is placed in a PDF before being served to a user. The text is being placed onto a lined background, much like notepad paper. I want to space the text so that only one line of text is between each background line. I was able to use the following code...
Pretty sure what yo u want to change is the leading. From the user manual in chapter 6. > To get double-spaced text, use a high > leading. If you set > autoLeading(default "off") to > "min"(use observed leading even if > smaller than specified) or "max"(use > the larger of observed and specified) > then an attempt is ...
Why did I need to specify a specific class to import in python?
5,710,029
4
2011-04-18T23:35:48Z
5,710,100
11
2011-04-18T23:50:18Z
[ "python" ]
I just upgraded to Python 2.7.1 (on Mac) so I could use OrderedDicts. After trying to run the following script: ``` import collections test = OrderedDict() ``` I got: ``` NameError: name 'OrderedDict' is not defined ``` I fixed it with: ``` from collections import OrderedDict ``` ...but I want to know why I nee...
``` import collections ``` imports the collections module into the current namespace, so you could work with this import like this: ``` import collections orderedDict = collections.OrderedDict() from collections import OrderedDict ``` imports just the specified class into the current namespace.
Is there a python data structure that is: keyed, ordered, and addressable via key and order?
5,710,266
3
2011-04-19T00:17:39Z
5,710,276
7
2011-04-19T00:20:10Z
[ "python", "data-structures" ]
I'm looking for a data structure that's a mix of OrderedDict but also addressable via an integer, depending on when the element was added. i.e. ``` config_key = OrderedDict([('Version_Number', 'a'), ('Hardware_Config', 'b'), ('Size_Of_Data', 'c'), ('Checksum', 'd')]) ``...
If you're using Python 2.7+ then there's one built in. <http://docs.python.org/library/collections.html#collections.OrderedDict> *edit:* So it looks like the order of items is supported via pop operations, but you could do the equivalent of what you want via `list(my_ordered_dict)[i]` where `i` is an integer. ``` # ...
Converting Python dict to kwargs?
5,710,391
124
2011-04-19T00:46:46Z
5,710,402
232
2011-04-19T00:48:54Z
[ "python", "dictionary", "kwargs" ]
I want to build a query for sunburnt(solr interface) using class inheritance and therefore adding key - value pairs together. The sunburnt interface takes keyword arguments. How can I transform a dict `({'type':'Event'})` into keyword arguments `(type='Event')`?
Use the [double-star](http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists) (aka [double-splat?](http://stackoverflow.com/questions/2322355/proper-name-for-python-operator/2322384#2322384)) operator: ``` func(**{'type':'Event'}) ``` is equivalent to ``` func(type='Event') ```
call Cython function from C++
5,710,441
11
2011-04-19T00:57:06Z
5,721,123
9
2011-04-19T18:45:25Z
[ "c++", "python", "callback", "cython" ]
I have a C++ library that has a Python wrapper (written with SWIG). This library allows executing small user-defined code (a callback), such as element-wise operations on a vector. I.e. instead of just a + you can do whatever arbitrary binary function. Right now this is accomplished by accepting a callable Python objec...
The trick with cython is in using the keyword [**public**](http://docs.cython.org/src/userguide/external_C_code.html#using-cython-declarations-from-c "Using Cython Declarations from C") ``` cdef public double cython_function( double value, double value2 ): return value + value2 ``` Then the command `cythonize <yo...
Python socket only accepting local connections
5,710,443
3
2011-04-19T00:57:30Z
5,710,797
7
2011-04-19T02:00:30Z
[ "python", "windows", "sockets" ]
Server: ``` import socket host = "" port = 4242 backlog = 5 size = 1024 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host,port)) s.listen(backlog) client, address = s.accept() while 1: data = client.recv(size) if data: client.send(data) print(data.decode("utf-8")) ``` Client...
Sounds like `host=''` is defaulting to bind to localhost (127.0.0.1) under Win 7 (I don't have access to a Win 7 machine at the moment). To make your server reachable on all (IPv4) interfaces on the host, this should work on Linux, Windows, Mac, etc: ``` host = '0.0.0.0' s.bind((host, 8080)) ``` To verify which addr...
Python pattern for sharing configuration throughout application
5,710,758
10
2011-04-19T01:54:38Z
5,710,775
9
2011-04-19T01:57:13Z
[ "python", "design-patterns", "configuration" ]
I have an application consisting of a base app that brings in several modules. The base app reads a parameter file into a configuration hash, and I want to share it across all my modules. Currently, I am passing a 'parent' object down to modules, and then those modules are doing stuff like self.parent.config to obtain...
You could just: ``` import config ``` and have a global config module --- excerpts from my comments: You can always add special rules for odd situations by just saying `oddValue if isOddSituation() else config.normalValue`. If you want to have configuration modules be hierarchically subclassable (like my other an...
Fastest 2D convolution or image filter in Python
5,710,842
16
2011-04-19T02:09:08Z
5,711,032
8
2011-04-19T02:42:04Z
[ "python", "optimization", "numpy", "python-imaging-library", "scipy" ]
Several users have asked about the speed or memory consumption of image convolutions in numpy or scipy [[1](http://stackoverflow.com/questions/2448015/2d-convolution-using-python-and-numpy), [2](http://stackoverflow.com/questions/5349521/python-image-filtering-with-pil-and-numpy-too-slow), [3](http://stackoverflow.com/...
It really depends on what you want to do... A lot of the time, you don't need a fully generic (read: slower) 2D convolution... (i.e. If the filter is separable, you use two 1D convolutions instead... This is why the various `scipy.ndimage.gaussian`, `scipy.ndimage.uniform`, are much faster than the same thing implement...
Fastest 2D convolution or image filter in Python
5,710,842
16
2011-04-19T02:09:08Z
5,729,604
9
2011-04-20T11:40:39Z
[ "python", "optimization", "numpy", "python-imaging-library", "scipy" ]
Several users have asked about the speed or memory consumption of image convolutions in numpy or scipy [[1](http://stackoverflow.com/questions/2448015/2d-convolution-using-python-and-numpy), [2](http://stackoverflow.com/questions/5349521/python-image-filtering-with-pil-and-numpy-too-slow), [3](http://stackoverflow.com/...
On my machine, a hand-crafted circular convolution using FFTs seems to be fasted: ``` import numpy x = numpy.random.random((2048, 2048)).astype(numpy.float32) y = numpy.random.random((32, 32)).astype(numpy.float32) z = numpy.fft.irfft2(numpy.fft.rfft2(x) * numpy.fft.rfft2(y, x.shape)) ``` Note that this might treat t...
Python: downloading and unzipping a .zip file without writing to disk
5,710,867
29
2011-04-19T02:13:24Z
5,710,885
11
2011-04-19T02:16:08Z
[ "python", "unzip" ]
I have managed to get my first python script to work which downloads a list of .ZIP files from a URL and then proceeds to extract the ZIP files and writes them to disk. I am now at a loss to achieve the next step. My primary goal is to download and extract the zip file and pass the contents (CSV data) via a TCP strea...
write to a temporary file which resides in RAM it turns out the `tempfile` module ( <http://docs.python.org/library/tempfile.html> ) has just the thing: > tempfile.SpooledTemporaryFile([max\_size=0[, > mode='w+b'[, bufsize=-1[, suffix=''[, > prefix='tmp'[, dir=None]]]]]]) > > This > function operates exactly as > Tem...
Python: downloading and unzipping a .zip file without writing to disk
5,710,867
29
2011-04-19T02:13:24Z
5,710,925
31
2011-04-19T02:23:00Z
[ "python", "unzip" ]
I have managed to get my first python script to work which downloads a list of .ZIP files from a URL and then proceeds to extract the ZIP files and writes them to disk. I am now at a loss to achieve the next step. My primary goal is to download and extract the zip file and pass the contents (CSV data) via a TCP strea...
My suggestion would be to use a [`StringIO`](http://docs.python.org/library/stringio.html) object. They emulate files, but reside in memory. So you could do something like this: ``` # get_zip_data() gets a zip archive containing 'foo.txt', reading 'hey, foo' from StringIO import StringIO zipdata = StringIO() zipdata....
Python: downloading and unzipping a .zip file without writing to disk
5,710,867
29
2011-04-19T02:13:24Z
5,711,095
33
2011-04-19T02:53:22Z
[ "python", "unzip" ]
I have managed to get my first python script to work which downloads a list of .ZIP files from a URL and then proceeds to extract the ZIP files and writes them to disk. I am now at a loss to achieve the next step. My primary goal is to download and extract the zip file and pass the contents (CSV data) via a TCP strea...
Below is a code snippet I used to fetch zipped csv file, please have a look: ``` from StringIO import StringIO from zipfile import ZipFile from urllib import urlopen url = urlopen("http://www.test.com/file.zip") zipfile = ZipFile(StringIO(url.read())) for line in zipfile.open(file).readlines(): print line ```
Getting error for ManytoMany in django?
5,712,221
3
2011-04-19T06:02:51Z
5,714,311
13
2011-04-19T09:30:42Z
[ "python", "django", "django-models" ]
When I am trying to validate, I am getting this error. ``` python manage.py validate Traceback (most recent call last): File "manage.py", line 11, in <module> execute_manager(settings) File "/usr/local/lib/python2.6/dist-packages/django/core/management/__init__.py", line 438, in execute_manager utility.exe...
You have a typo: categories = models.Many**T**oManyField
PyMongo vs MongoEngine for Django
5,712,857
14
2011-04-19T07:14:40Z
5,712,928
14
2011-04-19T07:22:50Z
[ "python", "django", "mongodb", "pymongo", "mongoengine" ]
For one of my projects I prefered using **Django+Mongo**. Why should I use **MongoEngine**, but not just **PyMongo**? What are advantages? Querying with PyMongo gives results that are **allready objects**, aren't they? So what is the purpose of MongoEngine?
I assume you have not read the MongoEngine claim. > MongoEngine is a Document-Object > Mapper (think ORM, but for document > databases) for working with MongoDB > from Python. This basically say it all. In addition: your claim that Pymongo would deliver objects is wrong....well in Python everything is an object - ev...
Regex search return result or empty
5,713,066
2
2011-04-19T07:35:31Z
5,713,088
8
2011-04-19T07:37:39Z
[ "python", "regex" ]
I learn Python, and bumped into interesting thing: I try to write lambda-function, which will search the pattern in the string, and return result if found matching, otherwise empty string. What I already have wrote: ``` >>> b = lambda x: re.search("_\w+_", x).group(0) if re.search("_\w+_", x) is not None else '' ``` ...
Don't write it at all. ``` >>> re.findall("_\\w+_", 'sdsd _sdsd_ sdsd sdsd _sssssssss_') ['_sdsd_', '_sssssssss_'] >>> re.findall("_\\w+_", '') [] ```
Dangling else in python
5,713,253
2
2011-04-19T07:54:05Z
5,713,264
8
2011-04-19T07:55:42Z
[ "python" ]
Just want confirmation that this assertion is correct: > python cannot ever experience the > dangling else problem *UPDATE* fixed typo
Python's blocks are indentation-based, not delimiter-based, therefore it is possible to unambiguously associate an `else` clause with its corresponding primary clause.
Simulate keystroke in Linux with Python
5,714,072
11
2011-04-19T09:11:03Z
5,714,100
13
2011-04-19T09:12:59Z
[ "python", "linux", "simulation", "keystroke" ]
How can I simulate a keystroke in python? I also want to press multiple keys simultaneously. Something like: ``` keystroke('CTRL+F4') ``` or ``` keystroke('Shift+A') ```
[python-uinput](http://codegrove.org/projects/python-uinput): > Pythonic API to Linux uinput kernel module... > > Python-uinput is Python interface to Linux uinput kernel module which allows attaching userspace device drivers into kernel. In practice, Python-uinput makes it dead simple to create virtual joysticks, key...
Simulate keystroke in Linux with Python
5,714,072
11
2011-04-19T09:11:03Z
5,714,298
10
2011-04-19T09:29:30Z
[ "python", "linux", "simulation", "keystroke" ]
How can I simulate a keystroke in python? I also want to press multiple keys simultaneously. Something like: ``` keystroke('CTRL+F4') ``` or ``` keystroke('Shift+A') ```
Although it's specific to X, you can install the xautomation package (`apt-get install xautomation` on Debian-based systems) and use `xte` to simulate keypresses, e.g.: ``` from subprocess import Popen, PIPE control_f4_sequence = '''keydown Control_L key F4 keyup Control_L ''' shift_a_sequence = '''keydown Shift_L k...
Simulate keystroke in Linux with Python
5,714,072
11
2011-04-19T09:11:03Z
12,096,748
9
2012-08-23T17:05:38Z
[ "python", "linux", "simulation", "keystroke" ]
How can I simulate a keystroke in python? I also want to press multiple keys simultaneously. Something like: ``` keystroke('CTRL+F4') ``` or ``` keystroke('Shift+A') ```
Consider [python-uinput](http://codegrove.org/projects/python-uinput) and [evdev](http://packages.python.org/evdev/). Example of `shift+a` with the latter: ``` from evdev import uinput, ecodes as e with uinput.UInput() as ui: ui.write(e.EV_KEY, e.KEY_LEFTSHIFT, 1) ui.write(e.EV_KEY, e.KEY_A, 1) ui.syn() `...
Why "except Exception" doesn't catch SystemExit?
5,714,525
11
2011-04-19T09:49:56Z
5,714,551
8
2011-04-19T09:51:41Z
[ "python", "exception-handling" ]
`isinstance(SystemExit(1), Exception)` evals to True, but this snippet prints `"caught by bare except SystemExit(1,)"`. ``` try: sys.exit(0) except Exception, e: print 'caught by except Exception', str(e) except: print 'caught by bare except', repr(sys.exc_info()[1]) ``` My testing environment is Python 2...
Your error is in the very first sentence of your question: ``` >>> isinstance(SystemExit(1), Exception) False ``` `SystemExit` is not a subclass of `Exception`.
Why "except Exception" doesn't catch SystemExit?
5,714,525
11
2011-04-19T09:49:56Z
5,714,666
9
2011-04-19T10:01:11Z
[ "python", "exception-handling" ]
`isinstance(SystemExit(1), Exception)` evals to True, but this snippet prints `"caught by bare except SystemExit(1,)"`. ``` try: sys.exit(0) except Exception, e: print 'caught by except Exception', str(e) except: print 'caught by bare except', repr(sys.exc_info()[1]) ``` My testing environment is Python 2...
`SystemExit` derives from [BaseException directly rather than from Exception](http://docs.python.org/library/exceptions.html#exceptions.SystemExit). `Exception` is the parent ["All built-in, non-system-exiting exceptions"](http://docs.python.org/library/exceptions.html#exceptions.Exception) SystemExit is a "system ex...
Why "except Exception" doesn't catch SystemExit?
5,714,525
11
2011-04-19T09:49:56Z
5,714,857
13
2011-04-19T10:17:23Z
[ "python", "exception-handling" ]
`isinstance(SystemExit(1), Exception)` evals to True, but this snippet prints `"caught by bare except SystemExit(1,)"`. ``` try: sys.exit(0) except Exception, e: print 'caught by except Exception', str(e) except: print 'caught by bare except', repr(sys.exc_info()[1]) ``` My testing environment is Python 2...
`isinstance(SystemExit(1), Exception)` is False on Python 2.6. Exception hierarchy in this version of Python was changed since Python 2.4. E.g. `KeyboardInterrupt` is not subclass of `Exception` any more. See more info <http://docs.python.org/release/2.6.6/library/exceptions.html#exception-hierarchy>
Can we shed some definitive light on how python packaging and import works?
5,714,916
39
2011-04-19T10:22:42Z
5,813,641
11
2011-04-28T04:30:24Z
[ "python", "documentation", "packaging" ]
I had my fair chance of getting through the python management of modules, and every time is a challenge: packaging is not what people do every day, and it becomes a burden to learn, and a burden to remember, even when you actually do it, since this happens normally once. I would like to collect here the definitive ove...
For the most part, this is an attempt to look at the packaging/distribution side, not the mechanics of `import`. Unfortunately, packaging is the place where Python provides way more than one way to do it. I'm just trying to get the ball rolling, hopefully others will help fill what I miss or point out mistakes. First ...
Unable to load the repository(PyDev for eclipse)
5,714,994
7
2011-04-19T10:28:45Z
24,468,636
15
2014-06-28T16:08:58Z
[ "python", "eclipse", "repository", "pydev" ]
I encountered the problem. When i am trying to create new PyDev project, an error occurs: Error: ``` Unable to load the repository http://pydev.org/updates Unknown Host: http://pydev.org/updates/content.xml ``` When i open this link(http://pydev.org/updates) in my browser, it redirects me here - <http://pydev.org/...
<http://pydev.org/> seems unavailable, use this <http://update-production-pydev.s3.amazonaws.com/pydev/updates/site.xml> instead of <http://pydev.org/updates>
Mix Python Twisted with multiprocessing?
5,715,217
10
2011-04-19T10:49:50Z
5,720,492
17
2011-04-19T17:49:54Z
[ "python", "twisted", "multiprocessing" ]
I need to write a proxy like program in Python, the work flow is very similar to a web proxy. The program sits in between the client and the server, incept requests sent by the client to the server, process the request, then send it to the original server. Of course the protocol used is a private protocol uses TCP. To...
Twisted has its own event-driven way of running subprocesses which is (in my humble, but correct, opinion) better than the `multiprocessing` module. The core API is [spawnProcess](http://twistedmatrix.com/documents/current/api/twisted.internet.interfaces.IReactorProcess.spawnProcess.html), but tools like [ampoule](http...
passing \n (new line) on stdout throught sys argument
5,715,414
3
2011-04-19T11:08:59Z
5,715,474
7
2011-04-19T11:14:19Z
[ "python", "stdout" ]
This is elementary I guess: Let's consider this snippet: ``` for i in range(3): sys.stdout.write(str(i) + '\n') ``` out: ``` 0 1 2 ``` and this: ``` for i in range(3): sys.stdout.write(str(i) + sys.argv[1]) ``` out (after passing \n as argument): ``` 0\n1\n2\n ``` So, how can I pass new-line as argumen...
``` sys.stdout.write(str(i) + sys.argv[1].decode("string_escape")) ```
Python: How to pass more than one argument to the property getter?
5,715,620
19
2011-04-19T11:27:36Z
5,715,659
21
2011-04-19T11:30:27Z
[ "python", "properties", "language-features" ]
Consider the following example: ``` class A: @property def x(self): return 5 ``` So, of course calling the `a = A(); a.x` will return `5` But imagine that you want to be able to modify the property x. This way, for example: ``` class A: @property def x(self, neg = False): return 5 if not neg else ...
I think you did not fully understand the purpose of properties. If you create a property `x`, you'll accessing it using `obj.x` instead of `obj.x()`. After creating the property it's not easily possible to call the underlying function directly. If you want to pass arguments, name your method `get_x` and do not make i...
Python: How to pass more than one argument to the property getter?
5,715,620
19
2011-04-19T11:27:36Z
5,718,537
25
2011-04-19T15:07:13Z
[ "python", "properties", "language-features" ]
Consider the following example: ``` class A: @property def x(self): return 5 ``` So, of course calling the `a = A(); a.x` will return `5` But imagine that you want to be able to modify the property x. This way, for example: ``` class A: @property def x(self, neg = False): return 5 if not neg else ...
Note that you don't *have* to use `property` as a decorator. You can quite happily use it the old way and expose the individual methods in addition to the property: ``` class A: def get_x(self, neg=False): return -5 if neg else 5 x = property(get_x) >>> a = A() >>> a.x 5 >>> a.get_x() 5 >>> a.get_x(Tr...
isinstance of bool?
5,717,738
7
2011-04-19T14:12:58Z
5,717,759
7
2011-04-19T14:13:56Z
[ "python", "boolean", "isinstance" ]
in Python, i'd like to check to make sure a command line argument is of type bool before I use it in a conditional statement. this: `isinstance(sys.argv[2], bool)` is coming back false. What's the right way to do this?
**ALL** command line arguments are strings. Please refine what you want. Do you want to check for the argument `true`? Then check if `sys.argv[2]` equals `true`.
Extracting whole words
5,717,886
7
2011-04-19T14:22:12Z
5,717,937
11
2011-04-19T14:25:35Z
[ "python", "regex", "word", "alphabetical", "text-extraction" ]
I have a large set of real-world text that I need to pull words out of to input into a spell checker. I'd like to extract as many *meaningful* words as possible without too much noise. I know there's plenty of regex ninjas around here, so hopefully someone can help me out. Currently I'm extracting all alphabetical seq...
If you restrict yourself to ASCII letters, then use (with the `re.I` option set) ``` \b[a-z]+\b ``` `\b` is a word boundary anchor, matching only at the start and end of alphanumeric "words". So `\b[a-z]+\b` matches `pie`, but not `pie21` or `21pie`. To also allow other non-ASCII letters, you can use something like ...
How to make exe file from pyc file
5,719,111
3
2011-04-19T15:49:57Z
5,719,225
7
2011-04-19T15:58:36Z
[ "python", "executable" ]
I want to create the window executable file of my project , I don't want to share the source code my project . i want to know where i started or which tool I use to create complete software . I use linux , py2exe does not run in linux,is there any other tool which is similar to py2exe?
I'd use [`cx_freeze`](http://cx-freeze.sourceforge.net/). I've tried `py2exe`, and it doesn't handle dependencies as well as `cx_freeze`. Best of all, it's cross-platform! I've made Windows and Linux binaries with it, so I can confirm it works properly. Here's a little tutorial to get you started: <http://www.blog.py...
MD5 hash discrepancy between Python and PHP?
5,719,471
22
2011-04-19T16:16:52Z
5,719,518
23
2011-04-19T16:20:44Z
[ "php", "python", "md5" ]
I'm trying to create a checksum of a binary file (flv/f4v, etc) to verify the contents of the file between the server and client computers. The application that's running on the client computer is python-based, while the server is using PHP. PHP code is as follows: ``` $fh = fopen($filepath, 'rb'); $contents = fread(...
I would rather assume that the base64 implementations differ. **EDIT** PHP: ``` php -r 'var_dump(base64_encode(str_repeat("x", 10)));' string(16) "eHh4eHh4eHh4eA==" ``` Python (Note the trailing newline): ``` >>> ("x" * 10).encode('base64') 'eHh4eHh4eHh4eA==\n' ```
MD5 hash discrepancy between Python and PHP?
5,719,471
22
2011-04-19T16:16:52Z
5,719,557
14
2011-04-19T16:24:46Z
[ "php", "python", "md5" ]
I'm trying to create a checksum of a binary file (flv/f4v, etc) to verify the contents of the file between the server and client computers. The application that's running on the client computer is python-based, while the server is using PHP. PHP code is as follows: ``` $fh = fopen($filepath, 'rb'); $contents = fread(...
PHP and python use different base64 flavors: * [PHP's base64\_encode](http://php.net/manual/en/function.base64-encode.php) uses [MIME (RFC 2045, see page 24)](http://www.ietf.org/rfc/rfc2045.txt) * [Python's base64 module](http://docs.python.org/library/base64.html) uses [RFC 3548](http://www.ietf.org/rfc/rfc3548.txt)...
Are there advantages to use the Python/C interface instead of Cython?
5,720,272
33
2011-04-19T17:27:18Z
5,756,844
59
2011-04-22T15:14:53Z
[ "python", "c", "numpy", "cython" ]
I want to extend python and numpy by writing some modules in C or C++, using BLAS and LAPACK. I also want to be able to distribute the code as standalone C/C++ libraries. I would like this libraries to use both single and double precision float. Some examples of functions I will write are conjugate gradient for solving...
The current "top answer" sounds a bit too much like FUD in my ears. For one, it is not immediately obvious that the Average Developer would write faster code in C than what NumPy+Cython gives you anyway. Quite the contrary, the time it takes to even get the necessary C code to work correctly in a Python environment is ...
Running Python script as root (with sudo) - what is the username of the effective user?
5,721,529
5
2011-04-19T19:21:02Z
6,447,942
18
2011-06-22T23:58:55Z
[ "python", "configuration", "user", "root", "sudo" ]
I've recently began using ConfigParser() for my python scripts to add some functionality to them for config files. I know how to use it but I have a problem. My script needs to run as the root user, using sudo. The config files are in `~/.config/scriptconfig/` but when you run a script as sudo it temporarily changes us...
If you run your script with sudo (`sudo myscript.py`) then the environment variable `$USER` will be `root` and the environment variable `$SUDO_USER` will be the name of the user who executed the command `sudo myscript.py`. This following is simply a clarification of the previous post by Cédric Julien. Consider the fol...
Does Python do slice-by-reference on strings?
5,722,006
11
2011-04-19T20:04:19Z
5,722,068
21
2011-04-19T20:10:08Z
[ "python", "string" ]
I want to know if when I do something like ``` a = "This could be a very large string..." b = a[:10] ``` a new string is created or a view/iterator is returned
[Python does slice-by-copy](http://mail.python.org/pipermail/python-dev/2008-May/079689.html), meaning every time you slice (except for [very trivial slices](http://mail.python.org/pipermail/python-dev/2008-May/079694.html), such as `a[:]`), it copies all of the data into a new string object. According to [one of the ...
django-mptt get_descendants for a list of nodes
5,722,767
9
2011-04-19T21:11:07Z
5,740,724
7
2011-04-21T07:07:31Z
[ "python", "django", "list", "mptt", "descendant" ]
I am trying to get all `descendants(include_self=True)` not for one Node, but for a list (a QuerySet) of Nodes. This should be one SQL query. Example (that actually is not working:) ``` some_nodes = Node.objects.filter( ...some_condition... ) some_nodes.get_descendants(include_self=True) #hopefully I would like to ...
Great thanks to Craig de Stigter answered my question on django-mptt-dev group, in case anybody need it I am kindly reposting **his** solution from <http://groups.google.com/group/django-mptt-dev/browse_thread/thread/637c8b2fe816304d> ``` from django.db.models import Q import operator def get_queryset_desce...
How to crop from one image and paste into another with PIL
5,723,400
6
2011-04-19T22:17:15Z
5,723,730
9
2011-04-19T22:57:33Z
[ "python", "python-imaging-library", "paste", "crop" ]
Hey, guys. This has probably been asked a million times, but i'm having a little trouble here. With PIL, i'm trying to copy a rectangle out of an image, and paste it into another. This is my code. ``` import Image ii = Image.open("ramza.png") box = (70, 70, 30, 30) region = ii.crop(box) io = Image.open("template.png")...
A PIL crop box is defined as a 4-tuple of pixel coordinates: **`(left, upper, right, lower)`**. To fix your code to get a 30x30 crop: ``` box = (70, 70, 100, 100) ``` Broken down into components: ``` x, y, w, h = (70, 70, 30, 30) box = (x, y, x + w, y + h) ```
How can I run the initialization code for a generator function immediately, rather than at the first call?
5,724,009
7
2011-04-19T23:41:18Z
5,724,453
12
2011-04-20T00:56:24Z
[ "python", "generator", "multiprocessing", "eager" ]
I have a generator function that goes something like this: ``` def mygenerator(): next_value = compute_first_value() # Costly operation while next_value != terminating_value: yield next_value next_value = compute_next_value() ``` I would like the initialization step (before the while loop) to ...
``` class mygenerator(object): def __init__(self): next_value = compute_first_value() def __iter__(self): return self def next(self): if next_value == terminating_value: raise StopIteration() return next_value ```
tail multiple logfiles in python
5,725,051
3
2011-04-20T02:59:28Z
5,725,135
8
2011-04-20T03:18:30Z
[ "python" ]
This is probably a bit of a silly excercise for me, but it raises a bunch of interesting questions. I have a directory of logfiles from my chat client, and I want to be notified using notify-osd every time one of them changes. The script that I wrote basically uses os.popen to run the linux tail command on every one o...
Not even looking at your source code, there are two ways you could easily do this more efficiently and handle multiple files. 1. Don't bother running tail unless you have to. Simply `os.stat` all of the files and record the last modified time. If the last modified time is different, then raise a notification. 2. Use [...
Check if a non-nullable field is null (Django)
5,725,065
3
2011-04-20T03:03:23Z
5,725,927
10
2011-04-20T05:31:28Z
[ "python", "django", "django-models", null, "django-orm" ]
I wanted to write some code like this: ``` class SomeModel(models.Model): field = models.ForeignKey(SomeOtherModel) def __init__(self, *args, **kwargs): super(SomeModel, self).__init__(*args, **kwargs) if self.field is None: self.field = SomeOtherModel() ... ``` However this...
Check if it has the attribute set - ``` if hasattr(self, 'field', False) ```
How do I use pdfminer as a library
5,725,278
55
2011-04-20T03:50:00Z
5,730,942
11
2011-04-20T13:16:30Z
[ "python", "pdf", "pdfminer" ]
I am trying to get text data from a pdf using [pdfminer](http://www.unixuser.org/~euske/python/pdfminer/index.html). I am able to extract this data to a .txt file successfully with the pdfminer command line tool pdf2txt.py. I currently do this and then use a python script to clean up the .txt file. I would like to inco...
I know it is poor taste to answer your own question, but I think I may have figured this out and I don't want anyone else to waste their time looking for a solution to my problem. I followed the suggestion in a one of the links posted in my question and re-purposed the current pdf2txt.py script included with pdfminer....
How do I use pdfminer as a library
5,725,278
55
2011-04-20T03:50:00Z
8,325,135
60
2011-11-30T11:24:20Z
[ "python", "pdf", "pdfminer" ]
I am trying to get text data from a pdf using [pdfminer](http://www.unixuser.org/~euske/python/pdfminer/index.html). I am able to extract this data to a .txt file successfully with the pdfminer command line tool pdf2txt.py. I currently do this and then use a python script to clean up the .txt file. I would like to inco...
Here is a cleaned up version I finally produced that worked for me. The following just simply returns the string in a PDF, given its filename. I hope this saves someone time. ``` from pdfminer.pdfinterp import PDFResourceManager, process_pdf from pdfminer.converter import TextConverter from pdfminer.layout import LAPa...
How do I use pdfminer as a library
5,725,278
55
2011-04-20T03:50:00Z
20,905,381
61
2014-01-03T14:02:11Z
[ "python", "pdf", "pdfminer" ]
I am trying to get text data from a pdf using [pdfminer](http://www.unixuser.org/~euske/python/pdfminer/index.html). I am able to extract this data to a .txt file successfully with the pdfminer command line tool pdf2txt.py. I currently do this and then use a python script to clean up the .txt file. I would like to inco...
Here is a new solution that works with the latest version: ``` from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.converter import TextConverter from pdfminer.layout import LAParams from pdfminer.pdfpage import PDFPage from cStringIO import StringIO def convert_pdf_to_txt(path): r...
How do I use pdfminer as a library
5,725,278
55
2011-04-20T03:50:00Z
26,351,413
8
2014-10-14T01:41:19Z
[ "python", "pdf", "pdfminer" ]
I am trying to get text data from a pdf using [pdfminer](http://www.unixuser.org/~euske/python/pdfminer/index.html). I am able to extract this data to a .txt file successfully with the pdfminer command line tool pdf2txt.py. I currently do this and then use a python script to clean up the .txt file. I would like to inco...
This worked for me using the most recent version of pdfminer (as of September 2014): ``` from pdfminer.pdfparser import PDFParser from pdfminer.pdfdocument import PDFDocument from pdfminer.pdfpage import PDFPage from pdfminer.pdfpage import PDFTextExtractionNotAllowed from pdfminer.pdfinterp import PDFResourceManager ...
How can I concatenate forloop.counter to a string in my django template
5,725,794
16
2011-04-20T05:12:39Z
5,726,302
35
2011-04-20T06:22:23Z
[ "python", "django", "django-templates", "for-loop", "string-concatenation" ]
I am already trying to concatenate like this: ``` {% for choice in choice_dict %} {% if choice =='2' %} {% with "mod"|add:forloop.counter|add:".html" as template %} {% include template %} {% endwith %} {% endif %} {% endfor %} ``` but for some reason I am only ge...
Your problem is that the forloop.counter is an integer and you are using the `add` template filter which will behave properly if you pass it all strings or all integers, but not a mix. One way to work around this is: ``` {% for x in some_list %} {% with y=forloop.counter|stringformat:"s" %} {% with template="...
how to get this string using python
5,726,134
2
2011-04-20T06:00:02Z
5,726,147
8
2011-04-20T06:02:27Z
[ "python", "string" ]
i have a list like this : ``` a=[1000,200,30] ``` and i want to get a list like this : ``` ['01000','00200','00030'] ``` so what can i do , thanks
``` >>> a=[1000,200,30] >>> [str(e).zfill(5) for e in a] ['01000', '00200', '00030'] ``` [str.zfill](http://docs.python.org/library/stdtypes.html#str.zfill)
buildout - using different python version
5,726,289
6
2011-04-20T06:21:31Z
5,727,084
8
2011-04-20T07:42:45Z
[ "python", "version", "buildout" ]
i have set up buildout project (django to be specific) that has to run in old machine, it works fine in my local system with python 2.7. In production server it runs python 2.5 and i want to configure buildout that it would download and use 2.6, but only this project not system wide. So i assume it should use some so...
Buildout specifically supports this scenario. Each part in a buildout can use it's own python interpreter, or you can set one python interpreter globally for all parts. This defaults to the python used to run buildout. To set the python interpreter used, set the `python` option to the name of a part that contains an `...
Python package external dependencies
5,729,051
17
2011-04-20T10:47:16Z
5,729,197
10
2011-04-20T10:59:46Z
[ "python", "packaging" ]
I'm writing a python script which uses an external library (paramiko). If I'm to release the package how do I package paramiko also? Is there anyway I can give it as we can give dependencies in java as .jar files? Edit: What I had in my mind was giving a single script and an archive file which contains all the depende...
Make it a proper package and read up about setuptools: [Python distribute link](http://pythonhosted.org/setuptools/setuptools.html) Dependencies can be specified using 'install\_requires' parameter inside the setup.py file of your package.
PyCUDA: Querying Device Status (Memory specifically)
5,730,010
3
2011-04-20T12:10:08Z
5,731,911
10
2011-04-20T14:23:57Z
[ "python", "cuda", "device-driver", "gpgpu", "pycuda" ]
PyCUDA's documentation mentions [Driver Interface](http://documen.tician.de/pycuda/driver.html) calls in passing, but I'm a bit think and can't see how to get information such as 'SHARED\_SIZE\_BYTES' out of my code. Can anyone point me to any examples of querying the device in this way? Is it possible to / How do I ...
Just for anyone else coming across this, spending half an hour with the [CUDA API](http://developer.download.nvidia.com/compute/cuda/4_0_rc2/toolkit/docs/CUDA_Toolkit_Reference_Manual.pdf) in one hand, and the [PyCUDA documentation](http://documen.tician.de/pycuda/driver.html#devices-and-contexts) in another does wonde...
How does get_FIELD_display (in django) work?
5,730,211
12
2011-04-20T12:24:49Z
5,730,401
17
2011-04-20T12:37:04Z
[ "python", "django" ]
I'm a novice in Django and Python, and recently came across a number of methods in Django docs, such as Model.get\_FOO\_display(). Help page says that you can substitute FOO for a name of a field. I've been trying to figure out how that is possible in Python and looked into 'Model' class souce. There I came across this...
This is all managed via the metaclass - you'll see in the source that the Model class defines a `__metaclass__` attribute, which is set to `ModelBase`. The metaclass is to the class as a class is to an instance. So the metaclass is called when a Django class is *defined*. The metaclass then executes various code which...
Export all keys and values from memcached with python-memcache
5,730,276
6
2011-04-20T12:28:34Z
9,005,792
18
2012-01-25T16:00:03Z
[ "python", "memcached" ]
I would like to export all keys and values from a memcached server, using python-memcache. There is no such function in that module. How to do it then ? Perhaps something more complicated involving the "socket" module would be needed. Thanks !
This will get you all the keys on a memcached server, you can use any memcached client library to get the value for each key. ``` import telnetlib def get_all_memcached_keys(host='127.0.0.1', port=11211): t = telnetlib.Telnet(host, port) t.write('stats items STAT items:0:number 0 END\n') items = t.read_un...
Export all keys and values from memcached with python-memcache
5,730,276
6
2011-04-20T12:28:34Z
14,491,419
8
2013-01-23T23:38:03Z
[ "python", "memcached" ]
I would like to export all keys and values from a memcached server, using python-memcache. There is no such function in that module. How to do it then ? Perhaps something more complicated involving the "socket" module would be needed. Thanks !
use the [memdump](http://docs.libmemcached.org/bin/memdump.html) and [memcat](http://docs.libmemcached.org/bin/memcat.html) utilities from the [libmemcached](http://docs.libmemcached.org/) suite. They can't guarantee you'll get all the data but they're easy to use. **Note:** On ubuntu/debian you can get these by intst...
codility absolute distinct count from an array
5,730,330
11
2011-04-20T12:32:20Z
5,730,464
8
2011-04-20T12:41:39Z
[ "c#", "java", "python", "c++", "algorithm" ]
so i took the codility interview test yesterday and was informed today that i failed, unfortunately i wasnt given any other information by either codility nor the employer as to where i screwed up so i would appreciate some help in knowing where i went wrong. i know codility pays alot of emphasis on how fast the progra...
If the array is sorted you can find duplicates by looking a neightbours. To compare absolute values to need to start at both the start and the end. This avoid creating a new structure. EDIT: IMHO HashMap/HashSet is O(log(log(n)) due to collisions, it is only O(1) if there is a perfect hash function. I would have thoug...
codility absolute distinct count from an array
5,730,330
11
2011-04-20T12:32:20Z
5,730,468
7
2011-04-20T12:41:54Z
[ "c#", "java", "python", "c++", "algorithm" ]
so i took the codility interview test yesterday and was informed today that i failed, unfortunately i wasnt given any other information by either codility nor the employer as to where i screwed up so i would appreciate some help in knowing where i went wrong. i know codility pays alot of emphasis on how fast the progra...
You should have pay attention to the fact that **the array is sorted in ascending order**. Lets assume that there are only positive numbers, or the question was not about **absolute** distinct. The you could count the Number by iterating trough the list, and increment the counter by one, if the actual element is diff...
installing only .pyc (python compiled) with setuptools
5,730,686
5
2011-04-20T12:57:45Z
5,731,055
11
2011-04-20T13:25:44Z
[ "python", "setuptools" ]
I want to run `python setup.py install` (the setup script uses setuptools), and I want only the .pyc files to be included in the resulting egg or directory. all .py files must not be present. How can I do this ?
not with `install`, but a possibility is to run the following command `python setup.py bdist_egg --exclude-source-files` and install the resulting egg in dist with easy\_install `easy_install dist/eggname.egg` Note that [according to the manual](http://peak.telecommunity.com/DevCenter/setuptools#install-run-easy-in...
Where can I find source code for itertools.combinations() function
5,731,505
7
2011-04-20T13:56:48Z
5,731,531
12
2011-04-20T13:58:47Z
[ "python", "python-3.x" ]
I'm trying to find a way to write a combination function. Where can I find it?
See in the documentation of [itertools.combinations](http://docs.python.org/library/itertools.html#itertools.combinations). There is an equivalent code for this function: ``` def combinations(iterable, r): # combinations('ABCD', 2) --> AB AC AD BC BD CD # combinations(range(4), 3) --> 012 013 023 123 pool ...
Where can I find source code for itertools.combinations() function
5,731,505
7
2011-04-20T13:56:48Z
5,731,578
9
2011-04-20T14:02:35Z
[ "python", "python-3.x" ]
I'm trying to find a way to write a combination function. Where can I find it?
The actual source code is written in C and can be found in the file [`itertoolsmodule.c`](http://svn.python.org/view/python/tags/r271/Modules/itertoolsmodule.c?view=markup). As pointed out in [eumiro's answer](http://stackoverflow.com/questions/5731505/where-can-i-find-source-code-for-itertools-combinations-function/57...
Simple random name generator in Python
5,731,670
5
2011-04-20T14:09:35Z
5,731,759
8
2011-04-20T14:15:03Z
[ "python" ]
I have a text file containing first and last 'syllables', demarcated with [part1] and [part2]: ``` [part1] Ae Di Mo Fam [part2] dar kil glar tres ``` All I want to do is pick a random line, between [part1] and [part2], and then another random line between [part2] and the end of the file, and concatenate the two toget...
Serialize ([pickle](http://docs.python.org/library/pickle.html)) a dictionary to a file instead. Example: ``` # create the dict and save it to a file d={ 'part1':[ 'Ae', 'Di', 'Mo', 'Fam',], 'part2':[ 'dar', 'kil', 'glar', 'tres',], } import pickle f=open('syllables','w') pickle.dump(...
Python memory management for list()
5,731,878
7
2011-04-20T14:22:15Z
5,731,957
10
2011-04-20T14:26:29Z
[ "python" ]
I'm creating a tuple, and then converting it to a list with the code: ``` y=("hello","the","world") y=list(y) ``` Does python simply mark the objects as now mutable and reachable through the label y, or does it create a complete copy of every object, add these to the new list structure, and then delete the original i...
You can find out by inspecting the `id` of each object. Here are the results from my run. ``` y=("hello","the","world") id(y), [id(i) for i in y] (18627040, [21912480, 21964056, 21910304]) y = list(y) id(y), [id(i) for i in y] (21905536, [21912480, 21964056, 21910304]) ``` As you can see the objects are the same. ...
Python memory management for list()
5,731,878
7
2011-04-20T14:22:15Z
5,731,974
14
2011-04-20T14:27:22Z
[ "python" ]
I'm creating a tuple, and then converting it to a list with the code: ``` y=("hello","the","world") y=list(y) ``` Does python simply mark the objects as now mutable and reachable through the label y, or does it create a complete copy of every object, add these to the new list structure, and then delete the original i...
During the execution of the line ``` y = list(y) ``` the following happens: 1. The right-hand side gets evaluated. This includes creating a new list object. The list object is filled with the items of the tuple object passed to the constructor. These items are not copied. Rather their reference count is increased, a...
How do I handle file upload via PUT request in Django?
5,731,984
17
2011-04-20T14:28:00Z
5,761,473
8
2011-04-23T01:19:30Z
[ "python", "django", "rest", "http-put", "django-1.3" ]
I'm implementing a REST-style interface and would like to be able to create (via upload) files via a HTTP PUT request. I would like to create either a `TemporaryUploadedFile` or a `InMemoryUploadedFile` which I can then pass to my existing `FileField` and `.save()` on the object that is part of the model, thereby stori...
> Django 1.3 is acceptable. So I can > either do something with > request.raw\_post\_data or > request.read() (or alternatively some > other better method of access). Any > ideas? You don't want to be touching `request.raw_post_data` - that implies reading the entire request body into memory, which if you're talking a...
How to iterate over the file in python
5,733,419
12
2011-04-20T16:15:00Z
5,733,475
7
2011-04-20T16:20:19Z
[ "python" ]
I have a text file with some hexadecimal numbers and i am trying to convert it to decimal. I could successfully convert it, but it seems before the loop exist it reads some unwanted character and so i am getting the following error. ``` Traceback (most recent call last): File "convert.py", line 7, in <module> pr...
Just use `for x in f: ...`, this gives you line after line, is much shorter and readable (partly because it automatically stops when the file ends) and also saves you the `rstrip` call because the trailing newline is already stipped. The error is caused by the exit condition, which can never be true: Even if the file ...
How to iterate over the file in python
5,733,419
12
2011-04-20T16:15:00Z
5,733,487
28
2011-04-20T16:20:56Z
[ "python" ]
I have a text file with some hexadecimal numbers and i am trying to convert it to decimal. I could successfully convert it, but it seems before the loop exist it reads some unwanted character and so i am getting the following error. ``` Traceback (most recent call last): File "convert.py", line 7, in <module> pr...
The traceback indicates that probably you have an empty line at the end of the file. You can fix it like this: ``` f = open('test.txt','r') g = open('test1.txt','w') while True: x = f.readline() x = x.rstrip() if not x: break print >> g, int(x, 16) ``` On the other hand it would be better to use `for...
How to create a month iterator
5,734,438
10
2011-04-20T17:45:27Z
5,734,564
22
2011-04-20T17:57:13Z
[ "python" ]
I would like to create a python function that would allow me to iterate over the months from a start point to a stop point. For example it would look something like ``` def months(start_month, start_year, end_month, end_year): ``` Calling `months(8, 2010, 3, 2011)` would return: ``` ((8, 2010), (9, 2010), (10, 2010)...
The calendar works like this. ``` def month_year_iter( start_month, start_year, end_month, end_year ): ym_start= 12*start_year + start_month - 1 ym_end= 12*end_year + end_month - 1 for ym in range( ym_start, ym_end ): y, m = divmod( ym, 12 ) yield y, m+1 ``` All multiple-unit things work l...
Sync django-piston models when using egg module
5,735,237
3
2011-04-20T18:57:08Z
8,282,918
8
2011-11-27T01:10:05Z
[ "python", "django", "django-piston" ]
I'm using django-piston and running into the following problem when running the manage.py syncdb command: ``` Traceback (most recent call last): File "./manage.py", line 13, in <module> execute_manager(settings) File "/home/appfirst/django/django/core/management/__init__.py", line 438, in execute_manager u...
Looks like this is a [known issue](https://bitbucket.org/jespern/django-piston/issue/173/) with Piston 0.2.3. You could apply [this patch](https://bitbucket.org/jespern/django-piston/issue/173/attributeerror-module-object-has-no#comment-455549) or just use version 0.2.2 by installing it as so: ``` pip install django-p...
Python: TypeError: 'list' object is not callable
5,735,841
22
2011-04-20T19:52:25Z
5,735,943
28
2011-04-20T20:00:42Z
[ "python", "callable" ]
I am trying to run this code where I have a list of lists. I need to add to inner lists, but I get the error TypeError: 'list' object is not callable. Can anyone tell me what am I doing wrong here. ``` def createlists(): global maxchar global minchar global worddict global wordlists for i in range...
Instead of: ``` print wordlists(len(words)) ``` you probably meant: ``` print worldlists[len(words)] ``` And instead of: ``` (wordlists(len(words))).append(words) ``` you probably meant: ``` worldlists[len(words)].append(words) ``` Though this is just guessing.
Django REST browser interface
5,736,868
2
2011-04-20T21:29:06Z
5,738,122
8
2011-04-21T00:20:14Z
[ "python", "django", "web-services", "testing", "rest" ]
I'm writing a set of REST services for a Django project. I've been using django-rest-framework for a while. Because of its limited functionality I had to switch to django-piston which I quite enjoy. However, django-rest-framework had one really nice feature - it was able to display an admin-like interface for testing ...
This may seem obvious, but: Why not just use Django's testing client (django.test.client.Client)? then instead of manually 'debugging' in your browser, you can write unit tests with expectations and get leverage out of those further down the track. e.g. ``` from django.test.client import Client client = Client() resp...
Is there an expression for an infinite generator?
5,737,196
54
2011-04-20T22:05:26Z
5,737,588
86
2011-04-20T22:58:30Z
[ "python", "generator", "infinite-loop" ]
Is there a straight-forward generator expression that can yield infinite elements? This is a purely theoretical question. No need for a "practical" answer here :) --- For example, it is easy to make a finite generator: ``` my_gen = (0 for i in xrange(42)) ``` However, to make an infinite one I need to "pollute" my...
[`itertools`](http://docs.python.org/2/library/itertools.html) provides three infinite generators: * [`count(start=0, step=1)`](http://docs.python.org/2/library/itertools.html#itertools.count): 0, 1, 2, 3, 4, ... * [`cycle(p)`](http://docs.python.org/2/library/itertools.html#itertools.cycle): p[0], p[1], ..., p[-1], p...
Is there an expression for an infinite generator?
5,737,196
54
2011-04-20T22:05:26Z
5,739,258
60
2011-04-21T03:41:13Z
[ "python", "generator", "infinite-loop" ]
Is there a straight-forward generator expression that can yield infinite elements? This is a purely theoretical question. No need for a "practical" answer here :) --- For example, it is easy to make a finite generator: ``` my_gen = (0 for i in xrange(42)) ``` However, to make an infinite one I need to "pollute" my...
``` for x in iter(int, 1): pass ``` * Two-argument `iter` = zero-argument callable + sentinel value * `int()` always returns `0` Therefore, `iter(int, 1)` is an infinite iterator. There are obviously a huge number of variations on this particular theme (especially once you add `lambda` into the mix). One variant of p...
Pythonic method of determining if a list's contents change from odd to even values
5,737,224
18
2011-04-20T22:08:43Z
5,737,378
8
2011-04-20T22:26:57Z
[ "list", "python" ]
Writing some test cases and my mind wanders, assuming there is a better way to write something like this. I have a list, its numbers transition from all odd values to all even, doesn't matter where. I need to assert this is the case, here's what I came up with: ``` values = [1, 3, 5, 7, 5, 3, 5, 3, 5, 7, 4, 6, 8, 4, 2...
A possible solution is to consider that you allow only ``` odd->odd odd->even even->even ``` in other words the only forbidden transition is ``` even->odd ``` and this translates to ``` (0, 1) not in ((x%2, y%2) for x, y in zip(values, values[1:])) ```
Python for loop slows and evenutally hangs
5,737,336
5
2011-04-20T22:21:15Z
5,737,432
8
2011-04-20T22:34:25Z
[ "python", "for-loop", "hang" ]
I'm totally new to Python (as of half an hour ago) and trying to write a simple script to enumerate users on an SMTP server. The users file is a simple list (one per line) of usernames. The script runs fine but with each iteration of the loop it slows until, around loop 14, it seems to hang completely. No error - I h...
Most likely your SMTP server is tarpitting your client connection. This is a defense against runaway clients, or clients which submit large volumes of "junk" commands. From the manpage for Postfix smtpd: ``` smtpd_junk_command_limit (normal: 100, stress: 1) The number of junk commands (NOOP, VRFY, ETRN or...
Anonymous class inheritance
5,737,728
5
2011-04-20T23:17:20Z
5,737,892
10
2011-04-20T23:43:47Z
[ "inheritance", "python" ]
I am building a python automation API around a device configuration that looks like this... ``` root@EX4200-24T# show interfaces ge-0/0/6 mtu 9216; unit 0 { family ethernet-switching { port-mode trunk; vlan { members [ v100 v101 v102 ]; } } } root@EX4200-24T# ``` I am def...
Does something like this help you? ``` from functools import partial S=partial(SET, Family='ethernet-switching', PortMode='trunk') S(Interface='ge-0/0/6.0', Vlan=['v100', 'v101', 'v102']) S(Interface='ge-0/0/7.0', Vlan=['v100', 'v101', 'v102']) S(Interface='ge-0/0/8.0', Vlan=['v100', 'v101', 'v102']) ```
Unable to handle DeadlineExceededError while using UrlFetch
5,738,146
15
2011-04-21T00:23:47Z
5,738,694
19
2011-04-21T01:59:22Z
[ "python", "google-app-engine" ]
I have this basic utility class fetches (possibly) shortened URLs in parallel and returns a dictionary that has final URLs. It uses the wait\_any functionality that was described in this [blog post](http://neopythonic.blogspot.com/2011/01/asynchronous-rpc-in-app-engine-today.html). ``` class UrlFetcher(object): @cl...
Per the inline docs for `google.appengine.runtime.DeadlineExceededError`: > Exception raised when the request > reaches its overall time limit. > > Not to be confused with > runtime.apiproxy\_errors.DeadlineExceededError. > That one is raised when individual API > calls take too long. This is a good demonstration of ...
Unable to handle DeadlineExceededError while using UrlFetch
5,738,146
15
2011-04-21T00:23:47Z
12,905,977
9
2012-10-16T00:39:41Z
[ "python", "google-app-engine" ]
I have this basic utility class fetches (possibly) shortened URLs in parallel and returns a dictionary that has final URLs. It uses the wait\_any functionality that was described in this [blog post](http://neopythonic.blogspot.com/2011/01/asynchronous-rpc-in-app-engine-today.html). ``` class UrlFetcher(object): @cl...
As you guessed and others noted, you want a different `DeadlineExceededError`: From <https://developers.google.com/appengine/articles/deadlineexceedederrors>, dated June 2012: > Currently, there are several errors named DeadlineExceededError for the Python runtime:> > > **google.appengine.runtime.DeadlineExceededErro...
What's an example use case for a Python classmethod?
5,738,470
39
2011-04-21T01:19:17Z
5,738,551
14
2011-04-21T01:33:49Z
[ "python", "class", "class-method" ]
I've read [What are Class methods in Python for?](http://stackoverflow.com/questions/38238/what-are-class-methods-in-python-for) but the examples in that post are complex. I am looking for a clear, simple, bare-bones example of a particular use case for classmethods in Python. Can you name a small, specific example us...
I don't know, something like named constructor methods? ``` class UniqueIdentifier(object): value = 0 def __init__(self, name): self.name = name @classmethod def produce(cls): instance = cls(cls.value) cls.value += 1 return instance class FunkyUniqueIdentifier(Unique...
What's an example use case for a Python classmethod?
5,738,470
39
2011-04-21T01:19:17Z
5,738,576
11
2011-04-21T01:39:18Z
[ "python", "class", "class-method" ]
I've read [What are Class methods in Python for?](http://stackoverflow.com/questions/38238/what-are-class-methods-in-python-for) but the examples in that post are complex. I am looking for a clear, simple, bare-bones example of a particular use case for classmethods in Python. Can you name a small, specific example us...
I find that I most often use `@classmethod` to associate a piece of code with a class, to avoid creating a global function, for cases where I don't require an instance of the class to use the code. For example, I might have a data structure which only considers a key valid if it conforms to some pattern. I may want to...
What's an example use case for a Python classmethod?
5,738,470
39
2011-04-21T01:19:17Z
5,738,586
33
2011-04-21T01:40:47Z
[ "python", "class", "class-method" ]
I've read [What are Class methods in Python for?](http://stackoverflow.com/questions/38238/what-are-class-methods-in-python-for) but the examples in that post are complex. I am looking for a clear, simple, bare-bones example of a particular use case for classmethods in Python. Can you name a small, specific example us...
Helper methods for initialization: ``` class MyStream(object): @classmethod def from_file(cls, filepath, ignore_comments=False): with open(filepath, 'r') as fileobj: for obj in cls(fileobj, ignore_comments): yield obj @classmethod def from_socket(cls, socket, i...
What's an example use case for a Python classmethod?
5,738,470
39
2011-04-21T01:19:17Z
5,738,629
22
2011-04-21T01:48:27Z
[ "python", "class", "class-method" ]
I've read [What are Class methods in Python for?](http://stackoverflow.com/questions/38238/what-are-class-methods-in-python-for) but the examples in that post are complex. I am looking for a clear, simple, bare-bones example of a particular use case for classmethods in Python. Can you name a small, specific example us...
Well `__new__` is a pretty important classmethod. It's where instances usually come from so `dict()` calls `dict.__new__` of course, but there is another handy way to make dicts sometimes which is the classmethod `dict.fromkeys()` eg. ``` >>> dict.fromkeys("12345") {'1': None, '3': None, '2': None, '5': None, '4': N...
Removing elements that have consecutive dupes
5,738,901
9
2011-04-21T02:39:13Z
5,738,933
17
2011-04-21T02:45:01Z
[ "python", "list", "duplicates", "implementation" ]
I was curios about the question: [Eliminate consecutive duplicates of list elements][1], and how it should be implemented in Python. What I came up with is this: ``` list = [1,1,1,1,1,1,2,3,4,4,5,1,2] i = 0 while i < len(list)-1: if list[i] == list[i+1]: del list[i] else: i = i+1 ``` Output:...
``` >>> L=[1,1,1,1,1,1,2,3,4,4,5,1,2] >>> from itertools import groupby >>> [x[0] for x in groupby(L)] [1, 2, 3, 4, 5, 1, 2] ``` If you wish, you can use map instead of the LC ``` >>> from operator import itemgetter >>> map(itemgetter(0), groupby(L)) [1, 2, 3, 4, 5, 1, 2] ``` For the second part ``` >>> [x for x,y ...
Python, pipes, and the "-c" option in the command line
5,739,066
4
2011-04-21T03:10:07Z
5,739,115
7
2011-04-21T03:19:33Z
[ "python", "command-line", "pipe" ]
I vaguely recall being able to do something like this in Python: ``` cat foo | python -c "<some python code>" | grep blah | ... ``` For some reason I'm blanking on how to actually use this to run Python code on each line of the input file. For instance, say I wanted to change every instance of the word "apple" in the...
I don't see how this can be helpful more than once, but here's a one-liner: ``` cat file | grep apple | python -c "for line in __import__('sys').stdin: print line.replace(\"apple\", \"orange\")," ```
Nested List and For Loop
5,740,232
3
2011-04-21T06:10:06Z
5,740,253
12
2011-04-21T06:12:59Z
[ "python" ]
Consider this: ``` list = 2*[2*[0]] for y in range(0,2): for x in range(0,2): if x ==0: list[x][y]=1 else: list[x][y]=2 print list ``` Result: ``` [[2,2],[2,2]] ``` Why doesn't the result be [[1,1],[2,2]]?
Because you are creating a list that is two references to the same sublist ``` >>> L = 2*[2*[0]] >>> id(L[0]) 3078300332L >>> id(L[1]) 3078300332L ``` so changes to L[0] will affect L[1] because they are the same list The usual way to do what you want would be ``` >>> L = [[0]*2 for x in range(2)] >>> id(L[0]) 3078...
Textmate Whitespace/Invisibles - Show Spaces
5,740,260
7
2011-04-21T06:13:53Z
19,243,383
12
2013-10-08T09:03:32Z
[ "python", "textmate", "haml", "yaml", "coffeescript" ]
Is there a way to show "Soft Tabs" (spaces) in TextMate? `View` → `Show Invisibles` works well for keeping track of indentation if you're using tabs for indentation. Unfortunately in languages where indentation is semantic you generally *have* to use spaces. (Python, YAML, HAML, CoffeeScript) Any suggestions for showi...
The [latest version](https://api.textmate.org/downloads/release) of TextMate 2 highlights spaces when `Show Invisibles` is enabled. ![invisibles](http://i.stack.imgur.com/aQ0ct.png) --- **EDIT:** You can even customize which invisibles to show with which character by modifying the `invisiblesMap` property in `.tm_p...
How to use Pipe in ipython
5,740,835
12
2011-04-21T07:18:02Z
5,740,863
15
2011-04-21T07:21:17Z
[ "python", "scroll", "ipython", "pager" ]
In linux terminal, when the output of one command is too long to read in one page, i can do this: ``` cat file | less ``` so that i can read and scroll up and down the output from "cat file" how can i do this in ipython ? for example: i tried this and it didnt work: ``` whos | less ``` my original problem is that...
In IPython, you can use `%page obj` to show the object `obj` using your standard pager (usually `less`). Alternatively, you can increase the scroll buffer of your terminal, which might be convenient in any case. **`%page obj`** -- display object similar to IPython default display (repr-like), using pager if output siz...
Syntax in Python (.T)
5,741,372
19
2011-04-21T08:17:45Z
5,741,396
23
2011-04-21T08:19:32Z
[ "python", "numpy" ]
In the help resource for the multivariate normal sampling function in SciPy, they give the following example: ``` x,y = np.random.multivariate_normal(mean,cov,5000).T ``` My question is rather basic: what does the final .T actually do? Thanks a lot, I know it is fairly simple, but it is hard to look in Google for "....
The `.T` accesses the attribute `T` of the object, which happens to be a NumPy array. The `T` attribute is the transpose of the array, see [the documentation](http://docs.scipy.org/doc/numpy-1.5.x/reference/generated/numpy.ndarray.T.html#numpy.ndarray.T). Apparently you are creating random coordinates in the plane. Th...
Reading each column from csv file
5,741,518
2
2011-04-21T08:30:45Z
5,741,588
13
2011-04-21T08:36:58Z
[ "python", "csv" ]
I want to read each column of a csv file and do some modification before storing them into table. I have a csv files as : ``` "1";"testOne";"ValueOne" "2";"testTwo";"ValueTwo" "3";"testThree";"ValueThree" ``` Here I want to read the first value "1" and then store it somewhere in a varaible and do something with this...
Python has a built-in [csv](http://docs.python.org/library/csv.html) module. ``` import csv with open('some.csv', 'rb') as f: reader = csv.reader(f, delimiter=';') for row in reader: print row[0] ```
django form with multiple file fields
5,742,119
11
2011-04-21T09:26:23Z
5,742,182
8
2011-04-21T09:32:33Z
[ "python", "django", "django-forms" ]
How do you handle multiple file fields in Django. For example if I had only one form field i would pass the request.FILES['file'] to a handling function. But what is the way to go when there are more files?
`request.FILES.get('filename', None)` responds to the existence of a form-named field like this: ``` <input type="file" name="filename"></input> ``` If you had two such fields: ``` <input type="file" name="file1"></input> <input type="file" name="file2"></input> ``` Then `request.FILES.get('file1', None)` and `requ...
django form with multiple file fields
5,742,119
11
2011-04-21T09:26:23Z
7,355,997
23
2011-09-09T00:31:24Z
[ "python", "django", "django-forms" ]
How do you handle multiple file fields in Django. For example if I had only one form field i would pass the request.FILES['file'] to a handling function. But what is the way to go when there are more files?
I'm late to the party, but I've been trying to figure this out for a while and finally have a solution. Have a look at the code used here: <https://code.djangoproject.com/ticket/12446> You can access multipart values with getlist. If my HTML form was: ``` <form enctype="multipart/form-data" action="" method="post"> <...
Python: Using split on a string and returning a tuple?
5,742,562
6
2011-04-21T10:07:30Z
5,742,622
11
2011-04-21T10:12:01Z
[ "python" ]
Say I do the following: ``` >>> a = foo@bar.com >>> uname, domain = a.split('@') ``` But what if I only ever want domain, and never uname? For example, if I only ever wanted uname and not domain, I could do this: ``` >>> uname, = a.split('@') ``` Is there a better way to split a into a tuple and have it throw away ...
To take into account some of the other answers, you have the following options: If you know that the string will have an '@' symbol in it then you can simply do the following: ``` >>> domain = a.split('@')[1] ``` If there is a chance that you don't have an '@' symbol, then one of the following is suggested: ``` >>>...