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
Get min and max elements for 2 corresponding series in pandas
18,454,067
4
2013-08-26T22:27:27Z
18,454,166
7
2013-08-26T22:36:40Z
[ "python", "pandas" ]
Suppose I have 2 Series in pandas: ``` from datetime import datetime, timedelta import pandas as pd d = datetime.now() index = [d + timedelta(seconds = i) for i in range(5)] a = pd.Series([1,4,5,7,8], index = index) b = pd.Series([2,3,6,7,8], index = index) ``` What is the best way to get min/max values for correspon...
Combine the series into a frame which automatically aligns by the index ``` In [51]: index Out[51]: [datetime.datetime(2013, 8, 26, 18, 33, 48, 990974), datetime.datetime(2013, 8, 26, 18, 33, 49, 990974), datetime.datetime(2013, 8, 26, 18, 33, 50, 990974), datetime.datetime(2013, 8, 26, 18, 33, 51, 990974), datet...
cant read this python format ( , ) [ . . ]
18,454,541
4
2013-08-26T23:14:46Z
18,454,565
10
2013-08-26T23:17:26Z
[ "python" ]
I'm newbie and I'm reading a snippet of code like this: ``` ... proto = ('http', 'https')[bool(self.https)] ... ``` It looks like this line is letting `proto` to switch between `'http'` and `'https'`. But what does the `( , )[ .. ]` mean? How can I make use of this style?
The second element (in the brackets) is the index that will be used on the first element. So in this case, you have a single tuple: ``` ('http', 'https') ``` And then a boolean that represents whether `self.https` is set. If it is true, the value will be `1`, making the call: ``` ('http', 'https')[1] ``` Which will...
How can i subtract two strings in python?
18,454,570
6
2013-08-26T23:18:17Z
18,454,597
7
2013-08-26T23:21:21Z
[ "python", "string", "addition", "subtract" ]
I have a long string, which is basically a list like `str="lamp, bag, mirror,"` (and other items) I was wondering if I can add or subtract some items, in other programming languages I can easily do: `str=str-"bag,"` and get `str="lamp, mirror,"` this doesnt work in python (I'm using 2.7 on a W8 pc) Is there a way to ...
You can do this as long as you use well-formed *lists*: ``` s0 = "lamp, bag, mirror" s = s0.split(", ") # s is a list: ["lamp", "bag", "mirror"] ``` If the list is not well-formed, you can do as follows, as suggested by @Lattyware: ``` s = [item.strip() for item in s0.split(',')] ``` Now to delete the element: ```...
How can i subtract two strings in python?
18,454,570
6
2013-08-26T23:18:17Z
18,454,665
10
2013-08-26T23:28:39Z
[ "python", "string", "addition", "subtract" ]
I have a long string, which is basically a list like `str="lamp, bag, mirror,"` (and other items) I was wondering if I can add or subtract some items, in other programming languages I can easily do: `str=str-"bag,"` and get `str="lamp, mirror,"` this doesnt work in python (I'm using 2.7 on a W8 pc) Is there a way to ...
you could also just do ``` print "lamp, bag, mirror".replace("bag,","") ```
How to count the number of letters in a string without the spaces?
18,455,222
8
2013-08-27T00:44:39Z
18,455,231
15
2013-08-27T00:46:21Z
[ "python" ]
This is my solution resulting in an error. Returns 0 PS: **I'd still love a fix to my code :)** ``` from collections import Counter import string def count_letters(word): global count wordsList = string.split(word) count = Counter() for words in wordsList: for letters in set(words): ...
``` def count_letters(word): return len(word) - word.count(' ') ``` Alternatively, if you have multiple letters to ignore, you could filter the string: ``` def count_letters(word): BAD_LETTERS = " " return len([letter for letter in word if letter not in BAD_LETTERS]) ```
How to count the number of letters in a string without the spaces?
18,455,222
8
2013-08-27T00:44:39Z
18,455,335
7
2013-08-27T01:01:53Z
[ "python" ]
This is my solution resulting in an error. Returns 0 PS: **I'd still love a fix to my code :)** ``` from collections import Counter import string def count_letters(word): global count wordsList = string.split(word) count = Counter() for words in wordsList: for letters in set(words): ...
Simply solution using the [sum](http://docs.python.org/2/library/functions.html#sum) function: ``` sum(c != ' ' for c in word) ``` It's a memory efficient solution because it uses a [generator](http://wiki.python.org/moin/Generators) rather than creating a temporary list and then calculating the sum of it. It's wort...
Python, write in memory zip to file
18,457,678
8
2013-08-27T05:32:26Z
18,457,698
19
2013-08-27T05:33:44Z
[ "python", "zip", "stringio" ]
How do I write an in memory zipfile to a file? ``` # Create in memory zip and add files zf = zipfile.ZipFile(StringIO.StringIO(), mode='w',compression=zipfile.ZIP_DEFLATED) zf.writestr('file1.txt', "hi") zf.writestr('file2.txt', "hi") # Need to write it out f = file("C:/path/my_zip.zip", "w") f.write(zf) # what to d...
[`StringIO.getvalue`](http://docs.python.org/2/library/stringio.html#StringIO.StringIO.getvalue) return content of `StringIO`: ``` >>> import StringIO >>> f = StringIO.StringIO() >>> f.write('asdf') >>> f.getvalue() 'asdf' ``` Alternatively, you can change position of the file using `seek`: ``` >>> f.read() '' >>> f...
Can't figure out how to print horizontally in python?
18,458,024
2
2013-08-27T05:59:08Z
18,458,152
10
2013-08-27T06:07:23Z
[ "python", "python-3.x" ]
I need to print this code: ``` for x in range (1, 21): if x%15==0: print("fizzbuzz") elif x%5==0: print("buzz") elif x%3==0: print("fizz") else: print (x) ``` Horizontally instead of it printing vertically, like this: ``` 1 2 3 ``` to ``` 1 2 3 ``` I am not ...
Two options: Accumulate a result string and `print` that at the end: ``` result = "" for x in range (1, 21): if x%15==0: result = result + "fizzbuzz " etc... print result ``` Or tell Python not to end the printed string with a newline character. In Python 3, which you seem to be using, you do t...
Python: plot list of tuples
18,458,734
15
2013-08-27T06:46:26Z
18,458,953
16
2013-08-27T06:58:47Z
[ "python", "numpy", "matplotlib", "scipy", "gnuplot" ]
I have the following data set. I would like to use python or gnuplot to plot the data. The tuples are of the form (x,y). The Y axis should be a log axis. I.E. log(y). A scatter plot or line plot would be ideal. How can this be done? ``` [(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08), (2, 7.6280656623374...
If I get your question correctly, you could do something like this. ``` >>> import matplotlib.pyplot as plt >>> testList =[(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08), (2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09), (4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)] >>> from math impo...
Average values in two Numpy arrays
18,461,623
13
2013-08-27T09:23:45Z
18,461,664
16
2013-08-27T09:25:56Z
[ "python", "arrays", "numpy" ]
Given two ndarrays ``` old_set = [[0, 1], [4, 5]] new_set = [[2, 7], [0, 1]] ``` I'm looking to get the mean of the respective values between the two arrays so that the data ends up something like: ``` end_data = [[1, 4], [2, 3]] ``` basically it would apply something like ``` for i in len(old_set): end_data[i...
``` >>> import numpy as np >>> old_set = [[0, 1], [4, 5]] >>> new_set = [[2, 7], [0, 1]] >>> (np.array(old_set) + np.array(new_set)) / 2 array([[1, 4], [2, 3]]) ```
Average values in two Numpy arrays
18,461,623
13
2013-08-27T09:23:45Z
18,461,943
37
2013-08-27T09:38:52Z
[ "python", "arrays", "numpy" ]
Given two ndarrays ``` old_set = [[0, 1], [4, 5]] new_set = [[2, 7], [0, 1]] ``` I'm looking to get the mean of the respective values between the two arrays so that the data ends up something like: ``` end_data = [[1, 4], [2, 3]] ``` basically it would apply something like ``` for i in len(old_set): end_data[i...
You can create a 3D array, then average along `axis=0` using `np.mean`: ``` np.mean( np.array([ old_set, new_set ]), axis=0 ) ```
ArgumentParser epilog and description formatting in conjunction with ArgumentDefaultsHelpFormatter
18,462,610
14
2013-08-27T10:10:04Z
18,462,760
16
2013-08-27T10:18:08Z
[ "python", "argparse" ]
I'm using [argparse](http://docs.python.org/dev/library/argparse.html) to take in command line input and also to produce help text. I want to use `ArgumentDefaultsHelpFormatter` as the `formatter_class`, however this prevents me from also using `RawDescriptionHelpFormatter` which would allow me to add custom formatting...
I just tried a multiple inheritance approach, and it works: ``` class CustomFormatter(argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter): pass parser = argparse.ArgumentParser(description='test\ntest\ntest.', epilog='test\ntest\ntest.', ...
What is the recommended way of allocating memory for a typed memory view?
18,462,785
41
2013-08-27T10:19:41Z
21,054,369
44
2014-01-10T21:04:42Z
[ "python", "memory", "memory-management", "buffer", "cython" ]
The [Cython documentation on typed memory views](http://docs.cython.org/src/userguide/memoryviews.html) list three ways of assigning to a typed memory view: 1. from a raw C pointer, 2. from a `np.ndarray` and 3. from a `cython.view.array`. Assume that I don't have data passed in to my cython function from outside but...
Look [here](https://groups.google.com/forum/#!topic/cython-users/CwtU_jYADgM) for an answer. The basic idea is that you want `cpython.array.array` and `cpython.array.clone` (**not** `cython.array.*`): ``` from cpython.array cimport array, clone # This type is what you want and can be cast to things of # the "double[...
Can I change the connection pool size for Python's "requests" module?
18,466,079
20
2013-08-27T12:55:44Z
18,845,952
45
2013-09-17T09:21:42Z
[ "python", "multithreading", "request" ]
(edit: Perhaps I am wrong in what this error means. Is this indicating that the connection pool at my CLIENT is full? or a connection pool at the SERVER is full and this is the error my client is being given?) I am attempting to make a large number of `http` requests concurrently using the python `threading` and `requ...
This should do the trick: ``` import requests sess = requests.Session() adapter = requests.adapters.HTTPAdapter(pool_connections=100, pool_maxsize=100) sess.mount('http://', adapter) resp = sess.get("/mypage") ```
Indentation marker/vertical lines for Python in pydev
18,468,594
6
2013-08-27T14:42:27Z
18,468,875
8
2013-08-27T14:53:38Z
[ "python", "eclipse", "aptana", "pydev" ]
Is there a setting in Pydev source editor (Aptana studio for Eclipse) where I can see what indentation level a particular line in a Python file has? Something like a vertical line or a marker on the top/bottom window edges (as seen in image processing tools). When having source code with a couple of indentation levels...
Doesn't look like it is available out of the box, however it is possible to add with plugins, for example: * <http://sschaef.github.io/IndentGuide/> * <http://editbox.sourceforge.net/> or you can configure to show whitespaces, however, it doesn't give you vertical indent guide, unless you willing to count dots: Prefe...
Flask SQLAlchemy pagination error
18,468,887
4
2013-08-27T14:54:05Z
18,471,636
14
2013-08-27T17:10:31Z
[ "python", "pagination", "flask", "flask-sqlalchemy" ]
I have this code and the `all()` method and every other method works on this and I have looked all over and I could that the method `paginate()` works on `BaseQuery` which is also `Query` ``` @app.route('/') @app.route('/index') @app.route('/blog') @app.route('/index/<int:page>') def index(page = 1): posts = db.se...
From your question... ``` that the method paginate() works on BaseQuery which is also Query ``` I think this is where you're being confused. "Query" refers to the SQLAlchemy [`Query`](http://docs.sqlalchemy.org/en/rel_1_0/orm/query.html#the-query-object) object. "BaseQuery" refers to the Flask-SQLALchemy [`BaseQuery`...
Python timedelta remove microseconds
18,470,627
7
2013-08-27T16:12:22Z
18,470,628
7
2013-08-27T16:12:22Z
[ "python", "datetime", "format", "timedelta" ]
I do a calculation of average time and I would like to display the resulted average without microseconds. ``` avg = sum(datetimes, datetime.timedelta(0)) / len(datetimes) ``` Thanks
Take the timedetla and remove its own microseconds, as microseconds and read-only attribute: ``` avg = sum(datetimes, datetime.timedelta(0)) / len(datetimes) avg = avg - datetime.timedelta(microseconds=avg.microseconds) ``` You can make your own little function if it is a recurring need: ``` import datetime def cho...
Can't print character '\u2019' in Python from JSON object
18,473,794
7
2013-08-27T19:22:58Z
18,474,067
12
2013-08-27T19:40:03Z
[ "python", "encoding", "printing", "python-3.x" ]
As a project to help me learn Python, I'm making a CMD viewer of Reddit using the json data (for example www.reddit.com/all/.json). When certain posts show up and I attempt to print them (that's what I assume is causing the error), I get this error: Traceback (most recent call last): File "C:\Users\nsaba\Desktop\reddi...
It's almost certain that you problem has nothing to do with the code you've shown, and can be reproduced in one line: ``` print(u'\2019') ``` If your terminal's character set can't handle U+2019 (or if Python is confused about what character set your terminal uses), there's no way to print it out. It doesn't matter w...
Joining onto a subquery in SQLAlchemy
18,474,311
8
2013-08-27T19:55:25Z
18,518,959
8
2013-08-29T18:55:56Z
[ "python", "sql", "sqlalchemy", "greatest-n-per-group" ]
I have the follwing SQL query (It get's the largest of a certain column per group, with 3 things to group by): ``` select p1.Name, p1.nvr, p1.Arch, d1.repo, p1.Date from Packages as p1 inner join Distribution as d1 on p1.rpm_id = d1.rpm_id inner join ( select Name, Arch, repo, max(Date) as Date ...
Apparently you need to add an `and_()` around multiple join conditions. ``` join( sq, and_(p1.Name==sq.c.Name, p1.Arch==sq.c.Arch, d1.repo==sq.c.repo, p1.Date==sq.c.Date)).\ ```
Decreasing the size of cPickle objects
18,474,791
5
2013-08-27T20:27:40Z
18,475,160
12
2013-08-27T20:45:35Z
[ "python", "serialization", "pickle" ]
I am running code that creates large objects, containing multiple user-defined classes, which I must then serialize for later use. From what I can tell, only pickling is versatile enough for my requirements. I've been using cPickle to store them but the objects it generates are approximately 40G in size, from code that...
You can combine your cPickle `dump` call with a zipfile: ``` import cPickle import gzip def save_zipped_pickle(obj, filename, protocol=-1): with gzip.open(filename, 'wb') as f: cPickle.dump(obj, f, protocol) ``` And to re-load a zipped pickled object: ``` def load_zipped_pickle(filename): with gzip....
Decreasing the size of cPickle objects
18,474,791
5
2013-08-27T20:27:40Z
18,475,192
14
2013-08-27T20:47:47Z
[ "python", "serialization", "pickle" ]
I am running code that creates large objects, containing multiple user-defined classes, which I must then serialize for later use. From what I can tell, only pickling is versatile enough for my requirements. I've been using cPickle to store them but the objects it generates are approximately 40G in size, from code that...
If you must use pickle and no other method of serialization works for you, you can always pipe the pickle through `bzip2`. The only problem is that `bzip2` is a little bit slowish... `gzip` should be faster, but the file size is almost 2x bigger: ``` In [1]: class Test(object): def __init__(self): ...
Python: requests.exceptions.ConnectionError. Max retries exceeded with url
18,478,013
15
2013-08-28T01:29:15Z
18,677,786
13
2013-09-07T20:48:20Z
[ "python", "python-requests" ]
``` This is the script: import requests import json import urlparse from requests.adapters import HTTPAdapter s = requests.Session() s.mount('http://', HTTPAdapter(max_retries=1)) with open('proxies.txt') as proxies: for line in proxies: proxy=json.loads(line) with open('urls.txt') as urls: ...
Looking at stack trace you've provided your error is caused by `httplib.BadStatusLine` exception, which, according to [docs](http://docs.python.org/library/httplib.html?highlight=badstatusline#httplib.BadStatusLine), is: > Raised if a server responds with a HTTP status code that we don’t understand. In other words ...
Making object JSON serializable with regular encoder
18,478,287
35
2013-08-28T02:04:00Z
18,561,055
39
2013-09-01T17:35:02Z
[ "python", "json", "serialization" ]
The regular way of JSON-serializing custom non-serializable objects is to subclass `json.JSONEncoder` and then pass a custom encoder to dumps. It usually looks like this: ``` class CustomEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, foo): return obj.to_json() r...
As I said in a comment to your question, after looking at the `json` module's source code, it does not appear to lend itself to doing what you want. However the goal could be achieved by applying what is known as a [*monkey-patch*](https://en.wikipedia.org/wiki/Monkey-patch) (see question [*What is a monkey patch?*](ht...
Difference between Kivy and PY4A
18,478,492
15
2013-08-28T02:32:46Z
18,485,384
15
2013-08-28T10:28:38Z
[ "android", "python", "kivy", "sl4a" ]
I'm new to android development, and I have had some experience with Java, C#, Python, etc. Python being my favourite, I'd like to code Android app with it. Then I saw this question: [Is there any way to run Python on Android?](http://stackoverflow.com/questions/101754/is-there-any-way-to-run-python-on-android) Th...
Confusingly, there are *two* projects called 'python for android'. SL4A lets you run python scripts on android. Their PY4A is a step in their toolchain, but I don't know much about it. I understand there is some integration with android apis (you can use some hardware etc.), but limitations in how to run the programs ...
Difference between Kivy and PY4A
18,478,492
15
2013-08-28T02:32:46Z
24,554,748
9
2014-07-03T13:16:24Z
[ "android", "python", "kivy", "sl4a" ]
I'm new to android development, and I have had some experience with Java, C#, Python, etc. Python being my favourite, I'd like to code Android app with it. Then I saw this question: [Is there any way to run Python on Android?](http://stackoverflow.com/questions/101754/is-there-any-way-to-run-python-on-android) Th...
I've found this very useful (and recent): **Embedding Python in Android (Tutorial series)** <http://techventura.wordpress.com/2014/04/21/embedding-python-in-android-series/> It describes how to embed Python in an Android app, using the Kivy-related Python-for-Android, but not Kivy itself (which isn't really describe...
float object is not callable
18,479,367
2
2013-08-28T04:17:20Z
18,479,384
8
2013-08-28T04:19:40Z
[ "python", "numpy" ]
I have multiple for-loops inside a while loop in my Python code. For the first iteration, everything works fine. For the second iteration of the while-loop, I get the following error: ``` File ".\simulated_annealing.py", line 209, in <module> for ii in range(0, 8, 1) : TypeError: 'float' object is not callable ``` B...
Don't use `range` as a variable name. It shadows builtin function`range`: ``` >>> range = 0.1 >>> range(1) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'float' object is not callable ```
Python Threading with Event object
18,485,098
7
2013-08-28T10:14:52Z
18,485,226
14
2013-08-28T10:20:56Z
[ "python", "python-multithreading" ]
I've seen a lot of Python scripts that use Threads in a class and a lot of them use the `threading.Event()`. For example: ``` class TimerClass(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.event = threading.Event() def run(self): while not self.event.is_se...
Because someone else will set it. You generally start a thread in one part of your application and continue to do whatever you do: ``` thread = TimerClass() thread.start() # Do your stuff ``` The thread does it's stuff, while you do your stuff. If you want to terminate the thread you just call: ``` thread.event.set...
Python regex slow when whitespace in string
18,485,316
9
2013-08-28T10:25:02Z
18,485,755
13
2013-08-28T10:45:47Z
[ "python", "regex" ]
I would like to match strings, using Pythons regex module. In my case I want to verify that strings start, end and consist of upper case letters combined by "\_". As an example, the following string is valid: "MY\_HERO2". The following strings are not valid: "\_MY\_HREO2", "MY HERO2", "MY\_HERO2\_" To validate a stri...
> So what is my problem? The problem is [catastrophic backtracking](http://www.regular-expressions.info/catastrophic.html). The regex engine is trying a whole lot of variations which is taking a lot of time. Let's try this with a pretty simple example: `A_B D`. The engine first matches `A` with `[A-Z,0-9]+` then it ...
how to print contents of PYTHONPATH
18,486,469
8
2013-08-28T11:21:43Z
18,486,534
13
2013-08-28T11:24:54Z
[ "python" ]
I have set path using ``` sys.path.insert(1, mypath) ``` Then, I tried to print contents of PYTHONPATH variable using os.environ as below ``` print(os.environ['PYTHONPATH']) ``` but I am getting error as ``` raise KeyError(key) KeyError: 'PYTHONPATH' ``` How can we print contents of PYTHONPATH variable.
Instead of using the `os.environ` dict, you can simple use the `sys` module: ``` import sys print(sys.path) ``` This solution should be platform independant. The `PYTHONPATH` key can vary depending on the OS.
Django template for loop
18,487,919
4
2013-08-28T12:28:21Z
18,488,316
9
2013-08-28T12:45:29Z
[ "python", "html", "django", "django-templates" ]
I have a template where I get certain variables back. One variable is instance.category which outputs: "words words words" which are values split by spaced. When I use the code below I get letter by letter back and not the words. ``` {% for icon in instance.category %} <p>{{ icon }}</p> {% endfor %} ``` Output `...
If your separator is always `" "` and `category` is a string, you don't actually need a custom template filter. You could simply call `split` with no parameters: ``` {% for icon in instance.category.split %} <p>{{ icon }}</p> {% endfor %} ```
What is the difference between locals and globals when using Python's eval()?
18,488,078
9
2013-08-28T12:35:08Z
18,488,207
8
2013-08-28T12:40:51Z
[ "python", "eval" ]
Why does it make a difference if variables are passed as globals or as locals to Python's function [eval()](http://docs.python.org/2/library/functions.html#eval)? As also [described in the documenation](http://docs.python.org/2/library/functions.html#eval), Python will copy `__builtins__` to globals, if not given expl...
Python looks up names as globals by default; only names assigned to in *functions* are looked up as locals (so any name that is a parameter to the function or was assigned to in the function). You can see this when you use the `dis.dis()` function to decompile code objects or functions: ``` >>> import dis >>> def fun...
Uninstalling Python 2.7 on OSX 10.8.4
18,488,619
4
2013-08-28T12:57:53Z
18,488,684
7
2013-08-28T13:00:36Z
[ "python", "osx", "uninstall" ]
**Main problem:** I've installed recently Python3.3 - If I run now in Terminal: `python script.py` (where script.py is coded in version 3.3) I'll get a python 2.7 output e.g.: ``` print('String',Var) --> ('String',Var) Instead of: print('String, Var) --> String Var ``` How can I uninstall Python 2.7 easily with Macp...
Bad idea to uninstall the pre installed version of python. Better idea is to alias python to whatever you want in your bashrc/bash\_profile. In your home directory, aka ~, you might already have a `.bash_profile`(If you don't have one, you can make it). You can edit that with your favorite text editor and add `alias p...
django submit two different forms with one submit button
18,489,393
9
2013-08-28T13:31:14Z
18,489,593
24
2013-08-28T13:39:38Z
[ "python", "django", "forms" ]
is it possible to submit two different forms, with one submit button in django? i have one form called "instrument" and 4 equal forms "config". now i'd like to submit always one config and instrument. e.g. instrument + config 1, and instrument + config 2. and every config have its own submit button. i have tried it wi...
Instead of having multiple `<form ..>` tags in html, use only one `<form>` tag and add fields of all forms under it. Example in template ``` <form > {{ form1.as_p }} {{ form2.as_p }} {{ form3.as_p }} </form> ``` So when user submits the form you will get all forms data in view, then you can do what you a...
Implicit Argument Passing in Python?
18,490,441
2
2013-08-28T14:13:49Z
18,490,586
9
2013-08-28T14:20:08Z
[ "python" ]
The code below is from hackermeter.com and I'm not sure what to think of it. Is the variable i being passed implicitly to run() or does it expect more modification than just where it specifies? ``` import sys def run(): # Code here! for i in range(int(sys.stdin.readline())): run() ```
I'd argue that this is a poor coding practice. The only reason `run()` has access to `i` is that `i` is global. The following is arguably better as it will force the programmer to pass `i` into `run()` explicitly (if required): ``` import sys def run(): # Code here! def main(): for i in range(int(sys.stdin.re...
Python: truth value of python string
18,491,777
5
2013-08-28T15:11:36Z
18,491,806
8
2013-08-28T15:12:45Z
[ "python" ]
``` if <boolean> : # do this ``` boolean has to be either True or False. then why ``` if "poi": print "yes" ``` output: yes i didn't get why yes is printing , since "poi" is nether True or False.
In python, any string except an empty string defaults to `True` ie, ``` if "MyString": # this will print foo print("foo") if "": # this will NOT print foo print("foo") ```
Python: truth value of python string
18,491,777
5
2013-08-28T15:11:36Z
18,491,862
14
2013-08-28T15:14:40Z
[ "python" ]
``` if <boolean> : # do this ``` boolean has to be either True or False. then why ``` if "poi": print "yes" ``` output: yes i didn't get why yes is printing , since "poi" is nether True or False.
Python will do its best to evaluate the "truthiness" of an expression when a boolean value is needed from that expression. The rule for strings is that an empty string is considered `False`, a non-empty string is considered `True`. The same rule is imposed on other containers, so an empty dictionary or list is conside...
Combining hdf5 files
18,492,273
13
2013-08-28T15:32:59Z
18,493,935
9
2013-08-28T16:57:50Z
[ "python", "hdf5", "h5py" ]
I have a number of hdf5 files, each of which have a single dataset. The datasets are too large to hold in RAM. I would like to combine these files into a single file containing all datasets separately (i.e. **not** to concatenate the datasets into a single dataset). One way to do this is to create a hdf5 file and then...
I found a non-python solution by using [h5copy](http://www.hdfgroup.org/HDF5/doc/RM/Tools.html#Tools-Copy) from the official hdf5 tools. h5copy can copy individual specified datasets from an hdf5 file into another existing hdf5 file. If someone finds a python/h5py-based solution I would be glad to hear about it.
Combining hdf5 files
18,492,273
13
2013-08-28T15:32:59Z
18,527,687
16
2013-08-30T07:50:47Z
[ "python", "hdf5", "h5py" ]
I have a number of hdf5 files, each of which have a single dataset. The datasets are too large to hold in RAM. I would like to combine these files into a single file containing all datasets separately (i.e. **not** to concatenate the datasets into a single dataset). One way to do this is to create a hdf5 file and then...
This is actually one of the use-cases of HDF5. If you just want to be able to access all the datasets from a single file, and don't care how they're actually stored on disk, you can use [external links](http://www.hdfgroup.org/HDF5/doc/RM/RM_H5L.html#Link-CreateExternal). From the [HDF5 website](http://www.hdfgroup.org...
how do i return a string from a regex match in python
18,493,677
17
2013-08-28T16:42:27Z
18,493,712
22
2013-08-28T16:44:26Z
[ "python", "regex" ]
I am running through lines in a text file using a `python` script. I want to search for an `img` tag within the text document and return the tag as text When i run the `regex` `re.match(line)` it returns a `_sre.SRE_MATCH` object. How do i get it to return a string? ``` import sys import string import re f = open("sa...
You should use `re.MatchObject.group(0)`. Like ``` imtag = re.match(r'<img.*?>', line).group(0) ``` Edit: You also might be better off doing something like ``` imgtag = re.match(r'<img.*?>',line) if imtag: print("yo it's a {}".format(imgtag.group(0))) ``` to eliminate all the `None`s.
Regular Expression: How to match using previous matches?
18,493,715
3
2013-08-28T16:44:32Z
18,493,746
7
2013-08-28T16:45:59Z
[ "python", "regex", "python-2.7" ]
I am searching for string patterns of the form: ``` XXXAXXX # exactly 3 Xs, followed by a non-X, followed by 3Xs ``` All of the Xs must be the same character and the A must not be an X. *Note: I am **not** searching explicitly for Xs and As - I just need to find this pattern of characters in general.* Is it possib...
You can try this: ``` (\w)\1{2}(?!\1)\w\1{3} ``` **Break Up:** ``` (\w) # Match a word character and capture in group 1 \1{2} # Match group 1 twice, to make the same character thrice - `XXX` (?!\1) # Make sure the character in group 1 is not ahead. (X is not ahead) \w # Then match a word c...
How to check if an object is a list of strings?
18,495,098
7
2013-08-28T18:02:56Z
18,495,133
12
2013-08-28T18:04:59Z
[ "python", "types", "isinstance" ]
**How to check if an object is a list of strings?** I could only check if an object is string as such: ``` def checktype(obj): if isinstance(obj,str): print "It's a string" obj1 = ['foo','bar','bar','black','sheet'] obj2 = [1,2,3,4,5,'bar'] obj3 = 'bar' for i in [obj1,obj2,obj3]: checktype(i) ``` Desired ou...
To test if all the items in a list are strings, use the [`all`](http://docs.python.org/2/library/functions.html#all) built-in and a generator: ``` if all(isinstance(s, str) for s in lis): ``` Note though that, if your list is empty, this will still return `True` since that is technically a list of 0 strings. However,...
How to check if an object is a list of strings?
18,495,098
7
2013-08-28T18:02:56Z
18,495,146
13
2013-08-28T18:05:30Z
[ "python", "types", "isinstance" ]
**How to check if an object is a list of strings?** I could only check if an object is string as such: ``` def checktype(obj): if isinstance(obj,str): print "It's a string" obj1 = ['foo','bar','bar','black','sheet'] obj2 = [1,2,3,4,5,'bar'] obj3 = 'bar' for i in [obj1,obj2,obj3]: checktype(i) ``` Desired ou...
Something like this, I presume? You could do some checks to see if it's a single string. ``` >>> def checktype(obj): return bool(obj) and all(isinstance(elem, basestring) for elem in obj) >>> obj1 = ['foo','bar','bar','black','sheet'] >>> obj2 = [1,2,3,4,5,'bar'] >>> obj3 = 'bar' >>> for i in [obj1, obj2, obj...
Pandas data from stdin
18,495,846
4
2013-08-28T18:44:27Z
18,495,906
7
2013-08-28T18:48:12Z
[ "python", "json", "pandas", "stdin" ]
Is it possible to have stdin data go into a pandas DataFrame? Currently I'm saving the data in an intermediate `json` file and then doing: ``` pandas.read_json('my_json_file.json') ``` but was wondering if it's possible to pipe the stdin directly in the python script. I found this: [How to read from stdin or from a ...
Just use the `sys.stdin` as a `file` object (which it actually is) and pass it to `pandas` `read_xy` method. ``` $ cat test.py import sys import pandas as pd df = pd.read_json(sys.stdin) print df $ cat data.json {"a": [1,2,3,4], "b":[3,4,5,6]} $ python test.py < data.json a b 0 1 3 1 2 4 2 3 5 3 4 6 ```
How to get csv attachment from email and save it
18,497,397
4
2013-08-28T20:16:13Z
18,499,052
7
2013-08-28T22:07:36Z
[ "python", "csv", "python-2.7", "email-attachments", "imaplib" ]
I am trying to get the attachment from an email and save it to a specific folder with the original file name. The email is very basic and does not have much to it other than the attachment. The file is a csv file and there will be only one per email. This is what I have so far, but I'm new to this and am not sure how t...
I looked around some more and tried a few more things. These: [Downloading multiple attachments using imaplib](http://stackoverflow.com/questions/6225763/downloading-multiple-attachments-using-imaplib) and [How do I download only unread attachments from a specific gmail label?](http://stackoverflow.com/questions/101824...
Beautifulsoup - How to open images and download them
18,497,840
3
2013-08-28T20:43:51Z
18,498,480
10
2013-08-28T21:25:08Z
[ "python", "beautifulsoup" ]
I am looking to grab the full size product images from [here](http://icecat.biz/p/toshiba/pscbxe-01t00een/satellite-pro-notebooks-4051528049077-Satellite+Pro+C8501GR-17732197.html) My thinking was: * Follow the image link * Download the picture * Go back * Repeat for n+1 pictures I know how to open the image thumbna...
This will get you all URL of the images: ``` import urllib2 from bs4 import BeautifulSoup url = "http://icecat.biz/p/toshiba/pscbxe-01t00een/satellite-pro-notebooks-4051528049077-Satellite+Pro+C8501GR-17732197.html" html = urllib2.urlopen(url) soup = BeautifulSoup(html) imgs = soup.findAll("div", {"class":"thumb-pic...
Python: Pep8 E128 indentation error... how can this by styled?
18,497,923
11
2013-08-28T20:50:05Z
18,498,073
13
2013-08-28T20:58:59Z
[ "python", "coding-style", "formatting", "pep8" ]
I have this statement as a few lines: ``` return render_to_response('foo/page.html', { 'situations': situations, 'active': active_req, }, context_instance=RequestContext(request)) ``` As it stands, using the PEP8 script, it gives me an "E128: continuation line under...
The problem is that all parameters are supposed to be indented to the same level. That includes any parameter(s) on the initial function call line. So, while you *could* fix it like this: ``` return render_to_response('foo/page.html', { 'situations': situations,...
numpy gradient function and numerical derivatives
18,498,457
10
2013-08-28T21:23:34Z
18,498,585
16
2013-08-28T21:31:47Z
[ "python", "numpy", "gradient", "numerical-methods" ]
The array the `numpy.gradient` function returns depends on the number of data-points/spacing of the data-points. Is this expected behaviour? For example: ``` y = lambda x: x x1 = np.arange(0,10,1) x2 = np.arange(0,10,0.1) x3 = np.arange(0,10,0.01) plt.plot(x1,np.gradient(y(x1)),'r--o') plt.plot(x2,np.gradient(y(x2))...
In `np.gradient` you should tell the sample distance. To get the same results you should type: ``` plt.plot(x1,np.gradient(y(x1),1),'r--o') plt.plot(x2,np.gradient(y(x2),0.1),'b--o') plt.plot(x3,np.gradient(y(x3),0.01),'g--o') ``` The default sample distance is 1 and that's why it works for x1. If the distance is no...
pythonic way of replacing one item with two or more in a list
18,498,634
3
2013-08-28T21:35:09Z
18,498,681
12
2013-08-28T21:38:39Z
[ "python" ]
how can i programaticaly replace one item in a list with two or more? I'm doing it with splits and indexes, and it looks very un-python. I'm wishing something like this exists: ``` values = [ "a", "b", "old", "c" ] [ yield ["new1", "new2"] if item == "old" else item for item in values ] // return [ "a", "b", "new1", ...
The best way to do this would be to use [`itertools.chain.from_iterable`](http://docs.python.org/3/library/itertools.html#itertools.chain.from_iterable): ``` itertools.chain.from_iterable( ("new1", "new2") if item == "old" else (item, ) for item in values) ``` The 'multiple items per item' problem you face is solve...
Boxplot with pandas groupby
18,498,690
4
2013-08-28T21:39:16Z
18,499,445
7
2013-08-28T22:39:29Z
[ "python", "group-by", "pandas", "dataframe" ]
Ok so I have a dataframe which contains timeseries data that has a multiline index for each columns. Here is a sample of what the data looks like and it is in csv format. Loading the data is not an issue here. ![enter image description here](http://i.stack.imgur.com/J9Bpm.png) What I want to do is to be able to creat...
I think I figured it out, maybe this will be helpful to someone: ``` grouped = data['2013-08-17'].groupby(axis=1, level='SPECIES').T grouped.boxplot() ``` Basically groupby output needed to be transposed so that the boxplot showed the right grouping: ![enter image description here](http://i.stack.imgur.com/LoOOz.png...
How do you make an errorbar plot in matplotlib using linestyle=None in rcParams?
18,498,742
5
2013-08-28T21:42:58Z
18,499,120
19
2013-08-28T22:12:05Z
[ "python", "matplotlib" ]
When plotting errorbar plots, matplotlib is not following the rcParams of no linestyle. Instead, it's plotting all of the points connected with a line. Here's a minimum working example: ``` import matplotlib.pyplot as plt lines = {'linestyle': 'None'} plt.rc('lines', **lines) plt.errorbar((0, 1), (1, 0), yerr=(0.1, ...
This is a "bug" in older versions of `matplotlib` (and has been [fixed](https://github.com/matplotlib/matplotlib/pull/3103/files) for the 1.4 series). The issue is that in `Axes.errorbar` there is a default value of `'-'` for `fmt`, which is then passed to the call to `plot` which is used to draw the markers and line. ...
Python remainder operator
18,499,458
3
2013-08-28T22:40:22Z
18,499,611
16
2013-08-28T22:53:47Z
[ "python" ]
Is there any remainder operator in Python? I do not ask for modulo operator, but remainder. For example: ``` -5 mod 2 = 1 ``` but ``` -5 rem 2 = -1 # where "rem" is a remainder operator. ``` Do I have to implement it by myself ;)?
There are actually three different definitions of "modulo" or "remainder", not two: * Truncated division remainder: sign is the same as the dividend. * Floored division remainder: sign is the same as the divisor. * Euclidean division remainder: sign is always positive. Calling one of them "modulo" and another "remain...
How to process SIGTERM signal gracefully?
18,499,497
40
2013-08-28T22:44:40Z
18,500,278
17
2013-08-29T00:08:08Z
[ "python", "daemon", "sigterm", "start-stop-daemon" ]
Let's assume we have such a trivial daemon written in python: ``` def mainloop(): while True: # 1. do # 2. some # 3. important # 4. job # 5. sleep mainloop() ``` and we daemonize it using `start-stop-daemon` which by default sends `SIGTERM` (`TERM`) signal on `--stop`. Le...
I think you are near to a possible solution. Execute `mainloop` in a separate thread and extend it with the property `shutdown_flag`. The signal can be caught with `signal.signal(signal.SIGTERM, handler)` in the main thread (not in a separate thread). The signal handler should set `shutdown_flag` to True and wait for ...
How to process SIGTERM signal gracefully?
18,499,497
40
2013-08-28T22:44:40Z
24,574,672
17
2014-07-04T12:45:31Z
[ "python", "daemon", "sigterm", "start-stop-daemon" ]
Let's assume we have such a trivial daemon written in python: ``` def mainloop(): while True: # 1. do # 2. some # 3. important # 4. job # 5. sleep mainloop() ``` and we daemonize it using `start-stop-daemon` which by default sends `SIGTERM` (`TERM`) signal on `--stop`. Le...
Firstly I'm not certain that you need a second thread to set the shutdown\_flag. Why not set it directly in the SIGTERM handler? An alternative is to raise an exception from the `SIGTERM` handler, which will be propagated up the stack. Assuming you've got proper exception handling (e.g. with `with`/`contextmanager` an...
How to process SIGTERM signal gracefully?
18,499,497
40
2013-08-28T22:44:40Z
31,464,349
45
2015-07-16T20:55:02Z
[ "python", "daemon", "sigterm", "start-stop-daemon" ]
Let's assume we have such a trivial daemon written in python: ``` def mainloop(): while True: # 1. do # 2. some # 3. important # 4. job # 5. sleep mainloop() ``` and we daemonize it using `start-stop-daemon` which by default sends `SIGTERM` (`TERM`) signal on `--stop`. Le...
A class based clean to use solution: ``` import signal import time import sys class GracefulKiller: kill_now = False def __init__(self): signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) def exit_gracefully(self,signum, frame): self.kill_now = Tr...
Horizontal box plots in matplotlib/Pandas
18,500,011
4
2013-08-28T23:36:33Z
18,500,068
10
2013-08-28T23:42:15Z
[ "python", "matplotlib", "pandas" ]
### Bar plots: `matplotlib` offers the function [`bar`](http://matplotlib.org/api/pyplot_api.html?highlight=bar#matplotlib.pyplot.bar) and [`barh`](http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.barh) to do **vertical** and **horizontal** bar plots. ### Box plots: `matplotlib` also offers the function [...
matplotlib's `boxplot(..., vert=False)` makes horizontal box plots. The keyword parameter `vert=False` can also be passed to `DataFrame.boxplot`: ``` import matplotlib.pyplot as plt import pandas as pd x = [[1.2, 2.3, 3.0, 4.5], [1.1, 2.2, 2.9, 5.0]] df = pd.DataFrame(x, index=['Age of pregnant women', 'Age of pr...
how do you reload a module in python version 3.3.2
18,500,283
2
2013-08-29T00:08:40Z
18,500,299
8
2013-08-29T00:10:08Z
[ "python" ]
whenever I try to reload a python module in python version 3.3.2 i get this error code ``` >>> import bigmeesh >>> bob=bigmeesh.testmod() this baby is happy >>> imp.reload(bigmeesh) Traceback (most recent call last): File "<pyshell#2>", line 1, in <module> imp.reload(bigmeesh) NameError: name 'imp' is not define...
You have to `import imp` before you can use it, just as with any other module: ``` >>> import bigmeesh >>> import imp >>> imp.reload(bigmeesh) ``` --- Note that [the documentation](http://docs.python.org/3.3/library/imp.html) clearly says: > Note: New programs should use `importlib` rather than this module. Howeve...
How to flatten a tuple in python
18,500,541
9
2013-08-29T00:36:56Z
18,500,566
10
2013-08-29T00:40:06Z
[ "python", "list", "tuples", "flatten" ]
I have the following element of a list, and the list is 100 elements long. ``` [(50, (2.7387451803816479e-13, 219))] ``` How do I convert each element to look like this? ``` [(50, 2.7387451803816479e-13, 219)] ```
``` [(a, b, c) for a, (b, c) in l] ``` [Tuple packing and unpacking](http://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences) solves the problem.
Python Peewee execute_sql() example
18,500,956
2
2013-08-29T01:36:11Z
18,516,670
9
2013-08-29T16:47:21Z
[ "python", "sql", "database", "peewee" ]
I am using the Peewee module as the ORM for my project. I read the entire documentation, there is no clear example on how to process the result from db.execute\_sql(). I traced the code, only can find db.execute\_sql() return back the cursor. Does anyone knows how to process the cursor, such as iterate over it and g...
Peewee returns a cursor. Then you can use the db-api 2 to iterate over it: ``` cursor = db.execute_sql('select * from tweets;') for row in cursor.fetchall(): print row cursor = db.execute_sql('select count(*) from tweets;') res = cursor.fetchone() print 'Total: ', res[0] ```
Postgresql - Insert into where not exists using sqlalchemy's INSERT from SELECT
18,501,347
9
2013-08-29T02:25:28Z
18,605,162
10
2013-09-04T03:58:08Z
[ "python", "postgresql", "sqlalchemy", "insert-update" ]
As pointed out [here](http://stackoverflow.com/a/13342031/697233) its possible to do the following with postgresql 9.1+ ``` INSERT INTO example_table (id, name) SELECT 1, 'John' WHERE NOT EXISTS ( SELECT id FROM example_table WHERE id = 1 ); ``` I've been having a play around with version 0.9 of s...
``` from sqlalchemy import * """ INSERT INTO example_table (id, name) SELECT 1, 'John' WHERE NOT EXISTS ( SELECT id FROM example_table WHERE id = 1 ); """ m = MetaData() example_table = Table("example_table", m, Column('id', Integer), Column('name',...
websocket server for django application
18,501,431
7
2013-08-29T02:35:13Z
18,512,124
8
2013-08-29T13:17:25Z
[ "python", "django", "websocket", "socket.io", "tornado" ]
I have a django application need to be deployed under Apache HTTP Server, also i need push event to client's web browser at real time. I'm rather new to python, could anyone suggest some websocket server could work in Python+Django+Apache?
Django is a synchronous web server. it means you cannot use websocket directly with it. But you have various option to do websocket in Django. **Use a full python stack to do it:** use [Tornado](http://www.tornadoweb.org/en/stable/) and Django. You can follow this [post](http://thinkfaster.co/2015/01/run-django-on-tor...
How can I vectorize this python count sort so it is absolutely as fast as it can be?
18,501,867
2
2013-08-29T03:33:51Z
18,502,321
8
2013-08-29T04:31:19Z
[ "python", "performance", "sorting" ]
I am trying to write a count sort in python to beat the built-in timsort in certain situations. Right now it beats the built in sorted function, but only for very large arrays (1 million integers in length and longer, I haven't tried over 10 million) and only for a range no larger than 10,000. Additionally, the victory...
With numpy, this function reduces to the following: ``` def countsort(unsorted): unsorted = numpy.asarray(unsorted) return numpy.repeat(numpy.arange(1+unsorted.max()), numpy.bincount(unsorted)) ``` This ran about 40 times faster when I tried it on 100000 random ints from the interval [0, 10000). [`bincount`](...
Python closure vs javascript closure
18,502,095
10
2013-08-29T04:04:02Z
18,503,395
14
2013-08-29T06:05:17Z
[ "javascript", "python", "closures" ]
The following closure function works fine in javascript. ``` function generateNextNumber(startNumber) { var current = startNumber; return function(){ return current += 1; } } var getNextNumber = generateNextNumber(10); for (var i = 0; i < 10; i++) { console.log(getNextNumber()); } ``` I tried...
Python assumes that all variables in a function are local. This is to avoid accidental use of a global variable of the same name, or in an enclosing scope. In some important way, this difference is consequence of the fact that in Python local variable declaration is automatic/implicit while in JavaScript it is not (you...
How to change GAE local server's login in user account?
18,502,277
2
2013-08-29T04:27:19Z
18,503,212
7
2013-08-29T05:51:27Z
[ "python", "google-app-engine", "user", "account" ]
There is an edit page on my GAE app only the admin can log in. It works well on GAE server. But on the local dev machine, when I go to ``` http://localhost:9080/editpage ``` it says ``` Current logged in user [email protected] is not authorized to view this page. ``` How can I change [email protected] to my admin acc...
You can go directly to /\_ah/login and change who you're logged in as. (Or to log out, or to change user/admin-status.)
Python Integer Partitioning with given k partitions
18,503,096
5
2013-08-29T05:41:26Z
18,503,391
10
2013-08-29T06:05:11Z
[ "python", "algorithm", "integer-partition" ]
I'm trying to find or develop Integer Partitioning code for Python. FYI, Integer Partitioning is representing a given integer n as a sum of integers smaller than n. For example, an integer 5 can be expressed as `4 + 1 = 3 + 2 = 3 + 1 + 1 = 2 + 2 + 1 = 2 + 1 + 1 + 1 = 1 + 1 + 1 + 1 + 1` I've found a number of solution...
I've written a generator solution ``` def partitionfunc(n,k,l=1): '''n is the integer to partition, k is the length of partitions, l is the min partition element size''' if k < 1: raise StopIteration if k == 1: if n >= l: yield (n,) raise StopIteration for i in range...
How to create user from django shell
18,503,770
10
2013-08-29T06:33:06Z
18,504,852
34
2013-08-29T07:34:38Z
[ "python", "django", "shell", "django-shell" ]
When i create user from `django-admin` user password's are encrypted . but when i create user from django shell user-pasword is saved in plain text . Example : ``` { "date_joined": "2013-08-28T04:22:56.322185", "email": "", "first_name": "", "id": 5, "is_active": true, "is_staff": false, "i...
You should not create the user via the normal `User(...)` syntax, add others have suggested. You should always use `User.objects.create_user()`, which takes care of setting the password properly. ``` user@host> manage.py shell >>> from django.contrib.auth.models import User >>> user=User.objects.create_user('foo', pas...
How to set the path for cairo in ubuntu-12.04?
18,504,531
5
2013-08-29T07:16:28Z
18,504,628
11
2013-08-29T07:21:38Z
[ "python", "python-3.x", "ubuntu-12.04", "pycairo" ]
I need to install pycairo with python3.2+.But I have error when installing the pycairo in my system, ``` Downloading/unpacking git+http://anongit.freedesktop.org/git/pycairo (from -r requirements.txt (line 7)) Cloning http://anongit.freedesktop.org/git/pycairo to /tmp/pip-ud145u-build Running setup.py egg_info for...
Install `libcairo2-dev` first: ``` sudo apt-get install libcairo2-dev ```
PIL decoder jpeg not available on ubuntu x64,
18,504,835
7
2013-08-29T07:33:52Z
20,091,508
18
2013-11-20T09:06:18Z
[ "python", "jpeg", "python-imaging-library" ]
I know that this question looks like a duplicate but I've followed many online instructions on how to properly install PIL and none have worked. I've tried everything in: [decoder JPEG not available PIL](http://stackoverflow.com/questions/8915296/decoder-jpeg-not-available-pil) with no success. When I run sudo pip in...
You can try this: **1. clear PIL packages** ``` rm -rf /usr/lib/python2.7/site-packages/PIL rm -rf /usr/lib/python2.7/site-packages/PIL.pth ``` **2. install required packages** ``` ubuntu: apt-get install libjpeg-dev libfreetype6-dev zlib1g-dev libpng12-dev centos: yum install zlib zlib-devel yum install libjpeg l...
How to find all indices above a specific value in a python multidimensional list
18,504,898
3
2013-08-29T07:37:07Z
18,505,100
7
2013-08-29T07:49:13Z
[ "python", "list", "multidimensional-array" ]
I have a two dimensional list in python with some floating point values. I want to find out indices of all the elements in the list which are above a specific value. For example, in a 2 x 4 list as below (integer for convenience): ``` 100 200 100 250 125 100 250 100 ``` I need the indices of all th...
Numpy is quite handy for this: ``` >>> import numpy as np >>> a = [[100, 200, 100, 250], [125, 100, 250, 100]] >>> a=np.array(a) >>> np.argwhere(a>=200) array([[0, 1], [0, 3], [1, 2]]) ```
pandas dataframe create new columns and fill with calculated values from same df
18,504,967
14
2013-08-29T07:40:53Z
18,505,101
22
2013-08-29T07:49:14Z
[ "python", "pandas", "calculated-columns" ]
Here is a simplified example of my df: ``` ds = pd.DataFrame(np.abs(randn(3, 4)), index=[1,2,3], columns=['A','B','C','D']) ds A B C D 1 1.099679 0.042043 0.083903 0.410128 2 0.268205 0.718933 1.459374 0.758887 3 0.680566 0.538655 0.038236 1.169403 ``` I would like to sum the...
You can do this easily manually for each column like this: ``` df['A_perc'] = df['A']/df['sum'] ``` --- If you want to do this in one step for all columns, you can use the `div` method (<http://pandas.pydata.org/pandas-docs/stable/basics.html#matching-broadcasting-behavior>): ``` ds.div(ds['sum'], axis=0) ``` And ...
Python oneline switch
18,507,523
3
2013-08-29T09:47:04Z
18,507,555
8
2013-08-29T09:48:05Z
[ "python" ]
I am looking for a more elegant way to do the following: ``` py_loglevel = logging.DEBUG if self.loglevel == "INFO": py_loglevel = logging.INFO elif self.loglevel == "WARNING": py_loglevel = logging.WARNING elif self.loglevel == "ERROR": py_loglevel = logging.ERROR ``` This works of couse, but it somehow ann...
Use a dictionary: ``` levels = { 'INFO': logging.INFO, 'WARNING': logging.WARNING, 'ERROR': logging.ERROR, } py_loglevel = levels.get(self.loglevel, logging.DEBUG) ``` Alternatively, look up the name as an attribute on the module: ``` py_loglevel = getattr(logging, self.loglevel, logging.DEBUG) ``` pro...
Stop processing Flask route if request aborted
18,511,119
20
2013-08-29T12:32:18Z
18,667,328
8
2013-09-06T22:09:57Z
[ "python", "http", "rest", "flask", "wsgi" ]
I have a flask REST endpoint that does some cpu-intensive image processing and takes a few seconds to return. Often, this endpoint gets called, then aborted by the client. In these situations I would like to cancel processing. How can I do this in flask? In node.js, I would do something like: ``` req.on('close', func...
There is a potentially... hacky solution to your problem. [Flask has the ability to stream content back to the user via a generator](http://flask.pocoo.org/docs/patterns/streaming/). The hacky part would be streaming blank data as a check to see if the connection is still open and then when your content is finished the...
Python Metaclass : Understanding the 'with_metaclass()'
18,513,821
14
2013-08-29T14:32:49Z
18,513,858
32
2013-08-29T14:34:19Z
[ "python", "metaclass", "six-python" ]
I want to ask what the `with_metaclass()` call means in the definition of a class. E.g.: ``` class Foo(with_metaclass(Cls1, Cls2)): ``` * Is it a special case where a class inherits from a metaclass? * Is the new class a metaclass, too?
[`with_metaclass()`](http://pythonhosted.org/six/#six.with_metaclass) is a utility class factory function provided by the [`six` library](http://pythonhosted.org/six/) to make it easier to develop code for both Python 2 and 3. It creates a base class with the specified meta class for you, compatible with the version o...
How to prevent YAML to dump long line without new line
18,514,205
3
2013-08-29T14:48:25Z
18,526,119
11
2013-08-30T06:09:29Z
[ "python", "yaml", "line-breaks", "dump", "long-lines" ]
Whenever my option goes beyond certain limit, pyyaml converts it into two lines. How to avoid this ? e.g. In [1]: x = "-c /home/user/test/test2/test23/tet/2s/test1/stest/longdirectory1/directory2/ --optnion12 --verbose" In [2]: `import yaml` In [3]: `print yaml.dump([dict(ATTRIBUTES=[dict(CONFIG=x)])], default_flo...
Thanks @MathieuMarques for suggesting to look @ dump options and link provided, YAML documentation was not good enough to find it out. Anyways solution is to specify `width` parameter for `dump` function. i.e. `yaml.dump(data, width=1000)`
How do I automatically fix an invalid JSON string?
18,514,910
8
2013-08-29T15:19:57Z
18,515,887
16
2013-08-29T16:06:15Z
[ "python", "json", "escaping" ]
From the 2gis API I got the following JSON string. ``` { "api_version": "1.3", "response_code": "200", "id": "3237490513229753", "lon": "38.969916127827", "lat": "45.069889625267", "page_url": null, "name": "ATB", "firm_group": { "id": "3237499103085728", "count": "1" ...
The answer by @Michael gave me an idea... not a very pretty idea, but it seems to work, at least on your example: Try to parse the JSON string, and if it fails, look for the character where it failed in the exception string and replace that character. ``` while True: try: result = json.loads(s) # try to ...
Listing select option values with Selenium and Python
18,515,692
5
2013-08-29T15:56:56Z
18,516,161
9
2013-08-29T16:20:20Z
[ "python", "selenium" ]
I have the following HTML code ``` <select name="countries" class_id="countries"> <option value="-1">--SELECT COUNTRY--</option> <option value="459">New Zealand</option> <option value="100">USA</option> <option value="300">UK</option> </select> ``` I am trying to get a list of the option values (like ...
check it out, here is how i did it before i knew what the Select Module did ``` from selenium import webdriver browser = webdriver.Firefox() #code to get you to the page select_box = browser.find_element_by_name("countries") # if your select_box has a name.. why use xpath?..... this step could use either xpath or nam...
Difference on performance between numpy and matlab
18,516,605
17
2013-08-29T16:43:53Z
18,517,922
25
2013-08-29T17:58:51Z
[ "python", "performance", "matlab", "numpy", "backpropagation" ]
I am computing the `backpropagation` algorithm for a sparse autoencoder. I have implemented it in python using `numpy` and in `matlab`. The code is almost the same, but the performance is very different. The time matlab takes to complete the task is 0.252454 seconds while numpy 0.973672151566, that is almost four times...
It would be wrong to say "Matlab is always faster than NumPy" or vice versa. Often their performance is comparable. When using NumPy, to get good performance you have to keep in mind that NumPy's speed comes from calling underlying functions written in C/C++/Fortran. It performs well when you apply those functions to w...
How to compile Python 2.4.6 with ssl, readline and zlib on Debian Lenny
18,516,956
2
2013-08-29T17:04:41Z
18,612,852
7
2013-09-04T11:40:43Z
[ "python", "linux", "ssl", "debian", "zlib" ]
I have a virtual Linux box with Debian 7.1 where I need a Python 2.4.6 to reanimate an old Zope installation (in order to update it to Plone 4, of course). I definitely need `ssl` support, and when I'm compiling, I want `readline` as well, of course. Finally, of course I need `zlib`, otherwise `ez_setup.py` etc. won't...
I found the solution [here](http://stackoverflow.com/a/11911570/1051649 "here"): I changed `setup.py`, looking for the first assignment to the lib\_dirs variable, changing it like so: ``` lib_dirs = self.compiler.library_dirs + [ '/lib64', '/usr/lib64', '/lib', '/usr/lib', '/usr/lib/x86_64-linux-gnu', # added '/usr...
Python: Indent all lines of a string except first while preserving linebreaks?
18,518,031
5
2013-08-29T18:04:54Z
18,518,470
10
2013-08-29T18:29:39Z
[ "python", "string", "text", "indentation", "textwrapping" ]
I want to indent all lines of a multi-line string except the first, without wrapping the text. For example, I want to turn: ``` A very very very very very very very very very very very very very very very very long mutiline string ``` into: ``` A very very very very very very very very very very very very very very...
You just need to replace the newline character `'\n'` with a new line character plus the white spaces `'\n    '` and save it to a variable (since `replace` won't change your original string, but return a new one with the replacements). ``` string = string.replace('\n', '\n ') ```
Python value testing 'abc' == True returns False
18,520,717
2
2013-08-29T20:50:44Z
18,520,746
7
2013-08-29T20:52:34Z
[ "python", "evaluation" ]
I was writing a unit test to assert the return value is not empty, so I wrote something like `assert(value, True)` and I got an error `AssertionError: '72a7090610eb11e398d40050569e0016' != True` ``` Python 2.7.3 (default, Aug 1 2012, 05:14:39) [GCC 4.6.3] on linux2 Type "help", "copyright", "credits" or "license" fo...
`'abc'` is not equal to `True`, but it's truthy. Those are two different concepts! in other words, this won't print `'ok'`: ``` if 'abc' == True: print 'ok' ``` ... But this will: ``` if 'abc': print 'ok' ```
defaultdict one-step initialization
18,520,825
9
2013-08-29T20:57:10Z
18,521,268
7
2013-08-29T21:28:48Z
[ "python", "defaultdict" ]
It would be convenient if a `defaultdict` could be initialized along the following lines ``` d = defaultdict(list, (('a', 1), ('b', 2), ('c', 3), ('d', 4), ('a', 2), ('b', 3))) ``` to produce ``` defaultdict(<type 'list'>, {'a': [1, 2], 'c': [3], 'b': [2, 3], 'd': [4]}) ``` Instead, I get ``` defaultdict(<type ...
What you're apparently missing is that `defaultdict` is a straightforward (not especially "magical") subclass of `dict`. All the first argument does is provide a factory function for *missing* keys. When you initialize a `defaultdict`, you're initializing a `dict`. If you want to produce ``` defaultdict(<type 'list'>...
defaultdict one-step initialization
18,520,825
9
2013-08-29T20:57:10Z
18,521,301
8
2013-08-29T21:31:08Z
[ "python", "defaultdict" ]
It would be convenient if a `defaultdict` could be initialized along the following lines ``` d = defaultdict(list, (('a', 1), ('b', 2), ('c', 3), ('d', 4), ('a', 2), ('b', 3))) ``` to produce ``` defaultdict(<type 'list'>, {'a': [1, 2], 'c': [3], 'b': [2, 3], 'd': [4]}) ``` Instead, I get ``` defaultdict(<type ...
the behavior you describe would not be consistent with the `defaultdict`s other behaviors. Seems like what you want is `FooDict` such that ``` >>> f = FooDict() >>> f['a'] = 1 >>> f['a'] = 2 >>> f['a'] [1, 2] ``` We can do that, but not with defaultdict; lets call it AppendDict ``` import collections class AppendDi...
Clarification of use-cases for Hadoop versus RabbitMQ+Celery
18,521,196
15
2013-08-29T21:23:33Z
18,522,257
16
2013-08-29T22:58:12Z
[ "python", "hadoop", "rabbitmq", "celery", "distributed-computing" ]
I know that there are similar questions to this, such as: * [Pros and cons of celery vs disco vs hadoop vs other distributed computing packages](http://stackoverflow.com/questions/8232194/pros-and-cons-of-celery-vs-disco-vs-hadoop-vs-other-distributed-computing-packag) * [Differentiate celery, kombu, PyAMQP and Rabbit...
1. They are the same in that both *can* solve the problem that you describe (map-reduce). They are different in that Hadoop is entirely build to solve only that usecase and Celey/RabbitMQ is build to facilitate Task execution on different nodes using message passing. Celery also supports different usecases. 2. Hadoop i...
selenium dosen't set downloaddir in FirefoxProfile
18,521,636
8
2013-08-29T21:58:22Z
18,536,224
15
2013-08-30T15:10:42Z
[ "python", "firefox", "selenium" ]
i want to auto download files and save them in directory, everything is done but firefox stills save files in User download folder e.g. `C:\users\root\Downloads` the function in class PyWebBot ``` @staticmethod def FirefoxProfile(path, handlers): from selenium import webdriver profile = webdriver.FirefoxProf...
There are couple methods to a solution for this problem, 1. Make sure that the path is valid. Use something like, `os.path.exists` or `os.isfile` 2. When the `Firefox` launches with the selenium driver, navigate to `about:config` and check the look up `browser.download.dir`, to make sure there was a change. 3. Finally...
Multiplying across in a numpy array
18,522,216
21
2013-08-29T22:53:00Z
18,522,281
27
2013-08-29T23:00:10Z
[ "python", "arrays", "numpy" ]
I'm trying to multiply each of the terms in a 2D array by the corresponding terms in a 1D array. This is very easy if I want to multiply every column by the 1D array, as shown in the [numpy.multiply](http://docs.scipy.org/doc/numpy/reference/generated/numpy.multiply.html) function. But I want to do the opposite, multip...
Normal multiplication like you showed: ``` >>> import numpy as np >>> m = np.array([[1,2,3],[4,5,6],[7,8,9]]) >>> c = np.array([0,1,2]) >>> m * c array([[ 0, 2, 6], [ 0, 5, 12], [ 0, 8, 18]]) ``` If you add an axis, it will multiply the way you want: ``` >>> m * c[:, np.newaxis] array([[ 0, 0, 0]...
Multiplying across in a numpy array
18,522,216
21
2013-08-29T22:53:00Z
18,522,755
12
2013-08-29T23:50:44Z
[ "python", "arrays", "numpy" ]
I'm trying to multiply each of the terms in a 2D array by the corresponding terms in a 1D array. This is very easy if I want to multiply every column by the 1D array, as shown in the [numpy.multiply](http://docs.scipy.org/doc/numpy/reference/generated/numpy.multiply.html) function. But I want to do the opposite, multip...
You could also use matrix multiplication (aka dot product): ``` a = [[1,2,3],[4,5,6],[7,8,9]] b = [0,1,2] c = numpy.diag(b) numpy.dot(c,a) ``` Which is more elegant is probably a matter of taste.
Multiplying across in a numpy array
18,522,216
21
2013-08-29T22:53:00Z
18,523,476
10
2013-08-30T01:23:44Z
[ "python", "arrays", "numpy" ]
I'm trying to multiply each of the terms in a 2D array by the corresponding terms in a 1D array. This is very easy if I want to multiply every column by the 1D array, as shown in the [numpy.multiply](http://docs.scipy.org/doc/numpy/reference/generated/numpy.multiply.html) function. But I want to do the opposite, multip...
Yet another trick (as of v1.6) ``` A=np.arange(1,10).reshape(3,3) b=np.arange(3) np.einsum('ij,i->ij',A,b) ``` I'm proficient with the numpy broadcasting (`newaxis`), but I'm still finding my way around this new `einsum` tool. So I had play around a bit to find this solution. Timings (using Ipython timeit): ``` ei...
CPython memory allocation
18,522,574
14
2013-08-29T23:30:31Z
18,523,553
18
2013-08-30T01:33:37Z
[ "python", "memory-management", "cpython" ]
This is a post inspired from [this comment](http://stackoverflow.com/questions/18520825/defaultdict-one-step-initialization/18520982?noredirect=1#comment27237819_18520982) about how memory is allocated for objects in CPython. Originally, this was in the context of creating a list and appending to it in a for loop *vis ...
Much of this is answered in the [Memory Management](http://docs.python.org/3/c-api/memory.html) chapter of the C API documentation. Some of the documentation is vaguer than you're asking for. For further details, you'd have to turn to the source code. And nobody's going to be willing to do that unless you pick a speci...
Why is eval('pass') a SyntaxError?
18,523,117
3
2013-08-30T00:36:00Z
18,523,135
9
2013-08-30T00:38:33Z
[ "python", "eval" ]
I was trying to temporarily null out a string I was passing to `eval` to do nothing (I didn't remove it because preserving the order was important for my hacky profile script), and was somewhat miffed that when I gave it `'pass'` it dumped on me, likewise with an empty string or some equivalent do-nothing statement. `...
Quoting from [eval's documentation](http://docs.python.org/2/library/functions.html#eval): "The expression argument is parsed and evaluated as a Python expression". Then, `pass` is a statement, not an expression.
Installing jpype in Mountain Lion
18,524,501
6
2013-08-30T03:36:17Z
18,966,783
9
2013-09-23T19:00:42Z
[ "java", "python", "osx", "jpype" ]
I am trying to install jpype in Mountain Lion. I followed all the steps suggested in this post: [How to install JPype on OS X Lion to use with Neo4j?](http://stackoverflow.com/questions/8525193/how-to-install-jpype-on-os-x-lion-to-use-with-neo4j) However, there is a glitch with Mountain Lion. I have modified the `setu...
This is on a system running OSX 10.8.5. I modified the setup.py for `JPype-0.5.4.2` and added an element to the end of the `self.includeDirs` list which is created in the function `setupInclusion`. This function is declared at line 61 for this particular version of JPype. ``` def setupInclusion(self): ...
Flask alternatives to achieve true multi-threading?
18,525,856
8
2013-08-30T05:49:45Z
21,176,422
18
2014-01-17T01:44:24Z
[ "python", "multithreading", "flask" ]
I had implemented a multi-threaded web server using the Flask micro framework. Basically, my server has a task queue and a thread pool. Hence, it can handle multiple requests. Since Flask is implemented in Python and Python threads are not truly concurrent, my web app is a bit laggy. Are there are any alternatives to ...
I came across this question and I was a little disappointed nobody had pointed out how flask (and most python web apps are *meant* to be deployed). See: <http://flask.pocoo.org/docs/deploying/#deployment> My preferred deployment option is the super-simple [Tornado](http://www.tornadoweb.org) which works equally well o...
python objects : digging deeper
18,526,251
3
2013-08-30T06:18:51Z
18,526,277
8
2013-08-30T06:21:03Z
[ "python" ]
Hi all I know what this code does: **1.] My first problem** ``` x = 4 y = x ``` But what about this. Why same addresses even for this case? ``` x = 4 y = 4 id(x) 12345678 id(y) 12345678 ``` **2.] My second problem** ``` x = 42 y = x x = x + 1 print x # Prints 43 print y # Prints 42 x = [1, 2, 3] y = x x[0...
1. Small integers are [cached in CPython](http://stackoverflow.com/questions/11476190/why-0-6-is-6-false), that's why their id's are same. 2. Integers are immutable, so modifying(i.e assigning it to a new object) one will not affect the other references. 3. Lists are mutable, so modifying any reference(in-place modific...
What is the meaning of True == True != False in Python and how to find out?
18,528,431
4
2013-08-30T08:35:17Z
18,528,643
9
2013-08-30T08:46:31Z
[ "python", "bytecode", "precedence" ]
I actually needed `xor` for my solution, but while thinking on it, I started wondering about the question above. What is the meaning of `True == True != False`? Looking at the documentation I suppose it's `True == True and True != False`, but I'd like a more general and certain approach. How do I quickly get readable ...
It's called [*operator chaining*](http://docs.python.org/2/reference/expressions.html#not-in). Whenever you have an expression like `A op1 B op2 C` with `op1` and `op2` comparisons it is "translated" to `A op1 B and B op2 C`. (Actually it does evaluate `B` only once). Note: comparisons operator include `in`, `not in`,...
python tornado send message to all connections
18,531,849
8
2013-08-30T11:31:11Z
18,532,575
8
2013-08-30T12:08:58Z
[ "python", "tornado" ]
I have this simple code for a websocket server: ``` import tornado.httpserver import tornado.websocket import tornado.ioloop import tornado.web import time class WSHandler(tornado.websocket.WebSocketHandler): def open(self): print 'New connection was opened' self.write_message("Conn!") def on_message(se...
At the first your should start to manage incoming connections manualy, that's cause tornado don't do that from the box. As naive implementation you could do like this: ``` class WSHandler(tornado.websocket.WebSocketHandler): connections = set() def open(self): self.connections.add(self) print 'New conne...
Opening and reading an excel .xlsx file in python
18,532,893
5
2013-08-30T12:26:06Z
18,533,282
9
2013-08-30T12:45:58Z
[ "python", "excel", "python-2.7", "pandas", "xlrd" ]
I'm trying to open an excel .xlsx file with python but am unable to find a way to do it, I've tried using pandas but it's wanting to use a library called NumPy I've tried to install numpy but it still can't find numpy. I've also tried using the xlrd library but I get the following traceback: ``` Traceback (most recen...
Maybe you could export your .xlsx to a .csv file? Then you could try: ``` import csv with open('file.csv','rb') as file: contents = csv.reader(file) [x for x in contents] ``` This may be useful: <http://docs.python.org/2/library/csv.html#csv.reader> Hope that helps! EDIT: If you want to locate a spectific...
xmlrpc response datatype long possible?
18,533,309
4
2013-08-30T12:47:26Z
18,860,433
9
2013-09-17T21:44:36Z
[ "python", "python-2.7", "xml-rpc", "xmlrpclib", "simplexmlrpcserver" ]
Is there any possibility to allow xmlrpc extensions (datatype `long int`) for the Python simplexmlrpc server? The client uses Apache xmlrpc, which [allows 8 byte integers](http://ws.apache.org/xmlrpc/types.html). Basically, I'm using the [example code](http://docs.python.org/2/library/simplexmlrpcserver.html) with th...
The second line in the following snippet changes the marshalling for long integers to emit `<i8>` instead of `<int>`. Yes, it's not too pretty, but should work and fix the problem. ``` >>> import xmlrpclib >>> xmlrpclib.Marshaller.dispatch[type(0L)] = lambda _, v, w: w("<value><i8>%d</i8></value>" % v) >>> xmlrpclib.d...
Getting the first non None value from list
18,533,620
11
2013-08-30T13:04:10Z
18,533,669
35
2013-08-30T13:06:16Z
[ "python", "list" ]
Given a list, is there a way to get the first non-None value? And, if so, what would be the pythonic way to do so? For example, I have: * `a = objA.addreses.country.code` * `b = objB.country.code` * `c = None` * `d = 'CA'` In this case, if a is None, then I would like to get b. If a and b are both None, the I would ...
You can use [`next()`](https://docs.python.org/2/library/functions.html#next): ``` >>> a = [None, None, None, 1, 2, 3, 4, 5] >>> next(item for item in a if item is not None) 1 ``` If the list contains only Nones, it will throw `StopIteration` exception. If you want to have a default value in this case, do this: ``` ...
Error when creating a new text file with python?
18,533,621
57
2013-08-30T13:04:11Z
18,533,704
90
2013-08-30T13:07:38Z
[ "python", "file", "python-3.x", "file-io" ]
This function doesn't work and raises an error. Do I need to change any arguments or parameters? ``` import sys def write(): print('Creating new text file') name = input('Enter name of text file: ')+'.txt' # Name of text file coerced with +.txt try: file = open(name,'r+') # Trying to create ...
If the file does not exists, `open(name,'r+')` will fail. You can use `open(name, 'w')`, which creates the file if the file does not exist, but it will truncate the existing file. Alternatively, you can use `open(name, 'a')`; this will create the file if the file does not exist, but will not truncate the existing fil...
Python: strip a wildcard word
18,533,636
2
2013-08-30T13:04:54Z
18,533,835
10
2013-08-30T13:14:07Z
[ "python", "regex", "string", "wildcard" ]
I have strings with words separated by points. Example: ``` string1 = 'one.two.three.four.five.six.eight' string2 = 'one.two.hello.four.five.six.seven' ``` How do I use this string in a python method, assigning one word as wildcard (because in this case for example the third word varies). I am thinking of regular ex...
Use [`re.sub(pattern, '', original_string)`](http://docs.python.org/2/library/re.html#re.sub) to remove matching part from *original\_string*: ``` >>> import re >>> string1 = 'one.two.three.four.five.six.eight' >>> string2 = 'one.two.hello.four.five.six.seven' >>> re.sub(r'^one\.two\.\w+\.four', '', string1) '.five.si...
Python: modules and packaging - why isn't __init__.py file executed before __main__.py?
18,536,462
7
2013-08-30T15:24:36Z
18,536,602
8
2013-08-30T15:31:47Z
[ "python", "module", "python-module" ]
I have a python program that is entirely contained in a directory with the following structure: ``` myprog/ ├── __init__.py ├── __main__.py ├── moduleone.py └── moduletwo.py ``` I would like to be able to package this and distribute it so that another developer can do `pip install -e /path/to/...
> Do I have to import these functions into `__main__` somehow? Yes. Only items in `builtins` are available without an import. Something like: ``` from myprog import func1, func2 ``` should do the trick. If you don't have `myprog` installed in the normal python path then you can work around it with something like: ...
Python: modules and packaging - why isn't __init__.py file executed before __main__.py?
18,536,462
7
2013-08-30T15:24:36Z
18,537,751
12
2013-08-30T16:42:02Z
[ "python", "module", "python-module" ]
I have a python program that is entirely contained in a directory with the following structure: ``` myprog/ ├── __init__.py ├── __main__.py ├── moduleone.py └── moduletwo.py ``` I would like to be able to package this and distribute it so that another developer can do `pip install -e /path/to/...
The `__init__.py` is only loaded when you are import the *package*. You are instead treating the directory as a *script*, by executing the directory. You can still treat the package as a script, instead of the directory however. To both treat the directory as a package *and* as the main script, by using the `-m` switc...