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,...
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 y...
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 y...
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[item...
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 = nump...
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...
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`...
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 t...
[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 t...
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 perfec...
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 t...
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 p...
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/thinkpyth...
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 ...
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 n...
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_inpu...
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 (unli...
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_inpu...
* 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): ...
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_inpu...
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 lan...
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_inpu...
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_inpu...
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_f...
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 mi...
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 ...
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 the...
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...
``` 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...
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...
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...
``` 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(te...
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...
``` 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...
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, fillva...
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 ``` an...
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, ...
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-...
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 i...
``` 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 i...
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( (10...
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 upd...
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...
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((...
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 neit...
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 ...
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 ...
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.Z...
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 ...
[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 ...
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 additio...
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 th...
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 s...
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...
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 nee...
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: ...
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> > > ``` >...
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 w...
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 > newspape...
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 w...
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 m...
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 w...
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-ma...
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@email.com:pwd:` `email@email.com` is the email and `pwd` is the password. Also, lets say we have this variable with a value ``` f = "[18] email@email.com:pwd:" ``` I would like to know if there is a way to make two other variables named `var1` and `var2`, where the `var1` v...
``` >>> var1, var2, _ = "[18] email@email.com:pwd:"[5:].split(":") >>> var1, var2 ('email@email.com', 'pwd') ``` Or if the "[18]" is not a fixed prefix: ``` >>> var1, var2, _ = "[18] email@email.com:pwd:".split("] ")[1].split(":") >>> var1, var2 ('email@email.com', '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@email.com:pwd:` `email@email.com` is the email and `pwd` is the password. Also, lets say we have this variable with a value ``` f = "[18] email@email.com:pwd:" ``` I would like to know if there is a way to make two other variables named `var1` and `var2`, where the `var1` v...
``` 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 stri...
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 f...
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...
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 wil...
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...
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 ...
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:zaptoit@hotmail.com` How do you split so it only be left `685158:zaptoit@hotmail.com`
``` >>> s = 'Zaptoit:685158:zaptoit@hotmail.com' >>> s.split( ':', 1 )[1] '685158:zaptoit@hotmail.com' ```
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 ...
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...
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)...
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)...
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.djangoprojec...
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)...
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 aut...
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...
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 ...
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 actu...
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 deprecate...
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/...
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 ...
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(); ...
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 o...
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: ``` ...
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 encounter...
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 ...
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. Typ...
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(ran...
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...
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 g...
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 ...
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 language...
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 sp...
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 i...
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...
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...
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...
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. ...
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...
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 ot...
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 ho...
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: ...
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 an...
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 lo...
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 cli...
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 t...
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 ...
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.m...
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 ...
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 duri...
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 ...
Check out the [DataNitro](http://datanitro.com/) project (previous name IronSpread). It is a Python plug-in for Excel.