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
Why are certain elements of this python list ignored?
4,023,739
2
2010-10-26T12:42:42Z
4,023,756
10
2010-10-26T12:45:11Z
[ "python" ]
I'm new to Python, and i'm struggling to understand the output of this simple program: ``` list = os.listdir(os.getcwd()) print(list) print() for element in list: print(element) if 'txt' not in element: list.remove(element) ``` Which gives me this output : ``` ['examples_list.txt', 'generate_patterns.py', 'l...
You cannot remove elements from the list while looping through it. Try and loop over a copy of the list, or create a new one with only the elements you want to keep. See also [Python strange behavior in for loop or lists](http://stackoverflow.com/questions/742371/python-strange-behavior-in-for-loop-or-lists)
How to get source line number from a Python generator object?
4,024,609
2
2010-10-26T14:18:06Z
4,024,725
7
2010-10-26T14:30:03Z
[ "python", "generator" ]
Here is an example: ``` def g(): yield str('123') yield int(123) yield str('123') o = g() while True: v = o.next() if isinstance( v, str ): print 'Many thanks to our generator...' else: # Or GOD! I don't know what to do with this type raise TypeError( '%s:%d Unknown yield value type %s.' % \ ...
Your generator object "o" in this case has all the information you want. You can paste your example into a Python console, and inspect with `dir` both the function "g" and the generator "o". The generator has the attributes "gi\_code" and "gi\_frame" which contain the information you want: ``` >>> o.gi_code.co_filena...
Python file.write creating extra carriage return
4,025,760
6
2010-10-26T16:31:17Z
4,025,988
13
2010-10-26T16:57:47Z
[ "python", "windows", "eol" ]
I'm writing a series of SQL statements to a file using python. The template string looks like: ``` store_insert = '\tinsert stores (storenum, ...) values (\'%s\', ...)' ``` I'm writing to the file like so: ``` for line in source: line = line.rstrip() fields = line.split('\t') script.write(store_insert % ...
`\n` is converted to `os.linesep` for files opened in text-mode. So when you write `os.linesep` to a text-mode file on Windows, you write `\r\n`, and the `\n` gets converted resulting in `\r\r\n`. See also [the docs](http://docs.python.org/library/os.html#os.linesep): > Do not use os.linesep as a line terminator when...
Differences Between Python and C++ Constructors
4,025,913
14
2010-10-26T16:49:58Z
4,026,017
15
2010-10-26T17:01:24Z
[ "c++", "python", "constructor" ]
I've been learning more about Python recently, and as I was going through the excellent [Dive into Python](http://diveintopython3.org) the author noted [here](http://diveintopython3.org/iterators.html#init-method) that the `__init__` method is not technically a constructor, even though it generally functions like one. ...
The distinction that the author draws is that, as far as the Python language is concerned, you have a valid object of the specified type *before* you even enter `__init__`. Therefore it's not a "constructor", since in C++ and theoretically, a constructor turns an invalid, pre-constructed object into a "proper" complete...
single list to dictionary
4,026,080
3
2010-10-26T17:09:13Z
4,026,118
9
2010-10-26T17:14:11Z
[ "python", "list", "dictionary" ]
I have this list: ``` single = ['key1', 'value1', 'key2', 'value2', 'key3', 'value3'] ``` What's the best way to create a dictionary from this? Thanks.
``` >>> single = ['key1', 'value1', 'key2', 'value2', 'key3', 'value3'] >>> dict(zip(single[::2], single[1::2])) {'key3': 'value3', 'key2': 'value2', 'key1': 'value1'} ```
single list to dictionary
4,026,080
3
2010-10-26T17:09:13Z
4,026,254
7
2010-10-26T17:31:34Z
[ "python", "list", "dictionary" ]
I have this list: ``` single = ['key1', 'value1', 'key2', 'value2', 'key3', 'value3'] ``` What's the best way to create a dictionary from this? Thanks.
Similar to SilentGhost's solution, without building temporary lists: ``` >>> from itertools import izip >>> single = ['key1', 'value1', 'key2', 'value2', 'key3', 'value3'] >>> si = iter(single) >>> dict(izip(si, si)) {'key3': 'value3', 'key2': 'value2', 'key1': 'value1'} ```
What is C#'s version of the GIL?
4,026,238
8
2010-10-26T17:29:54Z
4,026,276
11
2010-10-26T17:33:54Z
[ "c#", "java", "python", "gil" ]
In the current implementation of CPython, there is an object known as the "GIL" or "Global Interpreter Lock". It is essentially a mutex that prevents two Python threads from executing Python code at the same time. This prevents two threads from being able to corrupt the state of the Python interpreter, but also prevent...
Most other languages that support threading don't have an equivalent of the Python GIL; they require you to use mutexes, either implicitly or explicitly.
OSS implementation of Google app engine?
4,026,816
6
2010-10-26T18:33:20Z
4,026,917
9
2010-10-26T18:44:55Z
[ "java", "python", "google-app-engine", "cloud" ]
After Google pioneered map-reduce the community came out with Hadoop, is there a OSS Google AppEngine project? Or, put another way: What is the best off the shelf python or java cloud software? Specifically I'm looking for something that I could host on my own and have some sort of auto-scale feature (more frequently ...
I'm not sure what you mean by having an OSS version of Google app engine, but [AppScale](http://code.google.com/p/appscale/) is an open source framework for running Google app engine apps. You'll have to provide your own cloud, however. I think with the right technical expertise and hardware you could host this on you...
Confusing expression in python
4,027,103
2
2010-10-26T19:08:00Z
4,027,126
8
2010-10-26T19:11:10Z
[ "python", "list", "slice" ]
If I have the list: ``` lista=[99, True, "Una Lista", [1,3]] ``` What does the following expression mean? ``` mi_var = lista[0:4:2] ```
The syntax `lista[0:4:2]` is called [extended slice](http://docs.python.org/release/2.3.5/whatsnew/section-slices.html) syntax and returns a slice of the list consisting of the elements from index 0 (inclusive) to 4 (exclusive), but only including the even indexes (step = 2). In your example it will give `[99, "Una Li...
Vim: Use shorter textwidth in comments and docstrings
4,027,222
20
2010-10-26T19:22:30Z
4,028,423
11
2010-10-26T22:04:01Z
[ "python", "vim", "pep8", "autocmd" ]
From the mighty [PEP 8](http://www.python.org/dev/peps/pep-0008/): > [P]lease limit all lines to a maximum of 79 characters. For flowing long blocks of text (docstrings or comments), limiting the length to 72 characters is recommended. When editing Python code in Vim, I set my `textwidth` to 79, and Vim automatically...
So, I've never done any Vim scripting before, but based on [this question about doing something similar in C](http://stackoverflow.com/questions/3475072/vim-different-textwidth-for-multiline-c-comments) and [this tip for checking if you're currently in a comment](http://vim.wikia.com/wiki/Check_for_comments_independent...
Is it ok to skip "return None"?
4,027,586
25
2010-10-26T20:12:38Z
4,027,624
36
2010-10-26T20:17:42Z
[ "python", "function", "return-value" ]
I wonder if it is bad manner to skip `return None`, when it is not needed. Example: ``` def foo1(x): if [some condition]: return Baz(x) else: return None def foo2(x): if [some condition]: return Baz(x) bar1 = foo1(x) bar2 = foo2(x) ``` In both cases, when condition is false, fun...
Like you said, `return None` is (almost) never needed. But you should consider that the *intention* of your code is much clearer with an explicit `return None`. Remember: a piece of code also needs to be readable by human-beings, and being explicit usually helps.
Is it ok to skip "return None"?
4,027,586
25
2010-10-26T20:12:38Z
4,027,909
18
2010-10-26T20:51:44Z
[ "python", "function", "return-value" ]
I wonder if it is bad manner to skip `return None`, when it is not needed. Example: ``` def foo1(x): if [some condition]: return Baz(x) else: return None def foo2(x): if [some condition]: return Baz(x) bar1 = foo1(x) bar2 = foo2(x) ``` In both cases, when condition is false, fun...
To expound on what others have said, I use a `return None` if the function is supposed to return a value. In Python, all functions return a value, but often we write functions that only ever return None, because their return value is ignored. In some languages, these would be called procedures. So if a function is sup...
Pythonic Boolean Conversion
4,027,773
3
2010-10-26T20:37:17Z
4,027,830
8
2010-10-26T20:43:27Z
[ "python", "database", "boolean" ]
I'm writing a module to act on data being sent to a database from Python. Since boolean is not a SQL datatype, those values have to be converted to some pre-defined value. I decided while defining the tables that I would use 'T' and 'F' in a varchar(1) field as my Boolean stand in. In attempting to make this conversio...
You can use `is`: ``` if SQLParameters[i] is True: SQLParameters[i] = 'T' elif SQLParameters[i] is False: SQLParameters[i] = 'F' ```
Any ideas about the best work around for __new__ losing its arguments?
4,028,321
3
2010-10-26T21:49:39Z
4,028,415
9
2010-10-26T22:02:54Z
[ "python" ]
So, I only realised today that `__new__` is deprecated for receiving arguments, as of python 2.6 (it isn't mentioned in the documentation, which is also not true in terms of the behavior of `__new__` calling `__init__` as far as I can see). This means my functional code has started raising warnings, and I want to rid m...
`__new__` is not "deprecated for receiving arguments". What changed in Python 2.6 is that `object.__new__`, the `__new__` method of the *object* class, no longer ignores any arguments it's passed. (`object.__init__` also doesn't ignore the arguments anymore, but that's just a warning in 2.6.) You can't use `object` as ...
How do I download a zip file in python using urllib2?
4,028,697
21
2010-10-26T22:50:39Z
4,028,894
34
2010-10-26T23:39:33Z
[ "python", "urllib2" ]
Two part question. I am trying to download multiple archived Cory Doctorow podcasts from the internet archive. The old one's that do not come into my iTunes feed. I have written the script but the downloaded files are not properly formatted. Q1 - What do I change to download the zip mp3 files? Q2 - What is a better wa...
Here's how I'd deal with the url building and downloading. I'm making sure to name the file as the basename of the url (the last bit after the trailing slash) and I'm also using the `with` clause for opening the file to write to. This uses a [ContextManager](http://docs.python.org/library/stdtypes.html#typecontextmanag...
Simplify this python code
4,028,844
5
2010-10-26T23:17:09Z
4,028,950
11
2010-10-26T23:53:08Z
[ "python" ]
I've written a program to check if my thought about solution on paper is right (and it is). The task: how many zeros is in the back of multiplication of all numbers from 10 to 200. It is 48 and it is a simple to calculate manually. I never write on python seriously and this is what I get: ``` mul = 1 for i in range...
A straight-forward implementation that doesn't involve calculating the factorial (so that it works with big numbers, ie 2000000!) **(edited)**: ``` fives = 0 twos = 0 for i in range(10, 201): while i % 5 == 0: fives = fives + 1 i /= 5 while i % 2 == 0: twos = twos + 1 i /= 2 print(min(fiv...
Testing floating point equality
4,028,889
30
2010-10-26T23:38:37Z
4,029,332
8
2010-10-27T01:32:24Z
[ "python", "comparison", "floating-point" ]
Is there a function to test floating point approximate equality in python? Something like, ``` def approx_equal(a, b, tol): return abs(a - b) < tol ``` My use case is similar to how Google's C++ testing library, gtest.h, defines `EXPECT_NEAR`. Here is an example: ``` def bernoulli_fraction_to_angle(fraction):...
> Is there a function to test floating point approximate equality in python? There can't be **a** function, since the definition depends on context. ``` def eq( a, b, eps=0.0001 ): return abs(a - b) <= eps ``` Doesn't always work. There are circumstances where ``` def eq( a, b, eps=0.0001 ): return abs( a ...
Testing floating point equality
4,028,889
30
2010-10-26T23:38:37Z
4,029,392
18
2010-10-27T01:47:20Z
[ "python", "comparison", "floating-point" ]
Is there a function to test floating point approximate equality in python? Something like, ``` def approx_equal(a, b, tol): return abs(a - b) < tol ``` My use case is similar to how Google's C++ testing library, gtest.h, defines `EXPECT_NEAR`. Here is an example: ``` def bernoulli_fraction_to_angle(fraction):...
Another approach is to compute the [relative change](http://en.wikipedia.org/wiki/Relative_difference) (or relative difference) of the two numbers, which is "used to compare two quantities while taking into account the 'sizes' of the things being compared". The two [formulas](https://en.wikipedia.org/wiki/Relative_chan...
Testing floating point equality
4,028,889
30
2010-10-26T23:38:37Z
4,102,600
38
2010-11-05T00:21:42Z
[ "python", "comparison", "floating-point" ]
Is there a function to test floating point approximate equality in python? Something like, ``` def approx_equal(a, b, tol): return abs(a - b) < tol ``` My use case is similar to how Google's C++ testing library, gtest.h, defines `EXPECT_NEAR`. Here is an example: ``` def bernoulli_fraction_to_angle(fraction):...
* For testing numbers, there are `nose.tools.assert_almost_equal` and equivalently `unittest.assertAlmostEqual` * For testing numbers or arrays, there is `numpy.testing.assert_allclose` * For comparing numbers, there is `math.isclose` as per [PEP 485](https://www.python.org/dev/peps/pep-0485/) since Python 3.5. * For c...
Subtracting the current and previous item in a list
4,029,436
3
2010-10-27T01:58:19Z
4,036,607
12
2010-10-27T18:51:12Z
[ "python" ]
It is very common to write a loop and remember the previous. I want a generator that does that for me. Something like: ``` import operator def foo(it): it = iter(it) f = it.next() for s in it: yield f, s f = s ``` Now subtract pair-wise. ``` L = [0, 3, 4, 10, 2, 3] print list(foo(L)) p...
``` [y - x for x,y in zip(L,L[1:])] ```
Python: Correct way to initialize when superclasses accept different arguments?
4,029,550
18
2010-10-27T02:26:09Z
4,029,681
10
2010-10-27T03:02:04Z
[ "python", "multiple-inheritance" ]
If I've got three classes like this: ``` class BaseClass(object): def __init__(self, base_arg, base_arg2=None): ... class MixinClass(object): def __init__(self, mixin_arg): ... class ChildClass(BaseClass, MixinClass): def __init__(self, base_arg, mixin_arg, base_arg2=None): ??? ``...
Basically, in Python, [you *can't* support this type of inheritance safely](http://fuhm.net/super-harmful/). Luckily you almost never need to, since most methods don't care *what* something is, only that it supports a particular interface. Your best bet is to use composition or aggregation: have your class inherit from...
How do I derive from hashlib.sha256 in Python?
4,029,632
3
2010-10-27T02:50:16Z
4,029,716
7
2010-10-27T03:12:43Z
[ "python", "security", "cryptography" ]
A naive attempt fails miserably: ``` import hashlib class fred(hashlib.sha256): pass -> TypeError: Error when calling the metaclass bases cannot create 'builtin_function_or_method' instances ``` Well, it turns out that hashlib.sha256 is a callable, not a class. Trying something a bit more creative doesn'...
Make a new class, derive from object, create a hashlib.sha256 member var in **init**, then define methods expected of a hash class and proxy to the same methods of the member variable. Something like: ``` import hashlib class MyThing(object): def __init__(self): self._hasher = hashlib.sha256() def d...
Multiple configuration files with Python ConfigParser
4,029,946
13
2010-10-27T04:21:30Z
4,057,933
17
2010-10-30T08:43:12Z
[ "python", "configuration" ]
When calling ConfigParser.read you are allowed to pass a list of strings corresponding to potential locations for configuration files and the function returns a list of those files that were successfully read. What is the default behaviour when multiple configuration files are loaded that have overlapping sections/key...
After getting around to testing it, ConfigParser overwrites the keys with each successive file, the order in which the files are read is determined by the order of the file names in the list passed to ConfigParser.read
Why doesn't a %en0 suffix work to connect a link-local IPv6 TCP socket in Python?
4,030,269
6
2010-10-27T05:38:36Z
4,030,559
11
2010-10-27T06:33:45Z
[ "python", "tcp", "ipv6", "link-local", "scope-id" ]
A week or so ago someone on StackOverflow [asked](http://stackoverflow.com/questions/3895570/why-the-connect-failed-for-ipv6-at-python) why their Python code for connecting to an IPv6 link-local address wasn't working, and I replied that since it was a link-local address they needed to add a %en0 (or whatever the desir...
This is the correct way to do an ipv6 connection: ``` >>> addrinfo = getaddrinfo('fe80::225:ff:fecd:5aa0%en0', 2001, AF_INET6, SOCK_STREAM) >>> addrinfo [(30, 1, 6, '', ('fe80::225:ff:fecd:5aa0%en0', 2001, 0, 4))] >>> (family, socktype, proto, canonname, sockaddr) = addrinfo[0] >>> s = socket(family, socktype, proto) ...
How to set PATH to use Java and Python simultaneously
4,030,440
2
2010-10-27T06:14:02Z
4,030,443
8
2010-10-27T06:14:38Z
[ "java", "python", "windows", "path" ]
I was just wondering if there was any way to set to `%PATH%` variables so I can compile my Java code, along with my Python code? For instance.. PATH is currently `C:\ ... JDK_bin blah blah`, and that's it. To run my python code, I have to change my path variable completely. Any answers?
Just add a semicolon after your present path, and write the new one after that. ``` set PATH="C:\Program Files\Java\blah\blah";C:\Python31\;C:\Windows\System32 ``` etc...
How to set PATH to use Java and Python simultaneously
4,030,440
2
2010-10-27T06:14:02Z
4,030,461
7
2010-10-27T06:17:22Z
[ "java", "python", "windows", "path" ]
I was just wondering if there was any way to set to `%PATH%` variables so I can compile my Java code, along with my Python code? For instance.. PATH is currently `C:\ ... JDK_bin blah blah`, and that's it. To run my python code, I have to change my path variable completely. Any answers?
You need to **add** the path to python exe to your existing `PATH` variable which already has path to Java exes and many more paths in it. ``` path = %PATH%;C:\path\to\python\bin ``` You can also do this using windows [**GUI**](http://www.computerhope.com/issues/ch000549.htm). Note that doing an absolute assignment ...
Using Python to read images from a www.flickr.com account
4,030,824
2
2010-10-27T07:20:14Z
4,030,839
8
2010-10-27T07:22:22Z
[ "python", "flickr" ]
Ok, so I need to build this application where I'll read images from a www.flickr.com account and use the images in my Python app. How will I do that? Any ideas? Thanks.
You could use one of the various flickr python libraries : * <http://code.google.com/p/flickrpy/> * <http://pypi.python.org/pypi/Flickr.API/> * <http://stuvel.eu/projects/flickrapi> And for a good overview of flickr API, always look at the docs: <http://www.flickr.com/services/api/> An example: ``` import flickrapi...
Initialise class object by name
4,030,982
22
2010-10-27T07:50:00Z
4,031,043
38
2010-10-27T07:58:09Z
[ "python" ]
Since everything in python is an object, i was wondering if there was a way i could initialise a class object using the name of the class for example, ``` class Foo: """Class Foo""" ``` How could i access this class by "Foo", ie something like `c = get_class("Foo")`
If the class is in your scope: ``` get_class = lambda x: globals()[x] ``` If you need to get a class from a module, you can use `getattr`: ``` import urllib2 handlerClass = getattr(urllib2, 'HTTPHandler') ```
Why is there a need for Twisted?
4,031,402
10
2010-10-27T08:52:20Z
4,033,221
11
2010-10-27T12:36:06Z
[ "python", "asynchronous", "twisted" ]
I have been playing around with the twisted framework for about a week now(more because of curiosity rather than having to use it) and its been a lot of fun doing event driven asynchronous network programming. However, there is something that I fail to understand. The twisted documentation starts off with > Twisted i...
In a comment on another answer, you say "Every library is supposed to have ...". "Supposed" by whom? Having use-cases is certainly a nice way to nail down your requirements, but it's not the only way. It also doesn't make sense to talk about the use-cases for all of Twisted at once. There is no use case that justifies ...
Why is PyQt connect() syntax so verbose?
4,031,489
8
2010-10-27T09:03:44Z
4,032,125
27
2010-10-27T10:18:50Z
[ "python", "qt", "qt4", "pyqt", "pyqt4" ]
I'm just learning PyQt and looking at the Signals and Slots mechanism. I'm a bit baffled by the verbose syntax. Why do we have: ``` self.connect(dial, SIGNAL("valueChanged(int)"), spinbox.setValue) ``` I would much prefer to write the following: ``` self.connect(dial.valueChanged, spinbox.setValue) ``` Can anyone t...
You can use PyQt's [new style signals](http://qt-project.org/wiki/Signals_and_Slots_in_PySide) which are less verbose: ``` self.connect(dial, SIGNAL("valueChanged(int)"), spinbox.setValue) ``` Becomes: ``` dial.valueChanged.connect(spinbox.setValue) ```
Python: 'import node.py' raises "No module named py"-error
4,032,780
2
2010-10-27T11:36:55Z
4,032,786
9
2010-10-27T11:38:20Z
[ "python", "python-import" ]
I have a file main.py like this: ``` import node.py [my code...] ``` and a node.py like this: ``` [more of my code] ``` When executing main.py, I get this error: ``` File "/home/loldrup/repo/trunk/src/src/main.py", line 2, in <module> import node.py ImportError: No module named py ```
You should just say `import node`. The `.` in the name makes python think you want to load a submodule named `py` of the package`node`, hence the error. All of this is explained in detail in the [Python Tutorial](http://docs.python.org/tutorial/modules.html).
Is it safe to use SQLalchemy with gevent?
4,033,475
12
2010-10-27T13:01:07Z
4,049,187
16
2010-10-29T05:19:07Z
[ "python", "thread-safety", "sqlalchemy", "gevent" ]
I know that some database drivers and other libraries providing connection to external services are incompatible with coroutine-based network libraries. However, I couldn't find out if SQLAlchemy can be safely used with such libraries (namely, **gevent**), and if any workarounds should be applied to exclude possible er...
Did you try searching [gevent google group for SQLAlchemy](https://groups.google.com/forum/#!searchin/gevent/SQLAlchemy)? I found this report of using [SQLAlchemy + mysql-connector](http://groups.google.com/group/gevent/msg/0c3e638532a63a6f) successfully and this of using [SQLAlchemy + psycopg2](http://groups.google.c...
How to limit program's execution time when using subprocess?
4,033,578
6
2010-10-27T13:12:06Z
4,033,997
9
2010-10-27T13:52:22Z
[ "python", "subprocess", "kill" ]
I want to using subprocess to run a program, but I need to limit the execution time. For example, if it runs more than 2 seconds, I want to kill it. For common programs, kill() works well. But if I try to run `/usr/bin/time something`, kill() can't really kill the program. But my code below seems not works well, the ...
If you're using Python 2.6 or later, you can use the [multiprocessing](http://docs.python.org/library/multiprocessing.html) module. ``` from multiprocessing import Process def f(): # Stuff to run your process here p = Process(target=f) p.start() p.join(timeout) if p.is_alive(): p.terminate() ``` --- Actual...
Handling lazy JSON in Python - 'Expecting property name'
4,033,633
40
2010-10-27T13:16:20Z
4,033,740
31
2010-10-27T13:26:44Z
[ "python", "json" ]
Using Pythons (2.7) 'json' module I'm looking to process various JSON feeds. Unfortunately some of these feeds do not conform with JSON standards - in specific some keys are not wrapped in double speech-marks ("). This is causing Python to bug out. Before writing an ugly-as-hell piece of code to parse and repair the i...
You're trying to use a JSON parser to parse something that isn't JSON. Your best bet is to get the creator of the feeds to fix them. I understand that isn't always possible. You might be able to fix the data using regexes, depending on how broken it is: ``` j = re.sub(r"{\s*(\w)", r'{"\1', j) j = re.sub(r",\s*(\w)", ...
Handling lazy JSON in Python - 'Expecting property name'
4,033,633
40
2010-10-27T13:16:20Z
10,591,575
16
2012-05-14T21:51:27Z
[ "python", "json" ]
Using Pythons (2.7) 'json' module I'm looking to process various JSON feeds. Unfortunately some of these feeds do not conform with JSON standards - in specific some keys are not wrapped in double speech-marks ("). This is causing Python to bug out. Before writing an ugly-as-hell piece of code to parse and repair the i...
Another option is to use the [demjson](http://deron.meranda.us/python/demjson/) module which can parse json in non-strict mode.
Handling lazy JSON in Python - 'Expecting property name'
4,033,633
40
2010-10-27T13:16:20Z
21,643,508
9
2014-02-08T07:54:28Z
[ "python", "json" ]
Using Pythons (2.7) 'json' module I'm looking to process various JSON feeds. Unfortunately some of these feeds do not conform with JSON standards - in specific some keys are not wrapped in double speech-marks ("). This is causing Python to bug out. Before writing an ugly-as-hell piece of code to parse and repair the i...
The regular expressions pointed out by Ned and cheeseinvert don't take into account when the match is inside a string. See the following example (using cheeseinvert's solution): ``` >>> fixLazyJsonWithRegex ('{ key : "a { a : b }", }') '{ "key" : "a { "a": b }" }' ``` The problem is that the expected output is: ```...
How do I access command line arguments in Python?
4,033,723
73
2010-10-27T13:24:32Z
4,033,743
98
2010-10-27T13:27:12Z
[ "python", "command-line" ]
I use python to create my project settings setup, but I need help getting the command line arguments. I tried this on the terminal: ``` $python myfile.py var1 var2 var3 ``` In my Python file, I want to use all variables that are input.
[Python tutorial explains it](http://docs.python.org/tutorial/stdlib.html#command-line-arguments): ``` import sys print(sys.argv) ``` More specifically, if you run `python example.py one two three`: ``` >>> import sys >>> print(sys.argv) ['example.py', 'one', 'two', 'three'] ```
How do I access command line arguments in Python?
4,033,723
73
2010-10-27T13:24:32Z
4,033,791
38
2010-10-27T13:30:57Z
[ "python", "command-line" ]
I use python to create my project settings setup, but I need help getting the command line arguments. I tried this on the terminal: ``` $python myfile.py var1 var2 var3 ``` In my Python file, I want to use all variables that are input.
``` import sys sys.argv[1:] ``` will give you a list of arguments (not including the name of the python file)
How do I access command line arguments in Python?
4,033,723
73
2010-10-27T13:24:32Z
34,464,437
9
2015-12-25T16:19:58Z
[ "python", "command-line" ]
I use python to create my project settings setup, but I need help getting the command line arguments. I tried this on the terminal: ``` $python myfile.py var1 var2 var3 ``` In my Python file, I want to use all variables that are input.
You can use `sys.argv` to get the arguments as a list. If you need to access individual elements, you can use ``` sys.argv[i] ``` where `i` is index, `0` will give you the python filename being executed. Any index after that are the arguments passed.
How can I use HTML + Javascript to build a python GUI?
4,034,169
19
2010-10-27T14:09:50Z
4,066,169
8
2010-11-01T01:46:17Z
[ "python", "webkit" ]
I have been experimenting with Appcelerator Titanum yesterday and I think it's cool when it comes to Javascript. Python features on Appcelerator Titanum are so limited (can't use some modules for example). **My question is How can I use html & javascript as a GUI tool for a *real python application* ?** I am running...
If you're after webkit bindings for Python, look at PyQt, which includes Webkit, as well as wxWebkit (<http://wxwebkit.wxcommunity.com/>) if you're using wxWidgets. This lets you embed webkit in a Qt or Wxwidgets app so that you won't have to go through a browser. If you do use this, then you can either use a web serv...
Understanding __call__ and list.sort(key)
4,034,455
5
2010-10-27T14:39:30Z
4,034,549
8
2010-10-27T14:50:48Z
[ "python", "sorting" ]
I have the following code I am trying to understand: ``` >>> class DistanceFrom(object): def __init__(self, origin): self.origin = origin def __call__(self, x): return abs(x - self.origin) >>> nums = [1, 37, 42, 101, 13, 9, -20] >>> nums.sort(key=DistanceFrom(10)) >>> nums [9...
`__call__` in python allows a class to be run as if it's a function. You can try this out manually: ``` >>> dis = DistanceFrom(10) >>> print dis(10), dis(5), dis(0) 0 5 10 >>> ``` What sort does is call that function for every item in your list and uses the returned value as sort key. In this example you'll get a lis...
Understanding __call__ and list.sort(key)
4,034,455
5
2010-10-27T14:39:30Z
4,034,582
7
2010-10-27T14:53:46Z
[ "python", "sorting" ]
I have the following code I am trying to understand: ``` >>> class DistanceFrom(object): def __init__(self, origin): self.origin = origin def __call__(self, x): return abs(x - self.origin) >>> nums = [1, 37, 42, 101, 13, 9, -20] >>> nums.sort(key=DistanceFrom(10)) >>> nums [9...
Here I have defined a function `DistanceFrom()` which can be used in a similar way to your class, but might be easier to follow ``` >>> def DistanceFrom(origin): ... def f(x): ... retval = abs(x - origin) ... print "f(%s) = %s"%(x, retval) ... return retval ... return f ... >>> nums = ...
A good way to make Django geolocation aware? - Django/Geolocation
4,035,195
2
2010-10-27T16:00:23Z
4,035,748
7
2010-10-27T17:05:39Z
[ "python", "django", "geolocation" ]
**I would like to be able to associate various models (Venues, places, landmarks) with a City/Country.** But I am not sure what some good ways of implementing this would be. --- I'm following a simple route, I have implemented a Country and City model. Whenever a new city or country is mentioned it is automatically...
A good starting places would be to get a location dataset from a service like [Geonames](http://www.geonames.org/). There is also [GeoDjango](http://geodjango.org/) which came up in [this question](http://stackoverflow.com/questions/2053971/looking-for-python-django-framework-to-query-geolocation-data-in-db). As you en...
python twisted : retrieve a deferred's execution time
4,035,912
3
2010-10-27T17:25:50Z
4,036,018
7
2010-10-27T17:39:16Z
[ "python", "twisted", "deferred" ]
I would like to know how long a Deferred takes to execute, from the time the first callback is fired to the final result. Any ideas on how to do that, possibly in a non-invasive manner ( meaning no modification on any of the callback functions in order to track the execution time ) ?
If you are running your program with help of "twistd", then it has an option "--profile" which can help you with profiling twisted code. ``` twistd "other options" --profile=statsfile --profiler=cProfile --savestats ``` And to view the stats: ``` import pstats stats = pstats.Stats('statsfile') stats.sort_stats('time...
How can "k in d" be False, but "k in d.keys()" be True?
4,036,114
7
2010-10-27T17:50:10Z
4,036,202
18
2010-10-27T17:59:16Z
[ "python", "dictionary", "python-2.x" ]
I have some python code that's throwing a KeyError exception. So far I haven't been able to reproduce outside of the operating environment, so I can't post a reduced test case here. The code that's raising the exception is iterating through a loop like this: ``` for k in d.keys(): if condition: del d[k] `...
`k in d.keys()` will test equality iteratively for each key, while `k in d` uses `__hash__`, so your `__hash__` may be broken (i.e. it returns different hashes for objects that compare equal).
Efficient way to count unique elements in array in numpy/scipy in Python
4,037,262
15
2010-10-27T20:12:04Z
4,037,371
8
2010-10-27T20:24:32Z
[ "python", "numpy", "scipy" ]
I have a scipy array, e.g. ``` a = array([[0, 0, 1], [1, 1, 1], [1, 1, 1], [1, 0, 1]]) ``` I want to count the number of occurrences of each unique element in the array. For example, for the above array a, I want to get out that there is 1 occurrence of [0, 0, 1], 2 occurrences of [1, 1, 1] and 1 occurrence of [1, 0,...
If sticking with Python 2.7 (or 3.1) is not an issue and any of these two Python versions is available to you, perhaps the new [collections.Counter](http://docs.python.org/library/collections.html#collections.Counter) might be something for you if you stick to hashable elements like tuples: ``` >>> from collections im...
Is there a way to really pickle compiled regular expressions in python?
4,037,339
17
2010-10-27T20:21:14Z
4,037,539
9
2010-10-27T20:42:12Z
[ "python", "regex", "pickle" ]
I have a python console application that contains 300+ regular expressions. The set of regular expressions is fixed for each release. When users run the app, the entire set of regular expressions will be applied anywhere from once (a very short job) to thousands of times (a long job). I would like to speed up the shor...
As others have mentioned, you can simply pickle the compiled regex. They will pickle and unpickle just fine, and be usable. However, it doesn't look like the pickle actually contains the result of compilation. I suspect you will incur the compilation overhead again when you use the result of the unpickling. ``` >>> p....
Is there a way to really pickle compiled regular expressions in python?
4,037,339
17
2010-10-27T20:21:14Z
4,038,429
10
2010-10-27T23:02:02Z
[ "python", "regex", "pickle" ]
I have a python console application that contains 300+ regular expressions. The set of regular expressions is fixed for each release. When users run the app, the entire set of regular expressions will be applied anywhere from once (a very short job) to thousands of times (a long job). I would like to speed up the shor...
OK, this isn't pretty, but it might be what you want. I looked at the sre\_compile.py module from Python 2.6, and ripped out a bit of it, chopped it in half, and used the two pieces to pickle and unpickle compiled regexes: ``` import re, sre_compile, sre_parse, _sre import cPickle as pickle # the first half of sre_co...
"Caching" attributes of classes in Python
4,037,481
20
2010-10-27T20:36:09Z
4,037,580
16
2010-10-27T20:47:10Z
[ "python", "memoization" ]
I'm writing a class in python and I have an attribute that will take a relatively long time to compute, so **I only want to do it once**. Also, it will not be needed by every instance of the class, so **I don't want to do it by default** in `__init__`. I'm new to Python, but not to programming. I can come up with a wa...
The usual way would be to make the attribute a [property](http://docs.python.org/library/functions.html#property) and store the value the first time it is calculated ``` import time class Foo(object): def __init__(self): self._bar = None @property def bar(self): if self._bar is None: ...
"Caching" attributes of classes in Python
4,037,481
20
2010-10-27T20:36:09Z
4,037,979
25
2010-10-27T21:46:28Z
[ "python", "memoization" ]
I'm writing a class in python and I have an attribute that will take a relatively long time to compute, so **I only want to do it once**. Also, it will not be needed by every instance of the class, so **I don't want to do it by default** in `__init__`. I'm new to Python, but not to programming. I can come up with a wa...
I used to do this how gnibbler suggested, but I eventually got tired of the little housekeeping steps. So I built my own descriptor: ``` class cached_property(object): """ Descriptor (non-data) for building an attribute on-demand on first use. """ def __init__(self, factory): """ <fact...
"Caching" attributes of classes in Python
4,037,481
20
2010-10-27T20:36:09Z
19,979,379
13
2013-11-14T13:48:27Z
[ "python", "memoization" ]
I'm writing a class in python and I have an attribute that will take a relatively long time to compute, so **I only want to do it once**. Also, it will not be needed by every instance of the class, so **I don't want to do it by default** in `__init__`. I'm new to Python, but not to programming. I can come up with a wa...
* **Python >= 3.2** You should use both [`@property`](http://docs.python.org/2/library/functions.html#property) and [`@functools.lru_cache`](http://docs.python.org/3.3/library/functools.html#functools.lru_cache) decorators: ``` import functools class MyClass: @property @functools.lru_cache() def foo(self)...
Using multiple memcache servers in a pool
4,038,094
6
2010-10-27T22:04:24Z
4,038,108
9
2010-10-27T22:07:52Z
[ "python", "memcached" ]
I'm going through the documentation and I'm a little confused as to how memcache does internal load-balancing if multiple servers are specified. For example: ``` import memcache mc.set_servers(['127.0.0.1:11211','127.0.0.1:11212',]) mc.set("some_key", "Some value") print mc.get("some_key") ``` Will the setting and re...
memcached places keys on servers based on a hash of the key. As long as your server setup doesn't change, then a given key will always land on a given server.
SQLAlchemy JSON as blob/text
4,038,314
14
2010-10-27T22:41:17Z
4,050,483
12
2010-10-29T09:09:26Z
[ "python", "mysql", "database", "sqlalchemy" ]
I'm storing JSON down as blob/text in a column using MySQL. Is there a simple way to convert this into a dict using python/SQLAlchemy?
You can very easily [create your own type](http://www.sqlalchemy.org/docs/core/types.html#custom-types) with SQLAlchemy --- For SQLAlchemy versions >= 0.7, check out [Yogesh's answer](http://stackoverflow.com/a/25574866/457447) below --- ``` import jsonpickle import sqlalchemy.types as types class JsonType(types.M...
SQLAlchemy JSON as blob/text
4,038,314
14
2010-10-27T22:41:17Z
5,756,393
8
2011-04-22T14:21:51Z
[ "python", "mysql", "database", "sqlalchemy" ]
I'm storing JSON down as blob/text in a column using MySQL. Is there a simple way to convert this into a dict using python/SQLAlchemy?
I think the JSON example from the SQLAlchemy docs is also worth mentioning: <http://www.sqlalchemy.org/docs/core/types.html#marshal-json-strings> However, I think it can be improved to be less strict regarding NULL and empty strings: ``` class JSONEncodedDict(TypeDecorator): impl = VARCHAR def process_bind_...
converting bibtex files to html with python (maybe pybtex?)
4,038,703
6
2010-10-28T00:03:40Z
4,046,047
9
2010-10-28T18:30:16Z
[ "python", "html", "parsing", "text-parsing", "bibtex" ]
Hi I want to parse a bibtex publications file and sort for specific fields (e.g. year) and filter certain content, to then put it on a website. I came across pybtex, which works as far as reading and parsing the bibtex file, but it is basically not documented and I can't figure out how to sort the entries. Is pybtex t...
Found a solution, this sorts the entries in a descending order using pybtex, newest publications go first: ``` from pybtex.database.input import bibtex from operator import itemgetter, attrgetter import pprint parser = bibtex.Parser() bib_data = parser.parse_file('ref.bib') def sort_by_year(y, x): return int(x[1]...
Mixing two audio files together with python
4,039,158
5
2010-10-28T02:03:19Z
13,782,478
7
2012-12-08T22:13:50Z
[ "python" ]
I have two wav files that I want to mix together to form one wav file. They are both the same samples format etc... Been searching google endlessly. I would prefer to do it using the wave module in python. How can this be done?
You can use the [pydub](http://pydub.com) library (a light wrapper I wrote around the python wave module in the std lib) to do it pretty simply: ``` from pydub import AudioSegment sound1 = AudioSegment.from_file("/path/to/my_sound.wav") sound2 = AudioSegment.from_file("/path/to/another_sound.wav") combined = sound1....
Best way to find the months between two dates
4,039,879
39
2010-10-28T04:55:29Z
4,040,204
10
2010-10-28T06:00:34Z
[ "python", "datetime", "monthcalendar", "date-math" ]
I have the need to be able to accurately find the months between two dates in python. I have a solution that works but its not very good (as in elegant) or fast. ``` dateRange = [datetime.strptime(dateRanges[0], "%Y-%m-%d"), datetime.strptime(dateRanges[1], "%Y-%m-%d")] months = [] tmpTime = dateRange[0] oneWeek = t...
Get the ending month (relative to the year and month of the start month ex: 2011 January = 13 if your start date starts on 2010 Oct) and then generate the datetimes beginning the start month and that end month like so: ``` dt1, dt2 = dateRange start_month=dt1.month end_months=(dt2.year-dt1.year)*12 + dt2.month+1 dates...
Best way to find the months between two dates
4,039,879
39
2010-10-28T04:55:29Z
4,040,338
83
2010-10-28T06:25:01Z
[ "python", "datetime", "monthcalendar", "date-math" ]
I have the need to be able to accurately find the months between two dates in python. I have a solution that works but its not very good (as in elegant) or fast. ``` dateRange = [datetime.strptime(dateRanges[0], "%Y-%m-%d"), datetime.strptime(dateRanges[1], "%Y-%m-%d")] months = [] tmpTime = dateRange[0] oneWeek = t...
Start by defining some test cases, then you will see that the function is very simple and needs no loops ``` from datetime import datetime def diff_month(d1, d2): return (d1.year - d2.year)*12 + d1.month - d2.month assert diff_month(datetime(2010,10,1), datetime(2010,9,1)) == 1 assert diff_month(datetime(2010,10...
Best way to find the months between two dates
4,039,879
39
2010-10-28T04:55:29Z
28,290,050
10
2015-02-03T01:48:30Z
[ "python", "datetime", "monthcalendar", "date-math" ]
I have the need to be able to accurately find the months between two dates in python. I have a solution that works but its not very good (as in elegant) or fast. ``` dateRange = [datetime.strptime(dateRanges[0], "%Y-%m-%d"), datetime.strptime(dateRanges[1], "%Y-%m-%d")] months = [] tmpTime = dateRange[0] oneWeek = t...
One liner to find a list of datetimes, incremented by month, between two dates. ``` import datetime from dateutil.rrule import rrule, MONTHLY strt_dt = datetime.date(2001,1,1) end_dt = datetime.date(2005,6,1) dates = [dt for dt in rrule(MONTHLY, dtstart=strt_dt, until=end_dt)] ```
Python OLS calculation
4,040,322
4
2010-10-28T06:23:03Z
4,040,489
9
2010-10-28T06:52:58Z
[ "python" ]
Is there any good library to calculate linear least squares OLS (Ordinary Least Squares) in python? Thanks. Edit: Thanks for the SciKits and Scipy. @ars: Can X be a matrix? An example: ``` y(1) = a(1)*x(11) + a(2)*x(12) + a(3)*x(13) y(2) = a(1)*x(21) + a(2)*x(22) + a(3)*x(23) ..........................................
Try the [statsmodels](http://statsmodels.sourceforge.net/) package. Here's a quick example: ``` import pylab import numpy as np import statsmodels.api as sm x = np.arange(-10, 10) y = 2*x + np.random.normal(size=len(x)) # model matrix with intercept X = sm.add_constant(x) # least squares fit model = sm.OLS(y, X) fi...
Python verify url goes to a page
4,041,443
7
2010-10-28T09:23:34Z
4,041,514
10
2010-10-28T09:32:37Z
[ "python" ]
I have a list of urls (1000+) which have been stored for over a year now. I want to run through and verify them all to see if they still exist. What is the best / quickest way to check them all and return a list of ones which do not return a site?
this is kind of slow but you can use something like this to check if url is a live ``` import urllib2 try: urllib2.urlopen(url) return True # URL Exist except ValueError, ex: return False # URL not well formatted except urllib2.URLError, ex: return False # URL don't seem to be al...
Can I use a class attribute as a default value for an instance method?
4,041,624
21
2010-10-28T09:46:31Z
4,041,688
18
2010-10-28T09:54:53Z
[ "python" ]
I would like to use a class attribute as a default value for one of the arguments to my class's `__init__` method. This construct raises a `NameError` exception, though, and I don't understand why: ``` class MyClass(): __DefaultName = 'DefaultName' def __init__(self, name = MyClass.__DefaultName): self...
That's because, according to the [documentation](http://docs.python.org/reference/compound_stmts.html#function-definitions): > **Default parameter values are evaluated when the function definition > is executed.** This means that the > expression is evaluated once, when the > function is defined When `__init__()` is ...
Can I use a class attribute as a default value for an instance method?
4,041,624
21
2010-10-28T09:46:31Z
7,697,664
16
2011-10-08T15:03:35Z
[ "python" ]
I would like to use a class attribute as a default value for one of the arguments to my class's `__init__` method. This construct raises a `NameError` exception, though, and I don't understand why: ``` class MyClass(): __DefaultName = 'DefaultName' def __init__(self, name = MyClass.__DefaultName): self...
An important thing to keep in mind with Python is *when* different bits of code are executed, along with the fact that `class` and `def` statements are executed when *seen*, not just stored away for later. With a `def` it's a little easier to understand because the only thing being executed is whatever is between the `...
Reduce left and right margins in matplotlib plot
4,042,192
81
2010-10-28T10:57:59Z
4,046,233
123
2010-10-28T18:53:51Z
[ "python", "matplotlib" ]
I'm struggling to deal with my plot margins in matplotlib. I've used the code below to produce my chart: ``` plt.imshow(g) c = plt.colorbar() c.set_label("Number of Slabs") plt.savefig("OutputToUse.png") ``` However, I get an output figure with lots of white space on either side of the plot. I've searched google and ...
One way to automatically do this is the `bbox_inches='tight'` kwarg to [`plt.savefig`](http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure.savefig). E.g. ``` import matplotlib.pyplot as plt import numpy as np data = np.arange(3000).reshape((100,30)) plt.imshow(data) plt.savefig('test.png', bbox_inches=...
Reduce left and right margins in matplotlib plot
4,042,192
81
2010-10-28T10:57:59Z
4,066,599
67
2010-11-01T04:17:03Z
[ "python", "matplotlib" ]
I'm struggling to deal with my plot margins in matplotlib. I've used the code below to produce my chart: ``` plt.imshow(g) c = plt.colorbar() c.set_label("Number of Slabs") plt.savefig("OutputToUse.png") ``` However, I get an output figure with lots of white space on either side of the plot. I've searched google and ...
You can adjust the spacing around matplotlib figures using the subplots\_adjust() function: ``` import matplotlib.pyplot as plt plt.plot(whatever) plt.subplots_adjust(left=0.1, right=0.9, top=0.9, bottom=0.1) ``` This will work for both the figure on screen and saved to a file, and it is the right function to call ev...
Reduce left and right margins in matplotlib plot
4,042,192
81
2010-10-28T10:57:59Z
15,712,584
27
2013-03-29T22:46:53Z
[ "python", "matplotlib" ]
I'm struggling to deal with my plot margins in matplotlib. I've used the code below to produce my chart: ``` plt.imshow(g) c = plt.colorbar() c.set_label("Number of Slabs") plt.savefig("OutputToUse.png") ``` However, I get an output figure with lots of white space on either side of the plot. I've searched google and ...
All you need is ``` plt.tight_layout() ``` before your output. In addition to cutting down the margins, this also tightly groups the space between any subplots: ``` x = [1,2,3] y = [1,4,9] import matplotlib.pyplot as plt fig = plt.figure() subplot1 = fig.add_subplot(121) subplot1.plot(x,y) subplot2 = fig.add_subplo...
Defining Constants in Django
4,042,407
12
2010-10-28T11:27:06Z
4,042,578
13
2010-10-28T11:49:04Z
[ "python", "django", "constants" ]
I want to have some constants in a Django Projects. For example, let's say a constant called `MIN_TIME_TEST`. I would like to be able to access this constant in two places: from within my Python code, and from within any Templates. What's the best way to go about doing this? **EDIT:** To clarify, I know about Templa...
Both Luper and Vladimir are correct imho but you'll need both in order to complete your requirements. * Although, the constants don't *need* to be in the settings.py, you could put them anywhere and import them from that place into your view/model/module code. I sometimes put them into the `__init__.py` if I don't car...
Display help message with python argparse when script is called without any arguments
4,042,452
92
2010-10-28T11:33:34Z
4,042,861
124
2010-10-28T12:23:33Z
[ "python", "argparse" ]
This might be a simple one. Assume I have a program that uses argparse to process command line arguments/options. The following will print the 'help' message: ``` ./myprogram -h ``` or: ``` ./myprogram --help ``` But, if I run the script without any arguments whatsoever, it doesn't do anything. What I want it to do...
This answer comes from Steven Bethard [on Google groups](http://groups.google.com/group/argparse-users/browse_thread/thread/2dacd5fed110bd0c?pli=1). I'm reposting it here to make it easier for people without a Google account to access. You can override the default behavior of the `error` method: ``` import argparse i...
Display help message with python argparse when script is called without any arguments
4,042,452
92
2010-10-28T11:33:34Z
29,293,080
13
2015-03-27T04:03:12Z
[ "python", "argparse" ]
This might be a simple one. Assume I have a program that uses argparse to process command line arguments/options. The following will print the 'help' message: ``` ./myprogram -h ``` or: ``` ./myprogram --help ``` But, if I run the script without any arguments whatsoever, it doesn't do anything. What I want it to do...
Instead of writing a class, a try/except can be used instead ``` try: options = parser.parse_args() except: parser.print_help() sys.exit(0) ``` The upside is that the workflow is clearer and you don't need a stub class. The downside is that the first 'usage' line is printed twice. This will need at least...
Where does Python root logger store a log?
4,042,615
6
2010-10-28T11:54:03Z
4,042,790
8
2010-10-28T12:16:00Z
[ "python", "logging", "freebase" ]
I'm using the Freebase Python library. It creates a log before executing: ``` self.log = logging.getLogger("freebase") ``` **Where is this log in the file system?** It's not in the executing directory or tmp.
That call does not store anything. It merely creates a logger object which can be bound and configured however you would like. So if in your Python code, you were to add ``` logging.basicConfig(level=logging.WARNING) ``` All warnings and errors would be logged to the standard output (that's what basicConfig does), i...
What is __main__.py?
4,042,905
114
2010-10-28T12:28:20Z
4,042,949
15
2010-10-28T12:34:11Z
[ "python" ]
What is the `__main__.py` file for, what sort of code should I put into it, and when should I have one?
`__main__.py` is used for python programs in zip files. The `__main__.py` file will be executed when the zip file in run. For example, if the zip file was as such: ``` test.zip __main__.py ``` and the contents of `__main__.py` was ``` import sys print "hello %s" % sys.argv[1] ``` Then if we were to run `python...
What is __main__.py?
4,042,905
114
2010-10-28T12:28:20Z
4,042,951
10
2010-10-28T12:34:17Z
[ "python" ]
What is the `__main__.py` file for, what sort of code should I put into it, and when should I have one?
If your script is a directory or ZIP file rather than a single python file, `__main__.py` will be executed when the "script" is passed as an argument to the python interpreter.
What is __main__.py?
4,042,905
114
2010-10-28T12:28:20Z
4,043,007
116
2010-10-28T12:41:42Z
[ "python" ]
What is the `__main__.py` file for, what sort of code should I put into it, and when should I have one?
Often, a Python program is run by naming a .py file on the command line: ``` $ python my_program.py ``` You can also create a directory or zipfile full of code, and include a `__main__.py`. Then you can simply name the directory or zipfile on the command line, and it executes the `__main__.py` automatically: ``` $ p...
Python How to share a serial port with two different threads (Class A, Class B)
4,043,193
2
2010-10-28T13:06:47Z
4,043,762
11
2010-10-28T14:16:56Z
[ "python", "multithreading", "semaphore" ]
I have a single Python process which is using a serial port (unique resource) which is managed using an instance of a class A. There exists two different threads initialized using instances of classes B and C, which are constantly using the serial port resource through the objected already created. ``` import threadin...
While you *could* share the serial port using appropriate locking, I wouldn't recommend it. I've written several multi-threaded applications that communicate on the serial port in Python, and in my experience the following approach is better: * Have a single class, in a single thread, manage the actual serial port com...
Python: Should I use a class or dictionary?
4,045,161
34
2010-10-28T16:44:35Z
4,045,183
26
2010-10-28T16:47:02Z
[ "python", "oop", "class", "dictionary" ]
I have a class that contains only fields and no methods, like this: ``` class Request(object): def __init__(self, environ): self.environ = environ self.request_method = environ.get('REQUEST_METHOD', None) self.url_scheme = environ.get('wsgi.url_scheme', None) self.request_uri = wsg...
Use a dictionary unless you need the extra mechanism of a class. You could also use a [`namedtuple`](http://docs.python.org/dev/library/collections.html#collections.namedtuple) for a hybrid approach: ``` >>> from collections import namedtuple >>> request = namedtuple("Request", "environ request_method url_scheme") >>>...
Python: Should I use a class or dictionary?
4,045,161
34
2010-10-28T16:44:35Z
4,045,303
14
2010-10-28T17:00:01Z
[ "python", "oop", "class", "dictionary" ]
I have a class that contains only fields and no methods, like this: ``` class Request(object): def __init__(self, environ): self.environ = environ self.request_method = environ.get('REQUEST_METHOD', None) self.url_scheme = environ.get('wsgi.url_scheme', None) self.request_uri = wsg...
A class in python **is** a dict underneath. You do get some overhead with the class behavior, but you won't be able to notice it without a profiler. In this case, I believe you benefit from the class because: * All your logic lives in a single function * It is easy to update and stays encapsulated * If you change anyt...
Python: Should I use a class or dictionary?
4,045,161
34
2010-10-28T16:44:35Z
4,045,441
13
2010-10-28T17:18:27Z
[ "python", "oop", "class", "dictionary" ]
I have a class that contains only fields and no methods, like this: ``` class Request(object): def __init__(self, environ): self.environ = environ self.request_method = environ.get('REQUEST_METHOD', None) self.url_scheme = environ.get('wsgi.url_scheme', None) self.request_uri = wsg...
Why on earth would you make this a dictionary? What's the advantage? What happens if you later want to add some code? Where would your `__init__` code go? Classes are for bundling related data (and usually code). Dictionaries are for storing key-value relationships, where usually the keys are all of the same type, an...
Python: Should I use a class or dictionary?
4,045,161
34
2010-10-28T16:44:35Z
16,288,316
10
2013-04-29T21:10:19Z
[ "python", "oop", "class", "dictionary" ]
I have a class that contains only fields and no methods, like this: ``` class Request(object): def __init__(self, environ): self.environ = environ self.request_method = environ.get('REQUEST_METHOD', None) self.url_scheme = environ.get('wsgi.url_scheme', None) self.request_uri = wsg...
I think that the usage of each one is way too subjective for me to get in on that, so i'll just stick to numbers. I compared the time it takes to create and to change a variable in a dict, a new\_style class and a new\_style class with slots. Here's the code i used to test it(it's a bit messy but it does the job.) `...
Python: how to add the contents of an iterable to a set?
4,045,403
69
2010-10-28T17:12:30Z
4,045,505
105
2010-10-28T17:25:34Z
[ "python", "set", "conventions", "iterable" ]
What is the ["one [...] obvious way"](http://www.python.org/dev/peps/pep-0020/) to add all items of an iterable to an existing `set`?
by set, do you mean `set`? ``` >>> foo = set(range(0, 4)) >>> foo set([0, 1, 2, 3]) >>> foo.update(range(2, 6)) >>> foo set([0, 1, 2, 3, 4, 5]) ```
Python: how to add the contents of an iterable to a set?
4,045,403
69
2010-10-28T17:12:30Z
4,046,249
20
2010-10-28T18:55:52Z
[ "python", "set", "conventions", "iterable" ]
What is the ["one [...] obvious way"](http://www.python.org/dev/peps/pep-0020/) to add all items of an iterable to an existing `set`?
For the benefit of anyone who might believe e.g. that doing `aset.add()` in a loop would have performance competitive with doing `aset.update()`, here's an example of how you can test your beliefs quickly before going public: ``` >\python27\python -mtimeit -s"it=xrange(10000);a=set(xrange(100))" "a.update(it)" 1000 lo...
Python: Self is not defined
4,045,599
4
2010-10-28T17:36:03Z
4,045,619
12
2010-10-28T17:39:21Z
[ "python" ]
``` class a(object): def __init__(self): self.b = 1 self.c = 2 ``` This gives the error: NameError: name 'self' is not defined I looked at a previous post, but the error was for a different reason. Any help with this?
I'm assuming the single space before `def __init__(self):` is actually a tab in your file and displayed as four spaces by your editor. However python interprets a tab as 8 spaces, so the following two lines (which are indented by 8 spaces) are seen by python to be at the same level of indentation as the `def`. This i...
What is the best way to serve small static images?
4,046,242
3
2010-10-28T18:54:43Z
4,046,256
13
2010-10-28T18:57:11Z
[ "java", "javascript", "python", "image" ]
Right now I'm base 64 encoding them and using data uris. The idea was that this will somehow lower the number of requests the browser needs to make. Does this bucket hold any water? What is the best way of serving images in general? DB, from FS, S3? I am most interested in python and java based answers, but all are w...
I would definitely take a look at CSS Image Sprites, decent write-ups [here](http://www.alistapart.com/articles/sprites) and [here](http://www.smashingmagazine.com/2009/04/27/the-mystery-of-css-sprites-techniques-tools-and-tutorials/). The concept is pretty simple, combine your images into one, show only the slice you...
Is there something wrong with this python code, why does it run so slow compared to ruby?
4,046,514
4
2010-10-28T19:29:55Z
4,047,666
7
2010-10-28T22:32:29Z
[ "python", "ruby", "performance", "fibonacci" ]
I was interested in comparing ruby speed vs python so I took the simplest recursive calculation, namely print the fibonacci sequance. This is the python code ``` #!/usr/bin/python2.7 def fib(n): if n == 0: return 0 elif n == 1: return 1 else: return fib(n-1...
The recursion efficiency of python is the cause of this overhead. See [this article](http://eikke.com/re-python-recursion-performance-test/) for much more detail. The above solutions that solve this iteratively are better for python since they do not incur the function call overhead recursion does. My assumption about ...
Is it possible to use python suds to read a wsdl file from the file system?
4,046,628
31
2010-10-28T19:49:14Z
4,046,648
45
2010-10-28T19:51:30Z
[ "python", "soap", "wsdl", "suds" ]
From suds [documentation](https://fedorahosted.org/suds/wiki/Documentation#BASICUSAGE), I can create a `Client` if I have a url for the WSDL. ``` from suds.client import Client url = 'http://localhost:7080/webservices/WebServiceTestBean?wsdl' client = Client(url) ``` I currently have the WSDL file on my file system. ...
try to use `url='file:///path/to/file'`
Is it possible to use python suds to read a wsdl file from the file system?
4,046,628
31
2010-10-28T19:49:14Z
28,620,581
8
2015-02-20T02:11:14Z
[ "python", "soap", "wsdl", "suds" ]
From suds [documentation](https://fedorahosted.org/suds/wiki/Documentation#BASICUSAGE), I can create a `Client` if I have a url for the WSDL. ``` from suds.client import Client url = 'http://localhost:7080/webservices/WebServiceTestBean?wsdl' client = Client(url) ``` I currently have the WSDL file on my file system. ...
Based upon the comments in the accepted answer and the following answer: <http://stackoverflow.com/a/14298190/622276> ``` import urlparse, urllib, os url = urlparse.urljoin('file:', urllib.pathname2url(os.path.abspath("service.xml"))) ``` This is a more complete one liner that will let you specify just the local pat...
python - how to get the numebr of active threads started by specific class?
4,046,986
7
2010-10-28T20:37:33Z
4,047,415
9
2010-10-28T21:45:38Z
[ "python", "multithreading", "count" ]
code looks like below: ``` class workers1(Thread): ... def __init__(self): ... Thread.__init__(self) ... def run(self): ... ...do some stuff class workers2(Thread): ... def __init__(self): ... Thread.__init__(self) ... def run(self): ... ...do some stuff if __name__ == "__main__": ... ...
This is a minor modification of Doug Hellman's [multiprocessing ActivePool example code](http://www.doughellmann.com/PyMOTW/multiprocessing/index.html) (to use threading). The idea is to have your workers register themselves in a pool, unregister themselves when they finish, using a threading.Lock to coordinate modific...
Installing Python-2.7 on Ubuntu 10.4
4,047,212
13
2010-10-28T21:14:25Z
4,047,583
20
2010-10-28T22:14:38Z
[ "python", "zlib", "setuptools" ]
I can't seem to install zlib properly, I installed Python from source on Ubuntu10.4 '######## edit ##################### bobince and Luper helped. Make sure you install these packages and then recompile Python: sudo aptitude install zlib1g-dev libreadline6-dev libdb4.8-dev libncurses5-dev '####################...
You don't want `zlibc`, it's something else completely. You want `zlib1g` (which will certainly be installed already) and, as Luper mentioned, the ‘development’ package which is `zlib1g-dev`. Debian-based Linux distros split each C library into a separate runtime binary package and a development package which deli...
Installing Python-2.7 on Ubuntu 10.4
4,047,212
13
2010-10-28T21:14:25Z
7,820,197
9
2011-10-19T10:53:57Z
[ "python", "zlib", "setuptools" ]
I can't seem to install zlib properly, I installed Python from source on Ubuntu10.4 '######## edit ##################### bobince and Luper helped. Make sure you install these packages and then recompile Python: sudo aptitude install zlib1g-dev libreadline6-dev libdb4.8-dev libncurses5-dev '####################...
Keep in mind that **Ubuntu** is using a directory called **/lib/x86\_64-linux-gnu** for *x64* architectures. If you are using that architecture you need to create a symbolic link: ``` $ sudo ln -s /lib/x86_64-linux-gnu/libz.so.1 /lib/libz.so ``` Also, you should do same thing for others shared libraries.
Doctest and relative imports
4,047,227
12
2010-10-28T21:16:16Z
4,047,341
7
2010-10-28T21:32:42Z
[ "python", "doctest" ]
I'm having trouble using doctest with relative imports. The simple solution is just to get rid of the relative imports. Are there any others? Say I have a package called example containing 2 files: **`example/__init__.py`** ``` """ This package is entirely useless. >>> arnold = Aardvark() >>> arnold.talk() I am an a...
Create another file `my_doctest_runner.py`: ``` if __name__ == "__main__": import doctest import example doctest.testmod(example) ``` Execute `my_doctest_runner.py` to run doctests in `example/__init__.py`: ``` $ python2.7 my_doctest_runner.py *************************************************************...
Checking if an ISBN number is correct
4,047,511
11
2010-10-28T22:02:07Z
4,047,709
14
2010-10-28T22:40:14Z
[ "python" ]
I'm given some ISBN numbers e.g. `3-528-03851` (not valid) , `3-528-16419-0` (valid). I'm supposed to write a program which tests if the ISBN number is valid. Here' my code: ``` def check(isbn): check_digit = int(isbn[-1]) match = re.search(r'(\d)-(\d{3})-(\d{5})', isbn[:-1]) if match: digits = m...
First, try to avoid code like this: ``` if Action(): lots of code return True return False ``` Flip it around, so the bulk of code isn't nested. This gives us: ``` def check(isbn): check_digit = int(isbn[-1]) match = re.search(r'(\d)-(\d{3})-(\d{5})', isbn[:-1]) if not match: return Fals...
parallel file parsing, multiple CPU cores
4,047,789
8
2010-10-28T22:57:01Z
4,047,840
10
2010-10-28T23:06:53Z
[ "python", "python-3.x", "parallel-processing" ]
I asked a related but very general question earlier (see especially [this response](http://stackoverflow.com/questions/3939912/python-execution-speed-laptop-vs-desktop/3939948#3939948)). This question is very specific. This is all the code I care about: ``` result = {} for line in open('input.txt'): key, value = pa...
cPython does not provide the threading model you are looking for easily. You can get something similar using the `multiprocessing` module and a [process pool](http://docs.python.org/library/multiprocessing.html#using-a-pool-of-workers) such a solution could look something like this: ``` def worker(lines): """Make...
Python: unit testing socket-based code?
4,047,897
15
2010-10-28T23:16:48Z
4,048,029
7
2010-10-28T23:49:35Z
[ "python", "sockets", "testing", "gevent" ]
I'm writing a Python client+server that uses `gevent.socket` for communication. Are there any good ways of testing the socket-level operation of the code (for example, verifying that SSL connections with an invalid certificate will be rejected)? Or is it simplest to just `spawn` a real server? **Edit**: I don't believ...
There is another (IMO better) way: You should mock the library you are using. An example mocking helper for python is **[mox](http://code.google.com/p/pymox/wiki/MoxDocumentation)**. You don't need a set of servers with a valid certificate, another with an invalid certificate, with no ssl support at all, ones not resp...
Python: unit testing socket-based code?
4,047,897
15
2010-10-28T23:16:48Z
4,049,039
12
2010-10-29T04:45:00Z
[ "python", "sockets", "testing", "gevent" ]
I'm writing a Python client+server that uses `gevent.socket` for communication. Are there any good ways of testing the socket-level operation of the code (for example, verifying that SSL connections with an invalid certificate will be rejected)? Or is it simplest to just `spawn` a real server? **Edit**: I don't believ...
You can easily start a server and then access it in a test case. The gevent's [own test suite](http://bitbucket.org/denis/gevent/src/tip/greentest/) does exactly that for testing gevent's [built-in servers](http://gevent.org/servers.html). For example: ``` class SimpleServer(gevent.server.StreamServer): def hand...
How can I discover if a program is running from command line or from web?
4,048,275
7
2010-10-29T01:03:43Z
4,048,306
9
2010-10-29T01:11:03Z
[ "python", "command-line", "cgi" ]
I have a python script and I wanna know if the request is from web or from command line. How can I do this?
When run as a CGI, environment variables such as `REQUEST_METHOD` will be present. If not, then you're not running in a CGI environment. You can check this like this: ``` import os if os.getenv("REQUEST_METHOD"): print("running as CGI") else: print("not running as CGI") ```
Python function to convert seconds into minutes, hours, and days
4,048,651
11
2010-10-29T02:56:02Z
4,048,773
26
2010-10-29T03:30:45Z
[ "python" ]
Question: Write a program that asks the user to enter a number of seconds, and works as follows: * There are 60 seconds in a minute. If the number of seconds entered by the user is greater than or equal to 60, the program should display the number of minutes in that many seconds. * There are 3600 seconds in an hour. I...
This will convert *n* seconds into *d* days, *h* hours, *m* minutes, and *s* seconds. ``` from datetime import datetime, timedelta def GetTime(): sec = timedelta(seconds=int(input('Enter the number of seconds: '))) d = datetime(1,1,1) + sec print("DAYS:HOURS:MIN:SEC") print("%d:%d:%d:%d" % (d.day-1, ...
Python function to convert seconds into minutes, hours, and days
4,048,651
11
2010-10-29T02:56:02Z
24,542,445
13
2014-07-02T23:02:04Z
[ "python" ]
Question: Write a program that asks the user to enter a number of seconds, and works as follows: * There are 60 seconds in a minute. If the number of seconds entered by the user is greater than or equal to 60, the program should display the number of minutes in that many seconds. * There are 3600 seconds in an hour. I...
This tidbit is useful for displaying elapsed time to varying degrees of granularity. I personally think that questions of efficiency are practically meaningless here, so long as something grossly inefficient isn't being done. Premature optimization is the root of quite a bit of evil. This is fast enough that it'll nev...
printing tab-separated values of a list
4,048,964
12
2010-10-29T04:25:55Z
4,048,974
23
2010-10-29T04:27:11Z
[ "python", "printing", "python-3.x" ]
Here's my current code: ``` print(list[0], list[1], list[2], list[3], list[4], sep = '\t') ``` I'd like to write it better. But ``` print('\t'.join(list)) ``` won't work because list elements may numbers, other lists, etc., so `join` would complain.
``` print('\t'.join(map(str,list))) ```
printing tab-separated values of a list
4,048,964
12
2010-10-29T04:25:55Z
4,049,043
20
2010-10-29T04:45:42Z
[ "python", "printing", "python-3.x" ]
Here's my current code: ``` print(list[0], list[1], list[2], list[3], list[4], sep = '\t') ``` I'd like to write it better. But ``` print('\t'.join(list)) ``` won't work because list elements may numbers, other lists, etc., so `join` would complain.
``` print(*list, sep='\t') ``` Note that you shouldn't use the word `list` as a variable name, since it's the name of a builtin type.
How to get the sum of timedelta in Python?
4,049,825
9
2010-10-29T07:24:12Z
4,049,852
18
2010-10-29T07:27:36Z
[ "python", "datetime", "timedelta" ]
Python: How to get the sum of timedelta? Eg. I just got a lot of timedelta object, and now I want the sum. That's it!
To add timedeltas you can use the builtin operator `+`: ``` result = timedelta1 + timedelta2 ``` To add a lot of timedeltas you can use sum: ``` result = sum(timedeltas, datetime.timedelta()) ``` Or reduce: ``` import operator result = reduce(operator.add, timedeltas) ```
How to get the sum of timedelta in Python?
4,049,825
9
2010-10-29T07:24:12Z
4,049,857
8
2010-10-29T07:28:04Z
[ "python", "datetime", "timedelta" ]
Python: How to get the sum of timedelta? Eg. I just got a lot of timedelta object, and now I want the sum. That's it!
datetime combine method allows you to combine time with a delta ``` datetime.combine(date.today(), time()) + timedelta(hours=2) ``` timedelta can be combined using usual '+' operator ``` >>> timedelta(hours=3) datetime.timedelta(0, 10800) >>> timedelta(hours=2) datetime.timedelta(0, 7200) >>> >>> timedelta(hours=3)...