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
How to check if a path is absolute path or relative path in cross platform way with Python?
3,320,406
64
2010-07-23T16:45:41Z
3,320,429
91
2010-07-23T16:47:57Z
[ "python", "path" ]
UNIX absolute path starts with '/', whereas Windows starts with alphabet 'C:' or '\'. Does python has a standard function to check if a path is absolute or relative?
`os.path.isabs` returns `True` if the path is absolute, `False` if not. [The documentation](http://docs.python.org/library/os.path.html) says it works in windows (I can confirm it works in Linux personally). ``` os.path.isabs(my_path) ```
How to check if a path is absolute path or relative path in cross platform way with Python?
3,320,406
64
2010-07-23T16:45:41Z
3,320,458
21
2010-07-23T16:51:40Z
[ "python", "path" ]
UNIX absolute path starts with '/', whereas Windows starts with alphabet 'C:' or '\'. Does python has a standard function to check if a path is absolute or relative?
And if what you *really want* is the absolute path, don't bother checking to see if it is, just get the `abspath`: ``` import os print os.path.abspath('.') ```
Mutex locks vs Threading locks. Which to use?
3,320,514
4
2010-07-23T16:58:16Z
3,320,532
10
2010-07-23T17:00:20Z
[ "python", "multithreading", "locking", "mutex" ]
My main question is does the Threading lock object create atomic locks? It doesn't say that the lock is atomic in the module documentation. in pythons mutex documentation it does say the mutex lock is atomic but it seems that I read somewhere that in fact it isn't. I am wondering if someone could could give me a bit of...
Locks of any nature would be rather useless if they weren't atomic - the whole point of the lock is to allow for higher-level atomic operations. All of threading's synchronization objects (locks, rlocks, semaphores, boundedsemaphores) utilize atomic instructions, as do mutexes. You *should* use `threading`, since `mu...
Recursively walking a Python inheritance tree at run-time
3,321,029
6
2010-07-23T18:02:43Z
3,321,131
10
2010-07-23T18:15:26Z
[ "python", "reflection", "introspection" ]
I'm writing some serialization/deserialization code in Python that will read/write an inheritance hierarchy from some JSON. The exact composition will not be known until the request is sent in. So, I deem the elegant solution to recursively introspect the Python class hierarchy to be emitted and then, on the way back ...
You might try using the type.mro() method to find the method resolution order. ``` class A(object): pass class B(A): pass class C(A): pass a = A() b = B() c = C() >>> type.mro(type(b)) [<class '__main__.B'>, <class '__main__.A'>, <type 'object'>] >>> type.mro(type(c)) [<class '__main__.C'>,...
Implementing Load Balancing Using Python
3,321,722
3
2010-07-23T19:31:35Z
3,321,789
8
2010-07-23T19:41:03Z
[ "python", "parallel-processing", "module" ]
I am doing some research this summer and working on parallelizing pre-existing code. The main focus right now is a way to load balance the code so that it will run more efficient on the cluster. The current task is to make a proof of concept that creates several processes with each one having their own stack available ...
Here's a simple way to do this. 1. Create a single common shared queue of work to do. This application will fill this queue with work to do. 2. Create an application which gets one item from the queue, and does the work. This is the single-producer-multiple-consumer design. It works well and can swamp your machine...
Is this method of file locking acceptable?
3,322,011
2
2010-07-23T20:14:48Z
3,322,242
7
2010-07-23T20:49:34Z
[ "python", "linux", "networking", "locking" ]
We have 10 Linux boxes that must run 100 different tasks each week. These computers work at these tasks mostly at night when we are at home. One of my coworkers is working on a project to optimize run time by automating the starting of the tasks with Python. His program is going to read a list of tasks, grab an open ta...
You've basically developed a filesystem version of the binary semaphore (or mutex). It's a well-studied structure used for locking, so as long as you get the implementation details right, it should work. The trick is to get the "test and set" operation, or in your case "check existence and move," to be truly atomic. Fo...
Ensuring code coverage in unit testing?
3,322,123
22
2010-07-23T20:29:09Z
3,322,147
24
2010-07-23T20:32:39Z
[ "python", "unit-testing", "testing", "code-coverage" ]
We have noticed that even though we have a lot of doctests in our Python code, when we trace the testing using the methods described here: [traceit](http://stackoverflow.com/questions/2617120/how-to-use-traceit-to-report-function-input-variables-in-stack-trace) we find that there are certain lines of code that are ne...
[coverage.py](http://nedbatchelder.com/code/coverage/) is a very handy tool. Among other things, it provides [branch coverage](http://nedbatchelder.com/code/coverage/branch.html).
Ensuring code coverage in unit testing?
3,322,123
22
2010-07-23T20:29:09Z
3,322,167
15
2010-07-23T20:36:43Z
[ "python", "unit-testing", "testing", "code-coverage" ]
We have noticed that even though we have a lot of doctests in our Python code, when we trace the testing using the methods described here: [traceit](http://stackoverflow.com/questions/2617120/how-to-use-traceit-to-report-function-input-variables-in-stack-trace) we find that there are certain lines of code that are ne...
Do you have a mandate from management to be dogmatic about obtaining 100% code coverage with your test cases? If not, do you believe touching every line of code is the most effective way to find bugs in your code? Assuming you don't have infinite time and people resources, you should probably focus on reasonably testin...
Why is Python saying pow only has 2 arguments
3,322,272
8
2010-07-23T20:54:19Z
3,322,334
12
2010-07-23T21:02:42Z
[ "python", "syntax-error" ]
Why is python telling me "TypeError: pow expected 2 arguments, got 3" despite it working in IDLE (sometimes it tells me that in IDLE as well)? im simply doing `pow(a,b,c)`. my program is very short and i do not change the definition of `pow` at any time since i need to use it for some exponentiation. NOTE: This is the...
Built-in `pow` takes two or three arguments. If you do `from math import *` then it is replaced by math's `pow`, which takes only two arguments. My recommendation is to do `import math`, or explicitly list functions you use in import list. Similar issue happens with `open` vs. `os.open`.
Explain polymorphism
3,322,318
10
2010-07-23T21:00:35Z
3,322,677
18
2010-07-23T21:54:14Z
[ "python", "oop", "polymorphism", "definition" ]
What is polymorphism? I'm not sure I am understanding it correctly. In the Python scope, what I am getting out of it is that I can define parameters as followed: ``` def blah (x, y) ``` without having to specify the type, as opposed to another language like Java, where it'd look more along the lines of: ``` public ...
Beware that different people use different terminology; in particular there is often a rift between the [object oriented community](http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming) and the (rest of the) [programming language theory community](http://en.wikipedia.org/wiki/Type_polymorphism). Ge...
Explain polymorphism
3,322,318
10
2010-07-23T21:00:35Z
3,325,254
12
2010-07-24T13:26:12Z
[ "python", "oop", "polymorphism", "definition" ]
What is polymorphism? I'm not sure I am understanding it correctly. In the Python scope, what I am getting out of it is that I can define parameters as followed: ``` def blah (x, y) ``` without having to specify the type, as opposed to another language like Java, where it'd look more along the lines of: ``` public ...
Hope from this example, you will understand what `Polymorphism` is. In this picture, all objects have a method `Speak()` but each has a different implementation. Polymorphism allows you to do this, you can declare an action for a class and its subclasses but for each subclass, you can write exactly what you want later....
SQL Alchemy - How to Delete from a model instance?
3,322,337
5
2010-07-23T21:03:19Z
3,322,769
11
2010-07-23T22:11:43Z
[ "python", "sqlalchemy", "orm" ]
Say I get a model instance like this: ``` instance = session.query(MyModel).filter_by(id=1).first() ``` How can I delete that row? Is there a special method to call?
Ok I found it after further searching: ``` session.delete(instance) ```
Iterate across lines in two files simultaneously in Python
3,322,419
6
2010-07-23T21:15:11Z
3,322,448
19
2010-07-23T21:19:16Z
[ "python", "iterator" ]
I have two files, and I want to perform some line-wise operation across both of them. (In other words, the first lines of each file correspond, as do the second, etc.) Now, I can think of a number of slightly cumbersome ways to iterate across both files simultaneously; **however**, this is Python, so I imagine that the...
Use `itertools.izip` to join the two iterators. ``` from itertools import izip for line_from_file_1, line_from_file_2 in izip(open(file_1), open(file_2)): ``` If the files are of unequal length, use `izip_longest`.
How do I connect to a UDP port in Python?
3,322,850
6
2010-07-23T22:28:56Z
3,322,923
8
2010-07-23T22:47:07Z
[ "python", "sockets", "logging", "udp" ]
Like everyone else, I can say "I've tried everything!" I kind of did. I looked all over StackOverflow, and tried all the answers, but got nothing. Anyways, I am jetting to at least get some code printed by Python before I get even further in developing this. I want to receive UDP packets from my Garry's Mod server (lo...
(Not quite an answer, but a diagnostic path that might lead to an answer. Sometimes it helps just to know that it actually worked for someone else.) I've entered the above into a Python console, and then typed the code below into another Python console: ``` import socket sock = socket.socket(socket.AF_INET, socket.SO...
Maximum recursion depth?
3,323,001
117
2010-07-23T23:04:50Z
3,323,008
36
2010-07-23T23:07:17Z
[ "python", "recursion" ]
I have this tail recursive function here: ``` def fib(n, sum): if n < 1: return sum else: return fib(n-1, sum+n) c = 998 print(fib(c, 0)) ``` It works up to n=997, then it just breaks and spits a "maximum recursion depth exceeded in comparison" `RuntimeError`. Is this just a stack overflow? I...
Looks like you just need to set a higher recursion depth ``` sys.setrecursionlimit(1500) ```
Maximum recursion depth?
3,323,001
117
2010-07-23T23:04:50Z
3,323,012
13
2010-07-23T23:08:54Z
[ "python", "recursion" ]
I have this tail recursive function here: ``` def fib(n, sum): if n < 1: return sum else: return fib(n-1, sum+n) c = 998 print(fib(c, 0)) ``` It works up to n=997, then it just breaks and spits a "maximum recursion depth exceeded in comparison" `RuntimeError`. Is this just a stack overflow? I...
It's to avoid a stack overflow. The Python interpreter limits the depths of recursion to help you avoid infinite recursions, resulting in stack overflows. Try increasing the recursion limit (sys.setrecursionlimit) or re-writing your code without recursion. from [python website](https://docs.python.org/2/library/sys.ht...
Maximum recursion depth?
3,323,001
117
2010-07-23T23:04:50Z
3,323,013
134
2010-07-23T23:08:59Z
[ "python", "recursion" ]
I have this tail recursive function here: ``` def fib(n, sum): if n < 1: return sum else: return fib(n-1, sum+n) c = 998 print(fib(c, 0)) ``` It works up to n=997, then it just breaks and spits a "maximum recursion depth exceeded in comparison" `RuntimeError`. Is this just a stack overflow? I...
It is a guard against a stack overflow, yes. Python (or rather, the CPython implementation) doesn't optimize tail recursion, and unbridled recursion causes stack overflows. You can change the recursion limit with [`sys.setrecursionlimit`](http://docs.python.org/library/sys.html#sys.setrecursionlimit), but doing so is d...
Maximum recursion depth?
3,323,001
117
2010-07-23T23:04:50Z
3,323,029
16
2010-07-23T23:12:33Z
[ "python", "recursion" ]
I have this tail recursive function here: ``` def fib(n, sum): if n < 1: return sum else: return fib(n-1, sum+n) c = 998 print(fib(c, 0)) ``` It works up to n=997, then it just breaks and spits a "maximum recursion depth exceeded in comparison" `RuntimeError`. Is this just a stack overflow? I...
Use a language that guarantees tail-call optimisation. Or use iteration. Alternatively, get cute with [decorators](http://code.activestate.com/recipes/474088/).
Maximum recursion depth?
3,323,001
117
2010-07-23T23:04:50Z
18,649,326
10
2013-09-06T03:17:10Z
[ "python", "recursion" ]
I have this tail recursive function here: ``` def fib(n, sum): if n < 1: return sum else: return fib(n-1, sum+n) c = 998 print(fib(c, 0)) ``` It works up to n=997, then it just breaks and spits a "maximum recursion depth exceeded in comparison" `RuntimeError`. Is this just a stack overflow? I...
I realize this is an old question but for those reading, I would recommend against using recursion for problems such as this - lists are much faster and avoid recursion entirely. I would implement this as: ``` def fibonacci(n): f = [0,1,1] for i in xrange(3,n): f.append(f[i-1] + f[i-2]) return 'The...
celery-django can't find settings
3,323,125
13
2010-07-23T23:39:33Z
3,323,853
19
2010-07-24T04:49:14Z
[ "python", "django", "settings", "celery", "python-import" ]
I have a Django project that uses [Celery](http://pypi.python.org/pypi/django-celery) for running asynchronous tasks. I'm doing my development on a Windows XP machine. Starting my Django server (`python manage.py runserver 80`) works fine, but attempting to start the Celery Daemon (`python manage.py celeryd start`) fa...
Apparently this is a problem with [running Celery on Windows](http://groups.google.com/group/celery-users/browse_thread/thread/43a95be6865a636/d91ab2492885f3d4?lnk=gst&q=settings#d91ab2492885f3d4). Using the *--settings* argument ala `python manage.py celeryd start --settings=settings` did the trick.
Start ipython running a script
3,323,230
42
2010-07-24T00:14:12Z
3,323,899
21
2010-07-24T05:08:06Z
[ "python", "ipython" ]
My use case is I want to initialize some functions in a file and then start up ipython with those functions defined. Is there any way to do something like ipython --run\_script=myscript.py?
Per [the docs](http://ipython.org/ipython-doc/stable/interactive/reference.html), it's trivial: > You start IPython with the command: ``` $ ipython [options] files ``` > If invoked with no options, it > executes all the files listed in > sequence and drops you into the > interpreter while still acknowledging > any o...
Start ipython running a script
3,323,230
42
2010-07-24T00:14:12Z
9,923,008
53
2012-03-29T09:53:37Z
[ "python", "ipython" ]
My use case is I want to initialize some functions in a file and then start up ipython with those functions defined. Is there any way to do something like ipython --run\_script=myscript.py?
In recent versions of ipython you do need to add the `-i` option to get into the interactive environment afterwards. Without the `-i` it just runs the code in myfile.py and returns to the prompt. ``` $ ipython -i myfile.py ```
Start ipython running a script
3,323,230
42
2010-07-24T00:14:12Z
12,151,519
10
2012-08-28T01:04:48Z
[ "python", "ipython" ]
My use case is I want to initialize some functions in a file and then start up ipython with those functions defined. Is there any way to do something like ipython --run\_script=myscript.py?
Nowadays, you can use the startup folder of ipython, which is located in your home directory (C:\users\[username]\.ipython on Windows). Go into the default profile and you'll see a startup folder with a README file. Just put any Python scripts in there, or if you want ipython commands, put them in a file with an .ipy e...
Character detection in a text file in Python using the Universal Encoding Detector (chardet)
3,323,770
13
2010-07-24T04:07:19Z
3,323,810
24
2010-07-24T04:24:09Z
[ "python", "character-encoding" ]
I am trying to use the Universal Encoding Detector (chardet) in Python to detect the most probable character encoding in a text file ('infile') and use that in further processing. While chardet is designed primarily for detecting the character encoding of webpages, I have found an [example](http://dbaktiar.wordpress.c...
`chardet.detect` returns a dictionary which provides the encoding as the value associated with the key `'encoding'`. So you can do this: ``` import chardet rawdata = open(infile, "r").read() result = chardet.detect(rawdata) charenc = result['encoding'] ```
Is Python's ctypes.c_long 64 bit on 64 bit systems?
3,323,778
6
2010-07-24T04:09:10Z
3,324,018
8
2010-07-24T06:01:23Z
[ "python", "64bit", "ctypes" ]
In C, long is 64 bit on a 64 bit system. Is this reflected in Python's [ctypes](http://docs.python.org/library/ctypes.html#ctypes.c_long) module?
The size of `long` [depends on the memory model](http://en.wikipedia.org/wiki/64-bit#Specific_C-language_data_models). On Windows (LLP64) it is 32-bit, on UNIX (LP64) it is 64-bit. If you need a 64-bit integer, use [`c_int64`](http://docs.python.org/library/ctypes.html#ctypes.c_int64). If you need a pointer-sized int...
Puzzle that defies the brute force approach?
3,324,306
13
2010-07-24T07:59:20Z
3,324,868
7
2010-07-24T11:17:37Z
[ "python", "math", "puzzle" ]
I bought a blank DVD to record my favorite TV show. It came with 20 digit stickers. 2 of each of '0'-'9'. I thought it would be a good idea to numerically label my new DVD collection. I taped the '1' sticker on my first recorded DVD and put the 19 leftover stickers in a drawer. The next day I bought another blank D...
**This is old solution**, completely new 6 bajillion times faster solution [is on the bottom](http://stackoverflow.com/questions/3324306/puzzle-that-defies-the-brute-force-approach/3328629#3328629). Solution: ``` time { python solution.py; } 0: 0 1: 199990 2: 1999919999999980 3: 19999199999999919999999970 4: 1999919...
Declaring members only in constructor
3,324,697
7
2010-07-24T10:22:11Z
3,324,739
9
2010-07-24T10:35:00Z
[ "python", "constructor", "member" ]
I'm coming from a C++ background to python I have been declaring member variables and setting them in a C++esqe way like so: ``` class MyClass: my_member = [] def __init__(self,arg_my_member): self.my_member = arg_my_member ``` Then I noticed in some open source code, that the initial declaration `m...
The way you are doing it means that you'll now have a "static" member and a "non-static" member of the same name. ``` class MyClass: my_member = [] def __init__(self, arg_my_member): self.my_member = arg_my_member >>> a = MyClass(42) >>> print a.my_member 42 >>> print MyClass.my_member [] ```
Emailing admin when a 500 error occurs
3,324,743
4
2010-07-24T10:36:33Z
3,325,584
8
2010-07-24T15:06:01Z
[ "python", "bottle" ]
How can I send an email to admin when a 500 error occurs, in python. The web framework I'm using is 'bottle'.
Just use the `@error(code)` decorator to define an error handling page, like so: ``` from bottle import run, error, route @error(500) def handle_500_error(code): # add mail send code here return "Error message here" @route("/test_500") def cause_error(): raise Exception run() ``` Just navigate to `/test_500`...
Use of properties in python like in example C#
3,324,920
7
2010-07-24T11:33:38Z
3,324,956
7
2010-07-24T11:46:39Z
[ "c#", "python", "properties" ]
I currently work with Python for a while and I came to the point where I questioned myself whether I should use "Properties" in Python as often as in C#. In C# I've mostly created properties for the majority of my classes. It seems that properties are not that popular in python, am I wrong? How to use properties in Py...
I would you recommend to read this, even it is directed to Java progrmamers: [Python Is Not Java](http://dirtsimple.org/2004/12/python-is-not-java.html)
Use of properties in python like in example C#
3,324,920
7
2010-07-24T11:33:38Z
3,324,965
10
2010-07-24T11:49:19Z
[ "c#", "python", "properties" ]
I currently work with Python for a while and I came to the point where I questioned myself whether I should use "Properties" in Python as often as in C#. In C# I've mostly created properties for the majority of my classes. It seems that properties are not that popular in python, am I wrong? How to use properties in Py...
Properties are often no required if all you do is set and query member variables. Because Python has no concept of encapsulation, all member variables are public and often there is no need to encapsulate accesses. However, properties are possible, perfectly legitimate and popular: ``` class C(object): def __init__...
Yielding until all needed values are yielded, is there way to make slice to become lazy
3,324,947
3
2010-07-24T11:42:22Z
3,324,975
8
2010-07-24T11:52:23Z
[ "python", "generator", "variable-assignment", "slice", "lazy-sequences" ]
Is there way to stop yielding when generator did not finish values and all needed results have been read? I mean that generator is giving values without ever doing StopIteration. For example, this never stops: (REVISED) ``` from random import randint def devtrue(): while True: yield True answers=[False f...
You can call `close()` on the generator object. This way, a `GeneratorExit` exception is raised within the generator and further calls to its `next()` method will raise `StopIteration`: ``` >>> def test(): ... while True: ... yield True ... >>> gen = test() >>> gen <generator object test at ...> >>> gen.n...
Python - The request headers for mechanize
3,325,052
4
2010-07-24T12:20:37Z
3,325,068
8
2010-07-24T12:25:53Z
[ "python", "mechanize" ]
I am looking for a way to view the request (not response) headers, specifically what browser mechanize claims to be. Also how would I go about manipulating them, eg setting another browser? Example: ``` import mechanize browser = mechanize.Browser() # Now I want to make a request to eg example.com with custom headers...
``` browser.addheaders = [('User-Agent', 'Mozilla/5.0 blahblah')] ```
Creating indexes - MongoDB
3,325,505
2
2010-07-24T14:42:29Z
3,325,604
7
2010-07-24T15:13:49Z
[ "python", "django", "mongodb", "pymongo", "mongoengine" ]
My "table" looks like this: ``` {'name':'Rupert', 'type':'Unicorn', 'actions':[ {'time':0, 'position':[0,0], 'action':'run'}, {'time':50, 'position':[50,0], 'action':'stoprun'}, {'time':50, 'position':[50,0], 'action':'jump'}, {'time':55, 'position':[50,0], 'action':'laugh'}, ... ]} ``` Is there a...
Thanks to **skot** in **#mongodb**!! One solution is: ``` [...].ensureIndex({"actions.time":1}) ``` for creating an index on the time field within the actions list.
Creating indexes - MongoDB
3,325,505
2
2010-07-24T14:42:29Z
6,483,098
10
2011-06-26T09:16:34Z
[ "python", "django", "mongodb", "pymongo", "mongoengine" ]
My "table" looks like this: ``` {'name':'Rupert', 'type':'Unicorn', 'actions':[ {'time':0, 'position':[0,0], 'action':'run'}, {'time':50, 'position':[50,0], 'action':'stoprun'}, {'time':50, 'position':[50,0], 'action':'jump'}, {'time':55, 'position':[50,0], 'action':'laugh'}, ... ]} ``` Is there a...
Example for pymongo: ``` import pymongo mongo = pymongo.Connection('localhost') collection = mongo['database']['hosts'] collection.ensure_index('host_name', unique=True) ```
Python list, lookup object name, efficiency advice
3,325,711
3
2010-07-24T15:45:28Z
3,325,743
8
2010-07-24T15:56:52Z
[ "python", "algorithm", "list", "performance", "list-comprehension" ]
Suppose I have the following object: ``` class Foo(object): def __init__(self, name=None): self.name = name def __repr__(self): return self.name ``` And a list containing multiple instances, such as: ``` list = [Foo(name='alice'), Foo(name='bob'), Foo(name='charlie')] ``` If I want to find an object wi...
Try this for size: ``` class Foo(object): _all_names = {} def __init__(self, name=None): self.name = name @property def name(self): return self._name @name.setter def name(self, name): self._name = name self._all_names[name] = self @classmethod def get_by...
Simple list comprehension
3,326,428
3
2010-07-24T18:58:00Z
3,326,471
7
2010-07-24T19:12:18Z
[ "python", "list-comprehension" ]
I want a dictionary of files: ``` files = [files for (subdir, dirs, files) in os.walk(rootdir)] ``` But I get, ``` files = [['filename1', 'filename2']] ``` when I want ``` files = ['filename1', 'filename2'] ``` How do I prevent looping through that tuple? Thanks!
Both of these work: ``` [f for (subdir, dirs, files) in os.walk(rootdir) for f in files] sum([files for (subdir, dirs, files) in os.walk(rootdir)], []) ``` Sample output: ``` $ find /tmp/test /tmp/test /tmp/test/subdir1 /tmp/test/subdir1/file1 /tmp/test/subdir2 /tmp/test/subdir2/file2 $ python >>> import os >>> roo...
How to properly columnize tables in a Django template
3,326,514
2
2010-07-24T19:19:49Z
3,326,859
9
2010-07-24T20:51:59Z
[ "python", "django", "django-templates" ]
I am currently trying to break a list of people (aprox 20 to 30 items) into a table with 4 columns. Here is my current code. ``` <table> {% for person in people %} {% cycle "<tr><td>" "<td>" "<td>" "<td>" %} {{ person }} {% cycle "</td>" "</td>" "</td>" "</td></tr>" %} {% endfor %} </table> ``` Obviou...
Use the `divisibleby` filter. ``` <tr> {% for person in people %} <td>{{ person }}</td> {% if forloop.counter|divisibleby:4 and not forloop.last %}</tr><tr>{% endif %} {% endfor %} </tr> ```
Is it common/good practice to test for type values in Python?
3,327,454
10
2010-07-25T00:09:39Z
3,327,459
19
2010-07-25T00:13:32Z
[ "python", "oop", "introspection" ]
Is it common in Python to keep testing for type values when working in a OOP fashion? ``` class Foo(): def __init__(self,barObject): self.bar = setBarObject(barObject) def setBarObject(barObject); if (isInstance(barObject,Bar): self.bar = barObject else: # throw...
Nope, in fact it's overwhelmingly common *not* to test for type values, as in your second approach. The idea is that a client of your code (i.e. some other programmer who uses your class) should be able to pass any kind of object that has all the appropriate methods or properties. If it doesn't happen to be an instance...
Can the execution of statements in Python be delayed?
3,327,775
9
2010-07-25T02:37:37Z
3,327,776
34
2010-07-25T02:39:05Z
[ "python", "sleep", "delay", "timing" ]
I want it to run the first line **print 1** then wait 1 second to run the second command **print 2**, etc. Pseudo-code: ``` print 1 wait(1 seconds) print 2 wait(0.45 seconds) print 3 wait(3 seconds) print 4 ```
[`time.sleep(seconds)`](http://docs.python.org/library/time.html) ``` import time print 1 time.sleep(1) print 2 time.sleep(0.45) print 3 time.sleep(3) print 4 ```
Can the execution of statements in Python be delayed?
3,327,775
9
2010-07-25T02:37:37Z
3,328,021
13
2010-07-25T04:33:55Z
[ "python", "sleep", "delay", "timing" ]
I want it to run the first line **print 1** then wait 1 second to run the second command **print 2**, etc. Pseudo-code: ``` print 1 wait(1 seconds) print 2 wait(0.45 seconds) print 3 wait(3 seconds) print 4 ```
All the answers have assumed that you want or can manually insert `time.sleep` after each line, but may be you want a automated way to do that for a large number of lines of code e.g. consider this code ``` def func1(): print "func1 1",time.time() print "func1 2",time.time() def func2(): print "func2 1",t...
F# vs IronPython: When is one preferred to the other?
3,327,885
24
2010-07-25T03:34:33Z
3,381,150
22
2010-08-01T07:25:15Z
[ ".net", "python", "f#", "ironpython" ]
While the languages F# and IronPython are technically dissimilar, there is large overlap between their potential uses in my opinion. When is one more applicable than the other? So far it look to me like F# is computationally more efficient while IronPython inherits a better library from Python. I am happy to be correc...
> So the question boils down to: are > there any reasons, apart from a > preference of one paradigm to another > or some team or corporate preferences, > that would make you pick F# rather > than IronPython or vice versa? > Assuming you are equally confident in > both? Or are they exactly equivalent > for all practical...
How can I convert a Python datetime object to UTC?
3,327,946
32
2010-07-25T03:59:08Z
3,327,960
9
2010-07-25T04:05:10Z
[ "python", "datetime", "time", "utc" ]
I have a python datetime object which I would like to convert to UTC. I am planning to output it in RFC 2822 format to put in an HTTP header, but I am not sure if that matters for this question. I found some information on this site about converting time objects, and it looks simpler that way, but this time I really wa...
First you need to make sure the datetime is a timezone-aware object by setting its `tzinfo` member: <http://docs.python.org/library/datetime.html#datetime.tzinfo> You can then use the `.astimezone()` function to convert it: <http://docs.python.org/library/datetime.html#datetime.datetime.astimezone>
How can I convert a Python datetime object to UTC?
3,327,946
32
2010-07-25T03:59:08Z
13,624,191
22
2012-11-29T10:55:26Z
[ "python", "datetime", "time", "utc" ]
I have a python datetime object which I would like to convert to UTC. I am planning to output it in RFC 2822 format to put in an HTTP header, but I am not sure if that matters for this question. I found some information on this site about converting time objects, and it looks simpler that way, but this time I really wa...
``` from datetime import datetime, timedelta datetime.utcnow() + timedelta(minutes=5) ```
How can I tell if a file is a descendant of a given directory?
3,328,012
6
2010-07-25T04:30:52Z
3,328,028
7
2010-07-25T04:37:14Z
[ "python", "filesystems" ]
On the surface, this is pretty simple, and I could implement it myself easily. Just successively call dirname() to go up each level in the file's path and check each one to see if it's the directory we're checking for. But symlinks throw the whole thing into chaos. Any directory along the path of either the file or di...
Use [`os.path.realpath`](https://docs.python.org/3/library/os.path.html#os.path.realpath) and [`os.path.commonprefix`](https://docs.python.org/3/library/os.path.html#os.path.commonprefix): ``` os.path.commonprefix(['/the/dir/', os.path.realpath(filename)]) == "/the/dir/" ``` `os.path.realpath` will expand any symlink...
Python operator precedence
3,328,355
8
2010-07-25T06:54:43Z
3,328,359
14
2010-07-25T06:56:20Z
[ "python", "expression", "precedence" ]
Python docs say that \* and / have the same precedence. I know that expressions in python are evaluated from left to right. Can i rely in that and assume that j\*j/m is always equal to (j\*j)/m avoiding the parentheses? If this is the case can i assume that this holds for operators with the same precedence in gene...
Yes - different operators with the same precedence are left-associative; that is, the two leftmost items will be operated on, then the result and the 3rd item, and so on. An exception is the `**` operator: ``` >>> 2 ** 2 ** 3 256 ``` Also, comparison operators (`==`, `>`, et cetera) don't behave in an associative ma...
Python operator precedence
3,328,355
8
2010-07-25T06:54:43Z
3,328,407
13
2010-07-25T07:29:10Z
[ "python", "expression", "precedence" ]
Python docs say that \* and / have the same precedence. I know that expressions in python are evaluated from left to right. Can i rely in that and assume that j\*j/m is always equal to (j\*j)/m avoiding the parentheses? If this is the case can i assume that this holds for operators with the same precedence in gene...
But, if it is ambiguous to you - the coder - and it must be because you have to ask, then expect it will be at least as ambiguous for the reader and waste a couple octets for clarity. Relying on precedence rules is great if you happen to be a compiler. **added responses to comments**: For the person reading code who...
How to make Django's devserver public ? Is it generaly possible?
3,328,926
22
2010-07-25T11:06:02Z
3,328,937
72
2010-07-25T11:09:03Z
[ "python", "django", "devserver" ]
I've got a question. I'm currently trying out the Django framework and I would share/present/show some stuff I've made to my workmate/friends. I work in Ubuntu under Win7 via VMware. So my wish/desire is to send my current pub-IP with port (e.g <http://123.123.123.123:8181/django-app/>) to my friends so they could test...
``` python manage.py runserver 0.0.0.0:8181 ``` This will [run development server](http://docs.djangoproject.com/en/dev/ref/django-admin/?from=olddocs#runserver-port-or-ipaddr-port) that should listen on all IP's on port 8181. Note that as of [Jun 17, 2011 Django development](https://github.com/django/django/commit/c...
How to make Django's devserver public ? Is it generaly possible?
3,328,926
22
2010-07-25T11:06:02Z
12,295,583
8
2012-09-06T08:05:53Z
[ "python", "django", "devserver" ]
I've got a question. I'm currently trying out the Django framework and I would share/present/show some stuff I've made to my workmate/friends. I work in Ubuntu under Win7 via VMware. So my wish/desire is to send my current pub-IP with port (e.g <http://123.123.123.123:8181/django-app/>) to my friends so they could test...
Assuming you have ruby installed, you just have to get localtunnel: ``` gem install localtunnel ``` then start your python development server with: ``` python manage.py runserver 0.0.0.0:8000 ``` in another shell, start localtunnel: ``` localtunnel -k ~/.ssh/id_rsa.pub 8000 ``` That will output an url to access y...
how to remove '\xe2' from a list
3,328,995
8
2010-07-25T11:27:52Z
3,329,029
18
2010-07-25T11:40:36Z
[ "python", "regex" ]
I am new to python and am using it to use nltk in my project.After word-tokenizing the raw data obtained from a webpage I got a list containing '\xe2' ,'\xe3','\x98' etc.However I do not need these and want to delete them. I simply tried ``` if '\x' in a ``` and ``` if a.startswith('\xe') ``` and it gives me an er...
You can use `unicode(a, 'ascii', 'ignore')` to remove all non-ascii characters in the string at once.
how to remove '\xe2' from a list
3,328,995
8
2010-07-25T11:27:52Z
3,329,312
7
2010-07-25T13:18:04Z
[ "python", "regex" ]
I am new to python and am using it to use nltk in my project.After word-tokenizing the raw data obtained from a webpage I got a list containing '\xe2' ,'\xe3','\x98' etc.However I do not need these and want to delete them. I simply tried ``` if '\x' in a ``` and ``` if a.startswith('\xe') ``` and it gives me an er...
It helps here to understand the difference between a string literal and a string. A **string literal** is a sequence of characters in your *source code*. When parsed and compiled by the Python interpreter, it produces a **string**, which is a sequence of characters in *memory*. For example, the string literal `"` `a`...
Python library for monitoring /proc/diskstats?
3,329,165
5
2010-07-25T12:21:58Z
5,750,108
10
2011-04-21T21:44:00Z
[ "python", "linux", "io", "monitoring" ]
I would like to monitor system IO load from a python program, accessing statistics similar to those provided in `/proc/diskstats` in linux (although obviously a cross-platform library would be great). Is there an existing python library that I could use to query disk IO statistics on linux?
In case anyone else is trying to parse /proc/diskstats with Python like Alex suggested: ``` def diskstats_parse(dev=None): file_path = '/proc/diskstats' result = {} # ref: http://lxr.osuosl.org/source/Documentation/iostats.txt columns_disk = ['m', 'mm', 'dev', 'reads', 'rd_mrg', 'rd_sectors', ...
Limit the number of sentences in a string
3,329,386
5
2010-07-25T13:44:00Z
3,329,432
10
2010-07-25T13:57:21Z
[ "python" ]
A beginner's Python question: I have a string with x number of sentences. How to I extract first 2 sentences (may end with . or ? or !)
Ignoring considerations such as when a `.` constitutes the end of sentence: ``` import re ' '.join(re.split(r'(?<=[.?!])\s+', phrase, 2)[:-1]) ``` EDIT: Another approach that just occurred to me is this: ``` re.match(r'(.*?[.?!](?:\s+.*?[.?!]){0,1})', phrase).group(1) ``` Notes: 1. Whereas the first solution lets ...
How to remove u'' from python script result?
3,329,631
3
2010-07-25T14:55:01Z
3,329,789
7
2010-07-25T15:37:04Z
[ "python", "utf-8", "web-crawler", "scrapy" ]
I'm trying to write parsing script using python/scrapy. How can I remove [] and u' from strings in result file? Now I have text like this: ``` from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector from scrapy.utils.markup import remove_tags from googleparser.items import GoogleparserItem ...
more prettier - `print qqq.pop()`
What does this stand for?
3,329,775
3
2010-07-25T15:35:03Z
3,329,797
10
2010-07-25T15:39:03Z
[ "python", "syntax" ]
What does '\r' mean? What does it do? I have never seen it before and its giving me headaches. It doesnt seem to have any purpose, since 'a\ra' prints as 'aa', but its not the same as the string 'aa'. Im using python 2.6
It's an old control character from typewriters. It means "carriage return". In this time, when you pressed "enter", you were going to the next line, then the carriage went back to the beginning of the line (hence the carriage return). Then with computers, different OSes made different choices to represent new lines. On...
What does this stand for?
3,329,775
3
2010-07-25T15:35:03Z
3,329,892
8
2010-07-25T16:00:30Z
[ "python", "syntax" ]
What does '\r' mean? What does it do? I have never seen it before and its giving me headaches. It doesnt seem to have any purpose, since 'a\ra' prints as 'aa', but its not the same as the string 'aa'. Im using python 2.6
For me (on a Mac OS X 10.5 Terminal.App, Python 2.6.5): ``` >>> print 'a\ra' a ``` or to give a better example: ``` >>> print 'longstring\rshort' shorttring ``` IOW, the `\r` "returns the cursor to the start of the line" (without initiating a new long) so that `'short'` "overwrites" the beginning of `'longstring'`....
adjusting heights of individual subplots in matplotlib in Python
3,330,137
8
2010-07-25T17:04:20Z
14,071,972
8
2012-12-28T15:41:23Z
[ "python", "numpy", "matplotlib", "scipy" ]
if I have a series of subplots with one column and many rows, i.e.: ``` plt.subplot(4, 1, 1) # first subplot plt.subplot(4, 1, 2) # second subplot # ... ``` how can I adjust the height of the first N subplots? For example, if I have 4 subplots, each on its own row, I want all of them to have the same width but the fi...
Even though this question is old, I was looking to answer a very similar question. @Joe's reference to [AxesGrid](http://matplotlib.org/mpl_toolkits/axes_grid/users/overview.html#axesgrid), was the answer to my question, and has **very** straightforward usage, so I wanted to illustrate that functionality for completene...
How can I validate CSS within a script?
3,330,571
9
2010-07-25T18:57:59Z
3,330,582
10
2010-07-25T19:00:19Z
[ "php", "python", "css", "compiler-construction", "validation" ]
Is there a library out there which will validate CSS? The only tools I can find to do so are web sites. If one of these sites has an API, that would fit the bill, too. I have a script that serves as a CSS compiler. It sets various variables according to settings for a theme, and generates and writes a CSS file. Befor...
W3C has an API: <http://jigsaw.w3.org/css-validator/api.html> You can also download the validator and run it locally: <http://jigsaw.w3.org/css-validator/DOWNLOAD.html> You need to be able to run java from your script.
a StringIO like class, that extends django.core.files.File
3,330,677
6
2010-07-25T19:25:59Z
3,332,232
25
2010-07-26T04:36:37Z
[ "python", "django" ]
``` class MyModel(models.Model) image = models.FileField(upload_to="blagh blagh...") #more spam... ``` I have a file in memory and I want to save it via Django FileField save method, like this: ``` photo.image.save(name, buffer) # second arg should be django File ``` I've tried to use StringIO, but it doesn't exte...
You can use ContentFile instead of File ``` from django.core.files.base import ContentFile photo.image.save(name, ContentFile(buffer)) ```
a StringIO like class, that extends django.core.files.File
3,330,677
6
2010-07-25T19:25:59Z
7,749,840
7
2011-10-13T05:30:57Z
[ "python", "django" ]
``` class MyModel(models.Model) image = models.FileField(upload_to="blagh blagh...") #more spam... ``` I have a file in memory and I want to save it via Django FileField save method, like this: ``` photo.image.save(name, buffer) # second arg should be django File ``` I've tried to use StringIO, but it doesn't exte...
Re Jason's answer. Note that ContentFile only accepts strings, not any file-like object. Here's one that does -- ``` from django.core.files.base import * class StreamFile(ContentFile): """ Django doesn't provide a File wrapper suitable for file-like objects (eg StringIO) """ def __init__(self, st...
Prepend prefix to list elements with list comprehension
3,330,880
12
2010-07-25T20:29:09Z
3,330,891
27
2010-07-25T20:31:45Z
[ "python", "list-comprehension" ]
Having a list like this: ``` ['foo','spam','bar'] ``` is it possible, using list comprehension, to obtain this list as result? ``` ['foo','ok.foo', 'spam', 'ok.spam', 'bar', 'ok.bar'] ```
``` In [67]: alist = ['foo','spam', 'bar'] In [70]: [prefix+elt for elt in alist for prefix in ('','ok.') ] Out[70]: ['foo', 'ok.foo', 'spam', 'ok.spam', 'bar', 'ok.bar'] ```
What is the proper method of printing Python Exceptions?
3,330,991
9
2010-07-25T21:01:32Z
3,331,004
9
2010-07-25T21:04:47Z
[ "python", "exception" ]
``` except ImportError as xcpt: print "Import Error: " + xcpt.message ``` Gets you a deprecation warning in 2.6 because message is going away. [Stackoverflow](http://stackoverflow.com/questions/1272138/baseexception-message-deprecated-in-python-2-6) How should you be dealing with ImportError? (Not...
The correct approach is ``` xcpt.args ``` Only the `message` attribute is going away. The exception will continue to exist and it will continue to have arguments. Read this: <http://www.python.org/dev/peps/pep-0352/> which has some rational for removing the `messages` attribute.
Python: Unpacking an inner nested tuple/list while still getting its index number
3,331,643
21
2010-07-26T00:48:18Z
3,331,658
39
2010-07-26T00:51:46Z
[ "python", "list", "tuples", "enumerate", "iterable-unpacking" ]
I am familiar with using `enumerate()`: ``` >>> seq_flat = ('A', 'B', 'C') >>> for num, entry in enumerate(seq_flat): print num, entry 0 A 1 B 2 C ``` I want to be able to do the same for a nested list: ``` >>> seq_nested = (('A', 'Apple'), ('B', 'Boat'), ('C', 'Cat')) ``` I can unpack it with: ``` >>> for...
``` for i, (letter, word) in enumerate(seq_nested): print i, letter, word ```
obtaining pid of child process
3,332,043
5
2010-07-26T03:27:35Z
17,112,379
8
2013-06-14T15:46:24Z
[ "python", "django" ]
``` Hi, ``` I am using python's multiprocessing module to spawn new process as follows : ``` import multiprocessing import os d = multiprocessing.Process(target=os.system,args=('iostat 2 > a.txt',)) d.start() ``` I want to obtain pid of iostat command or the command executed using multiprocessing module When I exe...
Similar to @rakslice, you can use **psutil**: ``` import signal, psutil def kill_child_processes(parent_pid, sig=signal.SIGTERM): try: parent = psutil.Process(parent_pid) except psutil.NoSuchProcess: return children = parent.children(recursive=True) for process in children: process.se...
sqlalchemy filter multiple columns
3,332,991
22
2010-07-26T07:32:39Z
3,353,200
35
2010-07-28T13:18:12Z
[ "python", "sql", "database", "sqlalchemy" ]
How do I combine two columns and apply filter? For example, I want to search in both the "firstname" and "lastname" columns at the same time. Here is how I have been doing it if searching only one column: ``` query = meta.Session.query(User).filter(User.firstname.like(searchVar)) ```
You can use SQLAlchemy's [`or_` function](http://docs.sqlalchemy.org/en/latest/core/sqlelement.html?highlight=or_#sqlalchemy.sql.expression.or_) to search in more than one column (the underscore is necessary to distinguish it from Python's own `or`). Here's an example: ``` from sqlalchemy import or_ query = meta.Sess...
sqlalchemy filter multiple columns
3,332,991
22
2010-07-26T07:32:39Z
3,792,292
25
2010-09-25T03:00:18Z
[ "python", "sql", "database", "sqlalchemy" ]
How do I combine two columns and apply filter? For example, I want to search in both the "firstname" and "lastname" columns at the same time. Here is how I have been doing it if searching only one column: ``` query = meta.Session.query(User).filter(User.firstname.like(searchVar)) ```
You can simply call `filter` multiple times: ``` query = meta.Session.query(User).filter(User.firstname.like(searchVar1)). \ filter(User.lastname.like(searchVar2)) ```
stdout to tkinter GUI
3,333,334
3
2010-07-26T08:39:19Z
3,333,386
7
2010-07-26T08:49:32Z
[ "python", "tkinter" ]
How can I redirect stdout data to a tkinter Text widget?
You need to make a file-like class whose `write` method writes to the Tkinter widget instead, and then do `sys.stdout = <your new class>`. See [this question](http://stackoverflow.com/questions/2914603/why-do-i-get-a-segmentation-fault-while-redirecting-sys-stdout-to-tkinter-text-wi). Example (copied from the link): ...
Is there an online IDE for Google App Engine?
3,333,544
17
2010-07-26T09:18:17Z
13,254,380
12
2012-11-06T15:38:17Z
[ "python", "google-app-engine", "ide" ]
I am learning Google App Engine / Python and I love it. Unfortunately I am not allowed to use my own computer in the office and not allowed to install anything on the corporate machine. It would be so great to have an online IDE for Google App Engine where I could play with my Python code using any browser, including ...
[cloud-ide.com](http://cloud-ide.com/) offer **Exo IDE**. This is a richly featured, cloud-based IDE that you use in the browser. Importantly for you, it supports the full cycle of deployment to various Platform as a Service (PaaS) providers, including Google App Engine! I've used this before, and it's as simple as sa...
how to deal with unicode in mako?
3,333,550
12
2010-07-26T09:19:17Z
3,343,018
12
2010-07-27T11:15:35Z
[ "python", "unicode", "mako" ]
I constantly get this error using mako: ``` UnicodeEncodeError: 'ascii' codec can't encode character u'\xe0' in position 6: ordinal not in range(128) ``` I've told mako I'm using unicode in any possible way: ``` mylookup = TemplateLookup( directories=['plugins/stl/templates'], input_encoding='utf...
finally I saved my templates in unicode, actually (I guess) utf-16 instead of utf-8. their size on disk doubled and mako started complaining about a "CompileException("Unicode decode operation of encoding 'utf-8' bla bla", so I changed the first line in all of them in: ``` ## -*- coding: utf-16 -*- ``` and *removed* ...
Problem porting sudoku solver from C to Python
3,333,627
4
2010-07-26T09:30:38Z
3,333,688
11
2010-07-26T09:39:55Z
[ "python", "c", "scope", "porting", "sudoku" ]
I recently wrote a sudoku solver in C to practice programming. After completing it I decided to write an equivalent program in Python for a comparison between the languages and more practice and this is where the problem is. It seems to be that a global variable (sudokupossibilities[][][]) I declared outside the while ...
This line does not do what you think: ``` sudokupossibilities = [[[1] * 9] * 9] * 9 ``` Try this simple program: ``` sudokupossibilities = [[[1] * 9] * 9] * 9 sudokupossibilities sudokupossibilities[1][1][1]=2 sudokupossibilities ``` (And the output of a much-simplified version:) ``` >>> s=[[[1] * 3] * 3] * 3 >>> ...
python: urllib2 how to send cookie with urlopen request
3,334,809
68
2010-07-26T12:36:37Z
3,334,959
92
2010-07-26T12:58:17Z
[ "python", "urllib2" ]
I am trying to use urllib2 to open url and to send specific cookie text to the server. E.g. I want to open site [Solve chess problems](http://chess-problems.prg), with a specific cookie, e.g. search=1. How do I do it? I am trying to do the following: ``` import urllib2 (need to add cookie to the request somehow) urll...
Cookie is just another HTTP header. ``` import urllib2 opener = urllib2.build_opener() opener.addheaders.append(('Cookie', 'cookiename=cookievalue')) f = opener.open("http://example.com/") ``` See [urllib2 examples](http://docs.python.org/library/urllib2.html#examples) for other ways how to add HTTP headers to your r...
python: urllib2 how to send cookie with urlopen request
3,334,809
68
2010-07-26T12:36:37Z
8,206,372
51
2011-11-21T01:35:17Z
[ "python", "urllib2" ]
I am trying to use urllib2 to open url and to send specific cookie text to the server. E.g. I want to open site [Solve chess problems](http://chess-problems.prg), with a specific cookie, e.g. search=1. How do I do it? I am trying to do the following: ``` import urllib2 (need to add cookie to the request somehow) urll...
Maybe using [cookielib.CookieJar](http://docs.python.org/2/library/cookielib.html#cookiejar-and-filecookiejar-objects) can help you. For instance when posting to a page containing a form: ``` import urllib2 import urllib from cookielib import CookieJar cj = CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookie...
python: urllib2 how to send cookie with urlopen request
3,334,809
68
2010-07-26T12:36:37Z
10,865,139
14
2012-06-02T19:11:12Z
[ "python", "urllib2" ]
I am trying to use urllib2 to open url and to send specific cookie text to the server. E.g. I want to open site [Solve chess problems](http://chess-problems.prg), with a specific cookie, e.g. search=1. How do I do it? I am trying to do the following: ``` import urllib2 (need to add cookie to the request somehow) urll...
You might want to take a look at the excellent HTTP Python library called [Requests](http://docs.python-requests.org/en/latest/index.html). It makes every task involving HTTP a bit easier than urllib2. From [Cookies](http://docs.python-requests.org/en/latest/user/quickstart/#cookies) section of quickstart guide: > To ...
Get the current value of env.hosts list with Python Fabric Library
3,334,936
23
2010-07-26T12:55:09Z
3,335,029
33
2010-07-26T13:06:20Z
[ "python", "fabric" ]
I've got this code (`foo` and `bar` are local servers): ``` env.hosts = ['foo', 'bar'] def mytask(): print(env.hosts[0]) ``` Which, of course prints *foo* every iteration. As you probably know, Fabric iterates through the env.hosts list and executes mytask() on each of them this way: ``` fab mytask ``` does ...
Use `env.host_string`. You can find a full list of `env` variables [here](http://docs.fabfile.org/en/1.8/usage/env.html#full-list-of-env-vars).
Get the current value of env.hosts list with Python Fabric Library
3,334,936
23
2010-07-26T12:55:09Z
3,336,469
22
2010-07-26T15:43:56Z
[ "python", "fabric" ]
I've got this code (`foo` and `bar` are local servers): ``` env.hosts = ['foo', 'bar'] def mytask(): print(env.hosts[0]) ``` Which, of course prints *foo* every iteration. As you probably know, Fabric iterates through the env.hosts list and executes mytask() on each of them this way: ``` fab mytask ``` does ...
You can just do: ``` env.hosts = ['foo', 'bar'] def mytask(): print(env.host) ``` Because when you're in the task as executed by fab, you'll have that var set for free.
Are object literals Pythonic?
3,335,268
22
2010-07-26T13:35:01Z
3,335,315
52
2010-07-26T13:39:40Z
[ "python", "object-literal" ]
JavaScript has object literals, e.g. ``` var p = { name: "John Smith", age: 23 } ``` and .NET has anonymous types, e.g. ``` var p = new { Name = "John Smith", Age = 23}; // C# ``` Something similar can be emulated in Python by (ab)using named arguments: ``` class literal(object): def __init__(self, **kwar...
Why not just use a dictionary? ``` p = {'name': 'John Smith', 'age': 23} print p print p['name'] print p['age'] ```
Are object literals Pythonic?
3,335,268
22
2010-07-26T13:35:01Z
3,335,367
27
2010-07-26T13:46:09Z
[ "python", "object-literal" ]
JavaScript has object literals, e.g. ``` var p = { name: "John Smith", age: 23 } ``` and .NET has anonymous types, e.g. ``` var p = new { Name = "John Smith", Age = 23}; // C# ``` Something similar can be emulated in Python by (ab)using named arguments: ``` class literal(object): def __init__(self, **kwar...
Have you considered using a [named tuple](http://docs.python.org/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields)? Using your dict notation ``` >>> L = namedtuple('literal', 'name age')(**{'name': 'John Smith', 'age': 23}) ``` or keyword arguments ``` >>> L = namedtuple('literal', ...
Are object literals Pythonic?
3,335,268
22
2010-07-26T13:35:01Z
3,335,732
7
2010-07-26T14:22:59Z
[ "python", "object-literal" ]
JavaScript has object literals, e.g. ``` var p = { name: "John Smith", age: 23 } ``` and .NET has anonymous types, e.g. ``` var p = new { Name = "John Smith", Age = 23}; // C# ``` Something similar can be emulated in Python by (ab)using named arguments: ``` class literal(object): def __init__(self, **kwar...
From [ActiveState](http://code.activestate.com/recipes/52308-the-simple-but-handy-collector-of-a-bunch-of-named/): ``` class Bunch: def __init__(self, **kwds): self.__dict__.update(kwds) # that's it! Now, you can create a Bunch # whenever you want to group a few variables: point = Bunch(datum=y, squared...
How to check if a MySQL connection is closed in Python?
3,335,342
19
2010-07-26T13:43:20Z
3,335,408
19
2010-07-26T13:51:22Z
[ "python", "mysql" ]
The question says everything. How can I check if my MySQL connection is closed in Python? I'm using MySQLdb, see <http://mysql-python.sourceforge.net/>
The `Connection.open` field will be `1` if the connection is open and `0` otherwise. So you can say ``` if conn.open: # do something ```
Google App Engine: Handlers and WSGI urls
3,335,446
6
2010-07-26T13:55:09Z
3,337,509
9
2010-07-26T17:53:55Z
[ "python", "google-app-engine" ]
I am new to GAE and I am creating an application with the webapp framework. I was wondering when do you set handlers in your app.yaml and when you define them in your WSGI? At first I thought you only have one main.py main file running the WSGIApplication but I notice if you want to use the GAE authorization you defin...
Either method of URL-routing is acceptable. **app.yaml-based URL routing** If you can easily structure your app to use app.yaml routing (and authorization), then it's worth trying: it'll be less code you'll have to debug, test, and maintain. Here's an example (from Google) with multiple entry points: <http://google...
Is while True: a suitable way to repeat a block until an accepted case is reached?
3,336,052
3
2010-07-26T14:57:01Z
3,336,090
8
2010-07-26T15:00:00Z
[ "python", "while-loop" ]
Is `while True` an accepted method for looping over a block of code until an accepted case is reached as below? Is there a more elegant way to do this? ``` while True: value = input() if value == condition: break else: pass # Continue code here. ``` Thank you for any input.
That's the way to do this in Python. You don't need the `else: pass` bit though. Note, that in python 2.x you're likely to want `raw_input` rather than `input`.
Python's `urllib2`: Why do I get error 403 when I `urlopen` a Wikipedia page?
3,336,549
38
2010-07-26T15:53:49Z
3,336,649
8
2010-07-26T16:05:35Z
[ "python", "http", "urllib2" ]
I have a strange bug when trying to `urlopen` a certain page from Wikipedia. This is the page: <http://en.wikipedia.org/wiki/OpenCola_(drink>) This is the shell session: ``` >>> f = urllib2.urlopen('http://en.wikipedia.org/wiki/OpenCola_(drink)') Traceback (most recent call last): File "C:\Program Files\Wing IDE 4...
To debug this, you'll need to trap that exception. ``` try: f = urllib2.urlopen('http://en.wikipedia.org/wiki/OpenCola_(drink)') except urllib2.HTTPError, e: print e.fp.read() ``` When I print the resulting message, it includes the following > "English > > Our servers are currently experiencing > a technical...
Python's `urllib2`: Why do I get error 403 when I `urlopen` a Wikipedia page?
3,336,549
38
2010-07-26T15:53:49Z
3,336,735
80
2010-07-26T16:15:59Z
[ "python", "http", "urllib2" ]
I have a strange bug when trying to `urlopen` a certain page from Wikipedia. This is the page: <http://en.wikipedia.org/wiki/OpenCola_(drink>) This is the shell session: ``` >>> f = urllib2.urlopen('http://en.wikipedia.org/wiki/OpenCola_(drink)') Traceback (most recent call last): File "C:\Program Files\Wing IDE 4...
[Wikipedias stance is](http://meta.wikimedia.org/wiki/Bot_policy#Unacceptable_usage): > Data retrieval: Bots may not be used > to retrieve bulk content for any use > not directly related to an approved > bot task. This includes dynamically > loading pages from another website, > which may result in the website being >...
Overriding inherited properties’ getters and setters in Python
3,336,767
17
2010-07-26T16:19:25Z
9,343,762
15
2012-02-18T18:09:19Z
[ "python", "properties" ]
I’m currently using the `@property` decorator to achieve “getters and setters” in a couple of my classes. I wish to be able to inherit these `@property` methods in a child class. I have some Python code (specifically, I’m working in py3k) which looks vaguely like so: ``` class A: @property def attr(se...
To override a setter in python 2 I did this: ``` class A(object): def __init__(self): self._attr = None @property def attr(self): return self._attr @attr.setter def attr(self, value): self._attr = value class B(A): @A.attr.setter def attr(self, value): # ...
Python/Web: What's the best way to run Python on a web server?
3,336,787
3
2010-07-26T16:21:34Z
3,336,818
9
2010-07-26T16:24:41Z
[ "python", "webserver", "mod-wsgi" ]
I am leasing a dedicated web server. I have a Python web-application. Which configuration option (CGI, FCGI, mod\_python, Passenger, etc) would result in Python being served the fastest on my web server and how do I set it up that way? **UPDATE**: Note, I'm *not* using a Python framework such as Django or Pylons.
I usually go the Apache + [mod\_wsgi](http://code.google.com/p/modwsgi/) route. It is pretty easy to set up. To answer your question about speed, I pulled this from the provided link: > The mod\_wsgi module is written in C code directly against the internal Apache and Python application programming interfaces. As suc...
Crontab wont run python script
3,337,149
10
2010-07-26T17:06:06Z
3,337,222
26
2010-07-26T17:14:35Z
[ "python", "crontab" ]
When I execute my python script from the command line I have no problems like so: > [rv@med240-183 db]$ python formatdb.py > [rv@med240-183 db]$ When I try to use crontab to run the script every midnight I get a series of errors: ``` import: unable to open X server `' @ import.c/ImportImageCommand/367. /home/rv/nc...
Add ``` #!/usr/bin/env python ``` to the beginning of your script - right now it's trying to execute your script as a bash, that line says "I'm a python script, please use the right interpreter". It's also called a hash-bang line, but it needs to be the first line in your script.
Numpy matrix to array
3,337,301
64
2010-07-26T17:25:23Z
3,338,368
80
2010-07-26T19:41:30Z
[ "python", "arrays", "matrix", "numpy" ]
I am using numpy. I have a matrix with 1 column and N rows and I want to get an array from with N elements. For example, if i have `M = matrix([[1], [2], [3], [4]])`, I want to get `A = array([1,2,3,4])`. To achieve it, I use `A = np.array(M.T)[0]`. Does anyone know a more elegant way to get the same result? Thanks!
If you'd like something a bit more readable, you can do this: ``` A = np.squeeze(np.asarray(M)) ``` Equivalently, you could also do: `A = np.asarray(M).reshape(-1)`, but that's a bit less easy to read.
Numpy matrix to array
3,337,301
64
2010-07-26T17:25:23Z
13,102,287
9
2012-10-27T17:09:04Z
[ "python", "arrays", "matrix", "numpy" ]
I am using numpy. I have a matrix with 1 column and N rows and I want to get an array from with N elements. For example, if i have `M = matrix([[1], [2], [3], [4]])`, I want to get `A = array([1,2,3,4])`. To achieve it, I use `A = np.array(M.T)[0]`. Does anyone know a more elegant way to get the same result? Thanks!
``` A, = np.array(M.T) ``` depends what you mean by elegance i suppose but thats what i would do
Numpy matrix to array
3,337,301
64
2010-07-26T17:25:23Z
20,765,358
45
2013-12-24T18:34:31Z
[ "python", "arrays", "matrix", "numpy" ]
I am using numpy. I have a matrix with 1 column and N rows and I want to get an array from with N elements. For example, if i have `M = matrix([[1], [2], [3], [4]])`, I want to get `A = array([1,2,3,4])`. To achieve it, I use `A = np.array(M.T)[0]`. Does anyone know a more elegant way to get the same result? Thanks!
``` result = M.A1 ``` <http://docs.scipy.org/doc/numpy/reference/generated/numpy.matrix.A1.html#numpy.matrix.A1> ``` matrix.A1 1-d base array ```
Set global hotkey with Python 2.6
3,337,973
10
2010-07-26T18:52:16Z
3,338,528
7
2010-07-26T20:01:04Z
[ "python", "keyboard", "wxpython", "hotkeys", "shortcut-key" ]
I wanna setup a global hotkey in python 2.6 that listens to the keyboard shortcut `ctrl` + `D` or `ctrl`+ `alt`+ `D` on windows, please help me
Tim Golden's [python/win32](http://timgolden.me.uk/python/win32_how_do_i.html) site is a useful resource for win32 related programming in python. In particular, this example should help: * [Catch system-wide hotkeys](http://timgolden.me.uk/python/win32_how_do_i/catch_system_wide_hotkeys.html)
Python: Sharing global variables between modules and classes therein
3,338,283
31
2010-07-26T19:30:28Z
3,338,357
31
2010-07-26T19:39:51Z
[ "python", "scope", "global-variables", "module" ]
I know that it's possible to share a global variable across modules in Python. However, I would like to know the extent to which this is possible and why. For example, global\_mod.py ``` x = None ``` mid\_access\_mod.py ``` from global_mod import * class delta: def __init__(self): print x ``` bot\_mod...
This happens because you are using immutable values (ints and None), and importing variables is like passing things by value, not passing things by reference. If you made global\_mod.x a list, and manipulated its first element, it would work as you expect. When you do `from global_mod import x`, you are creating a na...
Python: Sharing global variables between modules and classes therein
3,338,283
31
2010-07-26T19:30:28Z
3,338,375
22
2010-07-26T19:42:52Z
[ "python", "scope", "global-variables", "module" ]
I know that it's possible to share a global variable across modules in Python. However, I would like to know the extent to which this is possible and why. For example, global\_mod.py ``` x = None ``` mid\_access\_mod.py ``` from global_mod import * class delta: def __init__(self): print x ``` bot\_mod...
`from whatever import *` is **not** a good idiom to use in your code -- it's intended for use, if ever, in an interactive session as a shortcut to save some typing. It basically "snapshots" all names from the module at that point in time -- if you ever rebind any of those names, the snapshot will have grown stale and a...
pexpect timeout is not being used, only the default of 30 is being used
3,338,602
4
2010-07-26T20:11:20Z
3,345,904
8
2010-07-27T16:48:03Z
[ "python", "pexpect" ]
I'm trying to do a lengthy operation but pexpect with the timeout argument doesn't seem to change the length of time before the timeout exception gets fired. Here is my code: ``` child = pexpect.spawn('scp file user@:/temp', timeout=300) whichMatched = child.expect(['(?i)Password','Are you sure you want to continue c...
It appears to work if you only specify the timeout in the .spawn call, you cannot override, or use timeout=300 in the .expect call by itself.
Python - When Is It Ok to Use os.system() to issue common Linux commands
3,338,616
8
2010-07-26T20:13:51Z
3,338,632
17
2010-07-26T20:16:07Z
[ "python", "linux", "centos" ]
Spinning off from another thread, when is it appropriate to use os.system() to issue commands like rm -rf, cd, make, xterm, ls ? Considering there are analog versions of the above commands (except make and xterm), I'm assuming it's safer to use these built-in python commands instead of using os.system() Any thoughts?...
Rule of thumb: if there's a built-in Python function to achieve this functionality use this function. Why? It makes your code portable across different systems, more secure and probably faster as there will be no need to spawn an additional process.
Dynamically update wxPython staticText
3,339,263
4
2010-07-26T21:50:43Z
3,345,429
9
2010-07-27T15:50:02Z
[ "python", "wxpython", "refresh" ]
i was wondering how to update a StaticText dynamically in wxpython? I have a script that goes every five minutes and reads a status from a webpage, then prints using wxpython the status in a static input. How would i dynamically, every 5 minutes update the statictext to reflect the status? thanks alot -soule
Use a wx.Timer. You bind the timer to an event and in the event handler you call the StaticText control's SetLabel. See the following page for an example on timers: <http://www.blog.pythonlibrary.org/2009/08/25/wxpython-using-wx-timers/> As for setting the label, the code would look something like this: self.myStat...
Comparison of IntelliJ Python plugin or PyCharm
3,339,399
23
2010-07-26T22:14:01Z
3,344,714
11
2010-07-27T14:36:46Z
[ "python", "ide", "intellij-idea", "pycharm" ]
So I have IntelliJ and love it, and have been using the Python plugin for a while. But I noticed that they have PyCharm coming out in beta now. I haven't been using PyCharm since I just use IntelliJ for everything, but is there a compelling reason to buy PyCharm?
Right now PyCharm is quite a bit farther ahead in terms of functionality compared to the Python plugin for IntelliJ IDEA 9. Once we start the EAP for IntelliJ IDEA 10, we'll also release a new version of the Python plugin containing all the latest features of PyCharm, but we don't currently plan to backport the new fea...
Comparison of IntelliJ Python plugin or PyCharm
3,339,399
23
2010-07-26T22:14:01Z
6,962,694
40
2011-08-05T21:11:52Z
[ "python", "ide", "intellij-idea", "pycharm" ]
So I have IntelliJ and love it, and have been using the Python plugin for a while. But I noticed that they have PyCharm coming out in beta now. I haven't been using PyCharm since I just use IntelliJ for everything, but is there a compelling reason to buy PyCharm?
> Since this question (and its accepted answer) are older and new > versions of both IDEA and PyCharm are available, I figured it would be > appropriate to add a new answer without modifying the existing > "correct" one... My company has licenses for both PyCharm 1.5 and IntelliJ IDEA 10.5 and I have used both for reg...
Smallest learning curve language to work with CSV files
3,339,403
14
2010-07-26T22:15:15Z
3,339,421
13
2010-07-26T22:19:09Z
[ "python", "excel", "vba", "csv" ]
VBA is not cutting it for me anymore. I have lots of huge Excel files to which I need to make lots of calculations and break them down into other Excel/CSV files. I need a language that I can pick up within the next couple of days to do what I need, because it is kind of an emergency. I have been suggested python, but...
Python is an excellent choice. The `csv` module makes reading and writing CSV files easy (even Microsoft's, uh, "idiosyncratic" version) and Python syntax is a breeze to pick up. I'd actually recommend *against* Perl, if you're coming to it fresh. While Perl is certainly powerful and fast, it's often cryptic to the po...
Change default Python version from 2.4 to 2.6
3,339,530
46
2010-07-26T22:45:01Z
3,339,564
48
2010-07-26T22:52:28Z
[ "python", "linux", "version" ]
I'm wanting to use some newer software that requires Python `2.6`, and we currently have both `2.4` and `2.6` installed on our dedicated CentOS server, which looks like this: ``` $ which python /usr/local/bin/python $ which python2.6 /usr/bin/python2.6 $ which python2.4 /usr/local/bin/python2.4 $ ls -l /usr/local/bin/...
As root: ``` ln -sf /usr/bin/python2.6 /usr/local/bin/python ``` This will make a symbolic link from /usr/local/bin/python --> /usr/bin/python2.6 (replacing the old hardlink).
Change default Python version from 2.4 to 2.6
3,339,530
46
2010-07-26T22:45:01Z
3,339,566
10
2010-07-26T22:53:01Z
[ "python", "linux", "version" ]
I'm wanting to use some newer software that requires Python `2.6`, and we currently have both `2.4` and `2.6` installed on our dedicated CentOS server, which looks like this: ``` $ which python /usr/local/bin/python $ which python2.6 /usr/bin/python2.6 $ which python2.4 /usr/local/bin/python2.4 $ ls -l /usr/local/bin/...
`rm /usr/local/bin/python ln -s /usr/local/bin/python2.6 /usr/local/bin/python`
Change default Python version from 2.4 to 2.6
3,339,530
46
2010-07-26T22:45:01Z
6,907,127
13
2011-08-02T04:03:37Z
[ "python", "linux", "version" ]
I'm wanting to use some newer software that requires Python `2.6`, and we currently have both `2.4` and `2.6` installed on our dedicated CentOS server, which looks like this: ``` $ which python /usr/local/bin/python $ which python2.6 /usr/bin/python2.6 $ which python2.4 /usr/local/bin/python2.4 $ ls -l /usr/local/bin/...
As an alternative, you can also just add an alias for the command "python" in the your bash shell's startup file. so open the startup file: emacs ~/.bashrc in the editor u append: alias "python" "python2.6" and restart the shell.