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
Including global package into a virtualenv that has been created with --no-site-packages
2,767,382
16
2010-05-04T17:11:29Z
16,217,474
8
2013-04-25T14:28:40Z
[ "python", "virtualenv", "easy-install", "pip" ]
I'd usually prefer to create virtualenvs with --no-site-packages option for more isolation, and also because default python global packages includes quite a lot of packages, and usually most of them are not needed. However I'd still want to keep a few select packages in global, like PIL or psycopg2. Is there a good way...
If you are using [virtualenvwrapper](https://bitbucket.org/dhellmann/virtualenvwrapper), the shell command `add2virtualenv` should be present in an active virtualenv. Use: ``` add2virtualenv /path/to/package ``` to add an entry to the PTH file `_virtualenv_path_extensions.pth` in your virtualenv site-packages. The b...
SQLAlchemy Relationship Filter?
2,767,503
12
2010-05-04T17:27:10Z
2,769,063
9
2010-05-04T21:21:35Z
[ "python", "sqlalchemy" ]
can i do: ``` table.relationship.filter( column = value ) ``` to get a subset of rows for relationships? and the same for order\_by?
According to the [`relationship()` documentation](http://docs.sqlalchemy.org/en/rel_0_9/orm/relationships.html), you can use `order_by` keyword argument with `relationship`s, to set the order that will be returned. On the same page, it mentions that you can also use `primaryjoin` keyword argument to define extra join p...
SQLAlchemy Relationship Filter?
2,767,503
12
2010-05-04T17:27:10Z
2,790,359
28
2010-05-07T17:19:19Z
[ "python", "sqlalchemy" ]
can i do: ``` table.relationship.filter( column = value ) ``` to get a subset of rows for relationships? and the same for order\_by?
`relationship()` with `lazy='dynamic'` option gives you a query (`AppenderQuery` object which allows you to add/remove items), so you can `.filter()`/`.filter_by()` and `.order_by()` it.
Generating content diffs using SequenceMatcher (Python)
2,767,822
2
2010-05-04T18:09:17Z
2,769,476
7
2010-05-04T22:50:14Z
[ "python", "diff" ]
I want to generate a diff between to revisions of text (more specifically, Markdown-formatted articles) in Python. I want to format this diff in a manner similar to what [Github](http://www.github.com/) does. I've looked at `difflib` and have found that it does what I want. However, the `Differ` class is too high-lev...
SequenceMatcher is actually not that low-level. The most interesting method for you is [`get_grouped_opcodes`](http://docs.python.org/library/difflib.html#difflib.SequenceMatcher.get_grouped_opcodes). It will return a generator, which generates lists with change descriptions. I'll explain it on an example from a [rand...
google app engine python download file
2,767,910
13
2010-05-04T18:21:05Z
2,767,946
27
2010-05-04T18:27:15Z
[ "python", "google-app-engine", "download" ]
I am trying to figure out a way where I can create a tab-delimited file containing data from user-defined fields and allow the user to download that file on google app engine. The sandbox environment that the app runs in does not allow the application to write to disk. Is there another way where I can create a downloa...
Sure there is! You can output your data as `csv`, for instance. All you need to do is to change the `Content-Type` header. It's something like this: ``` class Test(webapp.RequestHandler): def get(self, upload_type): self.response.headers['Content-Type'] = 'text/csv' self.response.out.write(','.joi...
google app engine python download file
2,767,910
13
2010-05-04T18:21:05Z
4,591,893
20
2011-01-04T08:51:02Z
[ "python", "google-app-engine", "download" ]
I am trying to figure out a way where I can create a tab-delimited file containing data from user-defined fields and allow the user to download that file on google app engine. The sandbox environment that the app runs in does not allow the application to write to disk. Is there another way where I can create a downloa...
In addition to jbochi's answer, you can also add a Content-Disposition header to save using a particular filename. ``` self.response.headers['Content-Disposition'] = "attachment; filename=fname.csv" ```
Iterating over key and value of defaultdict dictionaries
2,768,188
19
2010-05-04T19:03:08Z
2,768,203
36
2010-05-04T19:05:06Z
[ "python", "dictionary", "iterator" ]
The following works as expected: ``` d = [(1,2), (3,4)] for k,v in d: print "%s - %s" % (str(k), str(v)) ``` But this fails: ``` d = collections.defaultdict(int) d[1] = 2 d[3] = 4 for k,v in d: print "%s - %s" % (str(k), str(v)) ``` With: ``` Traceback (most recent call last): File "<stdin>", line 1, in <mo...
you need to iterate over `dict.iteritems()`: ``` for k,v in d.iteritems(): # will become d.items() in py3k print "%s - %s" % (str(k), str(v)) ```
Dynamic Class Creation in SQLAlchemy
2,768,607
15
2010-05-04T20:07:31Z
2,768,880
21
2010-05-04T20:47:26Z
[ "python", "sqlalchemy", "metaprogramming", "metaclass", "declarative" ]
We have a need to create SQLAlchemy classes to access multiple external data sources that will increase in number over time. We use the declarative base for our core ORM models and I know we can manually specify new ORM classes using the autoload=True to auto generate the mapping. The problem is that we need to be abl...
You can dynamically create `MyObject` using the [3-argument call to `type`](http://docs.python.org/library/functions.html#type): ``` type(name, bases, dict) Return a new type object. This is essentially a dynamic form of the class statement... ``` For example: ``` mydict={'__tablename__':stored['tablename'...
Iterating through String word at a time in Python
2,768,628
3
2010-05-04T20:10:45Z
2,769,248
7
2010-05-04T21:56:40Z
[ "python", "string", "string-matching" ]
I have a string buffer of a huge text file. I have to search a given words/phrases in the string buffer. Whats the efficient way to do it ? I tried using re module matches. But As i have a huge text corpus that i have to search through. This is taking large amount of time. Given a Dictionary of words and Phrases. I ...
Iterating word-by-word through the contents of a file (the Wizard of Oz from Project Gutenberg, in my case), three different ways: ``` from __future__ import with_statement import time import re from cStringIO import StringIO def word_iter_std(filename): start = time.time() with open(filename) as f: f...
how to erase the file contents of text file in Python
2,769,061
27
2010-05-04T21:21:06Z
2,769,090
81
2010-05-04T21:27:03Z
[ "c++", "python" ]
I have text file which I want to erase in Python. How do I do that?
In python: ``` open('file.txt', 'w').close() ``` Or alternatively, if you have already an opened file: ``` f = open('file.txt', 'r+') f.truncate() ``` In C++, you could use something similar.
how to erase the file contents of text file in Python
2,769,061
27
2010-05-04T21:21:06Z
20,879,930
13
2014-01-02T09:33:58Z
[ "c++", "python" ]
I have text file which I want to erase in Python. How do I do that?
Not a complete answer more of an extension to ondra's answer When using `truncate()` ( my preferred method ) make sure your cursor is at the required position. When a new file is opened for reading - `open('FILE_NAME','r')` it's cursor is at 0 by default. But if you have parsed the file within your code, make sure to ...
R or Python for file manipulation
2,770,030
3
2010-05-05T01:24:41Z
2,770,354
10
2010-05-05T03:01:57Z
[ "python", "file", "performance" ]
I have 4 reasonably complex r scripts that are used to manipulate csv and xml files. These were created by another department where they work exclusively in r. My understanding is that while r is very fast when dealing with data, it's not really optimised for file manipulation. Can I expect to get significant speed in...
I write in both R and Python regularly. I find Python modules for writing, reading and parsing information easier to use, maintain and update. Little niceties like the way python lets you deal with lists of items over R's indexing make things much easier to read. I highly doubt you will gain any significant speed-up b...
Python: create a function to modify a list by reference not value
2,770,038
12
2010-05-05T01:26:28Z
2,770,066
26
2010-05-05T01:32:53Z
[ "python", "list" ]
I'm doing some performance-critical Python work and want to create a function that removes a few elements from a list if they meet certain criteria. I'd rather not create any copies of the list because it's filled with a lot of really large objects. Functionality I want to implement: ``` def listCleanup(listOfElement...
Python passes everything the same way, but calling it "by value" or "by reference" will not clear everything up, since Python's semantics are different than the languages for which those terms usually apply. If I was to describe it, I would say that all passing was by value, and that the value was an object reference. ...
python regex of a date in some text
2,770,040
2
2010-05-05T01:26:48Z
2,770,062
9
2010-05-05T01:31:45Z
[ "python", "regex" ]
How can I find as many date patterns as possible from a text file by python? The date pattern is defined as: ``` dd mmm yyyy ^ ^ | | +---+--- spaces ``` where: * **dd** is a two digit number * **mmm** is three-character English month name (e.g. Jan, Mar, Dec) * **yyyy** is four digit year * there are two *...
Here's a way to find all dates matching your pattern ``` re.findall(r'\d\d\s(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}', text) ``` But after WilhelmTell's comment on your question, I'm also wondering whether this it what you were really asking for...
Are there builtin functions for elementwise boolean operators over boolean lists?
2,770,434
16
2010-05-05T03:36:08Z
2,770,502
14
2010-05-05T03:52:16Z
[ "python", "list", "built-in", "boolean-operations", "elementwise-operations" ]
For example, if you have n lists of bools of the same length, then elementwise boolean AND should return another list of that length that has True in those positions where all the input lists have True, and False everywhere else. It's pretty easy to write, i just would prefer to use a builtin if one exists (for the sa...
There is not a built-in way to do this. Generally speaking, list comprehensions and the like are how you do elementwise operations in Python. Numpy does provide this (using `&`, for technical limitations) in its array type. Numpy arrays usually perform operations elementwise.
Ruby LESS gem equivalent in Python
2,770,560
17
2010-05-05T04:08:46Z
3,176,166
15
2010-07-04T20:48:06Z
[ "python", "css", "ruby", "pylons", "less" ]
The Ruby [LESS gem](http://lesscss.org/) looks awesome - and I am working on a Python/Pylons web project where it would be highly useful. CSS is, as someone we're all familiar with [recently wrote about](http://www.codinghorror.com/blog/2010/04/whats-wrong-with-css.html), clunky in some important ways. So I'd like to m...
I have need for a Python lesscss compiler too, so have started work on one here: <http://code.google.com/p/lesscss-python/> Version 0.0.1 has been released, with no support for namespaces/accessors. It is probably riddled with bugs too. Please feel free to chip in with bug reports/coding or have a look at less-js <ht...
Multiple Models in a single django ModelForm?
2,770,810
60
2010-05-05T05:23:34Z
2,774,732
55
2010-05-05T15:45:59Z
[ "python", "django", "django-forms" ]
Is it possible to have multiple models included in a single `ModelForm` in django? I am trying to create a profile edit form. So I need to include some fields from the User model **and** the UserProfile model. Currently I am using 2 forms like this ``` class UserEditForm(ModelForm): class Meta: model = Us...
You can just show both forms in the template inside of one `<form>` html element. Then just process the forms separately in the view. You'll still be able to use `form.save()` and not have to process db loading and saving yourself. In this case you shouldn't need it, but if you're going to be using forms with the same...
Close a tag with no text in lxml
2,771,383
3
2010-05-05T07:47:37Z
2,771,410
7
2010-05-05T07:53:43Z
[ "python", "lxml" ]
I am trying to output a XML file using Python and lxml However, I notice one thing that if a tag has no text, it does not close itself. An example of this would be: ``` root = etree.Element('document') rootTree = etree.ElementTree(root) firstChild = etree.SubElement(root, 'test') ``` The output of this is: ``` <doc...
Note that `<test></test>` and `<test/>` mean exactly the same thing. What you want is for the test-tag to actually do have a text that consists in a single linebreak. However, an empty tag with no text is usually written as `<test/>` and it makes very little sense to insist on it to appear as `<test></test>`.
Python profiler and CPU seconds
2,771,561
4
2010-05-05T08:25:16Z
2,771,828
8
2010-05-05T09:11:10Z
[ "python", "profiling" ]
Hey, I'm totally behind this topic. Yesterday I was doing profiling using Python profiler module for some script I'm working on, and the unit for time spent was a 'CPU second'. Can anyone remind me with the definition of it? For example for some profiling I got: 200.750 CPU seconds. What does that supposed to mean? A...
Roughly speaking, a CPU time of, say, 200.75 seconds means that *if* only one processor worked on the task and that processor were working on it all the time, it would have taken 200.75 seconds. CPU time can be contrasted with *wall clock time*, which means the actual time elapsed from the start of the task to the end ...
Django datetime issues (default=datetime.now())
2,771,676
146
2010-05-05T08:48:24Z
2,771,701
338
2010-05-05T08:52:02Z
[ "python", "django" ]
I have such db model: ``` from datetime import datetime class TermPayment(models.Model): # cut out some fields, non relevant to the question date = models.DateTimeField(default=datetime.now(), blank=True) ``` And when new instance is added: ``` tp = TermPayment.objects.create(**kwargs) ``` I've an issu...
it looks like `datetime.now()` is being evaluated when the model is defined, and not each time you add a record. Django has a feature to accomplish what you are trying to do already: ``` date = models.DateTimeField(auto_now_add=True, blank=True) ``` or ``` date = models.DateTimeField(default=datetime.now, blank=Tru...
Django datetime issues (default=datetime.now())
2,771,676
146
2010-05-05T08:48:24Z
2,771,746
16
2010-05-05T08:59:25Z
[ "python", "django" ]
I have such db model: ``` from datetime import datetime class TermPayment(models.Model): # cut out some fields, non relevant to the question date = models.DateTimeField(default=datetime.now(), blank=True) ``` And when new instance is added: ``` tp = TermPayment.objects.create(**kwargs) ``` I've an issu...
From the [documentation](http://docs.djangoproject.com/en/dev/ref/models/fields/#default) on the django model default field: *The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created.* Therefore following should work: ``` date = model...
Django datetime issues (default=datetime.now())
2,771,676
146
2010-05-05T08:48:24Z
29,360,937
7
2015-03-31T05:03:19Z
[ "python", "django" ]
I have such db model: ``` from datetime import datetime class TermPayment(models.Model): # cut out some fields, non relevant to the question date = models.DateTimeField(default=datetime.now(), blank=True) ``` And when new instance is added: ``` tp = TermPayment.objects.create(**kwargs) ``` I've an issu...
David had the right answer. The parenthesis () makes it so that the *callable* timezone.now() is called every time the model is evaluated. If you remove the () from timezone.now() (or datetime.now(), if using the naive datetime object) to make it just this: ``` default=timezone.now ``` Then it will work as you expect...
Django datetime issues (default=datetime.now())
2,771,676
146
2010-05-05T08:48:24Z
32,117,864
8
2015-08-20T12:07:41Z
[ "python", "django" ]
I have such db model: ``` from datetime import datetime class TermPayment(models.Model): # cut out some fields, non relevant to the question date = models.DateTimeField(default=datetime.now(), blank=True) ``` And when new instance is added: ``` tp = TermPayment.objects.create(**kwargs) ``` I've an issu...
Instead of using `datetime.now` you should be really using `from django.utils.timezone import now`
Usage of Python 3 super()
2,771,904
17
2010-05-05T09:23:11Z
2,773,586
15
2010-05-05T13:28:15Z
[ "python", "oop", "python-3.x", "super" ]
I wonder when to use what flavour of Python 3 [super](http://docs.python.org/py3k/library/functions.html#super)(). ``` Help on class super in module builtins: class super(object) | super() -> same as super(__class__, <first argument>) | super(type) -> unbound super object | super(type, obj) -> bound super objec...
Let's use the following classes for demonstration: ``` class A(object): def m(self): print('m') class B(A): pass ``` Unbound `super` object doesn't dispatch attribute access to class, you have to use descriptor protocol: ``` >>> super(B).m Traceback (most recent call last): File "<stdin>", line 1, in ...
Programmatically sync the db in Django
2,772,990
12
2010-05-05T12:06:48Z
2,773,195
20
2010-05-05T12:38:38Z
[ "python", "django", "django-admin" ]
I'm trying to sync my db from a view, something like this: ``` from django import http from django.core import management def syncdb(request): management.call_command('syncdb') return http.HttpResponse('Database synced.') ``` The issue is, it will block the dev server by asking for user input from the termin...
``` management.call_command('syncdb', interactive=False) ```
Django admin's filter_horizontal (& filter_vertical) not working
2,773,324
7
2010-05-05T12:53:37Z
2,773,791
14
2010-05-05T13:52:38Z
[ "python", "django", "django-admin", "filtering" ]
I'm trying to use ModelAdmin.filter\_horizontal and ModelAdmin.filter\_vertical for ManyToMany field instead of select multiple box but all I get is: ![](http://www1.picturepush.com/photo/a/3385029/640/3385029.png) My model: ``` class Title(models.Model): #... production_companies = models.ManyToManyField(Com...
I finally got the solution. The problem was with the field's verbose name - it was str instead of unicode. Moving to unicode helped. Thanks :-)
JSON output sorting in Python
2,774,361
35
2010-05-05T15:01:45Z
2,774,404
30
2010-05-05T15:06:47Z
[ "python", "json", "sorting" ]
I've a problem with JSON in python. In fact, if I try to execute this code, python gives me a sorted JSON string! For example: ``` values = {'profile' : 'testprofile', 'format': 'RSA_RC4_Sealed', 'enc_key' : base64.b64encode(chiave_da_inviare), 'request' : base64.b64encode(data) ...
You are storing your values into a python [dict](http://docs.python.org/tutorial/datastructures.html#dictionaries) which has no inherent notion of ordering at all, it's just a key => value map. So your items lose all ordering when you place them into the "values" variable. In fact the only way to get a deterministic o...
JSON output sorting in Python
2,774,361
35
2010-05-05T15:01:45Z
10,720,186
68
2012-05-23T12:44:32Z
[ "python", "json", "sorting" ]
I've a problem with JSON in python. In fact, if I try to execute this code, python gives me a sorted JSON string! For example: ``` values = {'profile' : 'testprofile', 'format': 'RSA_RC4_Sealed', 'enc_key' : base64.b64encode(chiave_da_inviare), 'request' : base64.b64encode(data) ...
Try [`OrderedDict`](https://docs.python.org/2/library/collections.html#collections.OrderedDict) from the standard library [`collections`](https://docs.python.org/2/library/collections.html): ``` >>> import json >>> from collections import OrderedDict >>> values = OrderedDict([('profile','testprofile'), ...
Psycopg2 doesn't like table names that start with a lower case letter
2,774,406
4
2010-05-05T15:06:55Z
2,776,308
8
2010-05-05T19:52:26Z
[ "python", "sql", "postgresql" ]
I am running ActiveState's ActivePython 2.6.5.12 and PostgreSQL 9.0 Beta 1 under Windows XP. If I create a table with an upper case first letter (i.e. Books), psycopg2 returns the "Programming Error: relation "books" does not exist" error message when I run the select statement: `execute("SELECT * FROM Books")`. The s...
To add to the other answer, the behaviour of Postresql about case-sentivity of identifiers (table names and column names) is : * **If the name is not quoted, it is converted to lowercase**. Otherwise, it's left untouched. * Afterwards, a **case sensitive match** is attempted. This applies not only for queries, but al...
How do I strip the comma from the end of a string in Python?
2,774,558
3
2010-05-05T15:25:41Z
2,774,572
7
2010-05-05T15:27:38Z
[ "python", "string" ]
How do I strip comma from the end of a string? I tried ``` awk = subprocess.Popen([r"awk", "{print $10}"], stdin=subprocess.PIPE) awk_stdin = awk.communicate(uptime_stdout)[0] print awk_stdin temp = awk_stdin t = temp.strip(",") ``` also tried `t = temp.rstrip(",")`, both don't work. --- This is the code: ``` upti...
Err, how about the venerable: ``` if len(str) > 0: if str[-1:] == ",": str = str[:-1] ``` On second thought, `rstrip` itself should work fine, so there's something about the string you're getting from `awk` that's not quite what you expect. We'll need to see that. --- I suspect it's because your string ...
How do I strip the comma from the end of a string in Python?
2,774,558
3
2010-05-05T15:25:41Z
2,774,811
7
2010-05-05T15:55:05Z
[ "python", "string" ]
How do I strip comma from the end of a string? I tried ``` awk = subprocess.Popen([r"awk", "{print $10}"], stdin=subprocess.PIPE) awk_stdin = awk.communicate(uptime_stdout)[0] print awk_stdin temp = awk_stdin t = temp.strip(",") ``` also tried `t = temp.rstrip(",")`, both don't work. --- This is the code: ``` upti...
When you say ``` awk = subprocess.Popen([r"awk", "{print $11}"], stdin=subprocess.PIPE) awk_stdout = awk.communicate(uptime_stdout)[0] ``` then the output of the awk process is printed to stdout (e.g. a terminal). `awk_stdout` is set to `None`. `awk_stdout.rstrip('\n')` raises an `AttributeError` because `None` has n...
Child processes created with python multiprocessing module won't print
2,774,585
11
2010-05-05T15:28:58Z
2,774,623
15
2010-05-05T15:33:49Z
[ "python", "printing", "multiprocessing" ]
I have a problem with the code below, and with any code that uses the `print` function in the child processes. I can't see any printed statements, even if I use `sys.std[err|out].write('worker')` instead of `print`. This is the code ([from the official python documentation](http://docs.python.org/2/library/multiproces...
Try this: ``` from multiprocessing import Process import sys def f(name): print 'hello', name sys.stdout.flush() ... ``` AFAIK the standard output of processed spawned by the `multiprocessing` module is buffered, hence you will see the output only if the buffer becomes full or you explicitly flush `sys.stdo...
merging indexed array in Python
2,774,949
6
2010-05-05T16:14:20Z
2,775,008
8
2010-05-05T16:22:14Z
[ "python", "arrays", "numpy", "scipy" ]
Suppose that I have two numpy arrays of the form ``` x = [[1,2] [2,4] [3,6] [4,NaN] [5,10]] y = [[0,-5] [1,0] [2,5] [5,20] [6,25]] ``` is there an efficient way to merge them such that I have ``` xmy = [[0, NaN, -5 ] [1, 2, 0 ] [2, 4, 5 ] [3, 6, ...
See [numpy.lib.recfunctions.join\_by](http://presbrey.mit.edu:1234/numpy.lib.recfunctions.html) It only works on structured arrays or recarrays, so there are a couple of kinks. First you need to be at least somewhat familiar with structured arrays. See [here](http://docs.scipy.org/doc/numpy/user/basics.rec.html) if y...
Python Create unix timestamp five minutes in the future
2,775,864
285
2010-05-05T18:38:45Z
2,775,947
46
2010-05-05T18:51:26Z
[ "python", "datetime", "unix-timestamp" ]
I have to create an "Expires" value 5 minutes in the future, but I have to supply it in UNIX Timestamp format. I have this so far, but it seems like a hack. ``` def expires(): '''return a UNIX style timestamp representing 5 minutes from now''' epoch = datetime.datetime(1970, 1, 1) seconds_in_a_day = 60 * 6...
You can use `datetime.strftime` to get the time in Epoch form, using the `%s` format string: ``` def expires(): future = datetime.datetime.now() + datetime.timedelta(seconds=5*60) return int(future.strftime("%s")) ```
Python Create unix timestamp five minutes in the future
2,775,864
285
2010-05-05T18:38:45Z
2,775,982
339
2010-05-05T18:56:46Z
[ "python", "datetime", "unix-timestamp" ]
I have to create an "Expires" value 5 minutes in the future, but I have to supply it in UNIX Timestamp format. I have this so far, but it seems like a hack. ``` def expires(): '''return a UNIX style timestamp representing 5 minutes from now''' epoch = datetime.datetime(1970, 1, 1) seconds_in_a_day = 60 * 6...
Another way is to use [`calendar.timegm`](http://docs.python.org/3.3/library/calendar.html#calendar.timegm): ``` future = datetime.datetime.utcnow() + datetime.timedelta(minutes=5) return calendar.timegm(future.timetuple()) ``` It's also more portable than `%s` flag to `strftime` (which doesn't work on Windows).
Python Create unix timestamp five minutes in the future
2,775,864
285
2010-05-05T18:38:45Z
2,776,392
133
2010-05-05T20:06:34Z
[ "python", "datetime", "unix-timestamp" ]
I have to create an "Expires" value 5 minutes in the future, but I have to supply it in UNIX Timestamp format. I have this so far, but it seems like a hack. ``` def expires(): '''return a UNIX style timestamp representing 5 minutes from now''' epoch = datetime.datetime(1970, 1, 1) seconds_in_a_day = 60 * 6...
Just found this, and its even shorter. ``` import time def expires(): '''return a UNIX style timestamp representing 5 minutes from now''' return int(time.time()+300) ```
Python Create unix timestamp five minutes in the future
2,775,864
285
2010-05-05T18:38:45Z
13,423,911
11
2012-11-16T20:26:02Z
[ "python", "datetime", "unix-timestamp" ]
I have to create an "Expires" value 5 minutes in the future, but I have to supply it in UNIX Timestamp format. I have this so far, but it seems like a hack. ``` def expires(): '''return a UNIX style timestamp representing 5 minutes from now''' epoch = datetime.datetime(1970, 1, 1) seconds_in_a_day = 60 * 6...
Here's a less broken `datetime`-based solution to convert from datetime object to posix timestamp: ``` future = datetime.datetime.utcnow() + datetime.timedelta(minutes=5) return (future - datetime.datetime(1970, 1, 1)).total_seconds() ``` See more details at [Converting datetime.date to UTC timestamp in Python](http:...
Python Create unix timestamp five minutes in the future
2,775,864
285
2010-05-05T18:38:45Z
15,910,301
144
2013-04-09T18:57:12Z
[ "python", "datetime", "unix-timestamp" ]
I have to create an "Expires" value 5 minutes in the future, but I have to supply it in UNIX Timestamp format. I have this so far, but it seems like a hack. ``` def expires(): '''return a UNIX style timestamp representing 5 minutes from now''' epoch = datetime.datetime(1970, 1, 1) seconds_in_a_day = 60 * 6...
**Now in Python >= 3.3** you can just call the [timestamp() method](http://docs.python.org/3.3/library/datetime.html#datetime.datetime.timestamp) to get the timestamp as a float. ``` import datetime current_time = datetime.datetime.now(datetime.timezone.utc) unix_timestamp = current_time.timestamp() # works if Python ...
Python Create unix timestamp five minutes in the future
2,775,864
285
2010-05-05T18:38:45Z
16,307,378
56
2013-04-30T19:18:01Z
[ "python", "datetime", "unix-timestamp" ]
I have to create an "Expires" value 5 minutes in the future, but I have to supply it in UNIX Timestamp format. I have this so far, but it seems like a hack. ``` def expires(): '''return a UNIX style timestamp representing 5 minutes from now''' epoch = datetime.datetime(1970, 1, 1) seconds_in_a_day = 60 * 6...
This is what you need: ``` import time import datetime n = datetime.datetime.now() unix_time = time.mktime(n.timetuple()) ```
Difference between Python's Generators and Iterators
2,776,829
223
2010-05-05T21:14:08Z
2,776,865
261
2010-05-05T21:19:25Z
[ "python", "iterator", "generator" ]
What is the difference between iterators and generators? Some examples for when you would use each case would be helpful.
`iterator` is a more general concept: any object whose class has a `next` method (`__next__` in Python 3) and an `__iter__` method that does `return self`. Every generator is an iterator, but not vice versa. A generator is built by calling a function that has one or more `yield` expressions (`yield` statements, in Pyt...
Difference between Python's Generators and Iterators
2,776,829
223
2010-05-05T21:14:08Z
23,745,349
19
2014-05-19T19:05:58Z
[ "python", "iterator", "generator" ]
What is the difference between iterators and generators? Some examples for when you would use each case would be helpful.
Iterators: Iterator are objects which uses `next()` method to get next value of sequence. Generators: A generator is a function that produces or yields a sequence of values using `yield` method. Every `next()` method call on generator object(for ex: `f` as in below example) returned by generator function(for ex: `f...
Difference between Python's Generators and Iterators
2,776,829
223
2010-05-05T21:14:08Z
28,353,158
13
2015-02-05T20:12:52Z
[ "python", "iterator", "generator" ]
What is the difference between iterators and generators? Some examples for when you would use each case would be helpful.
> # What is the difference between iterators and generators? Some examples for when you would use each case would be helpful. ## A Generator *is* an Iterator A generator is a subtype of iterator: ``` >>> import collections >>> import types >>> def gen(): yield >>> g = gen() >>> isinstance(g, collections.Iterator) Tr...
Difference between Python urllib.urlretrieve() and wget
2,777,116
10
2010-05-05T22:04:45Z
2,815,800
14
2010-05-12T02:26:25Z
[ "python", "download", "wget", "urllib" ]
I am trying to retrieve a 500mb file using Python, and I have a script which uses `urllib.urlretrieve()`. There seems to some network problem between me and the download site, as this call consistently hangs and fails to complete. However, using `wget` to retrieve the file tends to work without problems. What is the di...
The answer is quite simple. Python's `urllib` and [`urllib2`](http://docs.python.org/library/urllib2.html) are nowhere near as mature and robust as they could be. Even better than wget in my experience is `cURL`. I've written code that downloads gigabytes of files over HTTP with file sizes ranging from 50 KB to over 2 ...
Making a python iterator go backwards?
2,777,188
16
2010-05-05T22:23:07Z
2,777,223
16
2010-05-05T22:30:41Z
[ "python", "list", "iterator" ]
Is there anyway to make a python list iterator to go backwards? Basically i have this ``` class IterTest(object): def __init__(self, data): self.data = data self.__iter = None def all(self): self.__iter = iter(self.data) for each in self.__iter: mtd = getattr(self,...
No, in general you cannot make a Python iterator go backwards. However, if you only want to step back once, you can try something like this: ``` def str(self, item): print item prev, current = None, self.__iter.next() while isinstance(current, int): print current prev, current = current, s...
python numpy roll with padding
2,777,907
26
2010-05-06T01:39:34Z
2,778,068
11
2010-05-06T02:28:45Z
[ "python", "arrays", "numpy" ]
I'd like to roll a 2D numpy in python, except that I'd like pad the ends with zeros rather than roll the data as if its periodic. Specifically, the following code ``` import numpy as np x = np.array([[1, 2, 3], [4, 5, 6]]) np.roll(x, 1, axis=1) ``` returns ``` array([[3, 1, 2],[6, 4, 5]]) ``` but what I would pr...
I don't think that you are going to find an easier way to do this that is built-in. The touch-up seems quite simple to me: ``` y = np.roll(x,1,axis=1) y[:,0] = 0 ``` If you want this to be more direct then maybe you could copy the roll function to a new function and change it to do what you want. The roll() function ...
python numpy roll with padding
2,777,907
26
2010-05-06T01:39:34Z
16,401,173
21
2013-05-06T14:41:52Z
[ "python", "arrays", "numpy" ]
I'd like to roll a 2D numpy in python, except that I'd like pad the ends with zeros rather than roll the data as if its periodic. Specifically, the following code ``` import numpy as np x = np.array([[1, 2, 3], [4, 5, 6]]) np.roll(x, 1, axis=1) ``` returns ``` array([[3, 1, 2],[6, 4, 5]]) ``` but what I would pr...
There is a new numpy function in version 1.7.0 [`numpy.pad`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.pad.html) that *can* do this in one-line. Pad seems to be quite powerful and can do much more than a simple "roll". The tuple `((0,0),(1,0))` used in this answer indicates the "side" of the matrix whic...
How can I find "week" in django's calendar app?
2,778,715
2
2010-05-06T05:42:27Z
2,779,341
10
2010-05-06T07:46:55Z
[ "python", "django", "calendar" ]
MyCalendar.py Code: ``` from django import template imort calendar import datetime date = datetime.date.today() week = ??? ... ``` The question is that I want to get the week which contains today's date. How can I do? Thanks for help! Ver: Django-1.0 Python-2.6.4
After reading your comment I think this is what you want: ``` import datetime today = datetime.date.today() weekday = today.weekday() start_delta = datetime.timedelta(days=weekday) start_of_week = today - start_delta week_dates = [start_of_week + datetime.timedelta(days=i) for i in range(7)] print week_dates ``` Pri...
socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions
2,778,840
15
2010-05-06T06:12:27Z
2,779,304
10
2010-05-06T07:40:35Z
[ "python", "sockets", "windows-7", "compatibility", "socketserver" ]
I'm trying to create a custom TCP stack using Python 2.6.5 on Windows 7 to serve valid http page requests on port 80 locally. But, I've run into a snag with what seems like Windows 7 tightened up security. This code worked on Vista. Here's my sample code: ``` import SocketServer import struct class MyTCPHandler(Sock...
On Windows Vista/7, with UAC, administrator accounts run programs in unprivileged mode by default. Programs must prompt for administrator access before they run as administrator, with the ever-so-familiar UAC dialog. Since Python scripts aren't directly executable, there's no "Run as Administrator" context menu option...
socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions
2,778,840
15
2010-05-06T06:12:27Z
14,928,504
17
2013-02-18T02:11:40Z
[ "python", "sockets", "windows-7", "compatibility", "socketserver" ]
I'm trying to create a custom TCP stack using Python 2.6.5 on Windows 7 to serve valid http page requests on port 80 locally. But, I've run into a snag with what seems like Windows 7 tightened up security. This code worked on Vista. Here's my sample code: ``` import SocketServer import struct class MyTCPHandler(Sock...
I just encountered the same issue, my system is Win7. just use the command on terminal like: netstat -na|findstr port, you will see the port has been used. So if you want to start the server without this message, you can change other port that not been used.
Python: Strip everything but spaces and alphanumeric
2,779,453
12
2010-05-06T08:04:18Z
2,779,487
15
2010-05-06T08:09:30Z
[ "python" ]
I have a large string with brackets and commas and such. I want to strip all those characters but keep the spacing. How can I do this. As of now I am using ``` strippedList = re.sub(r'\W+', '', origList) ```
``` re.sub(r'([^\s\w]|_)+', '', origList) ```
why in python giving to str func a unicode string will throw an exception?
2,780,413
2
2010-05-06T10:43:07Z
2,780,474
7
2010-05-06T10:52:48Z
[ "python", "unicode", "string" ]
for example the following: str(u'לשום') will throw an error. how can i prevent these?
Calling `str()` on a `unicode` is the same as calling `.encode(sys.getdefaultencoding())` on it. If the `unicode` contains characters that can't be encoded in the default encoding then it will throw a `UnicodeEncodeError`. The fix is to explicitly encode the `unicode` in a useful encoding, such as `'utf-8'`.
stop minidom converting < > to &lt; &gt;
2,780,506
3
2010-05-06T10:58:49Z
2,780,776
7
2010-05-06T11:46:38Z
[ "python", "xml", "google-app-engine", "minidom" ]
Im trying to output some data from my google app engine datastore to xml so that a flash file can read it, The problem is when using CDATA tags the outputted xml contains `&lt;` instead of < e.g ``` <name>&lt;![CDATA][name]]&gt;</name> ``` here is my python which outputs the xml: ``` doc = Document() feed...
It seems the createCDATASection method works for me. ``` for tag in tags: tag_element = doc.createCDATASection(tag.thetag) tags_element.appendChild(tag_element) ```
Python sum up time
2,780,897
6
2010-05-06T12:03:48Z
2,780,968
9
2010-05-06T12:17:28Z
[ "python", "datetime" ]
In python how to sum up the following time ``` 0:00:00 0:00:15 9:30:56 ``` Thanks..
As a list of strings? ``` timeList = [ '0:00:00', '0:00:15', '9:30:56' ] totalSecs = 0 for tm in timeList: timeParts = [int(s) for s in tm.split(':')] totalSecs += (timeParts[0] * 60 + timeParts[1]) * 60 + timeParts[2] totalSecs, sec = divmod(totalSecs, 60) hr, min = divmod(totalSecs, 60) print "%d:%02d:%02d" ...
Python sum up time
2,780,897
6
2010-05-06T12:03:48Z
2,780,979
14
2010-05-06T12:18:51Z
[ "python", "datetime" ]
In python how to sum up the following time ``` 0:00:00 0:00:15 9:30:56 ``` Thanks..
It depends on the form you have these times in, for example if you already have them as `datetime.timedelta`s, then you could just sum them up: ``` >>> s = datetime.timedelta(seconds=0) + datetime.timedelta(seconds=15) + datetime.timedelta(hours=9, minutes=30, seconds=56) >>> str(s) '9:31:11' ```
Where to put Django startup code?
2,781,383
45
2010-05-06T13:18:46Z
2,781,488
52
2010-05-06T13:30:51Z
[ "python", "django", "django-middleware" ]
I'd like to have these lines of code executed on server startup (both development and production): ``` from django.core import management management.call_command('syncdb', interactive=False) ``` Putting it in `settings.py` doesn't work, as it requires the settings to be loaded already. Putting them in a view and acc...
Write middleware that does this in `__init__` and afterwards raise `django.core.exceptions.MiddlewareNotUsed` from the `__init__`, django will remove it for all requests :). `__init__` is called at startup by the way, not at the first request, so it won't block your first user. There is talk about adding a startup sig...
name of the class that contains the method code
2,781,701
11
2010-05-06T14:12:07Z
2,781,900
7
2010-05-06T14:38:12Z
[ "python", "introspection" ]
I'm trying to find the name of the class that contains method code. In the example underneath I use `self.__class__.__name__`, but of course this returns the name of the class of which self is an instance and not class that contains the `test()` method code. `b.test()` will print `'B'` while I would like to get `'A'`....
In Python 3.x, you can simply use `__class__.__name__`. The `__class__` name is mildly magic, and not the same thing as the `__class__` attribute of `self`. In Python 2.x, there is no good way to get at that information. You can use stack inspection to get the code object, then walk the class hierarchy looking for the...
Why does Python output a string and a unicode of the same value differently?
2,782,085
3
2010-05-06T15:03:59Z
2,782,125
10
2010-05-06T15:10:25Z
[ "python", "unicode" ]
I'm using Python 2.6.5 and when I run the following in the Python shell, I get: ``` >>> print u'Andr\xc3\xa9' André >>> print 'Andr\xc3\xa9' André >>> ``` What's the explanation for the above? Given u'Andr\xc3\xa9', how can I display the above value properly in an html page so that it shows André instead of Andr...
`'\xc3\xa9'` is the UTF-8 encoding of the unicode character `u'\u00e9'` (which can also be specified as `u'\xe9'`). So you can use `u'Andr\u00e9'` or `u'Andr\xe9'`. You can convert from one to the other: ``` >>> 'Andr\xc3\xa9'.decode('utf-8') u'Andr\xe9' >>> u'Andr\xe9'.encode('utf-8') 'Andr\xc3\xa9' ``` Note that t...
Python: Is there a built in package to parse html into dom
2,782,097
26
2010-05-06T15:06:09Z
2,782,124
11
2010-05-06T15:10:23Z
[ "python", "html", "dom", "parsing" ]
I found HTMLParser for sax and xml.minidom for xml. I have a pretty well formed html so I don't need a too strong parser - any suggestions?
Take a look at [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/). It's popular and excellent at parsing HTML.
Python: Is there a built in package to parse html into dom
2,782,097
26
2010-05-06T15:06:09Z
2,782,492
22
2010-05-06T15:57:37Z
[ "python", "html", "dom", "parsing" ]
I found HTMLParser for sax and xml.minidom for xml. I have a pretty well formed html so I don't need a too strong parser - any suggestions?
I would recommend [lxml](http://lxml.de/). I like BeautifulSoup, but there are maintenance issues generally and compatibility issues with the later releases. I've been happy using lxml. --- Later: the best recommendations are to use lxml, html5lib, or BeautifulSoup 3.0.8. BeautifulSoup 3.1.x is meant for python 3.x a...
Most lightweight way to create a random string and a random hexadecimal number
2,782,229
49
2010-05-06T15:23:22Z
2,782,272
24
2010-05-06T15:28:39Z
[ "python" ]
What is the most lightweight way to create a random string of 30 characters like the following? > ufhy3skj5nca0d2dfh9hwd2tbk9sw1 And an hexadecimal number of 30 digits like the followin? > 8c6f78ac23b4a7b8c0182d7a89e9b1
``` import string import random lst = [random.choice(string.ascii_letters + string.digits) for n in xrange(30)] str = "".join(lst) print str ocwbKCiuAJLRJgM1bWNV1TPSH0F2Lb ```
Most lightweight way to create a random string and a random hexadecimal number
2,782,229
49
2010-05-06T15:23:22Z
2,782,293
41
2010-05-06T15:29:46Z
[ "python" ]
What is the most lightweight way to create a random string of 30 characters like the following? > ufhy3skj5nca0d2dfh9hwd2tbk9sw1 And an hexadecimal number of 30 digits like the followin? > 8c6f78ac23b4a7b8c0182d7a89e9b1
30 digit hex string: ``` >>> import os,binascii >>> print binascii.b2a_hex(os.urandom(15)) "c84766ca4a3ce52c3602bbf02ad1f7" ``` The advantage is that this gets randomness directly from the OS, which might be more secure and/or faster than the random(), and you don't have to seed it.
Most lightweight way to create a random string and a random hexadecimal number
2,782,229
49
2010-05-06T15:23:22Z
2,782,859
78
2010-05-06T16:52:37Z
[ "python" ]
What is the most lightweight way to create a random string of 30 characters like the following? > ufhy3skj5nca0d2dfh9hwd2tbk9sw1 And an hexadecimal number of 30 digits like the followin? > 8c6f78ac23b4a7b8c0182d7a89e9b1
I got a faster one for the hex output. Using the same t1 and t2 as above: ``` >>> t1 = timeit.Timer("''.join(random.choice('0123456789abcdef') for n in xrange(30))", "import random") >>> t2 = timeit.Timer("binascii.b2a_hex(os.urandom(15))", "import os, binascii") >>> t3 = timeit.Timer("'%030x' % random.randrange(16**3...
Most lightweight way to create a random string and a random hexadecimal number
2,782,229
49
2010-05-06T15:23:22Z
15,462,293
8
2013-03-17T15:06:59Z
[ "python" ]
What is the most lightweight way to create a random string of 30 characters like the following? > ufhy3skj5nca0d2dfh9hwd2tbk9sw1 And an hexadecimal number of 30 digits like the followin? > 8c6f78ac23b4a7b8c0182d7a89e9b1
Note: `random.choice(string.hexdigits)` is incorrect, because `string.hexdigits` returns `0123456789abcdefABCDEF` (both lowercase and uppercase), so you will get a biased result, with the hex digit 'c' twice as likely to appear as the digit '7'. Instead, just use `random.choice('0123456789abcdef')`.
Remove n characters from a start of a string
2,782,318
17
2010-05-06T15:31:48Z
2,782,338
8
2010-05-06T15:33:34Z
[ "python", "string" ]
I want to remove the first characters from a string. Is there a function that works like this? ``` >>> a = "BarackObama" >>> print myfunction(4,a) ckObama >>> b = "The world is mine" >>> print myfunction(6,b) rld is mine ```
Use slicing. ``` >>> a = "BarackObama" >>> a[4:] 'ckObama' >>> b = "The world is mine" >>> b[6:10] 'rld ' >>> b[:9] 'The world' ``` You can read about this and most other language features in the official tutorial: <http://docs.python.org/tut/>
Remove n characters from a start of a string
2,782,318
17
2010-05-06T15:31:48Z
2,782,341
18
2010-05-06T15:33:59Z
[ "python", "string" ]
I want to remove the first characters from a string. Is there a function that works like this? ``` >>> a = "BarackObama" >>> print myfunction(4,a) ckObama >>> b = "The world is mine" >>> print myfunction(6,b) rld is mine ```
Yes, just use slices: ``` >> a = "BarackObama" >> a[4:] 'ckObama' ``` Documentation is here <http://docs.python.org/tutorial/introduction.html#strings>
Remove n characters from a start of a string
2,782,318
17
2010-05-06T15:31:48Z
2,782,342
13
2010-05-06T15:34:06Z
[ "python", "string" ]
I want to remove the first characters from a string. Is there a function that works like this? ``` >>> a = "BarackObama" >>> print myfunction(4,a) ckObama >>> b = "The world is mine" >>> print myfunction(6,b) rld is mine ```
The function could be: ``` def cutit(s,n): return s[n:] ``` and then you call it like this: ``` name = "MyFullName" print cutit(name, 2) # prints "FullName" ```
yet another confusion with multiprocessing error, 'module' object has no attribute 'f'
2,782,961
38
2010-05-06T17:08:01Z
2,783,017
73
2010-05-06T17:15:50Z
[ "python", "multiprocessing" ]
I know this has been answered before, but it seems that executing the script directly "python filename.py" does not work. I have Python 2.6.2 on SuSE Linux. Code: ``` #!/usr/bin/python # -*- coding: utf-8 -*- from multiprocessing import Pool p = Pool(1) def f(x): return x*x p.map(f, [1, 2, 3]) ``` Command line: ...
Restructure your code so that the `f()` function is defined before you create instance of Pool. Otherwise the worker cannot see your function. ``` #!/usr/bin/python # -*- coding: utf-8 -*- from multiprocessing import Pool def f(x): return x*x p = Pool(1) p.map(f, [1, 2, 3]) ```
How do I convert a unicode to a string at the Python level?
2,783,079
7
2010-05-06T17:23:22Z
2,783,179
8
2010-05-06T17:38:39Z
[ "python", "unicode", "python-2.x" ]
The following unicode and string can exist on their own if defined explicitly: ``` >>> value_str='Andr\xc3\xa9' >>> value_uni=u'Andr\xc3\xa9' ``` If I only have `u'Andr\xc3\xa9'` assigned to a variable like above, how do I convert it to `'Andr\xc3\xa9'` in Python 2.5 or 2.6? **EDIT:** I did the following: ``` >>> ...
You seem to have gotten your encodings muddled up. It seems likely that what you really want is `u'Andr\xe9'` which is equivalent to `'André'`. But what you have seems to be a UTF-8 encoding that has been incorrectly decoded. You can fix it by converting the unicode string to an ordinary string. I'm not sure what the...
How does git-diff generate hunk descriptions?
2,783,086
12
2010-05-06T17:24:50Z
2,783,188
12
2010-05-06T17:41:15Z
[ "python", "git", "diff" ]
(git version 1.6.5.7) When I run `git diff` the output has a nice scope hint after the line numbers for my Python scripts, e.g.: ``` diff --git a/file.py b/file.py index 024f5bb..c3b5c56 100644 --- a/file.py +++ b/file.py @@ -14,6 +14,8 @@ TITF: Test Infrastructure Tags Format ... @@ -1507,13 +1533,16 @@ class Tags( ...
Git uses a regular expression to find a suitable line for the hunk headers. Python's is built-in, but you should be able to define your own expression in your ~/.gitconfig: ``` [diff "python"] xfuncname = "<regex goes here>" ``` More about this [here](http://ftp.sunet.se/pub/Linux/kernel.org/software/scm/git/...
Python - copy by reference
2,783,489
3
2010-05-06T18:33:14Z
2,783,511
8
2010-05-06T18:36:28Z
[ "python", "reference" ]
Is there any possibility to copy variable by reference no matter if its int or class instance? My goal is to have two lists of the same objects and when one changes, change is visible in second. In other words i need pointers:/ --- I simply want int, float and other standard types which are normally copied by value...
You can wrap you immutable objects in a class: ``` class MutableWrapper(object): def __init__(self, value): self.value = value a = MutableWrapper(10) b = a a.value = 20 assert b.value == 20 ```
Python - copy by reference
2,783,489
3
2010-05-06T18:33:14Z
2,784,336
8
2010-05-06T20:41:36Z
[ "python", "reference" ]
Is there any possibility to copy variable by reference no matter if its int or class instance? My goal is to have two lists of the same objects and when one changes, change is visible in second. In other words i need pointers:/ --- I simply want int, float and other standard types which are normally copied by value...
Python always works by reference, unless you explicitly ask for a copy (a slice of a built-in list is deemed to "ask for a copy" -- but a slice of a numpy array also works by reference). However, exactly because of that, `alist=anotherlist; alist.sort()` means the single list objects (with two equivalent names `alist` ...
Compare string with all values in array
2,783,969
19
2010-05-06T19:49:12Z
2,784,205
27
2010-05-06T20:24:02Z
[ "python" ]
I am trying to fumble through python, and learn the best way to do things. I have a string where I am doing a compare with another string to see if there is a match: ``` if paid[j].find(d)>=0: #BLAH BLAH ``` If 'd' were an array, what is the most efficient way to see if the string contained in paid[j] has a match...
If you only want to know if *any* item of `d` is contained in `paid[j]`, as you literally say: ``` if any(x in paid[j] for x in d): ... ``` If you also want to know *which* items of `d` are contained in `paid[j]`: ``` contained = [x for x in d if x in paid[j]] ``` `contained` will be an empty list if no items of `d...
Adding inheritance to a class programmatically in python?
2,783,974
2
2010-05-06T19:49:47Z
2,784,086
7
2010-05-06T20:05:16Z
[ "python" ]
Can I make a class inherit a class "in-program" in Python? heres what i have so far: ``` base = list(cls.__bases__) base.insert(0, ClassToAdd ) base = tuple( base ) cls = type( cls.__name__, base, dict(cls.__dict__) ) ```
Here is an example, using Greg Hewgill's suggestion: ``` class Foo(object): def beep(self): print('Hi') class Bar(object): x=1 bar=Bar() # bar.beep() # AttributeError: 'Bar' object has no attribute 'beep' Bar=type('Bar',(Foo,object),Bar.__dict__.copy()) bar.__class__=Bar bar.beep() # Hi ```
How do I unit test the methods in a method object?
2,784,519
5
2010-05-06T21:10:50Z
2,792,128
10
2010-05-07T22:47:34Z
[ "python", "unit-testing", "refactoring", "tdd" ]
I've performed the "[Replace Method with Method Object](http://sourcemaking.com/refactoring/replace-method-with-method-object)" refactoring described by [Beck](http://books.google.com/books?id=1MsETFPD3I0C&pg=PA135&lpg=PA135&dq=%22Replace+Method+with+Method+Object%22++Beck&source=bl&ots=pKS1l5PLff&sig=tp3gs4GUg66Fwch8k...
I'll answer my own question. After a bit of reading and thinking, I believe I shouldn't be unit testing these private methods. I should just test the public interface. If the private methods that do the internal processing are important enough to test independently and are not just coincidences of the current implement...
SQLAlchemy introspection of ORM classes/objects
2,784,986
5
2010-05-06T22:36:48Z
2,785,383
11
2010-05-07T00:13:30Z
[ "python", "sqlalchemy", "introspection" ]
I am looking for a way to introspect SQLAlchemy ORM classes/entities to determine the types and other constraints (like maximum lengths) of an entity's properties. For example, if I have a declarative class: ``` class User(Base): __tablename__ = "USER_TABLE" id = sa.Column(sa.types.Integer, primary_key=True)...
Something like: ``` table = User.__table__ field = table.c["fullname"] print "Type", field.type print "Length", field.type.length print "Nullable", field.nullable ``` **EDIT:** The upcoming 0.8 version has a [New Class Inspection System](http://www.sqlalchemy.org/trac/wiki/08Migration#NewClassInspectionSystem): > N...
How to split but ignore separators in quoted strings, in python?
2,785,755
41
2010-05-07T02:13:05Z
2,786,602
7
2010-05-07T06:22:48Z
[ "python", "regex" ]
I need to split a string like this, on semicolons. But I don't want to split on semicolons that are inside of a string (' or "). I'm not parsing a file; just a simple string with no line breaks. `part 1;"this is ; part 2;";'this is ; part 3';part 4;this "is ; part" 5` Result should be: * part 1 * "this is ; part 2;"...
You appears to have a semi-colon seperated string. Why not use the `csv` module to do all the hard work? Off the top of my head, this should work ``` import csv from StringIO import StringIO line = '''part 1;"this is ; part 2;";'this is ; part 3';part 4;this "is ; part" 5''' data = StringIO(line) reader = csv.re...
How to split but ignore separators in quoted strings, in python?
2,785,755
41
2010-05-07T02:13:05Z
2,787,064
37
2010-05-07T07:59:49Z
[ "python", "regex" ]
I need to split a string like this, on semicolons. But I don't want to split on semicolons that are inside of a string (' or "). I'm not parsing a file; just a simple string with no line breaks. `part 1;"this is ; part 2;";'this is ; part 3';part 4;this "is ; part" 5` Result should be: * part 1 * "this is ; part 2;"...
Most of the answers seem massively over complicated. You **don't** need back references. You **don't** need to depend on whether or not re.findall gives overlapping matches. Given that the input cannot be parsed with the csv module so a regular expression is pretty well the only way to go, all you need is to call re.sp...
How to split but ignore separators in quoted strings, in python?
2,785,755
41
2010-05-07T02:13:05Z
2,787,979
8
2010-05-07T10:57:57Z
[ "python", "regex" ]
I need to split a string like this, on semicolons. But I don't want to split on semicolons that are inside of a string (' or "). I'm not parsing a file; just a simple string with no line breaks. `part 1;"this is ; part 2;";'this is ; part 3';part 4;this "is ; part" 5` Result should be: * part 1 * "this is ; part 2;"...
``` re.split(''';(?=(?:[^'"]|'[^']*'|"[^"]*")*$)''', data) ``` Each time it finds a semicolon, the lookahead scans the entire remaining string, making sure there's an even number of single-quotes and an even number of double-quotes. (Single-quotes inside double-quoted fields, or vice-versa, are ignored.) If the lookah...
How to split but ignore separators in quoted strings, in python?
2,785,755
41
2010-05-07T02:13:05Z
2,788,579
10
2010-05-07T12:44:35Z
[ "python", "regex" ]
I need to split a string like this, on semicolons. But I don't want to split on semicolons that are inside of a string (' or "). I'm not parsing a file; just a simple string with no line breaks. `part 1;"this is ; part 2;";'this is ; part 3';part 4;this "is ; part" 5` Result should be: * part 1 * "this is ; part 2;"...
Here is an annotated [pyparsing](http://pyparsing.wikispaces.com/) approach: ``` from pyparsing import (printables, originalTextFor, OneOrMore, quotedString, Word, delimitedList) # unquoted words can contain anything but a semicolon printables_less_semicolon = printables.replace(';','') # capture content betwee...
Is there an easy way in Python to wait until certain condition is true?
2,785,821
8
2010-05-07T02:33:14Z
2,785,908
12
2010-05-07T02:57:19Z
[ "python" ]
I need to wait in a script until a certain number of conditions become true? I know I can roll my own eventing using condition variables and friends, but I don't want to go through all the trouble of implementing it, since some object property changes come from external thread in a wrapped C++ library (Boost.Python), ...
Unfortunately the only possibility to meet your constraints is to periodically *poll*, e.g....: ``` import time def wait_until(somepredicate, timeout, period=0.25, *args, **kwargs): mustend = time.time() + timeout while time.time() < mustend: if somepredicate(*args, **kwargs): return True time.sleep(perio...
Creating a list in Python with multiple copies of a given object in a single line
2,785,954
6
2010-05-07T03:10:41Z
2,785,959
13
2010-05-07T03:13:37Z
[ "python", "list" ]
Suppose I have a given Object (a string "a", a number - let's say 0, or a list `['x','y']` ) I'd like to create list containing many copies of this object, but without using a for loop: `L = ["a", "a", ... , "a", "a"]` or `L = [0, 0, ... , 0, 0]` or `L = [['x','y'],['x','y'], ... ,['x','y'],['x','y']]` I'm espec...
[`itertools.repeat()`](http://docs.python.org/library/itertools.html) is your friend. ``` L = list(itertools.repeat("a", 20)) # 20 copies of "a" L = list(itertools.repeat(10, 20)) # 20 copies of 10 L = list(itertools.repeat(['x','y'], 20)) # 20 copies of ['x','y'] ``` Note that in the third case, since lists are r...
Creating a list in Python with multiple copies of a given object in a single line
2,785,954
6
2010-05-07T03:10:41Z
2,785,963
26
2010-05-07T03:15:09Z
[ "python", "list" ]
Suppose I have a given Object (a string "a", a number - let's say 0, or a list `['x','y']` ) I'd like to create list containing many copies of this object, but without using a for loop: `L = ["a", "a", ... , "a", "a"]` or `L = [0, 0, ... , 0, 0]` or `L = [['x','y'],['x','y'], ... ,['x','y'],['x','y']]` I'm espec...
You can use the `*` operator : ``` L = ["a"] * 10 L = [0] * 10 L = [["x", "y"]] * 10 ``` Be careful this create N copies of the *same item*, meaning that in the third case you create a list containing N references to the `["x", "y"]` list ; changing `L[0][0]` for example will modify all other copies as well: ``` >>>...
Quickbooks integration: IPP/IDS: can these by used for actual data exchange?
2,786,122
4
2010-05-07T04:02:13Z
2,819,209
7
2010-05-12T13:30:52Z
[ "python", "quickbooks", "qbwc" ]
Poking around options for integrating an online app with Quickbooks, I've made a lot of headway with QBWC, but it's fairly ugly. From an end user perspective the usability of QBWC is pretty low. Intuit is now pushing Intuit Partner Platform (IPP) and Intuit Data Services (IDS). I can't quite figure out what these are ...
> Is IPP limited to using Flex, or can it work with existing web apps? It is **not** limited to Flex. You can use IPP/IDS from **any** web application, as long as you federate your application (allow logins using SAML via workplace.intuit.com). There are two "types" of IPP applications: 1. **Native apps** Native app...
Google app engine: query that return entity ID using python
2,786,244
5
2010-05-07T04:39:32Z
2,786,321
13
2010-05-07T04:59:37Z
[ "python", "google-app-engine" ]
how do I return the entity ID using python in GAE? Assuming I have following ``` class Names(db.Model): name = db.StringProperty() ```
You retrieve the entity, e.g. with a [query](http://code.google.com/appengine/docs/python/datastore/creatinggettinganddeletingdata.html#Getting_Entities_Using_a_Query), then you call `.key().id()` on that entity (will be `None` if the entity has no numeric id; see [here](http://code.google.com/appengine/docs/python/dat...
How to create and restore a backup from SqlAlchemy?
2,786,664
15
2010-05-07T06:35:58Z
2,788,014
9
2010-05-07T11:05:41Z
[ "python", "serialization", "sqlalchemy", "pylons" ]
I'm writing a Pylons app, and am trying to create a simple backup system where every table is serialized and tarred up into a single file for an administrator to download, and use to restore the app should something bad happen. I can serialize my table data just fine using the [SqlAlchemy serializer](http://www.sqlalc...
You have to use [`Session.merge()`](http://www.sqlalchemy.org/docs/reference/orm/sessions.html#sqlalchemy.orm.session.Session.merge) method instead of `Session.add()` to put deserialized object back into the session.
How do I attach event bindings to items on a canvas using Tkinter?
2,786,877
16
2010-05-07T07:21:11Z
2,790,122
34
2010-05-07T16:35:00Z
[ "python", "user-interface", "tkinter", "tkinter-canvas" ]
If I'm using a canvas to display data and I want the user to be able to click on various items on the canvas in order to get more information or interact with it in some way, what's the best way of going about this? Searching online I can find information about how to bind events to tags but that seems to be more indi...
To interact with objects contained in a Canvas object you need to use tag\_bind() which has this format: `tag_bind(item, event=None, callback, add=None)` The item parameter can be either a tag or an id. Here is an example to illustrate the concept: ``` from tkinter import * def onObjectClick(event): ...
Python: Open() using a variable
2,788,386
2
2010-05-07T12:09:31Z
2,788,394
9
2010-05-07T12:11:06Z
[ "python", "string-formatting" ]
I've run into a problem when opening a file with a randomly generated name in Python 2.6. ``` import random random = random.randint(1,10) localfile = file("%s","wb") % random ``` Then I get an error message about the last line: ``` TypeError: unsupported operand type(s) for %: 'file' and 'int' ``` I just can't fi...
This will probably work: ``` import random num = random.randint(1, 10) localfile = open("%d" % num, "wb") ``` Note that I've changed a couple of things here: 1. You shouldn't assign the generated random number to a variable named `random` as you are overwriting the existing reference to the module `random`. In othe...
python date difference in minutes
2,788,871
22
2010-05-07T13:29:07Z
6,879,077
47
2011-07-29T21:08:52Z
[ "python", "datetime" ]
How to calculate the difference in time in minutes for the following timestamp in python ``` 2010-01-01 17:31:22 2010-01-03 17:31:22 ```
The accepted answer above doesn't work in cases where the dates don't have the same exact time. original problem: ``` from datetime import datetime fmt = '%Y-%m-%d %H:%M:%S' d1 = datetime.strptime('2010-01-01 17:31:22', fmt) d2 = datetime.strptime('2010-01-03 17:31:22', fmt) daysDiff = (d2-d1).days print daysDiff >...
python date difference in minutes
2,788,871
22
2010-05-07T13:29:07Z
29,764,339
9
2015-04-21T06:17:38Z
[ "python", "datetime" ]
How to calculate the difference in time in minutes for the following timestamp in python ``` 2010-01-01 17:31:22 2010-01-03 17:31:22 ```
In case someone doesn't realize it, one way to do this would be to combine Christophe and RSabet's answers: ``` from datetime import datetime import time fmt = '%Y-%m-%d %H:%M:%S' d1 = datetime.strptime('2010-01-01 17:31:22', fmt) d2 = datetime.strptime('2010-01-03 20:15:14', fmt) diff = d2 -d1 diff_minutes = (diff....
Python add to a function dynamically
2,789,460
15
2010-05-07T14:52:42Z
2,789,535
10
2010-05-07T15:02:20Z
[ "python", "metaprogramming" ]
how do i add code to an existing function, either before or after? for example, i have a class: ``` class A(object): def test(self): print "here" ``` how do i edit the class wit metaprogramming so that i do this ``` class A(object): def test(self): print "here" print "and her...
The typical way to add functionality to a function is to use a [decorator](http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Decorators) (using [the wraps function](http://stackoverflow.com/questions/308999/what-does-functools-wraps-do)): ``` from functools import wraps def add_message(func): @wraps de...
Python add to a function dynamically
2,789,460
15
2010-05-07T14:52:42Z
2,789,542
17
2010-05-07T15:03:31Z
[ "python", "metaprogramming" ]
how do i add code to an existing function, either before or after? for example, i have a class: ``` class A(object): def test(self): print "here" ``` how do i edit the class wit metaprogramming so that i do this ``` class A(object): def test(self): print "here" print "and her...
You can use a decorator to modify the function if you want. However, since it's not a decorator applied at the time of the initial definition of the function, you won't be able to use the `@` syntactic sugar to apply it. ``` >>> class A(object): ... def test(self): ... print "orig" ... >>> first_a = A() >>...
Can i pass class method as and a default argument to another class method
2,791,291
5
2010-05-07T19:47:44Z
2,791,336
8
2010-05-07T19:57:22Z
[ "python", "class" ]
i want to to pass class method as and a default argument to another class method, so that i can re-use the method as a @classmethod ``` @classmethod class foo: def func1(self,x): do somthing; def func2(self, aFunc = self.func1): # make some a call to afunc afunc(4) ``` this why when the method func2 is called...
Default argument values are computed during function definition, not during function call. So no, you can't. You can do the following, however: ``` def func2(self, aFunc = None): if aFunc is None: aFunc = self.func1 ... ```
How do I take out the focus or minimize a window with Python?
2,791,489
5
2010-05-07T20:30:24Z
2,791,812
13
2010-05-07T21:33:53Z
[ "python", "window" ]
I need to get focus to a specified window, and the only way I'm seeing on my head, is minimizing all windows on front of it until I get the right one... How can I do it? Windows 7, and no specific toolkit.... Every type of window, for example, firefox and console command
You'll need to enumerate through the windows and match the title of the window to get the one you want. The code below searches for a window with "firefox" in the title and sets the focus: ``` import win32gui toplist = [] winlist = [] def enum_callback(hwnd, results): winlist.append((hwnd, win32gui.GetWindowText(...
Which is the easiest way to simulate keyboard and mouse on Python?
2,791,839
11
2010-05-07T21:41:49Z
2,791,974
10
2010-05-07T22:10:58Z
[ "python", "windows", "keyboard", "mouse" ]
I need to do some macros and I wanna know what is the most recommended way to do it. So, I need to write somethings and click some places with it and I need to emulate the TAB key to.
Maybe you are looking for [Sendkeys](http://pypi.python.org/pypi/SendKeys/0.3)? > SendKeys is a Python module for > Windows that can send one or more > keystrokes or keystroke combinations > to the active window. it seems it is windows only Also you have [pywinauto](https://code.google.com/p/pywinauto/) (copied from...
Which is the easiest way to simulate keyboard and mouse on Python?
2,791,839
11
2010-05-07T21:41:49Z
2,791,979
16
2010-05-07T22:12:03Z
[ "python", "windows", "keyboard", "mouse" ]
I need to do some macros and I wanna know what is the most recommended way to do it. So, I need to write somethings and click some places with it and I need to emulate the TAB key to.
I do automated testing stuff in Python. I tend to use the following: <http://www.tizmoi.net/watsup/intro.html> **Edit:** Link is dead, archived version: <https://web.archive.org/web/20100224025508/http://www.tizmoi.net/watsup/intro.html> <http://www.mayukhbose.com/python/IEC/index.php> I do not always (almost neve...
running code if try statements were successful in python
2,792,568
10
2010-05-08T01:22:10Z
2,792,574
9
2010-05-08T01:24:57Z
[ "python", "error-handling", "try-catch" ]
I was wondering if in python there was a simple way to run code if a try statement was successful that wasn't in the try statement itself. Is that what the else or finally commands do (I didn't understand their documentation)? I know I could use code like this: ``` successful = False try: #code that might fail ...
You are looking for the `else` keyword: ``` try: #code that might fail except SomeException: #error handling if code failed else: # do this if no exception occured ```
running code if try statements were successful in python
2,792,568
10
2010-05-08T01:22:10Z
2,792,575
18
2010-05-08T01:25:12Z
[ "python", "error-handling", "try-catch" ]
I was wondering if in python there was a simple way to run code if a try statement was successful that wasn't in the try statement itself. Is that what the else or finally commands do (I didn't understand their documentation)? I know I could use code like this: ``` successful = False try: #code that might fail ...
You want "else": ``` for i in [0, 1]: try: print '10 / %i: ' % i, 10 / i except: print 'Uh-Oh' else: print 'Yay!' ```
Reading and parsing email from Gmail using C#, C++ or Python
2,792,623
14
2010-05-08T01:46:54Z
2,792,949
14
2010-05-08T04:42:24Z
[ "c#", "python", "email", "gmail" ]
I have to do a Windows application that from times to times access a Gmail account and checks if there is a new email. In case there is, it must read the email body and subject (a simple text email, without images or attachments). Please, do not use paid libs, and in case of any other libs used, give the download path...
This prints the subject and body of unseen messages, and marks those messages as seen. ``` import imaplib import email def extract_body(payload): if isinstance(payload,str): return payload else: return '\n'.join([extract_body(part.get_payload()) for part in payload]) conn = imaplib.IMAP4_SSL(...
Python3 error: "Import error: No module name urllib2"
2,792,650
115
2010-05-08T01:58:52Z
2,792,652
146
2010-05-08T02:00:15Z
[ "python", "python-3.x", "urllib2" ]
Here's my code: ``` import urllib2.request response = urllib2.urlopen("http://www.google.com") html = response.read() print(html) ``` Any help?
As stated in the urllib2 documentation at <http://docs.python.org/library/urllib2.html>: > The urllib2 module has been split across several modules in Python 3.0 named urllib.request and urllib.error. The 2to3 tool will automatically adapt imports when converting your sources to 3 So you should instead be saying ```...
Python3 error: "Import error: No module name urllib2"
2,792,650
115
2010-05-08T01:58:52Z
14,510,349
30
2013-01-24T20:42:39Z
[ "python", "python-3.x", "urllib2" ]
Here's my code: ``` import urllib2.request response = urllib2.urlopen("http://www.google.com") html = response.read() print(html) ``` Any help?
The above didn't work for me in 3.3. Try this instead (YMMV, etc) ``` import urllib.request url = "http://www.google.com/" request = urllib.request.Request(url) response = urllib.request.urlopen(request) print (response.read().decode('utf-8')) ```