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
Ignore python multiple return value
431,866
112
2009-01-10T22:12:49Z
433,721
34
2009-01-11T21:15:51Z
[ "python", "function", "tuples" ]
Say I have a Python function that returns multiple values in a tuple: ``` def func(): return 1, 2 ``` Is there a nice way to ignore one of the results rather than just assigning to a temporary variable? Say if I was only interested in the first value, is there a better way than this: ``` x, temp = func() ```
If you're using Python 3, you can you use the star before a variable (on the left side of an assignment) to have it be a list in unpacking. ``` # Example 1: a is 1 and b is [2, 3] a, *b = [1, 2, 3] # Example 2: a is 1, b is [2, 3], and c is 4 a, *b, c = [1, 2, 3, 4] # Example 3: b is [1, 2] and c is 3 *b, c = [1, 2, 3] # Example 4: a is 1 and b is [] a, *b = [1] ```
Python: unpack to unknown number of variables?
431,944
6
2009-01-10T23:15:59Z
431,947
7
2009-01-10T23:18:02Z
[ "python", "casting", "iterable-unpacking" ]
How could I unpack a tuple of unknown to, say, a list? I have a number of columns of data and they get split up into a tuple by some function. I want to unpack this tuple to variables but I do not know how many columns I will have. Is there any way to dynamically unpack it to as many variables as I need? Thanks for your help :)
Unpack the tuple to a list? ``` l = list(t) ```
Python: unpack to unknown number of variables?
431,944
6
2009-01-10T23:15:59Z
431,959
11
2009-01-10T23:24:12Z
[ "python", "casting", "iterable-unpacking" ]
How could I unpack a tuple of unknown to, say, a list? I have a number of columns of data and they get split up into a tuple by some function. I want to unpack this tuple to variables but I do not know how many columns I will have. Is there any way to dynamically unpack it to as many variables as I need? Thanks for your help :)
You can use the asterisk to unpack a variable length. For instance: ``` foo, bar, *other = funct() ``` This should put the first item into `foo`, the second into `bar`, and all the rest into `other`. **Update:** I forgot to mention that this is Python 3.0 compatible only.
Is there a Numpy function to return the first index of something in an array?
432,112
190
2009-01-11T01:21:39Z
432,289
244
2009-01-11T03:12:03Z
[ "python", "arrays", "numpy" ]
I know there is a method for python list to return the first index of something ``` l = list(1,2,3) l.index(2) >>> 1 ``` Is there something like that for numpy arrays?
Yes, here is the answer given a Numpy array, array, and a value, item, to search for. ``` itemindex = numpy.where(array==item) ``` The result is a tuple with first all the row indices, then all the column indices. For example if array is two dimensions and it contained your item at two locations then ``` array[itemindex[0][0]][itemindex[1][0]] ``` would be equal to your item and so would ``` array[itemindex[0][1]][itemindex[1][1]] ``` [numpy.where](http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html)
Is there a Numpy function to return the first index of something in an array?
432,112
190
2009-01-11T01:21:39Z
432,325
8
2009-01-11T03:52:49Z
[ "python", "arrays", "numpy" ]
I know there is a method for python list to return the first index of something ``` l = list(1,2,3) l.index(2) >>> 1 ``` Is there something like that for numpy arrays?
If you're going to use this as an index into something else, you can use boolean indices if the arrays are broadcastable; you don't need explicit indices. The absolute simplest way to do this is to simply index based on a truth value. ``` other_array[first_array == item] ``` Any boolean operation works: ``` a = numpy.arange(100) other_array[first_array > 50] ``` The nonzero method takes booleans, too: ``` index = numpy.nonzero(first_array == item)[0][0] ``` The two zeros are for the tuple of indices (assuming first\_array is 1D) and then the first item in the array of indices.
Is there a Numpy function to return the first index of something in an array?
432,112
190
2009-01-11T01:21:39Z
1,044,443
43
2009-06-25T15:01:00Z
[ "python", "arrays", "numpy" ]
I know there is a method for python list to return the first index of something ``` l = list(1,2,3) l.index(2) >>> 1 ``` Is there something like that for numpy arrays?
If you need the index of the first occurrence of **only one value**, you can use `nonzero` (or `where`, which amounts to the same thing in this case): ``` >>> t = array([1, 1, 1, 2, 2, 3, 8, 3, 8, 8]) >>> nonzero(t == 8) (array([6, 8, 9]),) >>> nonzero(t == 8)[0][0] 6 ``` If you need the first index of each of **many values**, you could obviously do the same as above repeatedly, but there is a trick that may be faster. The following finds the indices of the first element of each *subsequence*: ``` >>> nonzero(r_[1, diff(t)[:-1]]) (array([0, 3, 5, 6, 7, 8]),) ``` Notice that it finds the beginning of both subsequence of 3s and both subsequences of 8s: [**1**, 1, 1, **2**, 2, **3**, **8**, **3**, **8**, 8] So it's slightly different than finding the first *occurrence* of each value. In your program, you may be able to work with a sorted version of `t` to get what you want: ``` >>> st = sorted(t) >>> nonzero(r_[1, diff(st)[:-1]]) (array([0, 3, 5, 7]),) ```
Is there a Numpy function to return the first index of something in an array?
432,112
190
2009-01-11T01:21:39Z
23,994,923
11
2014-06-02T12:47:58Z
[ "python", "arrays", "numpy" ]
I know there is a method for python list to return the first index of something ``` l = list(1,2,3) l.index(2) >>> 1 ``` Is there something like that for numpy arrays?
you can also convert a Numpy array to list in the air and get its index . for example ``` l = [1,2,3,4,5] #python list a = numpy.array(l) #numpy array i = a.tolist().index(2) # i will return index of 2 print i ``` Will print 1.
Short Python Code to say "Pick the lower value"?
432,211
6
2009-01-11T02:21:43Z
432,229
18
2009-01-11T02:30:58Z
[ "python", "code-snippets" ]
What I mean is, I'm looking for really short code that returns the lower value. for example: ``` a=[1,2,3,4,5,6,7,8,9,10] b=[1,2,3,4,5,6,7,8] len(a) = 10 len(b) = 8 if (fill-this-in): print(lesser-value) ``` And I forgot to add that if b is lower than a, I want b returned - not len(b) - the variable b.
``` print(min(a, b)) ```
Short Python Code to say "Pick the lower value"?
432,211
6
2009-01-11T02:21:43Z
432,345
25
2009-01-11T04:21:26Z
[ "python", "code-snippets" ]
What I mean is, I'm looking for really short code that returns the lower value. for example: ``` a=[1,2,3,4,5,6,7,8,9,10] b=[1,2,3,4,5,6,7,8] len(a) = 10 len(b) = 8 if (fill-this-in): print(lesser-value) ``` And I forgot to add that if b is lower than a, I want b returned - not len(b) - the variable b.
You're not hugely clear about what you want, so some alternatives. Given the following two lists: ``` a = [1,2,3,4,5,6,7,8,9,10] b = [1,2,3,4,5,6,7,8] ``` To print the shortest list, you can just do.. ``` >>> print(min(a, b)) [1, 2, 3, 4, 5, 6, 7, 8] ``` To get the shortest length as an number, you can either `min` the `len()` of each list, or do `len(min())` (both are identical, choose which ever you find most readable).. ``` >>> print(min( len(a), len(b) )) # or.. >>> print(len( min(a, b) )) 8 ``` To print the lowest value in either list, you can supply the list as a single argument to `min()` ``` >>> a.extend(b) # Appends b to a >>> print a [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8] >>> print(min(a)) 1 ``` Finally, another possibility, the list that has the lowest values in total: ``` >>> max( sum(a), sum(b) ) 55 ``` To print the actual list with the highest `sum()`, you could either use the ternary operator, like.. ``` >>> print a if sum(a) > sum(b) else b [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ``` ..although I never really liked (or use) it, instead using the slight longer, regular if/else statements.. ``` >>> if sum(a) > sum(b): ... print a ... else: ... print b ... [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] ```
SFTP in Python? (platform independent)
432,385
105
2009-01-11T04:48:19Z
432,403
77
2009-01-11T05:04:22Z
[ "python", "sftp" ]
I'm working on a simple tool that transfers files to a hard-coded location with the password also hard-coded. I'm a python novice, but thanks to ftplib, it was easy: ``` import ftplib info= ('someuser', 'password') #hard-coded def putfile(file, site, dir, user=(), verbose=True): """ upload a file by ftp to a site/directory login hard-coded, binary transfer """ if verbose: print 'Uploading', file local = open(file, 'rb') remote = ftplib.FTP(site) remote.login(*user) remote.cwd(dir) remote.storbinary('STOR ' + file, local, 1024) remote.quit() local.close() if verbose: print 'Upload done.' if __name__ == '__main__': site = 'somewhere.com' #hard-coded dir = './uploads/' #hard-coded import sys, getpass putfile(sys.argv[1], site, dir, user=info) ``` The problem is that I can't find any library that supports sFTP. What's the normal way to do something like this securely? Edit: Thanks to the answers here, I've gotten it working with Paramiko and this was the syntax. ``` import paramiko host = "THEHOST.com" #hard-coded port = 22 transport = paramiko.Transport((host, port)) password = "THEPASSWORD" #hard-coded username = "THEUSERNAME" #hard-coded transport.connect(username = username, password = password) sftp = paramiko.SFTPClient.from_transport(transport) import sys path = './THETARGETDIRECTORY/' + sys.argv[1] #hard-coded localpath = sys.argv[1] sftp.put(localpath, path) sftp.close() transport.close() print 'Upload done.' ``` Thanks again!
[Paramiko](http://www.lag.net/paramiko/) supports SFTP. I've used it, and I've used Twisted. Both have their place, but you might find it easier to start with Paramiko.
SFTP in Python? (platform independent)
432,385
105
2009-01-11T04:48:19Z
1,866,984
12
2009-12-08T13:29:52Z
[ "python", "sftp" ]
I'm working on a simple tool that transfers files to a hard-coded location with the password also hard-coded. I'm a python novice, but thanks to ftplib, it was easy: ``` import ftplib info= ('someuser', 'password') #hard-coded def putfile(file, site, dir, user=(), verbose=True): """ upload a file by ftp to a site/directory login hard-coded, binary transfer """ if verbose: print 'Uploading', file local = open(file, 'rb') remote = ftplib.FTP(site) remote.login(*user) remote.cwd(dir) remote.storbinary('STOR ' + file, local, 1024) remote.quit() local.close() if verbose: print 'Upload done.' if __name__ == '__main__': site = 'somewhere.com' #hard-coded dir = './uploads/' #hard-coded import sys, getpass putfile(sys.argv[1], site, dir, user=info) ``` The problem is that I can't find any library that supports sFTP. What's the normal way to do something like this securely? Edit: Thanks to the answers here, I've gotten it working with Paramiko and this was the syntax. ``` import paramiko host = "THEHOST.com" #hard-coded port = 22 transport = paramiko.Transport((host, port)) password = "THEPASSWORD" #hard-coded username = "THEUSERNAME" #hard-coded transport.connect(username = username, password = password) sftp = paramiko.SFTPClient.from_transport(transport) import sys path = './THETARGETDIRECTORY/' + sys.argv[1] #hard-coded localpath = sys.argv[1] sftp.put(localpath, path) sftp.close() transport.close() print 'Upload done.' ``` Thanks again!
If you want easy and simple, you might also want to look at [Fabric](http://docs.fabfile.org/0.9.0/). It's an automated deployment tool like Ruby's Capistrano, but simpler and ofc ourse for Python. It's build on top of Paramiko. You might not want to do 'automated deployment' but Fabric would suit your use case perfectly none the less. To show you how simple Fabric is: the fab file and command for your script would look like this (not tested, but 99% sure it will work): fab\_putfile.py: ``` from fabric.api import * env.hosts = ['THEHOST.com'] env.user = 'THEUSER' env.password = 'THEPASSWORD' def put_file(file): put(file, './THETARGETDIRECTORY/') # it's copied into the target directory ``` Then run the file with the fab command: ``` fab -f fab_putfile.py put_file:file=./path/to/my/file ``` And you're done! :)
SFTP in Python? (platform independent)
432,385
105
2009-01-11T04:48:19Z
23,900,341
24
2014-05-27T23:05:35Z
[ "python", "sftp" ]
I'm working on a simple tool that transfers files to a hard-coded location with the password also hard-coded. I'm a python novice, but thanks to ftplib, it was easy: ``` import ftplib info= ('someuser', 'password') #hard-coded def putfile(file, site, dir, user=(), verbose=True): """ upload a file by ftp to a site/directory login hard-coded, binary transfer """ if verbose: print 'Uploading', file local = open(file, 'rb') remote = ftplib.FTP(site) remote.login(*user) remote.cwd(dir) remote.storbinary('STOR ' + file, local, 1024) remote.quit() local.close() if verbose: print 'Upload done.' if __name__ == '__main__': site = 'somewhere.com' #hard-coded dir = './uploads/' #hard-coded import sys, getpass putfile(sys.argv[1], site, dir, user=info) ``` The problem is that I can't find any library that supports sFTP. What's the normal way to do something like this securely? Edit: Thanks to the answers here, I've gotten it working with Paramiko and this was the syntax. ``` import paramiko host = "THEHOST.com" #hard-coded port = 22 transport = paramiko.Transport((host, port)) password = "THEPASSWORD" #hard-coded username = "THEUSERNAME" #hard-coded transport.connect(username = username, password = password) sftp = paramiko.SFTPClient.from_transport(transport) import sys path = './THETARGETDIRECTORY/' + sys.argv[1] #hard-coded localpath = sys.argv[1] sftp.put(localpath, path) sftp.close() transport.close() print 'Upload done.' ``` Thanks again!
You should check out pysftp <https://pypi.python.org/pypi/pysftp> it depends on paramiko, but wraps most common use cases to just a few lines of code. ``` import pysftp import sys path = './THETARGETDIRECTORY/' + sys.argv[1] #hard-coded localpath = sys.argv[1] host = "THEHOST.com" #hard-coded password = "THEPASSWORD" #hard-coded username = "THEUSERNAME" #hard-coded with pysftp.Connection(host, username=username, password=password) as sftp: sftp.put(localpath, path) print 'Upload done.' ```
Materials for SICP with python?
432,637
5
2009-01-11T09:13:48Z
432,767
9
2009-01-11T11:24:17Z
[ "python", "sicp" ]
I want to try out SICP with Python. Can any one point to materials (video.article...) that teaches Structure and Interpretation of Computer Programs in **python**. Currently learning from SICP videos of Abelson, Sussman, and Sussman.
A direct translation of SICP in Python would make no sense - Scheme and Python are way too different. But there are a couple similar books in Python. The first that comes to mind is "thinking like a computer scientist". You'll find more informations about available material here: <http://www.greenteapress.com/thinkpython/thinkCSpy/>
Materials for SICP with python?
432,637
5
2009-01-11T09:13:48Z
433,688
7
2009-01-11T21:01:50Z
[ "python", "sicp" ]
I want to try out SICP with Python. Can any one point to materials (video.article...) that teaches Structure and Interpretation of Computer Programs in **python**. Currently learning from SICP videos of Abelson, Sussman, and Sussman.
Don't think there is a complete set of materials, [this](http://www.codepoetics.com/wiki/index.php?title=Topics:SICP_in_other_languages) is the best I know. If you are up to generating the material yourself, a bunch of us plan to work through SICP collectively [at](http://hn-sicp.pbwiki.com/). I know at least one guy will be using Haskell, so you will not be alone in pursuing an alternative route.
How can I assign a new class attribute via __dict__ in python?
432,786
30
2009-01-11T11:44:17Z
432,790
54
2009-01-11T11:47:26Z
[ "python", "oop", "class", "attributes" ]
I want to assign a class attribute via a string object - but how? Example: ``` class test(object): pass a = test() test.value = 5 a.value # -> 5 test.__dict__['value'] # -> 5 # BUT: attr_name = 'next_value' test.__dict__[attr_name] = 10 # -> 'dictproxy' object does not support item assignment ```
There is a builtin function for this: ``` setattr(test, attr_name, 10) ``` Reference: <http://docs.python.org/library/functions.html#setattr> Example: ``` >>> class a(object): pass >>> a.__dict__['wut'] = 4 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'dictproxy' object does not support item assignment >>> setattr(a, 'wut', 7) >>> a.wut 7 ```
How do you get the logical xor of two variables in Python?
432,842
310
2009-01-11T12:34:43Z
432,844
267
2009-01-11T12:35:51Z
[ "python", "logic" ]
How do you get the [logical xor](http://en.wikipedia.org/wiki/Exclusive_or) of two variables in Python? For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string): ``` str1 = raw_input("Enter string one:") str2 = raw_input("Enter string two:") if logical_xor(str1, str2): print "ok" else: print "bad" ``` The `^` operator seems to be bitwise, and not defined on all objects: ``` >>> 1 ^ 1 0 >>> 2 ^ 1 3 >>> "abc" ^ "" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for ^: 'str' and 'str' ```
You can always use the definition of xor to compute it from other logical operations: ``` (a and not b) or (not a and b) ``` But this is a little too verbose for me, and isn't particularly clear at first glance. Another way to do it is: ``` bool(a) ^ bool(b) ``` The xor operator on two booleans is logical xor (unlike on ints, where it's bitwise). Which makes sense, since [`bool` is just a subclass of `int`](http://docs.python.org/library/functions.html?highlight=bool#bool), but is implemented to only have the values `0` and `1`. And logical xor is equivalent to bitwise xor when the domain is restricted to `0` and `1`. So the `logical_xor` function would be implemented like: ``` def logical_xor(str1, str2): return bool(str1) ^ bool(str2) ``` Credit to [Nick Coghlan on the Python-3000 mailing list](http://mail.python.org/pipermail/python-3000/2007-December/011560.html).
How do you get the logical xor of two variables in Python?
432,842
310
2009-01-11T12:34:43Z
432,901
15
2009-01-11T13:10:52Z
[ "python", "logic" ]
How do you get the [logical xor](http://en.wikipedia.org/wiki/Exclusive_or) of two variables in Python? For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string): ``` str1 = raw_input("Enter string one:") str2 = raw_input("Enter string two:") if logical_xor(str1, str2): print "ok" else: print "bad" ``` The `^` operator seems to be bitwise, and not defined on all objects: ``` >>> 1 ^ 1 0 >>> 2 ^ 1 3 >>> "abc" ^ "" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for ^: 'str' and 'str' ```
* Python logical `or`: `A or B`: returns `A` if `bool(A)` is `True`, otherwise returns `B` * Python logical `and`: `A and B`: returns `A` if `bool(A)` is `False`, otherwise returns `B` To keep most of that way of thinking, my logical xor definintion would be: ``` def logical_xor(a, b): if bool(a) == bool(b): return False else: return a or b ``` That way it can return `a`, `b`, or `False`: ``` >>> logical_xor('this', 'that') False >>> logical_xor('', '') False >>> logical_xor('this', '') 'this' >>> logical_xor('', 'that') 'that' ```
How do you get the logical xor of two variables in Python?
432,842
310
2009-01-11T12:34:43Z
432,948
20
2009-01-11T13:44:31Z
[ "python", "logic" ]
How do you get the [logical xor](http://en.wikipedia.org/wiki/Exclusive_or) of two variables in Python? For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string): ``` str1 = raw_input("Enter string one:") str2 = raw_input("Enter string two:") if logical_xor(str1, str2): print "ok" else: print "bad" ``` The `^` operator seems to be bitwise, and not defined on all objects: ``` >>> 1 ^ 1 0 >>> 2 ^ 1 3 >>> "abc" ^ "" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for ^: 'str' and 'str' ```
As [Zach](http://stackoverflow.com/questions/432842/how-do-you-get-the-logical-xor-of-two-variables-in-python#432844) explained, you can use: ``` xor = bool(a) ^ bool(b) ``` Personally, I favor a slightly different dialect: ``` xor = bool(a) + bool(b) == 1 ``` This dialect is inspired from a logical diagramming language I learned in school where "OR" was denoted by a box containing `≥1` (greater than or equal to 1) and "XOR" was denoted by a box containing `=1`. This has the advantage of correctly implementing exclusive or on multiple operands. * "1 = a ^ b ^ c..." means the number of true operands is odd. This operator is "parity". * "1 = a + b + c..." means exactly one operand is true. This is "exclusive or", meaning "one to the exclusion of the others".
How do you get the logical xor of two variables in Python?
432,842
310
2009-01-11T12:34:43Z
433,161
694
2009-01-11T16:30:46Z
[ "python", "logic" ]
How do you get the [logical xor](http://en.wikipedia.org/wiki/Exclusive_or) of two variables in Python? For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string): ``` str1 = raw_input("Enter string one:") str2 = raw_input("Enter string two:") if logical_xor(str1, str2): print "ok" else: print "bad" ``` The `^` operator seems to be bitwise, and not defined on all objects: ``` >>> 1 ^ 1 0 >>> 2 ^ 1 3 >>> "abc" ^ "" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for ^: 'str' and 'str' ```
If you're already normalizing the inputs to booleans, then != is xor. ``` bool(a) != bool(b) ```
How do you get the logical xor of two variables in Python?
432,842
310
2009-01-11T12:34:43Z
11,036,506
85
2012-06-14T15:34:09Z
[ "python", "logic" ]
How do you get the [logical xor](http://en.wikipedia.org/wiki/Exclusive_or) of two variables in Python? For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string): ``` str1 = raw_input("Enter string one:") str2 = raw_input("Enter string two:") if logical_xor(str1, str2): print "ok" else: print "bad" ``` The `^` operator seems to be bitwise, and not defined on all objects: ``` >>> 1 ^ 1 0 >>> 2 ^ 1 3 >>> "abc" ^ "" Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for ^: 'str' and 'str' ```
Exclusive-or is already built-in to Python, in the [`operator`](http://docs.python.org/library/operator.html#operator.xor) module: ``` from operator import xor xor(bool(a), bool(b)) ```
How do I add a custom inline admin widget in Django?
433,251
10
2009-01-11T17:25:11Z
434,129
8
2009-01-12T00:44:41Z
[ "python", "django", "django-admin" ]
This is easy for non-inlines. Just override the following in the your admin.py AdminOptions: ``` def formfield_for_dbfield(self, db_field, **kwargs): if db_field.name == 'photo': kwargs['widget'] = AdminImageWidget() return db_field.formfield(**kwargs) return super(NewsOptions,self).formfield_for_dbfield(db_field,**kwargs) ``` I can't work out how to adapt this to work for inlines.
It works exactly the same way. The TabularInline and StackedInline classes also have a formfield\_for\_dbfield method, and you override it the same way in your subclass.
Column comparison in Django queries
433,294
12
2009-01-11T17:47:51Z
433,321
8
2009-01-11T18:00:30Z
[ "python", "django", "orm" ]
I have a following model: ``` class Car(models.Model): make = models.CharField(max_length=40) mileage_limit = models.IntegerField() mileage = models.IntegerField() ``` I want to select all cars where mileage is less than mileage\_limit, so in SQL it would be something like: ``` select * from car where mileage < mileage_limit; ``` Using Q object in Django, I know I can compare columns with any value/object, e.g. if I wanted to get cars that have mileage say less than 100,000 it would be something like: ``` cars = Car.objects.filter(Q(mileage__lt=100000)) ``` Instead of a fixed value I would like to use the column name (in my case it is mileage\_limit). So I would like to be able to do something like: ``` cars = Car.objects.filter(Q(mileage__lt=mileage_limit)) ``` However this results in an error, since it is expecting a value/object, not a column name. Is there a way to compare two columns using Q object? I feel like it would be a very commonly used feature and there should be an easy way to do this, however couldn't find anything about it in the documentation. *Note: this is a simplified example, for which the use of Q object might seam to be unnecessary. However the real model has many more columns, and the real query is more complex, that's why I am using Q. Here in this question I just wanted to figure out specifically how to compare columns using Q.* **EDIT** Apparently after release of Django 1.1 it would be possible to do the following: ``` cars = Car.objects.filter(mileage__lt=F('mileage_limit')) ``` Still not sure if F is supposed to work together with Q like this: ``` cars = Car.objects.filter(Q(mileage__lt=F('mileage_limit'))) ```
You can't do this right now without custom SQL. The django devs are working on an F() function that would make it possible: [#7210 - F() syntax, design feedback required.](http://groups.google.com/group/django-developers/browse_thread/thread/c8cff7e5e16c692a#)
Python Library to Generate VCF Files?
433,331
6
2009-01-11T18:05:15Z
433,453
7
2009-01-11T19:13:17Z
[ "python", "vcf" ]
Know of any good libraries for this? I did some searches and didn't come across anything. Someone somewhere must have done this before, I hate to reinvent the wheel.
I would look at: [http://vobject.skyhouseconsulting.com/usage.html](http://vobject.skyhouseconsulting.com/) (look under "Usage examples") Very easy parsing and generation of both vCal and vCard.
Python-Regex, what's going on here?
433,388
6
2009-01-11T18:36:21Z
433,418
8
2009-01-11T18:54:18Z
[ "python", "regex" ]
I've got a book on python recently and it's got a chapter on Regex, there's a section of code which I can't really understand. Can someone explain exactly what's going on here (this section is on Regex groups)? ``` >>> my_regex = r'(?P<zip>Zip:\s*\d\d\d\d\d)\s*(State:\s*\w\w)' >>> addrs = "Zip: 10010 State: NY" >>> y = re.search(my_regex, addrs) >>> y.groupdict('zip') {'zip': 'Zip: 10010'} >>> y.group(2) 'State: NY' ```
regex definition: ``` (?P<zip>...) ``` Creates a named group "zip" ``` Zip:\s* ``` Match "Zip:" and zero or more whitespace characters ``` \d ``` Match a digit ``` \w ``` Match a word character [A-Za-z0-9\_] ``` y.groupdict('zip') ``` The groupdict method returns a dictionary with named groups as keys and their matches as values. In this case, the match for the "zip" group gets returned ``` y.group(2) ``` Return the match for the second group, which is a unnamed group "(...)" Hope that helps.
Shorthand adding/appending in Python
433,795
7
2009-01-11T21:52:29Z
433,803
21
2009-01-11T21:54:52Z
[ "python" ]
I like that in PHP I can do the following ``` $myInteger++; $myString += 'more text'; ``` With Python I must do the following ``` myInteger = myInteger + 1 myString = myString + "more text" ``` Is there a better way to add or append to a variable in Python?
Python doesn't have the increment (++) and decrement (--) operators, but it does have the += operator (and -=, etc.) so you can do this: ``` myInteger += 1 myString += "more text" ```
What is the most "pythonic" way to iterate over a list in chunks?
434,287
241
2009-01-12T02:48:22Z
434,314
15
2009-01-12T03:02:59Z
[ "python", "list", "loops", "optimization", "chunks" ]
I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way: ``` for i in xrange(0, len(ints), 4): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] ``` It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better? ``` while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] ``` Still doesn't quite "feel" right, though. :-/ Related question: [How do you split a list into evenly sized chunks in Python?](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python)
``` import itertools def chunks(iterable,size): it = iter(iterable) chunk = tuple(itertools.islice(it,size)) while chunk: yield chunk chunk = tuple(itertools.islice(it,size)) # though this will throw ValueError if the length of ints # isn't a multiple of four: for x1,x2,x3,x4 in chunks(ints,4): foo += x1 + x2 + x3 + x4 for chunk in chunks(ints,4): foo += sum(chunk) ``` Another way: ``` import itertools def chunks2(iterable,size,filler=None): it = itertools.chain(iterable,itertools.repeat(filler,size-1)) chunk = tuple(itertools.islice(it,size)) while len(chunk) == size: yield chunk chunk = tuple(itertools.islice(it,size)) # x2, x3 and x4 could get the value 0 if the length is not # a multiple of 4. for x1,x2,x3,x4 in chunks2(ints,4,0): foo += x1 + x2 + x3 + x4 ```
What is the most "pythonic" way to iterate over a list in chunks?
434,287
241
2009-01-12T02:48:22Z
434,321
44
2009-01-12T03:06:09Z
[ "python", "list", "loops", "optimization", "chunks" ]
I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way: ``` for i in xrange(0, len(ints), 4): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] ``` It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better? ``` while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] ``` Still doesn't quite "feel" right, though. :-/ Related question: [How do you split a list into evenly sized chunks in Python?](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python)
I'm a fan of ``` chunkSize= 4 for i in xrange(0, len(ints), chunkSize): chunk = ints[i:i+chunkSize] # process chunk of size <= chunkSize ```
What is the most "pythonic" way to iterate over a list in chunks?
434,287
241
2009-01-12T02:48:22Z
434,328
233
2009-01-12T03:10:17Z
[ "python", "list", "loops", "optimization", "chunks" ]
I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way: ``` for i in xrange(0, len(ints), 4): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] ``` It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better? ``` while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] ``` Still doesn't quite "feel" right, though. :-/ Related question: [How do you split a list into evenly sized chunks in Python?](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python)
``` def chunker(seq, size): return (seq[pos:pos + size] for pos in xrange(0, len(seq), size)) ``` Simple. Easy. Fast. Works with any sequence: ``` text = "I am a very, very helpful text" for group in chunker(text, 7): print repr(group), # 'I am a ' 'very, v' 'ery hel' 'pful te' 'xt' print '|'.join(chunker(text, 10)) # I am a ver|y, very he|lpful text animals = ['cat', 'dog', 'rabbit', 'duck', 'bird', 'cow', 'gnu', 'fish'] for group in chunker(animals, 3): print group # ['cat', 'dog', 'rabbit'] # ['duck', 'bird', 'cow'] # ['gnu', 'fish'] ```
What is the most "pythonic" way to iterate over a list in chunks?
434,287
241
2009-01-12T02:48:22Z
434,398
10
2009-01-12T03:56:20Z
[ "python", "list", "loops", "optimization", "chunks" ]
I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way: ``` for i in xrange(0, len(ints), 4): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] ``` It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better? ``` while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] ``` Still doesn't quite "feel" right, though. :-/ Related question: [How do you split a list into evenly sized chunks in Python?](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python)
``` from itertools import izip_longest def chunker(iterable, chunksize, filler): return izip_longest(*[iter(iterable)]*chunksize, fillvalue=filler) ```
What is the most "pythonic" way to iterate over a list in chunks?
434,287
241
2009-01-12T02:48:22Z
434,411
174
2009-01-12T04:07:20Z
[ "python", "list", "loops", "optimization", "chunks" ]
I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way: ``` for i in xrange(0, len(ints), 4): # dummy op for example code foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3] ``` It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better? ``` while ints: foo += ints[0] * ints[1] + ints[2] * ints[3] ints[0:4] = [] ``` Still doesn't quite "feel" right, though. :-/ Related question: [How do you split a list into evenly sized chunks in Python?](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python)
Modified from the [recipes](http://docs.python.org/library/itertools.html#recipes) section of Python's [itertools](http://docs.python.org/library/itertools.html) docs: ``` from itertools import izip_longest def grouper(iterable, n, fillvalue=None): args = [iter(iterable)] * n return izip_longest(*args, fillvalue=fillvalue) ``` **Example** In pseudocode to keep the example terse. ``` grouper('ABCDEFG', 3, 'x') --> 'ABC' 'DEF' 'Gxx' ``` **Note:** `izip_longest` is new to Python 2.6. In Python 3 use `zip_longest`.
Comparing dictionaries in Python
434,353
5
2009-01-12T03:23:17Z
434,390
10
2009-01-12T03:50:58Z
[ "python", "dictionary" ]
Given two dictionaries, `d1` and `d2`, and an integer `l`, I want to find all keys `k` in `d1` such that either `d2[k]<l` or `k not in l`. I want to output the keys and the corresponding values in `d2`, except if `d2` does not contain the key, I want to print 0. For instance, if `d1` is ``` a: 1 b: 1 c: 1 d: 1 ``` and `d2` is ``` a: 90 b: 89 x: 45 d: 90 ``` and `l` is 90, the output would be (possibly in a different order) ``` b 89 c 0 ``` What is the best way to do this in Python? I am just starting to learn the language, and so far this is what I have: ``` for k in d1.keys(): if k not in d2: print k, 0 else: if d2[k]<l: print k, d2[k] ``` This works of course (unless I have a typo), but it seems to me that there would be a more pythonic way of doing it.
Yours is actually fine -- you could simplify it to ``` for k in d1: if d2.get(k, 0) < l: print k, d2.get(k, 0) ``` which is (to me) pythonic, and is pretty much a direct "translation" into code of your description. If you want to avoid the double lookup, you could do ``` for k in d1: val = d2.get(k, 0) if val < l: print k, val ```
For Python support, what company would be best to get hosting from?
434,580
11
2009-01-12T06:07:39Z
434,593
21
2009-01-12T06:18:24Z
[ "python", "web-hosting", "wsgi" ]
I want to be able to run WSGI apps but my current hosting restricts it. Does anybody know a company that can accommodate my requirements?
My automatic response would be [WebFaction](http://www.webfaction.com/). I haven't personally hosted with them, but they are primarily Python-oriented (founded by the guy who wrote CherryPy, for example, and as far as I know they were the first to roll out [Python 3.0 support](http://blog.webfaction.com/python-3-0-is-here)).
What is the fastest way to draw an image from discrete pixel values in Python?
434,583
20
2009-01-12T06:08:12Z
435,215
9
2009-01-12T11:57:48Z
[ "python", "image", "python-imaging-library" ]
I wish to draw an image based on computed pixel values, as a means to visualize some data. Essentially, I wish to take a 2-dimensional matrix of color triplets and render it. Do note that this is not image processing, since I'm not transforming an existing image nor doing any sort of whole-image transformations, and it's also not vector graphics as there is no pre-determined structure to the image I'm rendering- I'm probably going to be producing amorphous blobs of color one pixel at a time. I need to render images about 1kx1k pixels for now, but something scalable would be useful. Final target format is PNG or any other lossless format. I've been using PIL at the moment via ImageDraw's draw.point , and I was wondering, given the very specific and relatively basic features I require, is there any faster library available?
``` import Image im= Image.new('RGB', (1024, 1024)) im.putdata([(255,0,0), (0,255,0), (0,0,255)]) im.save('test.png') ``` Puts a red, green and blue pixel in the top-left of the image. `im.fromstring()` is faster still if you prefer to deal with byte values.
What is the fastest way to draw an image from discrete pixel values in Python?
434,583
20
2009-01-12T06:08:12Z
435,944
21
2009-01-12T16:20:57Z
[ "python", "image", "python-imaging-library" ]
I wish to draw an image based on computed pixel values, as a means to visualize some data. Essentially, I wish to take a 2-dimensional matrix of color triplets and render it. Do note that this is not image processing, since I'm not transforming an existing image nor doing any sort of whole-image transformations, and it's also not vector graphics as there is no pre-determined structure to the image I'm rendering- I'm probably going to be producing amorphous blobs of color one pixel at a time. I need to render images about 1kx1k pixels for now, but something scalable would be useful. Final target format is PNG or any other lossless format. I've been using PIL at the moment via ImageDraw's draw.point , and I was wondering, given the very specific and relatively basic features I require, is there any faster library available?
If you have numpy and scipy available (and if you are manipulating large arrays in Python, I would recommend them), then the scipy.misc.pilutil.toimage function is very handy. A simple example: ``` import numpy as np import scipy.misc as smp # Create a 1024x1024x3 array of 8 bit unsigned integers data = np.zeros( (1024,1024,3), dtype=np.uint8 ) data[512,512] = [254,0,0] # Makes the middle pixel red data[512,513] = [0,0,255] # Makes the next pixel blue img = smp.toimage( data ) # Create a PIL image img.show() # View in default viewer ``` The nice thing is toimage copes with diferent data types very well, so a 2d array of floating point numbers gets sensibly converted to greyscale etc. You can download numpy and scipy from <http://docs.scipy.org/doc/scipy/reference/misc.html>.
Open document with default application in Python
434,597
66
2009-01-12T06:23:51Z
434,612
48
2009-01-12T06:30:20Z
[ "python", "windows", "osx" ]
I need to be able to open a document using its default application in Windows and Mac OS. Basically, I want to do the same thing that happens when you double click on the document icon in Explorer or Finder. What is the best way to do this in Python?
In Mac OS, you can use the "open" command. There is a Windows API call that does something similar, but I don't remember it offhand. ### Update Okay, the "start" command will do it, so this should work. Mac OS/X: ``` os.system("open "+filename) ``` Windows: ``` os.system("start "+filename) ``` ### Much later update by Edward: os.system works, but *it only works with filenames that don't have any spaces in folders and files in the filename (e.g. A:\abc\def\a.txt)*. ### Later Update Okay, clearly this silly-ass controversy continues, so let's just look at doing this with subprocess. `open` and `start` are command interpreter things for Mac OS/X and Windows respectively. Now, let's say we use subprocess. Canonically, you'd use: ``` try: retcode = subprocess.call("open " + filename, shell=True) if retcode < 0: print >>sys.stderr, "Child was terminated by signal", -retcode else: print >>sys.stderr, "Child returned", retcode except OSError, e: print >>sys.stderr, "Execution failed:", e ``` Now, what are the advantages of this? In theory, this is more secure -- but in fact we're needing to execute a command line one way or the other; in either environment, we need the environment and services to interpet, get paths, and so forth. In neither case are we executing arbitrary text, so it doesn't have an inherent "but you can type `'filename ; rm -rf /'`" problem, and IF the file name can be corrupted, using `subprocess.call` gives us no protection. It doesn't actually give us any more error detection, we're still depending on the `retcode` in either case. We don't need to wait for the child process, since we're by problem statement starting a separate process. "But `subprocess` is preferred." However, `os.system()` is not deprecated, and it's the simplest tool for this particular job. Conclusion: using `os.system()` is the simplest, most straightforward way to do this, and is therefore a correct answer.
Open document with default application in Python
434,597
66
2009-01-12T06:23:51Z
435,291
18
2009-01-12T12:33:39Z
[ "python", "windows", "osx" ]
I need to be able to open a document using its default application in Windows and Mac OS. Basically, I want to do the same thing that happens when you double click on the document icon in Explorer or Finder. What is the best way to do this in Python?
I prefer: ``` os.startfile(path, 'open') ``` Note that this module supports filenames that have spaces in their folders and files e.g. ``` A:\abc\folder with spaces\file with-spaces.txt ``` ([python docs](http://docs.python.org/library/os.html#os.startfile)) 'open' does not have to be added (it is the default). The docs specifically mention that this is like double-clicking on a file's icon in Windows Explorer. This solution is windows only.
Open document with default application in Python
434,597
66
2009-01-12T06:23:51Z
435,631
26
2009-01-12T14:47:09Z
[ "python", "windows", "osx" ]
I need to be able to open a document using its default application in Windows and Mac OS. Basically, I want to do the same thing that happens when you double click on the document icon in Explorer or Finder. What is the best way to do this in Python?
Just for completeness (it wasn't in the question), [xdg-open](http://portland.freedesktop.org/xdg-utils-1.0/xdg-open.html) will do the same on Linux.
Open document with default application in Python
434,597
66
2009-01-12T06:23:51Z
435,669
91
2009-01-12T15:00:22Z
[ "python", "windows", "osx" ]
I need to be able to open a document using its default application in Windows and Mac OS. Basically, I want to do the same thing that happens when you double click on the document icon in Explorer or Finder. What is the best way to do this in Python?
Use the `subprocess` module available on Python 2.4+, not `os.system()`, so you don't have to deal with shell escaping. ``` import subprocess, os if sys.platform.startswith('darwin'): subprocess.call(('open', filepath)) elif os.name == 'nt': os.startfile(filepath) elif os.name == 'posix': subprocess.call(('xdg-open', filepath)) ``` The double parentheses are because `subprocess.call()` wants a sequence as its first argument, so we're using a tuple here. On Linux systems with Gnome there is also a `gnome-open` command that does the same thing, but `xdg-open` is the Free Desktop Foundation standard and works across Linux desktop environments.
Open document with default application in Python
434,597
66
2009-01-12T06:23:51Z
435,748
20
2009-01-12T15:28:07Z
[ "python", "windows", "osx" ]
I need to be able to open a document using its default application in Windows and Mac OS. Basically, I want to do the same thing that happens when you double click on the document icon in Explorer or Finder. What is the best way to do this in Python?
``` import os import subprocess def click_on_file(filename): try: os.startfile(filename): except AttributeError: subprocess.call(['open', filename]) ```
Open document with default application in Python
434,597
66
2009-01-12T06:23:51Z
11,479,099
10
2012-07-13T22:19:01Z
[ "python", "windows", "osx" ]
I need to be able to open a document using its default application in Windows and Mac OS. Basically, I want to do the same thing that happens when you double click on the document icon in Explorer or Finder. What is the best way to do this in Python?
If you have to use an heuristic method, you may consider `webbrowser`. It's standard library and despite of its name it would also try to open files: > Note that on some platforms, trying to open a filename using this > function, may work and start the operating system’s associated > program. However, this is neither supported nor portable. > ([Reference](http://docs.python.org/library/webbrowser.html#webbrowser.open)) I tried this code and it worked fine in Windows 7 and Ubuntu Natty: ``` import webbrowser webbrowser.open("path_to_file") ``` This code also works fine in Windows XP Professional, using Internet Explorer 8.
How do I set permissions (attributes) on a file in a ZIP file using Python's zipfile module?
434,641
27
2009-01-12T06:51:27Z
434,651
12
2009-01-12T06:57:36Z
[ "python", "attributes", "zip", "file-permissions", "zipfile" ]
When I extract files from a ZIP file created with the Python [`zipfile`](http://docs.python.org/library/zipfile.html) module, all the files are not writable, read only etc. The file is being created and extracted under Linux and Python 2.5.2. As best I can tell, I need to set the `ZipInfo.external_attr` property for each file, but this doesn't seem to be documented anywhere I could find, can anyone enlighten me?
Look at this: <http://stackoverflow.com/questions/279945/set-permissions-on-a-compressed-file-in-python> I'm not entirely sure if that's what you want, but it seems to be. The key line appears to be: ``` zi.external_attr = 0777 << 16L ``` It looks like it sets the permissions to `0777` there.
How do I set permissions (attributes) on a file in a ZIP file using Python's zipfile module?
434,641
27
2009-01-12T06:51:27Z
434,689
28
2009-01-12T07:14:46Z
[ "python", "attributes", "zip", "file-permissions", "zipfile" ]
When I extract files from a ZIP file created with the Python [`zipfile`](http://docs.python.org/library/zipfile.html) module, all the files are not writable, read only etc. The file is being created and extracted under Linux and Python 2.5.2. As best I can tell, I need to set the `ZipInfo.external_attr` property for each file, but this doesn't seem to be documented anywhere I could find, can anyone enlighten me?
This seems to work (thanks Evan, putting it here so the line is in context): ``` buffer = "path/filename.zip" # zip filename to write (or file-like object) name = "folder/data.txt" # name of file inside zip bytes = "blah blah blah" # contents of file inside zip zip = zipfile.ZipFile(buffer, "w", zipfile.ZIP_DEFLATED) info = zipfile.ZipInfo(name) info.external_attr = 0777 << 16L # give full access to included file zip.writestr(info, bytes) zip.close() ``` I'd still like to see something that documents this... An additional resource I found was a note on the Zip file format: <http://www.pkware.com/documents/casestudies/APPNOTE.TXT>
How do I set permissions (attributes) on a file in a ZIP file using Python's zipfile module?
434,641
27
2009-01-12T06:51:27Z
6,297,838
14
2011-06-09T19:00:35Z
[ "python", "attributes", "zip", "file-permissions", "zipfile" ]
When I extract files from a ZIP file created with the Python [`zipfile`](http://docs.python.org/library/zipfile.html) module, all the files are not writable, read only etc. The file is being created and extracted under Linux and Python 2.5.2. As best I can tell, I need to set the `ZipInfo.external_attr` property for each file, but this doesn't seem to be documented anywhere I could find, can anyone enlighten me?
[This link](http://trac.edgewall.org/attachment/ticket/8919/ZipDownload.patch) has more information than anything else I've been able to find on the net. Even the zip source doesn't have anything. Copying the relevant section for posterity. This patch isn't really about documenting this format, which just goes to show how pathetic (read non-existent) the current documentation is. ``` # external_attr is 4 bytes in size. The high order two # bytes represent UNIX permission and file type bits, # while the low order two contain MS-DOS FAT file # attributes, most notably bit 4 marking directories. if node.isfile: zipinfo.compress_type = ZIP_DEFLATED zipinfo.external_attr = 0644 << 16L # permissions -r-wr--r-- data = node.get_content().read() properties = node.get_properties() if 'svn:special' in properties and \ data.startswith('link '): data = data[5:] zipinfo.external_attr |= 0120000 << 16L # symlink file type zipinfo.compress_type = ZIP_STORED if 'svn:executable' in properties: zipinfo.external_attr |= 0755 << 16L # -rwxr-xr-x zipfile.writestr(zipinfo, data) elif node.isdir and path: if not zipinfo.filename.endswith('/'): zipinfo.filename += '/' zipinfo.compress_type = ZIP_STORED zipinfo.external_attr = 040755 << 16L # permissions drwxr-xr-x zipinfo.external_attr |= 0x10 # MS-DOS directory flag zipfile.writestr(zipinfo, '') ``` Also, [this link](http://www.pkware.com/documents/casestudies/APPNOTE.TXT) has the following. Here the low order byte presumably means the rightmost (lowest) byte of the four bytes. So this one is for MS-DOS and can presumably be left as zero otherwise. > external file attributes: (4 bytes) > > ``` > The mapping of the external attributes is > host-system dependent (see 'version made by'). For > MS-DOS, the low order byte is the MS-DOS directory > attribute byte. If input came from standard input, this > field is set to zero. > ``` Also, the source file unix/unix.c in the sources for InfoZIP's zip program, downloaded from [Debian's archives](http://packages.debian.org/source/stable/zip) has the following in comments. ``` /* lower-middle external-attribute byte (unused until now): * high bit => (have GMT mod/acc times) >>> NO LONGER USED! <<< * second-high bit => have Unix UID/GID info * NOTE: The high bit was NEVER used in any official Info-ZIP release, * but its future use should be avoided (if possible), since it * was used as "GMT mod/acc times local extra field" flags in Zip beta * versions 2.0j up to 2.0v, for about 1.5 years. */ ``` So taking all this together, it looks like only the second highest byte is actually used, at least for Unix. EDIT: I asked about the Unix aspect of this on Unix.SX, in the question "[The zip format's external file attribute](http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute)". Looks like I got a couple of things wrong. Specifically both of the top two bytes are used for Unix.
Cleaning up a database in django before every test method
434,700
9
2009-01-12T07:22:59Z
436,795
22
2009-01-12T19:59:19Z
[ "python", "django", "unit-testing", "django-models" ]
By default when Django runs against sqlite backend it creates a new in memory database for a test. That means for every class that derives from unittest.TestCase, I get a new database. Can this be changed so that it is cleared before every test method is run? Example: I am testing a manager class that provides additional abstraction on top of Django persistent objects. The code looks more-less like that ``` class TestForManager(unittest.TestCase): def testAddingBlah(self): manager = Manager() self.assertEquals(manager.getBlahs(), 0) manager.addBlah(...) self.assertEquals(manager.getBlahs(), 1) def testAddingBlahInDifferentWay(self): manager = Manager() self.assertEquals(manager.getBlahs(), 0) manager.addBlahInDifferentWay(...) self.assertEquals(manager.getBlahs(), 1) ``` Now, the first assertion of second test fails, because the state of the database is preserved between test calls and there already is an instance of `Blah` in the database.
As always, solution is trivial: use `django.test.TestCase` not `unittest.TestCase`. And it works in all major versions of Django!
Ensuring contact form email isn't lost (python)
436,003
2
2009-01-12T16:33:03Z
436,031
8
2009-01-12T16:40:21Z
[ "python", "email", "race-condition", "data-formats" ]
I have a website with a contact form. User submits name, email and message and the site emails me the details. Very occasionally my server has a problem with it's email system and so the user gets an error and those contact details are lost. (Don't say: get a better server, any server can have email go down now and then and we do get a lot of submissions). I would like to implement a system that could store the user's details if the mail sending function returns with an error code. Then on every further submission, check for any stored submissions and try to send them off to me. But how to store the data? I'm using python so I thought about using [shelve](http://docs.python.org/library/shelve.html) (single file semi-database). Or maybe someone could suggest a better data format? (I do think a full database solution would be overkill.) The problem I see with a single file approach is *race-conditions*: two or more failed emails at the same time would cause two edits to the data file resulting in data corruption. So what to do? Multi-file solution, file locking or something else?
When we implement email sending functionality in our environment we do it in a decoupled way. So for example a user would submit their data which would get stored in a database. We then have a separate service that runs, queries the database and sends out email. That way if there are ever any email server issues, the service will just try again later, data and user confidence is never lost.
What is an alternative to execfile in Python 3.0?
436,198
154
2009-01-12T17:23:36Z
436,214
11
2009-01-12T17:28:15Z
[ "python", "python-3.x" ]
It seems they canceled in Python 3.0 all the easy way to quickly load a script file - both execfile() and reload(). Is there an obvious alternative I'm missing?
If the script you want to load is in the same directory than the one you run, maybe "import" will do the job ? If you need to dynamically import code the built-in function [\_\_ import\_\_](http://docs.python.org/library/functions.html#__import__) and the module [imp](http://docs.python.org/library/imp.html) are worth looking at. ``` >>> import sys >>> sys.path = ['/path/to/script'] + sys.path >>> __import__('test') <module 'test' from '/path/to/script/test.pyc'> >>> __import__('test').run() 'Hello world!' ``` test.py: ``` def run(): return "Hello world!" ``` If you're using Python 3.1 or later, you should also take a look at [importlib](http://docs.python.org/release/3.1/library/importlib.html).
What is an alternative to execfile in Python 3.0?
436,198
154
2009-01-12T17:23:36Z
436,267
16
2009-01-12T17:38:43Z
[ "python", "python-3.x" ]
It seems they canceled in Python 3.0 all the easy way to quickly load a script file - both execfile() and reload(). Is there an obvious alternative I'm missing?
You could write your own function: ``` def xfile(afile, globalz=None, localz=None): with open(afile, "r") as fh: exec(fh.read(), globalz, localz) ``` If you really needed to...
What is an alternative to execfile in Python 3.0?
436,198
154
2009-01-12T17:23:36Z
437,857
147
2009-01-13T03:20:59Z
[ "python", "python-3.x" ]
It seems they canceled in Python 3.0 all the easy way to quickly load a script file - both execfile() and reload(). Is there an obvious alternative I'm missing?
You are just supposed to read the file and exec the code yourself. 2to3 current replaces ``` execfile("somefile.py", global_vars, local_vars) ``` as ``` with open("somefile.py") as f: code = compile(f.read(), "somefile.py", 'exec') exec(code, global_vars, local_vars) ``` (The compile call isn't strictly needed, but it associates the filename with the code object making debugging a little easier.) See: * <http://docs.python.org/release/2.7.3/library/functions.html#execfile> * <http://docs.python.org/release/3.2.3/library/functions.html#compile> * <http://docs.python.org/release/3.2.3/library/functions.html#exec>
What is an alternative to execfile in Python 3.0?
436,198
154
2009-01-12T17:23:36Z
2,849,077
11
2010-05-17T12:43:26Z
[ "python", "python-3.x" ]
It seems they canceled in Python 3.0 all the easy way to quickly load a script file - both execfile() and reload(). Is there an obvious alternative I'm missing?
This one is better, since it takes the globals and locals from the caller: ``` import sys def execfile(filename, globals=None, locals=None): if globals is None: globals = sys._getframe(1).f_globals if locals is None: locals = sys._getframe(1).f_locals with open(filename, "r") as fh: exec(fh.read()+"\n", globals, locals) ```
What is an alternative to execfile in Python 3.0?
436,198
154
2009-01-12T17:23:36Z
16,577,427
113
2013-05-16T01:03:00Z
[ "python", "python-3.x" ]
It seems they canceled in Python 3.0 all the easy way to quickly load a script file - both execfile() and reload(). Is there an obvious alternative I'm missing?
According to the documentation, instead of ``` execfile("./filename") ``` Use ``` exec(open("./filename").read()) ``` See: * [What’s New In Python 3.0](http://docs.python.org/3.3/whatsnew/3.0.html?highlight=execfile#builtins)
What is an alternative to execfile in Python 3.0?
436,198
154
2009-01-12T17:23:36Z
24,261,031
15
2014-06-17T10:06:15Z
[ "python", "python-3.x" ]
It seems they canceled in Python 3.0 all the easy way to quickly load a script file - both execfile() and reload(). Is there an obvious alternative I'm missing?
As [suggested on the python-dev](https://mail.python.org/pipermail/python-dev/2014-June/134992.html) mailinglist recently, the [runpy](https://docs.python.org/3/library/runpy.html) module might be a viable alternative. Quoting from that message: > <https://docs.python.org/3/library/runpy.html#runpy.run_path> > > ``` > import runpy > file_globals = runpy.run_path("file.py") > ``` There are subtle differences to `execfile`: * `run_path` always creates a new namespace. It executes the code as a module, so there is no difference between globals and locals (which is why there is only a `init_globals` argument). The globals are returned. `execfile` executed in the current namespace or the given namespace. The semantics of `locals` and `globals`, if given, were similar to locals and globals inside a class definition. * `run_path` can not only execute files, but also eggs and directories (refer to its documentation for details).
Python: Is there a way to determine the encoding of text file?
436,220
97
2009-01-12T17:30:27Z
436,299
100
2009-01-12T17:45:32Z
[ "python", "encoding", "text-files" ]
I know there is something buried in [here](http://stackoverflow.com/questions/90838/how-can-i-detect-the-encoding-codepage-of-a-text-file). But I was just wondering if there is an actual way built into Python to determine text file encoding? Thanks for your help :) Edit: As a side question, it can be ignored if you want but why is the type of encoding not put into the file so it could be detected easier?
Correctly detecting the encoding all times is **impossible**. (From chardet FAQ:) > However, some encodings are optimized > for specific languages, and languages > are not random. Some character > sequences pop up all the time, while > other sequences make no sense. A > person fluent in English who opens a > newspaper and finds “txzqJv 2!dasd0a > QqdKjvz” will instantly recognize that > that isn't English (even though it is > composed entirely of English letters). > By studying lots of “typical” text, a > computer algorithm can simulate this > kind of fluency and make an educated > guess about a text's language. There is the [chardet](http://pypi.python.org/pypi/chardet) library that uses that study to try to detect encoding. chardet is a port of the auto-detection code in Mozilla. You can also use [UnicodeDammit](http://www.crummy.com/software/BeautifulSoup/documentation.html#Beautiful%20Soup%20Gives%20You%20Unicode,%20Dammit). It will try the following methods: * An encoding discovered in the document itself: for instance, in an XML declaration or (for HTML documents) an http-equiv META tag. If Beautiful Soup finds this kind of encoding within the document, it parses the document again from the beginning and gives the new encoding a try. The only exception is if you explicitly specified an encoding, and that encoding actually worked: then it will ignore any encoding it finds in the document. * An encoding sniffed by looking at the first few bytes of the file. If an encoding is detected at this stage, it will be one of the UTF-\* encodings, EBCDIC, or ASCII. * An encoding sniffed by the [chardet](http://pypi.python.org/pypi/chardet) library, if you have it installed. * UTF-8 * Windows-1252
Python: Is there a way to determine the encoding of text file?
436,220
97
2009-01-12T17:30:27Z
14,734,061
13
2013-02-06T16:32:05Z
[ "python", "encoding", "text-files" ]
I know there is something buried in [here](http://stackoverflow.com/questions/90838/how-can-i-detect-the-encoding-codepage-of-a-text-file). But I was just wondering if there is an actual way built into Python to determine text file encoding? Thanks for your help :) Edit: As a side question, it can be ignored if you want but why is the type of encoding not put into the file so it could be detected easier?
Some encoding strategies, please uncomment to taste : ``` #!/bin/bash # tmpfile=$1 echo '-- info about file file ........' file -i $tmpfile enca -g $tmpfile echo 'recoding ........' #iconv -f iso-8859-2 -t utf-8 back_test.xml > $tmpfile #enca -x utf-8 $tmpfile #enca -g $tmpfile recode CP1250..UTF-8 $tmpfile ``` You might like to check the encoding by opening and reading the file in a form of a loop... but you might need to check the filesize first : ``` encodings = ['utf-8', 'windows-1250', 'windows-1252' ...etc] for e in encodings: try: fh = codecs.open('file.txt', 'r', encoding=e) fh.readlines() fh.seek(0) except UnicodeDecodeError: print('got unicode error with %s , trying different encoding' % e) else: print('opening the file with encoding: %s ' % e) break ```
Python: Is there a way to determine the encoding of text file?
436,220
97
2009-01-12T17:30:27Z
16,203,777
22
2013-04-24T23:10:05Z
[ "python", "encoding", "text-files" ]
I know there is something buried in [here](http://stackoverflow.com/questions/90838/how-can-i-detect-the-encoding-codepage-of-a-text-file). But I was just wondering if there is an actual way built into Python to determine text file encoding? Thanks for your help :) Edit: As a side question, it can be ignored if you want but why is the type of encoding not put into the file so it could be detected easier?
Another option for working out the encoding is to use [libmagic](http://linux.die.net/man/3/libmagic) (which is the code behind the [file](http://linux.die.net/man/1/file) command). There are a profusion of python bindings available. The python bindings that live in the file source tree are available as the [python-magic](http://packages.debian.org/search?keywords=python-magic&searchon=names&suite=all&section=all) (or [python3-magic](http://packages.debian.org/search?keywords=python3-magic&searchon=names&suite=all&section=all)) debian package. If can determine the encoding of a file by doing: ``` import magic blob = open('unknown-file').read() m = magic.open(magic.MAGIC_MIME_ENCODING) m.load() encoding = m.buffer(blob) # "utf-8" "us-ascii" etc ``` There is an identically named, but incompatible, [python-magic](https://pypi.python.org/pypi/python-magic) pip package on pypi that also uses libmagic. It can also get the encoding, by doing: ``` import magic blob = open('unknown-file').read() m = magic.Magic(mime_encoding=True) encoding = m.from_buffer(blob) ```
How do I split email address/password string in two in Python?
436,394
2
2009-01-12T18:12:29Z
436,412
9
2009-01-12T18:15:58Z
[ "python", "parsing", "split" ]
Lets say we have this string: `[18] [email protected]:pwd:` `[email protected]` is the email and `pwd` is the password. Also, lets say we have this variable with a value ``` f = "[18] [email protected]:pwd:" ``` I would like to know if there is a way to make two other variables named `var1` and `var2`, where the `var1` variable will take the exact email info from variable `f` and `var2` the exact password info from `var2`. The result after running the app should be like: ``` var1 = "[email protected]" ``` and ``` var2 = "pwd" ```
``` >>> var1, var2, _ = "[18] [email protected]:pwd:"[5:].split(":") >>> var1, var2 ('[email protected]', 'pwd') ``` Or if the "[18]" is not a fixed prefix: ``` >>> var1, var2, _ = "[18] [email protected]:pwd:".split("] ")[1].split(":") >>> var1, var2 ('[email protected]', 'pwd') ```
How do I split email address/password string in two in Python?
436,394
2
2009-01-12T18:12:29Z
436,415
7
2009-01-12T18:16:08Z
[ "python", "parsing", "split" ]
Lets say we have this string: `[18] [email protected]:pwd:` `[email protected]` is the email and `pwd` is the password. Also, lets say we have this variable with a value ``` f = "[18] [email protected]:pwd:" ``` I would like to know if there is a way to make two other variables named `var1` and `var2`, where the `var1` variable will take the exact email info from variable `f` and `var2` the exact password info from `var2`. The result after running the app should be like: ``` var1 = "[email protected]" ``` and ``` var2 = "pwd" ```
``` import re var1, var2 = re.findall(r'\s(.*?):(.*):', f)[0] ``` If findall()[0] feels like two steps forward and one back: ``` var1, var2 = re.search(r'\s(.*?):(.*):', f).groups() ```
pyPdf for IndirectObject extraction
436,474
6
2009-01-12T18:31:52Z
441,747
8
2009-01-14T02:46:14Z
[ "python", "pdf", "stream", "pypdf" ]
Following this example, I can list all elements into a pdf file ``` import pyPdf pdf = pyPdf.PdfFileReader(open("pdffile.pdf")) list(pdf.pages) # Process all the objects. print pdf.resolvedObjects ``` now, I need to extract a non-standard object from the pdf file. My object is the one named MYOBJECT and it is a string. The piece printed by the python script that concernes me is: ``` {'/MYOBJECT': IndirectObject(584, 0)} ``` The pdf file is this: ``` 558 0 obj <</Contents 583 0 R/CropBox[0 0 595.22 842]/MediaBox[0 0 595.22 842]/Parent 29 0 R/Resources <</ColorSpace <</CS0 563 0 R>> /ExtGState <</GS0 568 0 R>> /Font<</TT0 559 0 R/TT1 560 0 R/TT2 561 0 R/TT3 562 0 R>> /ProcSet[/PDF/Text/ImageC] /Properties<</MC0<</MYOBJECT 584 0 R>>/MC1<</SubKey 582 0 R>> >> /XObject<</Im0 578 0 R>>>> /Rotate 0/StructParents 0/Type/Page>> endobj ... ... ... 584 0 obj <</Length 8>>stream 1_22_4_1 --->>>> this is the string I need to extract from the object endstream endobj ``` How can I follow the `584` value in order to refer to my string (under pyPdf of course)??
each element in `pdf.pages` is a dictionary, so assuming it's on page 1, `pdf.pages[0]['/MYOBJECT']` should be the element you want. You can try to print that individually or poke at it with `help` and `dir` in a python prompt for more about how to get the string you want Edit: after receiving a copy of the pdf, i found the object at `pdf.resolvedObjects[0][558]['/Resources']['/Properties']['/MC0']['/MYOBJECT']` and the value can be retrieved via getData() the following function gives a more generic way to solve this by recursively looking for the key in question ``` import types import pyPdf pdf = pyPdf.PdfFileReader(open('file.pdf')) pages = list(pdf.pages) def findInDict(needle,haystack): for key in haystack.keys(): try: value = haystack[key] except: continue if key == needle: return value if type(value) == types.DictType or isinstance(value,pyPdf.generic.DictionaryObject): x = findInDict(needle,value) if x is not None: return x answer = findInDict('/MYOBJECT',pdf.resolvedObjects).getData() ```
Python: import the containing package
436,497
50
2009-01-12T18:38:15Z
436,511
20
2009-01-12T18:40:53Z
[ "python", "module", "package", "python-import" ]
In a module residing inside a package, i have the need to use a function defined within the `__init__.py` of that package. how can i import the package within the module that resides within the package, so i can use that function? Importing `__init__` inside the module will not import the package, but instead a module named `__init__`, leading to two copies of things with different names... Is there a pythonic way to do this?
This doesn't exactly answer your question, but I'm going to suggest that you move the function outside of the `__init__.py` file, and into another module inside that package. You can then easily import that function into your other module. If you want, you can have an import statement in the `__init__.py` file that will import that function (when the package is imported) as well.
Python: import the containing package
436,497
50
2009-01-12T18:38:15Z
436,768
39
2009-01-12T19:52:19Z
[ "python", "module", "package", "python-import" ]
In a module residing inside a package, i have the need to use a function defined within the `__init__.py` of that package. how can i import the package within the module that resides within the package, so i can use that function? Importing `__init__` inside the module will not import the package, but instead a module named `__init__`, leading to two copies of things with different names... Is there a pythonic way to do this?
Also, starting in Python 2.5, relative imports are possible. e.g.: ``` from . import foo ``` Quoting from <http://docs.python.org/tutorial/modules.html#intra-package-references>: --- Starting with Python 2.5, in addition to the implicit relative imports described above, you can write explicit relative imports with the from module import name form of import statement. These explicit relative imports use leading dots to indicate the current and parent packages involved in the relative import. From the surrounding module for example, you might use: ``` from . import echo from .. import formats from ..filters import equalizer ```
Python Split String
436,599
12
2009-01-12T19:10:57Z
436,614
13
2009-01-12T19:15:09Z
[ "python", "regex", "parsing", "split" ]
Lets Say we have `Zaptoit:685158:[email protected]` How do you split so it only be left `685158:[email protected]`
``` >>> s = 'Zaptoit:685158:[email protected]' >>> s.split( ':', 1 )[1] '685158:[email protected]' ```
How to implement a python REPL that nicely handles asynchronous output?
437,025
12
2009-01-12T21:11:44Z
437,088
8
2009-01-12T21:33:20Z
[ "python", "readline", "read-eval-print-loop" ]
I have a Python-based app that can accept a few commands in a simple read-eval-print-loop. I'm using `raw_input('> ')` to get the input. On Unix-based systems, I also `import readline` to make things behave a little better. All this is working fine. The problem is that there are asynchronous events coming in, and I'd like to print output as soon as they happen. Unfortunately, this makes things look ugly. The "> " string doesn't show up again after the output, and if the user is halfway through typing something, it chops their text in half. It should probably redraw the user's text-in-progress after printing something. This seems like it must be a solved problem. What's the proper way to do this? Also note that some of my users are Windows-based. TIA Edit: The accepted answer works under Unixy platforms (when the readline module is available), but if anyone knows how to make this work under Windows, it would be much appreciated!
Maybe something like this will do the trick: ``` #!/usr/bin/env python2.6 from __future__ import print_function import readline import threading PROMPT = '> ' def interrupt(): print() # Don't want to end up on the same line the user is typing on. print('Interrupting cow -- moo!') print(PROMPT, readline.get_line_buffer(), sep='', end='') def cli(): while True: cli = str(raw_input(PROMPT)) if __name__ == '__main__': threading.Thread(target=cli).start() threading.Timer(2, interrupt).start() ``` I don't think that stdin is thread-safe, so you can end up losing characters to the interrupting thread (that the user will have to retype at the end of the `interrupt`). I exaggerated the amount of `interrupt` time with the `time.sleep` call. The `readline.get_line_buffer` call won't display the characters that get lost, so it all turns out alright. Note that stdout itself isn't thread safe, so if you've got multiple interrupting threads of execution, this can still end up looking gross.
Duplicating model instances and their related objects in Django / Algorithm for recusrively duplicating an object
437,166
26
2009-01-12T21:58:55Z
437,251
9
2009-01-12T22:24:51Z
[ "python", "django", "django-models", "duplicates" ]
I've models for `Books`, `Chapters` and `Pages`. They are all written by a `User`: ``` from django.db import models class Book(models.Model) author = models.ForeignKey('auth.User') class Chapter(models.Model) author = models.ForeignKey('auth.User') book = models.ForeignKey(Book) class Page(models.Model) author = models.ForeignKey('auth.User') book = models.ForeignKey(Book) chapter = models.ForeignKey(Chapter) ``` What I'd like to do is duplicate an existing `Book` and update it's `User` to someone else. The wrinkle is I would also like to duplicate all related model instances to the `Book` - all it's `Chapters` and `Pages` as well! Things get really tricky when look at a `Page` - not only will the new `Pages` need to have their `author` field updated but they will also need to point to the new `Chapter` objects! Does Django support an out of the box way of doing this? What would a generic algorithm for duplicating a model look like? Cheers, John --- Update: The classes given above are just an example to illustrate the problem I'm having!
I haven't tried it in django but python's [deepcopy](http://docs.python.org/library/copy.html) might just work for you **EDIT:** You can define custom copy behavior for your models if you implement functions: ``` __copy__() and __deepcopy__() ```
Duplicating model instances and their related objects in Django / Algorithm for recusrively duplicating an object
437,166
26
2009-01-12T21:58:55Z
441,453
12
2009-01-14T00:28:16Z
[ "python", "django", "django-models", "duplicates" ]
I've models for `Books`, `Chapters` and `Pages`. They are all written by a `User`: ``` from django.db import models class Book(models.Model) author = models.ForeignKey('auth.User') class Chapter(models.Model) author = models.ForeignKey('auth.User') book = models.ForeignKey(Book) class Page(models.Model) author = models.ForeignKey('auth.User') book = models.ForeignKey(Book) chapter = models.ForeignKey(Chapter) ``` What I'd like to do is duplicate an existing `Book` and update it's `User` to someone else. The wrinkle is I would also like to duplicate all related model instances to the `Book` - all it's `Chapters` and `Pages` as well! Things get really tricky when look at a `Page` - not only will the new `Pages` need to have their `author` field updated but they will also need to point to the new `Chapter` objects! Does Django support an out of the box way of doing this? What would a generic algorithm for duplicating a model look like? Cheers, John --- Update: The classes given above are just an example to illustrate the problem I'm having!
This no longer works in Django 1.3 as CollectedObjects was removed. See [changeset 14507](http://code.djangoproject.com/changeset/14507) [I posted my solution on Django Snippets.](http://www.djangosnippets.org/snippets/1282/) It's based heavily on the [`django.db.models.query.CollectedObject`](http://code.djangoproject.com/browser/django/trunk/django/db/models/query.py#L33) code used for deleting objects: ``` from django.db.models.query import CollectedObjects from django.db.models.fields.related import ForeignKey def duplicate(obj, value, field): """ Duplicate all related objects of `obj` setting `field` to `value`. If one of the duplicate objects has an FK to another duplicate object update that as well. Return the duplicate copy of `obj`. """ collected_objs = CollectedObjects() obj._collect_sub_objects(collected_objs) related_models = collected_objs.keys() root_obj = None # Traverse the related models in reverse deletion order. for model in reversed(related_models): # Find all FKs on `model` that point to a `related_model`. fks = [] for f in model._meta.fields: if isinstance(f, ForeignKey) and f.rel.to in related_models: fks.append(f) # Replace each `sub_obj` with a duplicate. sub_obj = collected_objs[model] for pk_val, obj in sub_obj.iteritems(): for fk in fks: fk_value = getattr(obj, "%s_id" % fk.name) # If this FK has been duplicated then point to the duplicate. if fk_value in collected_objs[fk.rel.to]: dupe_obj = collected_objs[fk.rel.to][fk_value] setattr(obj, fk.name, dupe_obj) # Duplicate the object and save it. obj.id = None setattr(obj, field, value) obj.save() if root_obj is None: root_obj = obj return root_obj ```
Duplicating model instances and their related objects in Django / Algorithm for recusrively duplicating an object
437,166
26
2009-01-12T21:58:55Z
3,120,410
9
2010-06-25T18:20:17Z
[ "python", "django", "django-models", "duplicates" ]
I've models for `Books`, `Chapters` and `Pages`. They are all written by a `User`: ``` from django.db import models class Book(models.Model) author = models.ForeignKey('auth.User') class Chapter(models.Model) author = models.ForeignKey('auth.User') book = models.ForeignKey(Book) class Page(models.Model) author = models.ForeignKey('auth.User') book = models.ForeignKey(Book) chapter = models.ForeignKey(Chapter) ``` What I'd like to do is duplicate an existing `Book` and update it's `User` to someone else. The wrinkle is I would also like to duplicate all related model instances to the `Book` - all it's `Chapters` and `Pages` as well! Things get really tricky when look at a `Page` - not only will the new `Pages` need to have their `author` field updated but they will also need to point to the new `Chapter` objects! Does Django support an out of the box way of doing this? What would a generic algorithm for duplicating a model look like? Cheers, John --- Update: The classes given above are just an example to illustrate the problem I'm having!
Here's an easy way to copy your object. Basically: (1) set the id of your original object to None: book\_to\_copy.id = None (2) change the 'author' attribute and save the ojbect: book\_to\_copy.author = new\_author book\_to\_copy.save() (3) INSERT performed instead of UPDATE (It doesn't address changing the author in the Page--I agree with the comments regarding re-structuring the models)
How do I unload (reload) a Python module?
437,589
410
2009-01-13T00:33:36Z
437,591
386
2009-01-13T00:34:40Z
[ "python", "module", "reload", "python-import" ]
I have a long-running Python server and would like to be able to upgrade a service without restarting the server. What's the best way do do this? ``` if foo.py has changed: unimport foo <-- How do I do this? import foo myfoo = foo.Foo() ```
You can reload a module when it has already been imported by using the [`reload`](http://docs.python.org/library/functions.html?highlight=reload#reload) builtin function in Python 2: ``` import foo while True: # Do some things. if is_changed(foo): foo = reload(foo) ``` In Python 3, `reload` was moved to the [`imp`](https://docs.python.org/3.2/library/imp.html) module. In 3.4, `imp` was deprecated in favor of [`importlib`](https://docs.python.org/3.4/library/importlib.html), and `reload` was added to the latter. When targeting 3 or later, either reference the appropriate module when calling `reload` or import it. I think that this is what you want. Web servers like Django's development server use this so that you can see the effects of your code changes without restarting the server process itself. To quote from the docs: > Python modules’ code is recompiled and > the module-level code reexecuted, > defining a new set of objects which > are bound to names in the module’s > dictionary. The init function of > extension modules is not called a > second time. As with all other objects > in Python the old objects are only > reclaimed after their reference counts > drop to zero. The names in the module > namespace are updated to point to any > new or changed objects. Other > references to the old objects (such as > names external to the module) are not > rebound to refer to the new objects > and must be updated in each namespace > where they occur if that is desired. As you noted in your question, you'll have to reconstruct `Foo` objects if the `Foo` class resides in the `foo` module.
How do I unload (reload) a Python module?
437,589
410
2009-01-13T00:33:36Z
438,845
41
2009-01-13T12:53:25Z
[ "python", "module", "reload", "python-import" ]
I have a long-running Python server and would like to be able to upgrade a service without restarting the server. What's the best way do do this? ``` if foo.py has changed: unimport foo <-- How do I do this? import foo myfoo = foo.Foo() ```
`reload(module)`, but only if it's completely stand-alone. If anything else has a reference to the module (or any object belonging to the module), then you'll get subtle and curious errors caused by the old code hanging around longer than you expected, and things like `isinstance` not working across different versions of the same code. If you have one-way dependencies, you must also reload all modules that depend on the the reloaded module to get rid of all the references to the old code. And then reload modules that depend on the reloaded modules, recursively. If you have circular dependencies, which is very common for example when you are dealing with reloading a package, you must unload all the modules in the group in one go. You can't do this with `reload()` because it will re-import each module before its dependencies have been refreshed, allowing old references to creep into new modules. The only way to do it in this case is to hack `sys.modules`, which is kind of unsupported. You'd have to go through and delete each `sys.modules` entry you wanted to be reloaded on next import, and also delete entries whose values are `None` to deal with an implementation issue to do with caching failed relative imports. It's not terribly nice but as long as you have a fully self-contained set of dependencies that doesn't leave references outside its codebase, it's workable. It's probably best to restart the server. :-)
How do I unload (reload) a Python module?
437,589
410
2009-01-13T00:33:36Z
487,718
54
2009-01-28T14:03:47Z
[ "python", "module", "reload", "python-import" ]
I have a long-running Python server and would like to be able to upgrade a service without restarting the server. What's the best way do do this? ``` if foo.py has changed: unimport foo <-- How do I do this? import foo myfoo = foo.Foo() ```
It can be especially difficult to delete a module if it is not pure Python. Here is some information from: [How do I really delete an imported module?](http://web.archive.org/web/20080926094551/http://mail.python.org/pipermail/python-list/2003-December/241654.html) > You can use sys.getrefcount() to find out the actual number of > references. ``` >>> import sys, empty, os >>> sys.getrefcount(sys) 9 >>> sys.getrefcount(os) 6 >>> sys.getrefcount(empty) 3 ``` > Numbers greater than 3 indicate that > it will be hard to get rid of the > module. The homegrown "empty" > (containing nothing) module should be > garbage collected after ``` >>> del sys.modules["empty"] >>> del empty ``` > as the third reference is an artifact > of the getrefcount() function.
How do I unload (reload) a Python module?
437,589
410
2009-01-13T00:33:36Z
1,547,978
166
2009-10-10T13:36:30Z
[ "python", "module", "reload", "python-import" ]
I have a long-running Python server and would like to be able to upgrade a service without restarting the server. What's the best way do do this? ``` if foo.py has changed: unimport foo <-- How do I do this? import foo myfoo = foo.Foo() ```
In Python 3.0–3.3 you would use: [`imp.reload(module)`](http://docs.python.org/3.3/library/imp.html?highlight=imp#imp.reload) The [BDFL](http://docs.python.org/3.3/glossary.html#term-bdfl) has [answered](http://mail.python.org/pipermail/edu-sig/2008-February/008421.html) this question. However, [`imp` was deprecated in 3.4, in favour of `importlib`](https://docs.python.org/dev/library/imp.html) (thanks [@Stefan!](http://stackoverflow.com/users/2068635/stefan)). I *think*, therefore, you’d now use [`importlib.reload(module)`](https://docs.python.org/dev/library/importlib.html#importlib.reload), although I’m not sure.
How do I unload (reload) a Python module?
437,589
410
2009-01-13T00:33:36Z
3,194,343
39
2010-07-07T11:44:10Z
[ "python", "module", "reload", "python-import" ]
I have a long-running Python server and would like to be able to upgrade a service without restarting the server. What's the best way do do this? ``` if foo.py has changed: unimport foo <-- How do I do this? import foo myfoo = foo.Foo() ```
``` if 'myModule' in sys.modules: del sys.modules["myModule"] ```
How do I unload (reload) a Python module?
437,589
410
2009-01-13T00:33:36Z
13,477,119
13
2012-11-20T16:01:08Z
[ "python", "module", "reload", "python-import" ]
I have a long-running Python server and would like to be able to upgrade a service without restarting the server. What's the best way do do this? ``` if foo.py has changed: unimport foo <-- How do I do this? import foo myfoo = foo.Foo() ```
The following code allows you Python 2/3 compatibility: ``` try: reload except NameError: # Python 3 from imp import reload ``` The you can use it as `reload()` in both versions which makes things simpler.
How do I unload (reload) a Python module?
437,589
410
2009-01-13T00:33:36Z
31,906,907
9
2015-08-09T17:28:31Z
[ "python", "module", "reload", "python-import" ]
I have a long-running Python server and would like to be able to upgrade a service without restarting the server. What's the best way do do this? ``` if foo.py has changed: unimport foo <-- How do I do this? import foo myfoo = foo.Foo() ```
For Python 2 use built-in function [reload()](https://docs.python.org/2/library/functions.html#reload): ``` reload(module) ``` For Python 2 and 3.2–3.3 use [reload from module imp](https://docs.python.org/3/library/imp.html#imp.reload): ``` imp.reload(module) ``` But `imp` [is deprecated](https://docs.python.org/3/library/imp.html) since version 3.4 [in favor of importlib](https://docs.python.org/3/library/importlib.html#importlib.reload), so use: ``` importlib.reload(module) ```
Google App Engine - Importing my own source modules (multiple files)
437,791
3
2009-01-13T02:33:57Z
437,845
8
2009-01-13T03:10:46Z
[ "python", "google-app-engine" ]
I am writing a GAE application and am having some difficulty with the following problem. I've created multiple python files (say a.py and b.py) which are both stored in the same folder. I am able to call code in a.py or b.py by mapping URL's to them (using app.yaml). What I haven't figured out how to do is import the code from one into another. Can anyone help me with the syntax and/or any config that is required here? For instance, I am under the impression that I can include the code from b.py in the file a.py by issuing the following statement in a.py ``` import b ``` I'm not having any success with this approach. Specifically I receive this error: ``` ImportError: No module named b ``` Any suggestions? Thanks, Matt
Have you tried importing as if you were starting at the top level? Like ``` import modules.b ```
Is there a pure Python Lucene?
438,315
26
2009-01-13T08:24:28Z
533,603
28
2009-02-10T18:43:11Z
[ "python", "full-text-search", "lucene", "ferret" ]
The ruby folks have [Ferret](https://github.com/dbalmain/ferret). Someone know of any similar initiative for Python? We're using PyLucene at current, but I'd like to investigate moving to pure Python searching.
[Whoosh](http://pypi.python.org/pypi/Whoosh/) is a new project which is similar to lucene, but is pure python.
How to call java objects and functions from CPython?
438,594
8
2009-01-13T10:49:01Z
438,693
7
2009-01-13T11:28:40Z
[ "java", "python", "function", "language-interoperability" ]
I have a python program, which runs on the CPython implementation, and inside it I must call a function defined in a java program. How can I do this? It would be nice to be able to use some java objects too. Jython is not an option. I must run the python part in CPython.
The easiest thing to do is 1. Write a trivial CLI for your java "function". (There's no such thing, so I'll assume you actually mean a method function of a Java class.) ``` public class ExposeAMethod { public static void main( String args[] ) { TheClassToExpose x = new TheClassToExpose(); x.theFunction(); } } ``` 2. Compile and build an executable JAR file with this as the entry point. Call it `ExposeAMethod.jar` 3. Call this from a command created by subprocess. ``` import subprocess p = subprocess.Popen("java -jar ExposeAMethod.jar", shell=True) sts = os.waitpid(p.pid, 0) ``` This is the minimum. And it's really not much. I count 6 lines of java, 3 lines of Python and you're up and running. If you want to pass arguments to this Java class constructor or method function, you'll have to write a few more lines of code. You have two choices. * Read the arguments from stdin, write the results on stdout. This is relatively easy and performs really well. * Parse the arguments as command-line options to Java, write the results on stdout. This is slightly harder, but generalizes very nicely. The bonus is that you now have a useful command-line Java program that you can reuse.
How to call java objects and functions from CPython?
438,594
8
2009-01-13T10:49:01Z
3,793,504
12
2010-09-25T10:55:08Z
[ "java", "python", "function", "language-interoperability" ]
I have a python program, which runs on the CPython implementation, and inside it I must call a function defined in a java program. How can I do this? It would be nice to be able to use some java objects too. Jython is not an option. I must run the python part in CPython.
Apologies for resurrecting the thread, but I think I have a better answer :-) You could also use [Py4J](http://py4j.sourceforge.net/index.html) which has two parts: a library that runs in CPython (or any Python interpreter for that matter) and a library that runs on the Java VM you want to call. There is an example on the frontpage and lots of documentation, but essentially, you just call Java methods from your python code as if they were python methods: ``` >>> from py4j.java_gateway import JavaGateway >>> gateway = JavaGateway() # connect to the JVM >>> java_object = gateway.jvm.mypackage.MyClass() # invoke constructor >>> other_object = java_object.doThat() >>> other_object.doThis(1,'abc') >>> gateway.jvm.java.lang.System.out.println('Hello World!') # call a static method ``` The communication is done through sockets instead of JNI. *Disclaimer: I am the author of Py4J*
Is there a label/goto in Python?
438,844
78
2009-01-13T12:53:23Z
438,848
61
2009-01-13T12:55:57Z
[ "python", "goto" ]
Is there a `goto` or any equivalent in Python to be able to jump to a specific line of code?
No, Python does not support labels and goto, if that is what you're after. It's a (highly) structured programming language.
Is there a label/goto in Python?
438,844
78
2009-01-13T12:53:23Z
438,869
40
2009-01-13T13:04:56Z
[ "python", "goto" ]
Is there a `goto` or any equivalent in Python to be able to jump to a specific line of code?
Python offers you the ability to do some of the things you could do with a goto using first class functions. For example: ``` void somefunc(int a) { if (a == 1) goto label1; if (a == 2) goto label2; label1: ... label2: ... } ``` Could be done in python like this: ``` def func1(): ... def func2(): ... funcmap = {1 : func1, 2 : func2} def somefunc(a): funcmap[a]() #Ugly! But it works. ``` Granted, that isn't the best way to substitute for goto. But without knowing exactly what you're trying to do with the goto, it's hard to give specific advice. @[ascobol](http://stackoverflow.com/questions/438844/is-there-a-label-in-python#438866): Your best bet is to either enclose it in a function or use an exception. For the function: ``` def loopfunc(): while 1: while 1: if condition: return ``` For the exception: ``` try: while 1: while 1: raise BreakoutException #Not a real exception, invent your own except BreakoutException: pass ``` Using exceptions to do stuff like this may feel a bit awkward if you come from another programming language. But I would argue that if you dislike using exceptions, Python isn't the language for you. :-)
Is there a label/goto in Python?
438,844
78
2009-01-13T12:53:23Z
453,678
11
2009-01-17T17:42:56Z
[ "python", "goto" ]
Is there a `goto` or any equivalent in Python to be able to jump to a specific line of code?
To answer the [`@ascobol`'s question](http://stackoverflow.com/questions/438844/is-there-a-label-in-python#438866) using `@bobince`'s suggestion from the comments: ``` for i in range(5000): for j in range(3000): if should_terminate_the_loop: break else: continue # no break encountered break ``` Though I never saw such a code in practice.
Is there a label/goto in Python?
438,844
78
2009-01-13T12:53:23Z
32,683,845
8
2015-09-20T20:15:04Z
[ "python", "goto" ]
Is there a `goto` or any equivalent in Python to be able to jump to a specific line of code?
I recently [wrote a function decorator](https://github.com/snoack/python-goto) that enables `goto` in Python, just like that: ``` from goto import with_goto @with_goto def range(start, stop): i = start result = [] label .begin if i == stop: goto .end result.append(i) i += 1 goto .begin label .end return result ``` I'm not sure why one would like to do something like that though. That said, I'm not too serious about it. But I'd like to point out that this kind of meta programming is actual possible in Python, at least in CPython and PyPy, and not only by misusing the debugger API as that [other guy](http://entrian.com/goto/) did. You have to mess with the bytecode though.
How do I stop a program when an exception is raised in Python?
438,894
16
2009-01-13T13:13:24Z
438,902
23
2009-01-13T13:16:02Z
[ "python", "exception-handling" ]
I need to stop my program when an exception is raised in Python. How do I implement this?
``` import sys try: print("stuff") except: sys.exit(0) ```
How do I stop a program when an exception is raised in Python?
438,894
16
2009-01-13T13:13:24Z
439,137
17
2009-01-13T14:33:53Z
[ "python", "exception-handling" ]
I need to stop my program when an exception is raised in Python. How do I implement this?
You can stop catching the exception, or - if you need to catch it (to do some custom handling), you can re-raise: ``` try: doSomeEvilThing() except Exception, e: handleException(e) raise ``` Note that typing `raise` without passing an exception object causes the original traceback to be preserved. Typically it is much better than `raise e`. Of course - you can also explicitly call ``` import sys sys.exit(exitCodeYouFindAppropriate) ``` This causes SystemExit exception to be raised, and (unless you catch it somewhere) terminates your application with specified exit code.
random Decimal in python
439,115
7
2009-01-13T14:26:49Z
439,169
15
2009-01-13T14:44:36Z
[ "python", "random", "decimal" ]
How do I get a random decimal.Decimal? It appears that the random module only returns floats which are a pita to convert to Decimals.
From the [standard library reference](http://docs.python.org/dev/3.0/library/decimal.html) : To create a Decimal from a float, first convert it to a string. This serves as an explicit reminder of the details of the conversion (including representation error). ``` >>> import random, decimal >>> decimal.Decimal(str(random.random())) Decimal('0.467474014342') ``` Is this what you mean? It doesn't seem like a pita to me. You can scale it into whatever range and precision you want.
random Decimal in python
439,115
7
2009-01-13T14:26:49Z
439,282
18
2009-01-13T15:09:41Z
[ "python", "random", "decimal" ]
How do I get a random decimal.Decimal? It appears that the random module only returns floats which are a pita to convert to Decimals.
What's "a random decimal"? Decimals have arbitrary precision, so generating a number with as much randomness as you can hold in a Decimal would take the entire memory of your machine to store. You have to know how many decimal digits of precision you want in your random number, at which point it's easy to just grab an random integer and divide it. For example if you want two digits above the point and two digits in the fraction (see [randrange here](https://docs.python.org/2/library/random.html#random.randrange)): ``` decimal.Decimal(random.randrange(10000))/100 ```
PIL vs RMagick/ruby-gd
439,641
4
2009-01-13T16:21:17Z
440,298
7
2009-01-13T19:00:38Z
[ "python", "ruby", "python-imaging-library", "rmagick" ]
For my next project I plan to create images with text and graphics. I'm comfortable with ruby, but interested in learning python. I figured this may be a good time because PIL looks like a great library to use. However, I don't know how it compares to what ruby has to offer (e.g. RMagick and ruby-gd). From what I can gather PIL had better documentation (does ruby-gd even have a homepage?) and more features. Just wanted to hear a few opinions to help me decide. Thanks. Vince
PIL is a good library, use it. ImageMagic (what RMagick wraps) is a very heavy library that should be avoided if possible. Its good for doing local processing of images, say, a batch photo editor, but way too processor inefficient for common image manipulation tasks for web. **EDIT:** In response to the question, PIL supports drawing vector shapes. It can draw polygons, curves, lines, fills and text. I've used it in a project to produce rounded alpha corners to PNG images on the fly over the web. It essentially has most of the drawing features of GDI+ (in Windows) or GTK (in Gnome on Linux).
Re-creating threading and concurrency knowledge in increasingly popular languages
440,036
7
2009-01-13T17:52:42Z
440,086
11
2009-01-13T18:04:08Z
[ "java", "python", "ruby", "multithreading", "concurrency" ]
I am primarily a Java developer, and I've been reading a lot of in-depth work on threads and concurrency. Many very smart people (Doug Lea, Brian Goetz, etc) have authored books on these topics and made contributions to new concurrency libraries for Java. As I start to learn more about Python, Ruby, and other languages, I'm wondering: does all of that work have to be re-created for these languages? Will there be, or does there need to be, a "Doug Lea of Python," or a "Brian Goetz of Ruby," who make similarly powerful contributions to the concurrency features of those languages? **Does all of this concurrency work done in Java have to be re-created for future languages?** Or will the work done in Java establish lessons and guidance for future languages?
The basic principles of concurrent programming existed before java and were summarized in those java books you're talking about. The java.util.concurrent library was similarly derived from previous code and research papers on concurrent programming. However, some implementation issues are specific to Java. It has a specified memory model, and the concurrent utilities in Java are tailored to the specifics of that. With some modification those can be ported to other languages/environments with different memory model characteristics. So, you might need a book to teach you the canonical usage of the concurrency tools in other languages but it wouldn't be reinventing the wheel.
unicode() vs. str.decode() for a utf8 encoded byte string (python 2.x)
440,320
28
2009-01-13T19:06:16Z
440,432
23
2009-01-13T19:32:49Z
[ "python", "unicode", "utf-8" ]
Is there any reason to prefer `unicode(somestring, 'utf8')` as opposed to `somestring.decode('utf8')`? My only thought is that `.decode()` is a bound method so python may be able to resolve it more efficiently, but correct me if I'm wrong.
It's easy to benchmark it: ``` >>> from timeit import Timer >>> ts = Timer("s.decode('utf-8')", "s = 'ééé'") >>> ts.timeit() 8.9185450077056885 >>> tu = Timer("unicode(s, 'utf-8')", "s = 'ééé'") >>> tu.timeit() 2.7656929492950439 >>> ``` Obviously, `unicode()` is faster. FWIW, I don't know where you get the impression that methods would be faster - it's quite the contrary.
unicode() vs. str.decode() for a utf8 encoded byte string (python 2.x)
440,320
28
2009-01-13T19:06:16Z
440,461
22
2009-01-13T19:36:52Z
[ "python", "unicode", "utf-8" ]
Is there any reason to prefer `unicode(somestring, 'utf8')` as opposed to `somestring.decode('utf8')`? My only thought is that `.decode()` is a bound method so python may be able to resolve it more efficiently, but correct me if I'm wrong.
I'd prefer `'something'.decode(...)` since the `unicode` type is no longer there in Python 3.0, while `text = b'binarydata'.decode(encoding)` is still valid.
python, sorting a list by a key that's a substring of each element
440,541
10
2009-01-13T19:58:28Z
440,562
23
2009-01-13T20:04:35Z
[ "python", "list", "sorting" ]
Part of a programme builds this list, ``` [u'1 x Affinity for war', u'1 x Intellect', u'2 x Charisma', u'2 x Perception', u'3 x Population growth', u'4 x Affinity for the land', u'5 x Morale'] ``` I'm currently trying to sort it alphabetically by the name of the evolution rather than by the number. Is there any way I can do this without just changing the order the two things appear in the list (as in 'intellect x 1)?
You have to get the "key" from the string. ``` def myKeyFunc( aString ): stuff, x, label = aString.partition(' x ') return label aList.sort( key= myKeyFunc ) ```
python, sorting a list by a key that's a substring of each element
440,541
10
2009-01-13T19:58:28Z
440,599
9
2009-01-13T20:12:33Z
[ "python", "list", "sorting" ]
Part of a programme builds this list, ``` [u'1 x Affinity for war', u'1 x Intellect', u'2 x Charisma', u'2 x Perception', u'3 x Population growth', u'4 x Affinity for the land', u'5 x Morale'] ``` I'm currently trying to sort it alphabetically by the name of the evolution rather than by the number. Is there any way I can do this without just changing the order the two things appear in the list (as in 'intellect x 1)?
How about: ``` lst.sort(key=lamdba s: s.split(' x ')[1]) ```
Installing Python 3.0 on Cygwin
440,547
11
2009-01-13T20:00:20Z
440,970
8
2009-01-13T21:55:50Z
[ "python", "windows", "cygwin" ]
### The Question What is the correct way to install Python 3.0 alongside Python 2.x using Cygwin? ### Notes I already have a working copy of Cygwin, and Python 2.x is installed within Cygwin (`/lib/python2.x`, not `c:\python2.x`). Also, I would like to be able to call python 3 separately (and only intentionally) by leaving `python` pointing to Python 2.x to preserve existing dependencies. I would like to use `python30` or some alternative. Any pointers to guides on the subject would be much appreciated. I cannot seem to find one either at the cygwin site or python.org.
The standard `make install` target of the Python 3.0 sources doesn't install a python binary. Instead, make install prints at the end ``` * Note: not installed as 'python'. * Use 'make fullinstall' to install as 'python'. * However, 'make fullinstall' is discouraged, * as it will clobber your Python 2.x installation. ``` So don't worry. If you easily want to remove the entire installation, do something like `configure --prefix=/usr/local/py3`
Installing Python 3.0 on Cygwin
440,547
11
2009-01-13T20:00:20Z
11,666,901
9
2012-07-26T09:59:15Z
[ "python", "windows", "cygwin" ]
### The Question What is the correct way to install Python 3.0 alongside Python 2.x using Cygwin? ### Notes I already have a working copy of Cygwin, and Python 2.x is installed within Cygwin (`/lib/python2.x`, not `c:\python2.x`). Also, I would like to be able to call python 3 separately (and only intentionally) by leaving `python` pointing to Python 2.x to preserve existing dependencies. I would like to use `python30` or some alternative. Any pointers to guides on the subject would be much appreciated. I cannot seem to find one either at the cygwin site or python.org.
As of yesterday (Wed 25 July 2012), [Python 3.2.3 is included in the standard Cygwin installer](http://cygwin.com/ml/cygwin/2012-07/msg00553.html). Just run Cygwin's `setup.exe` again (download it from [cygwin.com](http://www.cygwin.com) again if you need to), and you should be able to select and install it like any other package. This will install as `python3`, leaving any existing 2.x install in place: ``` $ python -V Python 2.6.8 $ python3 -V Python 3.2.3 $ ls -l $(which python) $(which python3) lrwxrwxrwx 1 me Domain Users 13 Jun 21 15:12 /usr/bin/python -> python2.6.exe lrwxrwxrwx 1 me root 14 Jul 26 10:56 /usr/bin/python3 -> python3.2m.exe ```
Using "with" statement for CSV files in Python
441,130
13
2009-01-13T22:36:28Z
441,446
18
2009-01-14T00:24:41Z
[ "python", "csv", "with-statement" ]
Is it possible to use the `with` statement directly with CSV files? It seems natural to be able to do something like this: ``` import csv with csv.reader(open("myfile.csv")) as reader: # do things with reader ``` But csv.reader doesn't provide the `__enter__` and `__exit__` methods, so this doesn't work. I can however do it in two steps: ``` import csv with open("myfile.csv") as f: reader = csv.reader(f) # do things with reader ``` Is this second way the ideal way to do it? Why wouldn't they make csv.reader directly compatible with the with statement?
The primary use of `with` statement is an exception-safe cleanup of an object used in the statement. `with` makes sure that files are closed, locks are released, contexts are restored, etc. Does [csv.reader](http://docs.python.org/library/csv.html#csv.reader) have things to cleanup in case of exception? I'd go with: ``` with open("myfile.csv") as f: for row in csv.reader(f): # process row ``` You don't need to submit the patch to use `csv.reader` and `with` statement together. ``` import contextlib ``` Help on function contextmanager in module [contextlib](http://docs.python.org/library/contextlib.html): ``` contextmanager(func) @contextmanager decorator. ``` Typical usage: ``` @contextmanager def some_generator(<arguments>): <setup> try: yield <value> finally: <cleanup> ``` This makes this: ``` with some_generator(<arguments>) as <variable>: <body> ``` equivalent to this: ``` <setup> try: <variable> = <value> <body> finally: <cleanup> ``` Here's a concrete example how I've used it: [curses\_screen](http://stackoverflow.com/questions/327026/attribute-bold-doesnt-seem-to-work-in-my-curses#327072).
How can I subtract a day from a Python date?
441,147
330
2009-01-13T22:39:36Z
441,152
535
2009-01-13T22:41:39Z
[ "python", "datetime", "date" ]
I have a Python [`datetime.datetime`](https://docs.python.org/library/datetime.html#datetime-objects) object. What is the best way to subtract one day?
You can use a [timedelta](http://docs.python.org/3.3/library/datetime.html?highlight=datetime#timedelta-objects) object: ``` from datetime import datetime, timedelta d = datetime.today() - timedelta(days=days_to_subtract) ```
How can I subtract a day from a Python date?
441,147
330
2009-01-13T22:39:36Z
441,154
47
2009-01-13T22:42:03Z
[ "python", "datetime", "date" ]
I have a Python [`datetime.datetime`](https://docs.python.org/library/datetime.html#datetime-objects) object. What is the best way to subtract one day?
Subtract `datetime.timedelta(days=1)`
How can I subtract a day from a Python date?
441,147
330
2009-01-13T22:39:36Z
24,045,285
14
2014-06-04T18:48:53Z
[ "python", "datetime", "date" ]
I have a Python [`datetime.datetime`](https://docs.python.org/library/datetime.html#datetime-objects) object. What is the best way to subtract one day?
Just to Elaborate **an alternate method** and a Use case for which it is helpful: * Subtract 1 day from current datetime: > ``` > from datetime import datetime, timedelta > print datetime.now() + timedelta(days=-1) # Here, I am adding a negative timedelta > ``` * **Useful in the Case**, If you want to add 5 days and subtract 5 hours from current datetime. i.e. What is the Datetime 5 days from now but 5 hours less ? > ``` > from datetime import datetime, timedelta > print datetime.now() + timedelta(days=5, hours=-5) > ``` It can similarly be used with other parameters e.g. seconds, weeks etc
How can I subtract a day from a Python date?
441,147
330
2009-01-13T22:39:36Z
25,427,822
17
2014-08-21T13:38:27Z
[ "python", "datetime", "date" ]
I have a Python [`datetime.datetime`](https://docs.python.org/library/datetime.html#datetime-objects) object. What is the best way to subtract one day?
If your Python datetime object is timezone-aware than you should be careful to avoid errors around DST transitions (or changes in UTC offset for other reasons): ``` from datetime import datetime, timedelta from tzlocal import get_localzone # pip install tzlocal DAY = timedelta(1) local_tz = get_localzone() # get local timezone now = datetime.now(local_tz) # get timezone-aware datetime object day_ago = local_tz.normalize(now - DAY) # exactly 24 hours ago, time may differ naive = now.replace(tzinfo=None) - DAY # same time yesterday = local_tz.localize(naive, is_dst=None) # but elapsed hours may differ ``` In general, `day_ago` and `yesterday` may differ if UTC offset for the local timezone has changed in the last day. For example, daylight saving time/summer time ends on Sun 2-Nov-2014 at 02:00:00 A.M. in America/Los\_Angeles timezone therefore if: ``` import pytz # pip install pytz local_tz = pytz.timezone('America/Los_Angeles') now = local_tz.localize(datetime(2014, 11, 2, 10), is_dst=None) # 2014-11-02 10:00:00 PST-0800 ``` then `day_ago` and `yesterday` differ: * `day_ago` is exactly 24 hours ago (relative to `now`) but at 11 am, not at 10 am as `now` * `yesterday` is yesterday at 10 am but it is 25 hours ago (relative to `now`), not 24 hours.
Why am I seeing 'connection reset by peer' error?
441,374
3
2009-01-13T23:52:10Z
441,383
8
2009-01-13T23:56:45Z
[ "python", "sockets", "network-programming", "system" ]
I am testing [cogen](http://code.google.com/p/cogen/) on a Mac OS X 10.5 box using python 2.6.1. I have a simple echo server and client-pumper that creates 10,000 client connections as a test. 1000, 5000, etc. all work splendidly. However at around 10,000 connections, the server starts dropping random clients - the clients see 'connection reset by peer'. Is there some basic-networking background knowledge I'm missing here? Note that my system is configured to handle open files (launchctl limit, sysctl (maxfiles, etc.), and ulimit -n are all valid; been there, done that). Also, I've verified that cogen is picking to use kqueue under the covers. If I add a slight delay to the client-connect() calls everything works great. Thus, my question is, why would a server under stress drop other clients when there's a high frequency of connections in a short period of time? Anyone else ever run into this? For completeness' sake, here's my code. Here is the server: ``` # echoserver.py from cogen.core import sockets, schedulers, proactors from cogen.core.coroutines import coroutine import sys, socket port = 1200 @coroutine def server(): srv = sockets.Socket() srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) addr = ('0.0.0.0', port) srv.bind(addr) srv.listen(64) print "Listening on", addr while 1: conn, addr = yield srv.accept() m.add(handler, args=(conn, addr)) client_count = 0 @coroutine def handler(sock, addr): global client_count client_count += 1 print "SERVER: [connect] clients=%d" % client_count fh = sock.makefile() yield fh.write("WELCOME TO (modified) ECHO SERVER !\r\n") yield fh.flush() try: while 1: line = yield fh.readline(1024) #print `line` if line.strip() == 'exit': yield fh.write("GOOD BYE") yield fh.close() raise sockets.ConnectionClosed('goodbye') yield fh.write(line) yield fh.flush() except sockets.ConnectionClosed: pass fh.close() sock.close() client_count -= 1 print "SERVER: [disconnect] clients=%d" % client_count m = schedulers.Scheduler() m.add(server) m.run() ``` And here is the client: ``` # echoc.py import sys, os, traceback, socket, time from cogen.common import * from cogen.core import sockets port, conn_count = 1200, 10000 clients = 0 @coroutine def client(num): sock = sockets.Socket() sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) reader = None try: try: # remove this sleep and we start to see # 'connection reset by peer' errors time.sleep(0.001) yield sock.connect(("127.0.0.1", port)) except Exception: print 'Error in client # ', num traceback.print_exc() return global clients clients += 1 print "CLIENT #=%d [connect] clients=%d" % (num,clients) reader = sock.makefile('r') while 1: line = yield reader.readline(1024) except sockets.ConnectionClosed: pass except: print "CLIENT #=%d got some other error" % num finally: if reader: reader.close() sock.close() clients -= 1 print "CLIENT #=%d [disconnect] clients=%d" % (num,clients) m = Scheduler() for i in range(0, conn_count): m.add(client, args=(i,)) m.run() ``` Thanks for any information!
Python's socket I/O sometimes suffers from connection reset by peer. It has to do with the Global Interpreter Lock and how threads are scheduled. I [blogged](http://homepage.mac.com/s_lott/iblog/architecture/C551260341/E20081031204203/index.html) some references on the subject. The `time.sleep(0.0001)` appears to be the recommended solution because it adjusts thread scheduling and allows the socket I/O to finish.
Driving Excel from Python in Windows
441,758
34
2009-01-14T02:53:26Z
441,786
18
2009-01-14T03:11:30Z
[ "python", "excel", "scripting" ]
We have various spreadsheets that employ deliciously complicated macros and third party extensions to produce complicated models. I'm working on a project that involves slightly tweaking various inputs and seeing the results. Rather than doing this by hand or writing VBA, I'd like to see if I can write a python script to drive this. In other words, the python script will start up, load the excel sheet, and then interact with the sheet by making minor changes in some cells and seeing how they affect other cells. So, my question is twofold: * What is the best library to use to drive excel from python in such fashion? * Where's the best documentation/examples on using said library? Cheers, /YGA
I've done this by using [pywin32](http://python.net/crew/mhammond/win32/Downloads.html). It's not a particularly pleasant experience, since there's not really any abstraction; it's like using VBA, but with python syntax. You can't rely on docstrings, so you'll want to have the MSDN Excel reference handy (<http://msdn.microsoft.com/en-us/library/aa220733.aspx> is what I used, if I remember correctly. You should be able to find the Excel 2007 docs if you dig around a bit.). See [here](http://web.archive.org/web/20090916091434/http://www.markcarter.me.uk/computing/python/excel.html) for a simple example. ``` from win32com.client import Dispatch xlApp = Dispatch("Excel.Application") xlApp.Visible = 1 xlApp.Workbooks.Add() xlApp.ActiveSheet.Cells(1,1).Value = 'Python Rules!' xlApp.ActiveWorkbook.ActiveSheet.Cells(1,2).Value = 'Python Rules 2!' xlApp.ActiveWorkbook.Close(SaveChanges=0) # see note 1 xlApp.Quit() xlApp.Visible = 0 # see note 2 del xlApp ``` Good luck!
Driving Excel from Python in Windows
441,758
34
2009-01-14T02:53:26Z
445,961
44
2009-01-15T07:48:43Z
[ "python", "excel", "scripting" ]
We have various spreadsheets that employ deliciously complicated macros and third party extensions to produce complicated models. I'm working on a project that involves slightly tweaking various inputs and seeing the results. Rather than doing this by hand or writing VBA, I'd like to see if I can write a python script to drive this. In other words, the python script will start up, load the excel sheet, and then interact with the sheet by making minor changes in some cells and seeing how they affect other cells. So, my question is twofold: * What is the best library to use to drive excel from python in such fashion? * Where's the best documentation/examples on using said library? Cheers, /YGA
For controlling Excel, use pywin32, like @igowen suggests. Note that it is possible to use static dispatch. Use `makepy.py` from the pywin32 project to create a python module with the python wrappers. Using the generated wrappers simplifies development, since for instance ipython gives you tab completion and help during development. Static dispatch example: ``` x:> makepy.py "Microsoft Excel 11.0 Object Library" ... Generating... Importing module x:> ipython ``` ``` > from win32com.client import Dispatch > excel = Dispatch("Excel.Application") > wb = excel.Workbooks.Append() > range = wb.Sheets[0].Range("A1") > range.[Press Tab] range.Activate range.Merge range.AddComment range.NavigateArrow range.AdvancedFilter range.NoteText ... range.GetOffset range.__repr__ range.GetResize range.__setattr__ range.GetValue range.__str__ range.Get_Default range.__unicode__ range.GoalSeek range._get_good_object_ range.Group range._get_good_single_object_ range.Insert range._oleobj_ range.InsertIndent range._prop_map_get_ range.Item range._prop_map_put_ range.Justify range.coclass_clsid range.ListNames range.__class__ > range.Value = 32 ... ``` Documentation links: * The O'Reilly book [Python Programming on Win32](http://my.safaribooksonline.com/1565926218) has an [Integrating with Excel](http://my.safaribooksonline.com/1565926218/ch09-84996) chapter. * Same book, free sample chapter [Advanced Python and COM](http://oreilly.com/catalog/pythonwin32/chapter/ch12.html) covers makepy in detail. * [Tutorials](http://www.google.com/search?q=python+excel+tutorial) * [win32com documentation](http://docs.activestate.com/activepython/2.4/pywin32/html/com/win32com/HTML/docindex.html), I suggest you read [this](http://docs.activestate.com/activepython/2.4/pywin32/html/com/win32com/HTML/QuickStartClientCom.html) first.
Driving Excel from Python in Windows
441,758
34
2009-01-14T02:53:26Z
10,977,701
8
2012-06-11T09:43:42Z
[ "python", "excel", "scripting" ]
We have various spreadsheets that employ deliciously complicated macros and third party extensions to produce complicated models. I'm working on a project that involves slightly tweaking various inputs and seeing the results. Rather than doing this by hand or writing VBA, I'd like to see if I can write a python script to drive this. In other words, the python script will start up, load the excel sheet, and then interact with the sheet by making minor changes in some cells and seeing how they affect other cells. So, my question is twofold: * What is the best library to use to drive excel from python in such fashion? * Where's the best documentation/examples on using said library? Cheers, /YGA
Check out the [DataNitro](http://datanitro.com/) project (previous name IronSpread). It is a Python plug-in for Excel.