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
Generating unique, ordered Pythagorean triplets
575,117
17
2009-02-22T16:00:34Z
578,789
11
2009-02-23T18:43:00Z
[ "python", "math" ]
This is a program I wrote to calculate Pythagorean triplets. When I run the program it prints each set of triplets twice because of the if statement. Is there any way I can tell the program to only print a new set of triplets once? Thanks. ``` import math def main(): for x in range (1, 1000): for y in ran...
The previously listed algorithms for generating [Pythagorean triplets](http://en.wikipedia.org/wiki/Pythagorean_triplets) are all modifications of the naive approach derived from the basic relationship `a^2 + b^2 = c^2` where `(a, b, c)` is a triplet of positive integers. It turns out that Pythagorean triplets satisfy ...
Generating unique, ordered Pythagorean triplets
575,117
17
2009-02-22T16:00:34Z
8,263,898
22
2011-11-25T00:59:17Z
[ "python", "math" ]
This is a program I wrote to calculate Pythagorean triplets. When I run the program it prints each set of triplets twice because of the if statement. Is there any way I can tell the program to only print a new set of triplets once? Thanks. ``` import math def main(): for x in range (1, 1000): for y in ran...
Substantially faster than any of the solutions so far. Finds triplets via a ternary tree. > [Wolfram](http://mathworld.wolfram.com/PythagoreanTriple.html) says: > > Hall (1970) and Roberts (1977) prove that is a primitive Pythagorean triple if and only if > > `(a,b,c)=(3,4,5)M` > > where M is a finite product of the m...
In Python, why can a function modify some arguments as perceived by the caller, but not others?
575,196
77
2009-02-22T16:42:51Z
575,204
11
2009-02-22T16:47:13Z
[ "python" ]
I'm new to Python and am trying to understand its approach to variable scope. In this example, why is `f()` able to alter the value of `x`, as perceived within `main()`, but not the value of `n`? ``` def f(n, x): n = 2 x.append(4) print 'In f():', n, x def main(): n = 1 x = [0,1,2,3] print 'Be...
`f` doesn't actually alter the value of `x` (which is always the same reference to an instance of a list). Rather, it alters the *contents* of this list. In both cases, a *copy* is passed to the function. But since `x` is a reference to a list instance, only the reference is copied, not the contents of the list. In c...
In Python, why can a function modify some arguments as perceived by the caller, but not others?
575,196
77
2009-02-22T16:42:51Z
575,337
109
2009-02-22T18:06:13Z
[ "python" ]
I'm new to Python and am trying to understand its approach to variable scope. In this example, why is `f()` able to alter the value of `x`, as perceived within `main()`, but not the value of `n`? ``` def f(n, x): n = 2 x.append(4) print 'In f():', n, x def main(): n = 1 x = [0,1,2,3] print 'Be...
Some answers contain the word "copy" in a context of a function call. I find it confusing. **Python doesn't copy *objects* you pass during a function call *ever*.** Function parameters are *names*. When you call a function Python binds these parameters to whatever objects you pass (via names in a caller scope). Obje...
In Python, why can a function modify some arguments as perceived by the caller, but not others?
575,196
77
2009-02-22T16:42:51Z
575,887
11
2009-02-22T21:52:14Z
[ "python" ]
I'm new to Python and am trying to understand its approach to variable scope. In this example, why is `f()` able to alter the value of `x`, as perceived within `main()`, but not the value of `n`? ``` def f(n, x): n = 2 x.append(4) print 'In f():', n, x def main(): n = 1 x = [0,1,2,3] print 'Be...
You've got a number of answers already, and I broadly agree with J.F. Sebastian, but you might find this useful as a shortcut: Any time you see **`varname =`**, you're creating a *new* name binding within the function's scope. Whatever value `varname` was bound to before is lost *within this scope*. Any time you see ...
How does python close files that have been gc'ed?
575,278
14
2009-02-22T17:26:49Z
575,320
19
2009-02-22T17:53:46Z
[ "python", "file", "garbage-collection", "del" ]
I had always assumed that a file would leak if it was opened without being closed, but I just verified that if I enter the following lines of code, the file will close: ``` >>> f = open('somefile.txt') >>> del f ``` Just out of sheer curiosity, how does this work? I notice that file doesn't include a `__`del`__` meth...
In CPython, at least, files are closed when the file object is deallocated. See the `file_dealloc` function in `Objects/fileobject.c` in the CPython source. Dealloc methods are sort-of like `__del__` for C types, except without some of the problems inherent to `__del__`.
Why not always use psyco for Python code?
575,385
37
2009-02-22T18:23:50Z
1,437,939
20
2009-09-17T10:23:30Z
[ "python", "optimization", "psyco" ]
[psyco](http://psyco.sourceforge.net/) seems to be quite helpful in optimizing Python code, and it does it in a very non-intrusive way. Therefore, one has to wonder. Assuming you're always on a x86 architecture (which is where most apps run these days), why not just always use `psyco` for all Python code? Does it make...
1) The memory overhead is the main one, as described in other answers. You also pay the compilation cost, which can be prohibitive if you aren't selective. From the [user reference](http://psyco.sourceforge.net/psycoguide/module-psyco.html): > Compiling everything is often overkill for medium- or large-sized applicati...
How to obtain the keycodes in Python
575,650
5
2009-02-22T20:01:21Z
575,656
8
2009-02-22T20:03:45Z
[ "python", "input", "keycode" ]
I have to know what key is pressed, but not need the code of the Character, i want to know when someone press the 'A' key even if the key obtained is 'a' or 'A', and so with all other keys. I can't use PyGame or any other library (including Tkinter). Only Python Standard Library. And this have to be done in a terminal...
Depending on what you are trying to accomplish, perhaps using a library such as [pygame](http://pygame.org) would do what you want. Pygame contains more advanced keypress handling than is normally available with Python's standard libraries.
How to obtain the keycodes in Python
575,650
5
2009-02-22T20:01:21Z
575,781
16
2009-02-22T21:02:36Z
[ "python", "input", "keycode" ]
I have to know what key is pressed, but not need the code of the Character, i want to know when someone press the 'A' key even if the key obtained is 'a' or 'A', and so with all other keys. I can't use PyGame or any other library (including Tkinter). Only Python Standard Library. And this have to be done in a terminal...
See [tty](http://docs.python.org/library/tty.html) standard module. It allows switching from default line-oriented (cooked) mode into char-oriented (cbreak) mode with [tty.setcbreak(sys.stdin)](http://docs.python.org/library/tty.html#tty.setcbreak). Reading single char from sys.stdin will result into next pressed keybo...
How to convert rational and decimal number strings to floats in python?
575,925
9
2009-02-22T22:08:47Z
575,944
16
2009-02-22T22:18:47Z
[ "python", "rational-numbers" ]
How can I convert strings which can denote decimal or rational numbers to floats ``` >>> ["0.1234", "1/2"] ['0.1234', '1/2'] ``` I'd want [0.1234, 0.5]. eval is what I was thinking but no luck: ``` >>> eval("1/2") 0 ```
I'd parse the string if conversion fails: ``` >>> def convert(s): try: return float(s) except ValueError: num, denom = s.split('/') return float(num) / float(denom) ... >>> convert("0.1234") 0.1234 >>> convert("1/2") 0.5 ``` Generally using eval is a bad idea, since it's a security r...
How to convert rational and decimal number strings to floats in python?
575,925
9
2009-02-22T22:08:47Z
575,976
7
2009-02-22T22:34:55Z
[ "python", "rational-numbers" ]
How can I convert strings which can denote decimal or rational numbers to floats ``` >>> ["0.1234", "1/2"] ['0.1234', '1/2'] ``` I'd want [0.1234, 0.5]. eval is what I was thinking but no luck: ``` >>> eval("1/2") 0 ```
As others have pointed out, using `eval` is potentially a security risk, and certainly a bad habit to get into. (if you don't think it's as risky as `exec`, imagine `eval`ing something like: `__import__('os').system('rm -rf /')`) However, if you have python 2.6 or up, you can use [`ast.literal_eval`](http://docs.pytho...
PyGame not receiving events when 3+ keys are pressed at the same time
576,634
3
2009-02-23T05:55:34Z
576,643
10
2009-02-23T06:02:08Z
[ "python", "pygame", "keyboard-events" ]
*I am developing a simple game in [PyGame](http://www.pygame.org/)... A rocket ship flying around and shooting stuff.* --- **Question:** Why does pygame stop emitting keyboard events when too may keys are pressed at once? **About the Key Handling:** The program has a number of variables like `KEYSTATE_FIRE, KEYSTATE...
This sounds like a input problem, not a code problem - are you sure the problem isn't the keyboard itself? Most keyboards have limitations on the number of keys that can be pressed at the same time. Often times you can't press more than a few keys that are close together at a time. To test it out, just start pressing ...
How can I reference columns by their names in python calling SQLite?
576,933
10
2009-02-23T08:50:12Z
576,954
9
2009-02-23T09:01:05Z
[ "python", "sqlite" ]
I have some code which I've been using to query MySQL, and I'm hoping to use it with SQLite. My real hope is that this will not involve making too many changes to the code. Unfortunately, the following code doesn't work with SQLite: ``` cursor.execute(query) rows = cursor.fetchall() data = [] for row in rows data....
I'm not sure if this is the best approach, but here's what I typically do to retrieve a record set using a DB-API 2 compliant module: ``` cursor.execute("""SELECT foo, bar, baz, quux FROM table WHERE id = %s;""", (interesting_record_id,)) for foo, bar, baz, quux in cursor.fetchall(): frobnicate...
How can I reference columns by their names in python calling SQLite?
576,933
10
2009-02-23T08:50:12Z
577,004
13
2009-02-23T09:25:44Z
[ "python", "sqlite" ]
I have some code which I've been using to query MySQL, and I'm hoping to use it with SQLite. My real hope is that this will not involve making too many changes to the code. Unfortunately, the following code doesn't work with SQLite: ``` cursor.execute(query) rows = cursor.fetchall() data = [] for row in rows data....
To access columns by name, use the [`row_factory`](http://oss.itsystementwicklung.de/download/pysqlite/doc/sqlite3.html#sqlite3.Connection.row_factory) attribute of the Connection instance. It lets you set a function that takes the arguments `cursor` and `row`, and return whatever you'd like. There's a few builtin to p...
How can I reference columns by their names in python calling SQLite?
576,933
10
2009-02-23T08:50:12Z
7,099,412
8
2011-08-17T21:00:19Z
[ "python", "sqlite" ]
I have some code which I've been using to query MySQL, and I'm hoping to use it with SQLite. My real hope is that this will not involve making too many changes to the code. Unfortunately, the following code doesn't work with SQLite: ``` cursor.execute(query) rows = cursor.fetchall() data = [] for row in rows data....
This can be done by adding a single line after the "connect" statment: ``` conn.row_factory = sqlite3.Row ``` Check the documentation here: <http://docs.python.org/library/sqlite3.html#accessing-columns-by-name-instead-of-by-index>
How can I reference columns by their names in python calling SQLite?
576,933
10
2009-02-23T08:50:12Z
20,042,292
8
2013-11-18T07:27:11Z
[ "python", "sqlite" ]
I have some code which I've been using to query MySQL, and I'm hoping to use it with SQLite. My real hope is that this will not involve making too many changes to the code. Unfortunately, the following code doesn't work with SQLite: ``` cursor.execute(query) rows = cursor.fetchall() data = [] for row in rows data....
In the five years since the question was asked and then answered, a very simple solution has arisen. Any new code can simply wrap the connection object with a row factory. Code example: ``` import sqlite3 conn = sqlite3.connect('./someFile') conn.row_factory = sqlite3.Row // Here's the magic! cursor = conn.ex...
How to exit a module before it has finished parsing?
577,119
4
2009-02-23T10:15:09Z
577,211
8
2009-02-23T10:51:16Z
[ "python", "import", "module" ]
I have a module that imports a module, but in some cases the module being imported may not exist. After the module is imported there is a class inherits from a class the imported module. If I was to catch the `ImportError` exception in the case the module doesn't exist, how can I stop Python from parsing the rest of th...
try: supports an else: clause ``` try: from skynet import SkyNet except ImportError: class SelfAwareSkyNet(): pass else: class SelfAwareSkyNet(SkyNet): pass ```
Python "extend" for a dictionary
577,234
211
2009-02-23T10:59:32Z
577,241
352
2009-02-23T11:01:49Z
[ "python", "dictionary" ]
Which is the best way to extend a dictionary with another one? For instance: ``` >>> a = { "a" : 1, "b" : 2 } >>> b = { "c" : 3, "d" : 4 } >>> a {'a': 1, 'b': 2} >>> b {'c': 3, 'd': 4} ``` I'm looking for any operation to obtain this avoiding `for` loop: ``` { "a" : 1, "b" : 2, "c" : 3, "d" : 4 } ``` I wish to do s...
``` a.update(b) ``` [Python Standard Library Documentation](http://docs.python.org/2/library/stdtypes.html#dict.update)
Python "extend" for a dictionary
577,234
211
2009-02-23T10:59:32Z
577,245
18
2009-02-23T11:04:22Z
[ "python", "dictionary" ]
Which is the best way to extend a dictionary with another one? For instance: ``` >>> a = { "a" : 1, "b" : 2 } >>> b = { "c" : 3, "d" : 4 } >>> a {'a': 1, 'b': 2} >>> b {'c': 3, 'd': 4} ``` I'm looking for any operation to obtain this avoiding `for` loop: ``` { "a" : 1, "b" : 2, "c" : 3, "d" : 4 } ``` I wish to do s...
``` a.update(b) ``` Will add keys and values from *b* to *a*, overwriting if there's already a value for a key.
Python "extend" for a dictionary
577,234
211
2009-02-23T10:59:32Z
1,552,420
109
2009-10-12T02:27:52Z
[ "python", "dictionary" ]
Which is the best way to extend a dictionary with another one? For instance: ``` >>> a = { "a" : 1, "b" : 2 } >>> b = { "c" : 3, "d" : 4 } >>> a {'a': 1, 'b': 2} >>> b {'c': 3, 'd': 4} ``` I'm looking for any operation to obtain this avoiding `for` loop: ``` { "a" : 1, "b" : 2, "c" : 3, "d" : 4 } ``` I wish to do s...
A beautiful gem in [this closed question](http://stackoverflow.com/questions/1551666/how-can-2-python-dictionaries-become-1/1551878#1551878): The "oneliner way", altering neither of the input dicts, is ``` basket = dict(basket_one, **basket_two) ``` Learn what [`**basket_two` (the `**`) means here](http://www.saltyc...
Python "extend" for a dictionary
577,234
211
2009-02-23T10:59:32Z
12,697,215
12
2012-10-02T19:48:15Z
[ "python", "dictionary" ]
Which is the best way to extend a dictionary with another one? For instance: ``` >>> a = { "a" : 1, "b" : 2 } >>> b = { "c" : 3, "d" : 4 } >>> a {'a': 1, 'b': 2} >>> b {'c': 3, 'd': 4} ``` I'm looking for any operation to obtain this avoiding `for` loop: ``` { "a" : 1, "b" : 2, "c" : 3, "d" : 4 } ``` I wish to do s...
As others have mentioned, `a.update(b)` for some dicts `a` and `b` will achieve the result you've asked for in your question. However, I want to point out that many times I have seen the `extend` method of mapping/set objects desire that in the syntax `a.extend(b)`, `a`'s values should NOT be overwritten by `b`'s value...
Django - how do I _not_ dispatch a signal?
577,376
4
2009-02-23T11:45:25Z
577,432
11
2009-02-23T12:05:29Z
[ "python", "django", "django-signals" ]
I wrote some smart generic counters and managers for my models (to avoid `select count` queries etc.). Therefore I got some heavy logic going on for post\_save. I would like to prevent handling the signal when there's no need to. I guess the perfect interface would be: ``` instance.save(dispatch_signal=False) ``` Ho...
A quick and dirty solution would be: ``` from django.db.models.signals import post_save from somewhere_in_my_app import my_post_save_handler post_save.disconnect(my_post_save_handler) instance.save() post_save.connect(my_post_save_handler) ``` But otherwise i strongly recommend moving your logic into the `save()` me...
Django - how do I _not_ dispatch a signal?
577,376
4
2009-02-23T11:45:25Z
10,881,618
11
2012-06-04T12:49:48Z
[ "python", "django", "django-signals" ]
I wrote some smart generic counters and managers for my models (to avoid `select count` queries etc.). Therefore I got some heavy logic going on for post\_save. I would like to prevent handling the signal when there's no need to. I guess the perfect interface would be: ``` instance.save(dispatch_signal=False) ``` Ho...
You can disconnect and reconnect the signal. Try using a `with:` statement with this utility class: ``` class SignalBlocker(object): def __init__(self, signal, receiver, **kwargs): self.signal = signal self.receiver = receiver self.kwargs = kwargs def __enter__(self, *args, **kwargs): ...
Django - how do I _not_ dispatch a signal?
577,376
4
2009-02-23T11:45:25Z
16,556,300
11
2013-05-15T03:25:55Z
[ "python", "django", "django-signals" ]
I wrote some smart generic counters and managers for my models (to avoid `select count` queries etc.). Therefore I got some heavy logic going on for post\_save. I would like to prevent handling the signal when there's no need to. I guess the perfect interface would be: ``` instance.save(dispatch_signal=False) ``` Ho...
I found simple and easy solution: ``` MyModel.objects.filter(pk=instance.id).update(**data) ``` It is due to (<https://docs.djangoproject.com/en/1.5/ref/models/querysets/#update>): > Finally, realize that update() does an update at the SQL level and, > thus, does not call any save() methods on your models, nor does ...
Pause in Python
577,467
38
2009-02-23T12:20:26Z
577,487
12
2009-02-23T12:29:39Z
[ "python", "command-line" ]
I am running command-line Python scripts from the Windows taskbar by having a shortcut pointing to the Python interpreter with the actual script as a parameter. After the script has been processed, the interpreter terminates and the output window is closed which makes it impossible to read script output. What is the ...
There's no need to wait for input before closing, just change your command like so: ``` cmd /K python <script> ``` The `/K` switch will execute the command that follows, but leave the command interpreter window open, in contrast to `/C`, which executes and then closes.
Pause in Python
577,467
38
2009-02-23T12:20:26Z
577,488
43
2009-02-23T12:30:06Z
[ "python", "command-line" ]
I am running command-line Python scripts from the Windows taskbar by having a shortcut pointing to the Python interpreter with the actual script as a parameter. After the script has been processed, the interpreter terminates and the output window is closed which makes it impossible to read script output. What is the ...
One way is to leave a `raw_input()` at the end so the script waits for you to press Enter before it terminates.
Pause in Python
577,467
38
2009-02-23T12:20:26Z
577,529
7
2009-02-23T12:51:41Z
[ "python", "command-line" ]
I am running command-line Python scripts from the Windows taskbar by having a shortcut pointing to the Python interpreter with the actual script as a parameter. After the script has been processed, the interpreter terminates and the output window is closed which makes it impossible to read script output. What is the ...
> One way is to leave a raw\_input() at the end so the script waits for you to press enter before it terminates. The advantage of using raw\_input() instead of msvcrt.\* stuff is that the former is a part of standard Python (i.e. absolutely cross-platform). This also means that the script window will be alive after do...
Pause in Python
577,467
38
2009-02-23T12:20:26Z
4,130,571
26
2010-11-09T04:41:40Z
[ "python", "command-line" ]
I am running command-line Python scripts from the Windows taskbar by having a shortcut pointing to the Python interpreter with the actual script as a parameter. After the script has been processed, the interpreter terminates and the output window is closed which makes it impossible to read script output. What is the ...
Try `os.system("pause")`I used it and it worked for me :)
How do I prevent Python's os.walk from walking across mount points?
577,761
7
2009-02-23T14:16:59Z
577,830
15
2009-02-23T14:39:56Z
[ "python", "linux", "unix" ]
In Unix all disks are exposed as paths in the main filesystem, so `os.walk('/')` would traverse, for example, `/media/cdrom` as well as the primary hard disk, and that is undesirable for some applications. How do I get an `os.walk` that stays on a single device? Related: * [Is there a way to determine if a subdirect...
From `os.walk` docs: > When topdown is true, the caller can > modify the dirnames list in-place > (perhaps using del or slice > assignment), and walk() will only > recurse into the subdirectories whose > names remain in dirnames; this can be > used to prune the search So something like this should work: ``` for root...
How can I make this Python recursive function return a flat list?
577,940
9
2009-02-23T15:12:37Z
577,955
10
2009-02-23T15:16:14Z
[ "python", "recursion" ]
Look at this simple function ``` def prime_factors(n): for i in range(2,n): if n % i == 0: return i, prime_factors(n / i) return n ``` Here's the result of `prime_factors(120)` ``` (2, (2, (2, (3, 5)))) ``` Instead of nested tuples, I want it to return one flat tuple or list. ``` (2, 2, 2, 3,...
``` def prime_factors(n): for i in range(2,n): if n % i == 0: yield i for p in prime_factors(n / i): yield p return yield n ``` Example: ``` >>> tuple(prime_factors(100)) (2, 2, 5, 5) ```
How can I make this Python recursive function return a flat list?
577,940
9
2009-02-23T15:12:37Z
577,961
18
2009-02-23T15:17:03Z
[ "python", "recursion" ]
Look at this simple function ``` def prime_factors(n): for i in range(2,n): if n % i == 0: return i, prime_factors(n / i) return n ``` Here's the result of `prime_factors(120)` ``` (2, (2, (2, (3, 5)))) ``` Instead of nested tuples, I want it to return one flat tuple or list. ``` (2, 2, 2, 3,...
``` def prime_factors(n): for i in range(2,n): if n % i == 0: return [i] + prime_factors(n / i) return [n] ```
How can I make this Python recursive function return a flat list?
577,940
9
2009-02-23T15:12:37Z
577,971
7
2009-02-23T15:19:23Z
[ "python", "recursion" ]
Look at this simple function ``` def prime_factors(n): for i in range(2,n): if n % i == 0: return i, prime_factors(n / i) return n ``` Here's the result of `prime_factors(120)` ``` (2, (2, (2, (3, 5)))) ``` Instead of nested tuples, I want it to return one flat tuple or list. ``` (2, 2, 2, 3,...
Without changing the original function, from [Python Tricks](http://kogs-www.informatik.uni-hamburg.de/~meine/python_tricks): ``` def flatten(x): """flatten(sequence) -> list Returns a single, flat list which contains all elements retrieved from the sequence and all recursively contained sub-sequences ...
Python program to find fibonacci series. More Pythonic way
578,379
6
2009-02-23T16:53:23Z
578,424
16
2009-02-23T17:02:01Z
[ "python" ]
There is another thread to discuss Fibo series in Python. This is to tweak code into more pythonic. [How to write the Fibonacci Sequence in Python](http://stackoverflow.com/questions/494594/how-to-write-the-fibonacci-sequence-in-python) I am in love with this program I wrote to solve Project Euler Q2. I am newly codin...
Using generators is a Pythonic way to generate long sequences while preserving memory: ``` def fibonacci(): a, b = 0, 1 while True: yield a a, b = b, a + b import itertools upto_4000000 = itertools.takewhile(lambda x: x <= 4000000, fibonacci()) print(sum(x for x in upto_4000000 if x % 2 == 0)) ```
Python program to find fibonacci series. More Pythonic way
578,379
6
2009-02-23T16:53:23Z
578,426
12
2009-02-23T17:02:33Z
[ "python" ]
There is another thread to discuss Fibo series in Python. This is to tweak code into more pythonic. [How to write the Fibonacci Sequence in Python](http://stackoverflow.com/questions/494594/how-to-write-the-fibonacci-sequence-in-python) I am in love with this program I wrote to solve Project Euler Q2. I am newly codin...
First I'd do fibo() as a generator: ``` def fibo(a=-1,b=1,upto=4000000): while a+b<upto: a,b = b,a+b yield b ``` Then I'd also select for evenness as a generator rather than a list comprehension. ``` print sum(i for i in fibo() if not i%2) ```
Alternative to 'for i in xrange(len(x))'
578,677
9
2009-02-23T18:10:52Z
578,685
22
2009-02-23T18:12:36Z
[ "python", "for-loop", "anti-patterns" ]
So I see in [another post](http://stackoverflow.com/questions/576988/python-specific-antipatterns) the following "bad" snippet, but the only alternatives I have seen involve patching Python. ``` for i in xrange(len(something)): workwith = something[i] # do things with workwith... ``` What do I do to avoid this "a...
See [Pythonic](http://docs.python.org/glossary.html#term-pythonic) ``` for workwith in something: # do things with workwith ```
Alternative to 'for i in xrange(len(x))'
578,677
9
2009-02-23T18:10:52Z
578,694
23
2009-02-23T18:14:59Z
[ "python", "for-loop", "anti-patterns" ]
So I see in [another post](http://stackoverflow.com/questions/576988/python-specific-antipatterns) the following "bad" snippet, but the only alternatives I have seen involve patching Python. ``` for i in xrange(len(something)): workwith = something[i] # do things with workwith... ``` What do I do to avoid this "a...
If you need to know the index in the loop body: ``` for index, workwith in enumerate(something): print "element", index, "is", workwith ```
Alternative to 'for i in xrange(len(x))'
578,677
9
2009-02-23T18:10:52Z
582,541
11
2009-02-24T16:54:18Z
[ "python", "for-loop", "anti-patterns" ]
So I see in [another post](http://stackoverflow.com/questions/576988/python-specific-antipatterns) the following "bad" snippet, but the only alternatives I have seen involve patching Python. ``` for i in xrange(len(something)): workwith = something[i] # do things with workwith... ``` What do I do to avoid this "a...
As there are [two](http://stackoverflow.com/questions/578677/alternative-to-for-i-in-xrangelenx/578694#578694) [answers](http://stackoverflow.com/questions/578677/alternative-to-for-i-in-xrangelenx/578685#578685) to question that are perfectly valid (with an assumption each) and author of the question didn't inform us ...
Need help understanding function passing in Python
578,812
4
2009-02-23T18:47:43Z
578,869
13
2009-02-23T18:59:04Z
[ "python" ]
I am trying to teach myself Python by working through some problems I came up with, and I need some help understanding how to pass functions. Let's say I am trying to predict tomorrow's temperature based on today's and yesterday's temperature, and I have written the following function: ``` def predict_temp(temp_today...
Here is an example of how to pass a function into another function. `apply_func_to` will take a function `f` and a number `num` as parameters and `return f(num)`. ``` def my_func(x): return x*x def apply_func_to(f, num): return f(num) >>>apply_func_to(my_func, 2) 4 ``` If you wanna be clever you can use lam...
Is there a pattern for propagating details of both errors and warnings?
579,097
6
2009-02-23T19:58:15Z
579,117
7
2009-02-23T20:05:54Z
[ "python", "design-patterns", "error-handling", "warnings" ]
Is there a common pattern for propagating details of both errors and warnings? By *errors* I mean serious problems that should cause the flow of code to stop. By *warnings* I mean issues that merit informing the user of a problem, but are too trivial to stop program flow. I currently use exceptions to deal with hard e...
Look into Python's `warnings` module, <http://docs.python.org/library/warnings.html> I don't think there's much you can say about this problem without specifying the language, as non-terminal error handling varies greatly from one language to another.
Instantiating a python class in C#
579,272
36
2009-02-23T20:47:25Z
579,609
46
2009-02-23T22:14:43Z
[ "c#", ".net", "python", "ironpython", "cross-language" ]
I've written a class in python that I want to wrap into a .net assembly via IronPython and instantiate in a C# application. I've migrated the class to IronPython, created a library assembly and referenced it. Now, how do I actually get an instance of that class? The class looks (partially) like this: ``` class PokerC...
IronPython classes are *not* .NET classes. They are instances of IronPython.Runtime.Types.PythonType which is the Python metaclass. This is because Python classes are dynamic and support addition and removal of methods at runtime, things you cannot do with .NET classes. To use Python classes in C# you will need to use...
Instantiating a python class in C#
579,272
36
2009-02-23T20:47:25Z
2,722,635
30
2010-04-27T15:39:13Z
[ "c#", ".net", "python", "ironpython", "cross-language" ]
I've written a class in python that I want to wrap into a .net assembly via IronPython and instantiate in a C# application. I've migrated the class to IronPython, created a library assembly and referenced it. Now, how do I actually get an instance of that class? The class looks (partially) like this: ``` class PokerC...
Now that .Net 4.0 is released and has the dynamic type, this example should be updated. Using the same python file as in m-sharp's original answer: ``` class Calculator(object): def add(self, a, b): return a + b ``` Here is how you would call it using .Net 4.0: ``` string scriptPath = "Calculator.py"; Sc...
formatting long numbers as strings in python
579,310
10
2009-02-23T20:55:58Z
579,376
20
2009-02-23T21:11:36Z
[ "python", "formatting", "string", "integer" ]
What is an easy way in Python to format integers into strings representing thousands with K, and millions with M, and leaving just couple digits after comma? I'd like to show 7436313 as 7.44M, and 2345 as 2,34K. Is there some % string formatting operator available for that? Or that could be done only by actually divi...
I don't think there's a built-in function that does that. You'll have to roll your own, e.g.: ``` def human_format(num): magnitude = 0 while abs(num) >= 1000: magnitude += 1 num /= 1000.0 # add more suffixes if you need them return '%.2f%s' % (num, ['', 'K', 'M', 'G', 'T', 'P'][magnitud...
Using only the DB part of Django
579,511
32
2009-02-23T21:45:54Z
579,537
8
2009-02-23T21:51:51Z
[ "python", "django", "orm" ]
Does somebody know how "modular" is Django? Can I use just the ORM part, to get classes that map to DB tables and know how to read/write from these tables? If not, what would you recommend as "the Python equivalent of Hibernate"?
You can certainly use various parts of Django in a stand-alone fashion. It is after-all just a collection of Python modules, which you can import to any other code you would like to use them. I'd also recommend looking at [SQL Alchemy](http://www.sqlalchemy.org/) if you are only after the ORM side of things.
Using only the DB part of Django
579,511
32
2009-02-23T21:45:54Z
579,567
9
2009-02-23T22:00:22Z
[ "python", "django", "orm" ]
Does somebody know how "modular" is Django? Can I use just the ORM part, to get classes that map to DB tables and know how to read/write from these tables? If not, what would you recommend as "the Python equivalent of Hibernate"?
The short answer is: no, you can't use the Django ORM separately from Django. The long answer is: yes, you can if you are willing to load large parts of Django along with it. For example, the database connection that is used by Django is opened when a request to Django occurs. This happens when a signal is sent so you...
Using only the DB part of Django
579,511
32
2009-02-23T21:45:54Z
584,208
72
2009-02-25T00:01:21Z
[ "python", "django", "orm" ]
Does somebody know how "modular" is Django? Can I use just the ORM part, to get classes that map to DB tables and know how to read/write from these tables? If not, what would you recommend as "the Python equivalent of Hibernate"?
If you like Django's ORM, it's perfectly simple to use it "standalone"; I've [written up several techniques for using parts of Django outside of a web context](http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/), and you're free to use any of them (or roll your own). Shane above seems to be a bit misi...
How do I copy a string to the clipboard on Windows using Python?
579,687
123
2009-02-23T22:38:02Z
579,715
10
2009-02-23T22:43:08Z
[ "python", "clipboard" ]
I'm kind of new to Python and I'm trying to make a basic Windows application that builds a string out of user input then adds it to the clipboard. How do I copy a string to the clipboard using Python?
Looks like you need to add win32clipboard to your site-packages. It's part of the [pywin32 package](http://sourceforge.net/projects/pywin32/)
How do I copy a string to the clipboard on Windows using Python?
579,687
123
2009-02-23T22:38:02Z
3,429,034
22
2010-08-07T03:33:26Z
[ "python", "clipboard" ]
I'm kind of new to Python and I'm trying to make a basic Windows application that builds a string out of user input then adds it to the clipboard. How do I copy a string to the clipboard using Python?
You can also use ctypes to tap into the windows API and avoid the massive pywin32 package. This is what I use, (excuse the poor style, but the idea is there.) ``` import ctypes #Get required functions, strcpy.. strcpy = ctypes.cdll.msvcrt.strcpy ocb = ctypes.windll.user32.OpenClipboard #Basic Clipboard functions e...
How do I copy a string to the clipboard on Windows using Python?
579,687
123
2009-02-23T22:38:02Z
4,203,897
196
2010-11-17T11:31:06Z
[ "python", "clipboard" ]
I'm kind of new to Python and I'm trying to make a basic Windows application that builds a string out of user input then adds it to the clipboard. How do I copy a string to the clipboard using Python?
Actually, `pywin32` and `ctypes` seem to be an overkill for this simple task. `Tkinter` is a cross-platform GUI framework, which ships with Python by default and has clipboard accessing methods along with other cool stuff. If all you need is to put some text to system clipboard, this will do it: ``` from Tkinter impo...
How do I copy a string to the clipboard on Windows using Python?
579,687
123
2009-02-23T22:38:02Z
9,409,898
53
2012-02-23T09:06:00Z
[ "python", "clipboard" ]
I'm kind of new to Python and I'm trying to make a basic Windows application that builds a string out of user input then adds it to the clipboard. How do I copy a string to the clipboard using Python?
I didn't have a solution just a work around Windows vista onwards has an inbuilt command called clip that takes the output of a command from command line and puts it into the clipboard. E.g. ipconfig | clip So i made a function with the os module which takes the string and adds it to the clipboard using the inbuilt w...
How do I copy a string to the clipboard on Windows using Python?
579,687
123
2009-02-23T22:38:02Z
24,523,659
17
2014-07-02T05:43:27Z
[ "python", "clipboard" ]
I'm kind of new to Python and I'm trying to make a basic Windows application that builds a string out of user input then adds it to the clipboard. How do I copy a string to the clipboard using Python?
You can use [**pyperclip**](http://coffeeghost.net/2010/10/09/pyperclip-a-cross-platform-clipboard-module-for-python/) - cross-platform clipboard module. Or [**Xerox**](https://github.com/kennethreitz/xerox) - similar module, except requires the win32 Python module to work on Windows.
Python ORM that auto-generates/updates tables and uses SQLite?
579,770
9
2009-02-23T22:59:10Z
579,787
16
2009-02-23T23:05:02Z
[ "python", "sqlite", "orm", "auto-generate" ]
I am doing some prototyping for a new desktop app i am writing in Python, and i want to use SQLite and an ORM to store data. My question is, are there any ORM libraries that support auto-generating/updating the database schema and work with SQLite?
[SQLAlchemy](http://www.sqlalchemy.org/) is a great choice in the Python ORM space that supports SQLite.
What's the Pythonic way to combine two sequences into a dictionary?
579,856
7
2009-02-23T23:33:26Z
579,862
42
2009-02-23T23:35:34Z
[ "python" ]
Is there a more concise way of doing this in Python?: ``` def toDict(keys, values): d = dict() for k,v in zip(keys, values): d[k] = v return d ```
Yes: ``` dict(zip(keys,values)) ```
Python windows File Version attribute
580,924
16
2009-02-24T08:26:26Z
1,237,635
16
2009-08-06T08:34:19Z
[ "python", "windows", "file-attributes" ]
Last time I asked a similar question but that was about svn related versioning info. Now I am wondering how to query windows "File version" attribute about eg. a dll. I payed attention to wmi and win32file modules as well without success.
Better to add a try/except in case the file has no version number attribute. filever.py ``` from win32api import GetFileVersionInfo, LOWORD, HIWORD def get_version_number (filename): try: info = GetFileVersionInfo (filename, "\\") ms = info['FileVersionMS'] ls = info['FileVersionLS'] return H...
Python windows File Version attribute
580,924
16
2009-02-24T08:26:26Z
2,310,098
9
2010-02-22T10:06:42Z
[ "python", "windows", "file-attributes" ]
Last time I asked a similar question but that was about svn related versioning info. Now I am wondering how to query windows "File version" attribute about eg. a dll. I payed attention to wmi and win32file modules as well without success.
You can use the `pyWin32` module from <http://sourceforge.net/projects/pywin32/>: ``` from win32com.client import Dispatch ver_parser = Dispatch('Scripting.FileSystemObject') info = ver_parser.GetFileVersion(path) if info == 'No Version Information Available': info = None ```
Python windows File Version attribute
580,924
16
2009-02-24T08:26:26Z
7,993,095
13
2011-11-03T10:08:02Z
[ "python", "windows", "file-attributes" ]
Last time I asked a similar question but that was about svn related versioning info. Now I am wondering how to query windows "File version" attribute about eg. a dll. I payed attention to wmi and win32file modules as well without success.
Here is a function which reads all file attributes as a dictionary: ``` import win32api #============================================================================== def getFileProperties(fname): #============================================================================== """ Read all properties of the g...
regex '|' operator vs separate runs for each sub-expression
580,993
5
2009-02-24T08:55:29Z
581,011
7
2009-02-24T09:03:55Z
[ "python", "regex", "performance" ]
I've got a fairly large string (~700k) against which I need to run 10 regexes and count all the matches of any of the regexes. My quick and dirty impl was to do something like re.search('(expr1)|(expr2)|...'), but I was wondering if we'd see any performance gains by matching in a loop instead: In other words, I want t...
The two things will give slightly different results, unless it is guaranteed that a match will match one and only one regex. Otherwise if something matches 2 it will be counted twice. In theory your solution ought to be quicker (if the expression are mutually exclusive) because the regex compiler ought to be able to m...
Python web programming
581,038
12
2009-02-24T09:15:24Z
581,356
8
2009-02-24T11:05:43Z
[ "python", "cherrypy" ]
Good morning. As the title indicates, I've got some questions about using python for web development. * What is the best setup for a development environment, more specifically, what webserver to use, how to bind python with it. Preferably, I'd like it to be implementable in both, \*nix and win environment. My major ...
**What is the best setup for a development environment?** Doesn't much matter. We use Django, which runs in Windows and Unix nicely. For production, we use Apache in Red Hat. **Is having to reload webserver to see the changes considered normal?** Yes. Not clear why you'd want anything different. Web application soft...
Can someone explain why scipy.integrate.quad gives different results for equally long ranges while integrating sin(X)?
581,186
3
2009-02-24T10:10:29Z
581,250
7
2009-02-24T10:32:18Z
[ "python", "integration", "scipy", "numerical-methods" ]
I am trying to numerically integrate an arbitrary (known when I code) function in my program using numerical integration methods. I am using Python 2.5.2 along with SciPy's numerical integration package. In order to get a feel for it, i decided to try integrating sin(x) and observed this behavior- ``` >>> from math im...
The `quad` function is a function from an old Fortran library. It works by judging by the flatness and slope of the function it is integrating how to treat the step size it uses for numerical integration in order to maximize efficiency. What this means is that you may get slightly different answers from one region to t...
Similar to Pass in Python for C#
581,343
12
2009-02-24T11:00:30Z
581,348
16
2009-02-24T11:03:27Z
[ "c#", "python" ]
In python we can .. ``` a = 5 if a == 5: pass #Do Nothing else: print "Hello World" ``` I wonder if it a similar way to do this in C#
Use empty braces. ``` int a = 5; if (a == 5) {} else { Console.Write("Hello World"); } ```
Similar to Pass in Python for C#
581,343
12
2009-02-24T11:00:30Z
581,357
11
2009-02-24T11:05:56Z
[ "c#", "python" ]
In python we can .. ``` a = 5 if a == 5: pass #Do Nothing else: print "Hello World" ``` I wonder if it a similar way to do this in C#
Why not just say: ``` if (a != 5) { Console.Write("Hello World"); } ```
In Python, how do I make a temp file that persists until the next run?
581,851
3
2009-02-24T14:03:26Z
581,902
16
2009-02-24T14:18:50Z
[ "python", "temporary-files" ]
I need to create a folder that I use only once, but need to have it exist until the next run. It seems like I should be using the tmp\_file module in the standard library, but I'm not sure how to get the behavior that I want. Currently, I'm doing the following to create the directory: ``` randName = "temp" + str(rand...
Creating the folder with a 4-digit random number is insecure, and you also need to worry about collisions with other instances of your program. A much better way is to create the folder using [`tempfile.mkdtemp`](http://docs.python.org/library/tempfile.html), which does exactly what you want (i.e. the folder is not de...
In Python, how do I make a temp file that persists until the next run?
581,851
3
2009-02-24T14:03:26Z
582,243
8
2009-02-24T15:43:23Z
[ "python", "temporary-files" ]
I need to create a folder that I use only once, but need to have it exist until the next run. It seems like I should be using the tmp\_file module in the standard library, but I'm not sure how to get the behavior that I want. Currently, I'm doing the following to create the directory: ``` randName = "temp" + str(rand...
What you've suggested is dangerous. You may have race conditions if anyone else is trying to create those directories -- including other instances of your application. Also, deleting anything containing "temp" may result in deleting more than you intended. As others have mentioned, [tempfile.mkdtemp](http://docs.python...
How can you profile a Python script?
582,336
702
2009-02-24T16:01:26Z
582,337
755
2009-02-24T16:01:40Z
[ "python", "performance", "profiling", "time-complexity" ]
Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to `__main__`. What is a good way to profile how long a python program takes to run?
Python includes a profiler called cProfile. It not only gives the total running time, but also times each function separately, and tells you how many times each function was called, making it easy to determine where you should make optimizations. You can call it from within your code, or from the interpreter, like thi...
How can you profile a Python script?
582,336
702
2009-02-24T16:01:26Z
583,452
10
2009-02-24T20:31:10Z
[ "python", "performance", "profiling", "time-complexity" ]
Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to `__main__`. What is a good way to profile how long a python program takes to run?
In Virtaal's [source](https://translate.svn.sourceforge.net/svnroot/translate/src/trunk/virtaal/devsupport/profiling.py) there's a very useful class and decorator that can make it profiling (even for specific methods/functions) very easy. The output can then be viewed very comfortably in KCacheGrind.
How can you profile a Python script?
582,336
702
2009-02-24T16:01:26Z
1,922,945
140
2009-12-17T16:30:34Z
[ "python", "performance", "profiling", "time-complexity" ]
Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to `__main__`. What is a good way to profile how long a python program takes to run?
It's worth pointing out that using the profiler only works (by default) on the main thread, and you won't get any information from other threads if you use them. This can be a bit of a gotcha as it is completely unmentioned in the [profiler documentation](http://docs.python.org/library/profile.html). If you also want ...
How can you profile a Python script?
582,336
702
2009-02-24T16:01:26Z
7,693,928
103
2011-10-08T00:04:12Z
[ "python", "performance", "profiling", "time-complexity" ]
Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to `__main__`. What is a good way to profile how long a python program takes to run?
The python wiki is a great page for profiling resources: <http://wiki.python.org/moin/PythonSpeed/PerformanceTips#Profiling_Code> as is the python docs: <http://docs.python.org/library/profile.html> as shown by Chris Lawlor cProfile is a great tool and can easily be used to print to the screen: ``` python -m cProfil...
How can you profile a Python script?
582,336
702
2009-02-24T16:01:26Z
7,838,845
19
2011-10-20T16:05:34Z
[ "python", "performance", "profiling", "time-complexity" ]
Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to `__main__`. What is a good way to profile how long a python program takes to run?
A nice profiling module is the line\_profiler (called using the script kernprof.py). It can be downloaded [here](http://packages.python.org/line_profiler/). My understanding is that cProfile only gives information about total time spent in each function. So individual lines of code are not timed. This is an issue in s...
How can you profile a Python script?
582,336
702
2009-02-24T16:01:26Z
8,065,384
8
2011-11-09T12:59:04Z
[ "python", "performance", "profiling", "time-complexity" ]
Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to `__main__`. What is a good way to profile how long a python program takes to run?
Following Joe Shaw's answer about multi-threaded code not to work as expected, I figured that the `runcall` method in cProfile is merely doing `self.enable()` and `self.disable()` calls around the profiled function call, so you can simply do that yourself and have whatever code you want in-between with minimal interfer...
How can you profile a Python script?
582,336
702
2009-02-24T16:01:26Z
11,822,995
275
2012-08-06T05:37:07Z
[ "python", "performance", "profiling", "time-complexity" ]
Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to `__main__`. What is a good way to profile how long a python program takes to run?
A while ago I made [`pycallgraph`](http://pycallgraph.slowchop.com/) which generates a visualisation from your Python code. **Edit:** I've updated the example to work with the latest release. After a `pip install pycallgraph` and installing [GraphViz](http://www.graphviz.org/) you can run it from the command line: ``...
How can you profile a Python script?
582,336
702
2009-02-24T16:01:26Z
13,830,132
83
2012-12-11T23:16:39Z
[ "python", "performance", "profiling", "time-complexity" ]
Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to `__main__`. What is a good way to profile how long a python program takes to run?
@Maxy's comment on [this answer](http://stackoverflow.com/a/7693928/25616) helped me out enough that I think it deserves its own answer: I already had cProfile-generated .pstats files and I didn't want to re-run things with pycallgraph, so I used [gprof2dot](http://code.google.com/p/jrfonseca/wiki/Gprof2Dot), and got p...
How can you profile a Python script?
582,336
702
2009-02-24T16:01:26Z
28,660,109
18
2015-02-22T16:18:05Z
[ "python", "performance", "profiling", "time-complexity" ]
Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to `__main__`. What is a good way to profile how long a python program takes to run?
Also worth mentioning is the GUI cProfile dump viewer [RunSnakeRun](http://www.vrplumber.com/programming/runsnakerun/). It allows you to sort and select, thereby zooming in on the relevant parts of the program. The sizes of the rectangles in the picture is proportional to the time taken. If you mouse over a rectangle i...
How can you profile a Python script?
582,336
702
2009-02-24T16:01:26Z
28,808,860
11
2015-03-02T11:36:47Z
[ "python", "performance", "profiling", "time-complexity" ]
Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to `__main__`. What is a good way to profile how long a python program takes to run?
# pprofile `line_profiler` (already presented here) also inspired [`pprofile`](https://github.com/vpelletier/pprofile), which is described as: > Line-granularity, thread-aware deterministic and statistic pure-python > profiler It provides line-granularity as `line_profiler`, is pure Python, can be used as a standalo...
How can you profile a Python script?
582,336
702
2009-02-24T16:01:26Z
29,344,687
7
2015-03-30T11:11:13Z
[ "python", "performance", "profiling", "time-complexity" ]
Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to `__main__`. What is a good way to profile how long a python program takes to run?
cProfile is great for quick profiling but most of the time it was ending for me with the errors. Function runctx solves this problem by initializing correctly the environment and variables, hope it can be useful for someone: ``` import cProfile cProfile.runctx('foo()', None, locals()) ```
How can you profile a Python script?
582,336
702
2009-02-24T16:01:26Z
32,139,774
7
2015-08-21T11:59:43Z
[ "python", "performance", "profiling", "time-complexity" ]
Project Euler and other coding contests often have a maximum time to run or people boast of how fast their particular solution runs. With python, sometimes the approaches are somewhat kludgey - i.e., adding timing code to `__main__`. What is a good way to profile how long a python program takes to run?
There's a lot of great answers but they either use command line or some external program for profiling and/or sorting the results. I really missed some way I could use in my IDE (eclipse-PyDev) without touching the command line or installing anything. So here it is. # Profiling without command line ``` def count(): ...
py2exe + sqlalchemy + sqlite problem
582,449
19
2009-02-24T16:28:11Z
582,520
29
2009-02-24T16:49:55Z
[ "python", "sqlite", "sqlalchemy", "py2exe" ]
I am playing around with getting some basic stuff to work in Python before i go into full speed dev mode. Here are the specifics: ``` Python 2.5.4 PyQt4 4.4.3 SqlAlchemy 0.5.2 py2exe 0.6.9 setuptools 0.6c9 pysqlite 2.5.1 ``` setup.py: ``` from distutils.core import setup import py2exe setup(windows=[{"script" : "ma...
you need to include the sqlalchemy.databases.sqlite package ``` setup( windows=[{"script" : "main.py"}], options={"py2exe" : { "includes": ["sip", "PyQt4.QtSql"], "packages": ["sqlalchemy.databases.sqlite"] }}) ```
How to import classes defined in __init__.py
582,723
46
2009-02-24T17:35:55Z
583,065
36
2009-02-24T18:52:35Z
[ "python", "packages" ]
I am trying to organize some modules for my own use. I have something like this: ``` lib/ __init__.py settings.py foo/ __init__.py someobject.py bar/ __init__.py somethingelse.py ``` In `lib/__init__.py`, I want to define some classes to be used if I import lib. However, I can't seem to figure...
1. '`lib/`'s parent directory must be in `sys.path`. 2. Your '`lib/__init__.py`' might look like this: ``` from . import settings # or just 'import settings' on old Python versions class Helper(object): pass ``` Then the following example should work: ``` from lib.settings import Values from lib...
Run a linux system command as a superuser, using a python script
583,216
15
2009-02-24T19:32:21Z
583,239
18
2009-02-24T19:39:15Z
[ "python", "linux", "sysadmin", "sudo", "root" ]
I have got postfix installed on my machine and I am updating virtual\_alias on the fly programmatically(using python)(on some action). Once I update the entry in the /etc/postfix/virtual\_alias, I am running the command: ``` sudo /usr/sbin/postmap /etc/postfix/virtual_alias 2>>/work/postfix_valias_errorfile ``` But I...
You can either run your python script as root itself - then you won't need to add privilege to reload postfix. Or you can configure sudo to not need a password for `/etc/init.d/postfix`. sudo configuration (via visudo) allows NOPASSWD: to allow the command without a password. See [http://www.sudo.ws/sudo/man/sudoers....
What is the best way to print a table with delimiters in Python
583,557
4
2009-02-24T20:56:53Z
583,757
17
2009-02-24T21:47:41Z
[ "python", "coding-style" ]
I want to print a table mixed with string and float values, as tab delimited output printout. Sure I can get the job done: ``` >>> tab = [['a', 1], ['b', 2]] >>> for row in tab: ... out = "" ... for col in row: ... out = out + str(col) + "\t" ... print out.rstrip() ... a 1 b 2 ``` But I h...
Your shorter solution would work well as something quick and dirty. But if you need to handle large amounts of data, it'd be better to use `csv` module: ``` import sys, csv writer = csv.writer(sys.stdout, delimiter="\t") writer.writerows(data) ``` The benefit of this solution is that you may easily customize all aspe...
Is it possible to generate and return a ZIP file with App Engine?
583,791
19
2009-02-24T21:56:09Z
583,819
32
2009-02-24T22:06:10Z
[ "python", "google-app-engine", "zip", "in-memory" ]
I have a small project that would be perfect for Google App Engine. Implementing it hinges on the ability to generate a ZIP file and return it. Due to the distributed nature of App Engine, from what I can tell, the ZIP file couldn't be created "in-memory" in the traditional sense. It would basically have to be generat...
[zipfile](http://docs.python.org/library/zipfile.html) is available at appengine and reworked [example](http://www.tareandshare.com/2008/09/28/Zip-Google-App-Engine-GAE/) follows: ``` from contextlib import closing from zipfile import ZipFile, ZIP_DEFLATED from google.appengine.ext import webapp from google.appengine...
Is it possible to generate and return a ZIP file with App Engine?
583,791
19
2009-02-24T21:56:09Z
2,386,804
9
2010-03-05T12:54:24Z
[ "python", "google-app-engine", "zip", "in-memory" ]
I have a small project that would be perfect for Google App Engine. Implementing it hinges on the ability to generate a ZIP file and return it. Due to the distributed nature of App Engine, from what I can tell, the ZIP file couldn't be created "in-memory" in the traditional sense. It would basically have to be generat...
``` import zipfile import StringIO text = u"ABCDEFGHIJKLMNOPQRSTUVWXYVabcdefghijklmnopqqstuvweyxáéöüï东 廣 広 广 國 国 国 界" zipstream=StringIO.StringIO() file = zipfile.ZipFile(file=zipstream,compression=zipfile.ZIP_DEFLATED,mode="w") file.writestr("data.txt.zip",text.encode("utf-8")) file.close() zips...
Determine if a listing is a directory or file in Python over FTP
584,865
5
2009-02-25T05:54:36Z
585,232
10
2009-02-25T09:04:16Z
[ "python", "ftp" ]
Python has a standard library module `ftplib` to run FTP communications. It has two means of getting a listing of directory contents. One, `FTP.nlst()`, will return a list of the contents of a directory given a directory name as an argument. (It will return the name of a file if given a file name instead.) This is a ro...
Unfortunately FTP doesn't have a command to list just folders so parsing the results you get from ftp.dir() would be 'best'. A simple app assuming a standard result from ls (not a windows ftp) ``` from ftplib import FTP ftp = FTP(host, user, passwd) for r in ftp.dir(): if r.upper().startswith('D'): print...
Find all strings in python code files
585,529
6
2009-02-25T10:44:02Z
585,884
11
2009-02-25T12:54:41Z
[ "python" ]
I would like to list all strings within my large python project. Imagine the different possibilities to create a string in python: ``` mystring = "hello world" mystring = ("hello " "world") mystring = "hello " \ "world" ``` I need a tool that outputs "filename, linenumber, string" for each s...
unwind's suggestion of using the ast module in 2.6 is a good one. (There's also the undocumented \_ast module in 2.5.) Here's example code for that ``` code = """a = 'blah' b = '''multi line string''' c = u"spam" """ import ast root = ast.parse(code) class ShowStrings(ast.NodeVisitor): def visit_Str(self, node): ...
Python regular expression matching a multiline block of text
587,345
42
2009-02-25T19:00:49Z
587,518
10
2009-02-25T19:47:22Z
[ "python", "regex", "multiline" ]
I'm having a bit of trouble getting a Python regex to work when matching against text that spans multiple lines. The example text is ('\n' is a newline) ``` some Varying TEXT\n \n DSJFKDAFJKDAFJDSAKFJADSFLKDLAFKDSAF\n [more of the above, ending with a newline]\n [yep, there is a variable number of lines here]\n \n (re...
This will work: ``` >>> import re >>> rx_sequence=re.compile(r"^(.+?)\n\n((?:[A-Z]+\n)+)",re.MULTILINE) >>> rx_blanks=re.compile(r"\W+") # to remove blanks and newlines >>> text="""Some varying text1 ... ... AAABBBBBBCCCCCCDDDDDDD ... EEEEEEEFFFFFFFFGGGGGGG ... HHHHHHIIIIIJJJJJJJKKKK ... ... Some varying text 2 ... .....
Python regular expression matching a multiline block of text
587,345
42
2009-02-25T19:00:49Z
587,620
56
2009-02-25T20:06:01Z
[ "python", "regex", "multiline" ]
I'm having a bit of trouble getting a Python regex to work when matching against text that spans multiple lines. The example text is ('\n' is a newline) ``` some Varying TEXT\n \n DSJFKDAFJKDAFJDSAKFJADSFLKDLAFKDSAF\n [more of the above, ending with a newline]\n [yep, there is a variable number of lines here]\n \n (re...
Try this: ``` re.compile(r"^(.+)\n((?:\n.+)+)", re.MULTILINE) ``` I think your biggest problem is that you're expecting the `^` and `$` anchors to match linefeeds, but they don't. In multiline mode, `^` matches the position immediately *following* a newline and `$` matches the position immediately *preceding* a newli...
How to increment a value with leading zeroes?
587,647
8
2009-02-25T20:13:22Z
587,656
8
2009-02-25T20:15:43Z
[ "python" ]
What would be the best way to increment a value that contains leading zeroes? For example, I'd like to increment "00000001". However, it should be noted that the number of leading zeroes will not exceed 30. So there may be cases like "0000012", "00000000000000099", or "000000000000045". I can think of a couple ways, b...
``` int('00000001') + 1 ``` if you want the leading zeroes back: ``` "%08g" % (int('000000001') + 1) ```
How to increment a value with leading zeroes?
587,647
8
2009-02-25T20:13:22Z
587,690
8
2009-02-25T20:23:18Z
[ "python" ]
What would be the best way to increment a value that contains leading zeroes? For example, I'd like to increment "00000001". However, it should be noted that the number of leading zeroes will not exceed 30. So there may be cases like "0000012", "00000000000000099", or "000000000000045". I can think of a couple ways, b...
"%%0%ii" % len(x) % (int(x)+1) -- MarkusQ P.S. For x = "0000034" it unfolds like so: ``` "%%0%ii" % len("0000034") % (int("0000034")+1) "%%0%ii" % 7 % (34+1) "%07i" % 35 "0000035" ```
How to increment a value with leading zeroes?
587,647
8
2009-02-25T20:13:22Z
587,791
15
2009-02-25T20:50:12Z
[ "python" ]
What would be the best way to increment a value that contains leading zeroes? For example, I'd like to increment "00000001". However, it should be noted that the number of leading zeroes will not exceed 30. So there may be cases like "0000012", "00000000000000099", or "000000000000045". I can think of a couple ways, b...
Use the much overlooked str.zfill(): ``` str(int(x) + 1).zfill(len(x)) ```
a question on for loops in python
588,052
3
2009-02-25T21:47:41Z
588,067
8
2009-02-25T21:52:06Z
[ "python", "for-loop" ]
I want to calaculate pythagorean triplets(code below) and I want to calculate infinitly how do I do it without using the three for loops? Could I use a for loop in some way? thanks. ``` import math def main(): for x in range (10000, 1000): for y in range (10000, 1000): for z in range(10000, 1000): ...
Generally, you can't. Three variables, three loops. But this is a special case, as [nobody](http://stackoverflow.com/questions/588052/a-question-on-for-loops-in-python/588087#588087) pointed out. You can solve this problem with two loops. Also, there's no point in checking y, z and z, y. Oh, and `range(10000, 1000) ...
Python Daemon Packaging Best Practices
588,749
23
2009-02-26T01:32:39Z
588,780
14
2009-02-26T01:46:15Z
[ "python", "packaging", "setuptools", "distutils" ]
I have a tool which I have written in python and generally should be run as a daemon. What are the best practices for packaging this tool for distribution, particularly how should settings files and the daemon executable/script be handled? Relatedly are there any common tools for setting up the daemon for running on b...
The best tool I found for helping with init.d scripts is "start-stop-daemon". It will run any application, monitor run/pid files, create them when necessary, provide ways to stop the daemon, set process user/group ids, and can even background your process. For example, this is a script which can start/stop a wsgi serv...
Python Daemon Packaging Best Practices
588,749
23
2009-02-26T01:32:39Z
588,891
8
2009-02-26T02:44:33Z
[ "python", "packaging", "setuptools", "distutils" ]
I have a tool which I have written in python and generally should be run as a daemon. What are the best practices for packaging this tool for distribution, particularly how should settings files and the daemon executable/script be handled? Relatedly are there any common tools for setting up the daemon for running on b...
There are many snippets on the internet offering to write a daemon in pure python (no bash scripts) <http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/> looks clean... If you want to write your own, the principle is the same as with the bash daemon function. Basically: **On start:** * yo...
Python Daemon Packaging Best Practices
588,749
23
2009-02-26T01:32:39Z
588,904
11
2009-02-26T02:48:06Z
[ "python", "packaging", "setuptools", "distutils" ]
I have a tool which I have written in python and generally should be run as a daemon. What are the best practices for packaging this tool for distribution, particularly how should settings files and the daemon executable/script be handled? Relatedly are there any common tools for setting up the daemon for running on b...
To answer one part of your question, there are no tools I know of that will do daemon setup portably even across Linux systems let alone Windows or Mac OS X. Most Linux distributions seem to be using `start-stop-daemon` within init scripts now, but you're still going to have minor difference in filesystem layout and b...
Miminal Linux For a Pylons Web App?
589,115
2
2009-02-26T04:33:49Z
589,127
8
2009-02-26T04:37:24Z
[ "python", "linux", "pylons" ]
I am going to be building a Pylons-based web application. For this purpose, I'd like to build a minimal Linux platform, upon which I would then install the necessary packages such as Python and Pylons, and other necessary dependencies. The other reason to keep it minimal is because this machine will be virtual, probabl...
I really like [JeOS](http://www.ubuntu.com/products/whatisubuntu/serveredition/jeos) "Just enough OS" which is a minimal distribution of the Ubuntu Server Edition.
imploding a list for use in a python MySQLDB IN clause
589,284
35
2009-02-26T05:59:25Z
589,416
68
2009-02-26T06:46:38Z
[ "python", "mysql" ]
I know how to map a list to a string: ``` foostring = ",".join( map(str, list_of_ids) ) ``` And I know that I can use the following to get that string into an IN clause: ``` cursor.execute("DELETE FROM foo.bar WHERE baz IN ('%s')" % (foostring)) ``` What I need is to accomplish the same thing SAFELY (avoiding SQL i...
Use the `list_of_ids` directly: ``` format_strings = ','.join(['%s'] * len(list_of_ids)) cursor.execute("DELETE FROM foo.bar WHERE baz IN (%s)" % format_strings, tuple(list_of_ids)) ``` That way you avoid having to quote yourself, and avoid all kinds of sql injection. Note that the data (`list_of_ids...
Python - How to check if a file is used by another application?
589,407
8
2009-02-26T06:44:48Z
589,440
7
2009-02-26T06:55:28Z
[ "python", "windows", "unix", "logging", "file-io" ]
I want to open a file which is periodically written to by another application. This application cannot be modified. I'd therefore like to only open the file when I know it is not been written to by an other application. Is there a pythonic way to do this? Otherwise, how do I achieve this in Unix and Windows? **edit**...
Will your python script desire to open the file for writing or for reading? Is the legacy application opening and closing the file between writes, or does it keep it open? It is extremely important that we understand what the legacy application is doing, and what your python script is attempting to achieve. This area...
Python or IronPython
590,007
26
2009-02-26T10:41:16Z
590,026
13
2009-02-26T10:47:57Z
[ "python", "ironpython", "cpython" ]
How does IronPython stack up to the default Windows implementation of Python from python.org? If I am learning Python, will I be learning a subtley different language with IronPython, and what libraries would I be doing without? Are there, alternatively, any pros to IronPython (not including .NET IL compiled classes) ...
There are some subtle differences in how you write your code, but the biggest difference is in the libraries you have available. With IronPython, you have all the .Net libraries available, but at the expense of some of the "normal" python libraries that haven't been ported to the .Net VM I think. Basically, you shoul...
Python or IronPython
590,007
26
2009-02-26T10:41:16Z
590,782
27
2009-02-26T14:30:48Z
[ "python", "ironpython", "cpython" ]
How does IronPython stack up to the default Windows implementation of Python from python.org? If I am learning Python, will I be learning a subtley different language with IronPython, and what libraries would I be doing without? Are there, alternatively, any pros to IronPython (not including .NET IL compiled classes) ...
There are a number of important differences: 1. Interoperability with other .NET languages. You can use other .NET libraries from an IronPython application, or use IronPython from a C# application, for example. This interoperability is increasing, with a movement toward greater support for dynamic types in .NET 4.0. F...
How to change a Python module name?
590,250
3
2009-02-26T12:01:22Z
590,262
8
2009-02-26T12:05:14Z
[ "python", "module" ]
Is it only possible if I rename the file? Or is there a `__module__` variable to the file to define what's its name?
Yes, you should rename the file. Best would be after you have done that to remove the `oldname.pyc` and `oldname.pyo` compiled files (if present) from your system, otherwise the module will be importable under the old name too.
How to change a Python module name?
590,250
3
2009-02-26T12:01:22Z
590,312
15
2009-02-26T12:16:09Z
[ "python", "module" ]
Is it only possible if I rename the file? Or is there a `__module__` variable to the file to define what's its name?
If you really want to import the file 'oldname.py' with the statement 'import newname', there is a trick that makes it possible: Import the module *somewhere* with the old name, then inject it into `sys.modules` with the new name. Subsequent import statements will also find it under the new name. Code sample: ``` # th...
How to change a Python module name?
590,250
3
2009-02-26T12:01:22Z
590,353
9
2009-02-26T12:26:13Z
[ "python", "module" ]
Is it only possible if I rename the file? Or is there a `__module__` variable to the file to define what's its name?
You can change the name used for a module when importing by using as: ``` import foo as bar print bar.baz ```
Django - designing models with virtual fields?
590,921
2
2009-02-26T15:08:17Z
590,968
13
2009-02-26T15:17:49Z
[ "python", "django", "django-models" ]
I'd like to ask about the most elegant approach when it comes to designing models with virtual fields such as below in Django... Let's say we're building an online store and all the products in the system are defined by the model "*Product*". ``` class Product(models.Model): # common fields that all products shar...
Products have Features. ``` class Feature( models.Model ): feature_name = models.CharField( max_length=128 ) feature_value = models.TextField() part_of = models.ForeignKey( Product ) ``` Like that. Just a list of features. ``` p= Product( "iPhone", "Apple", 350 ) p.save() f= Feature( "mp3 capacity", "16...