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
Django sub-applications & module structure
2,617,522
17
2010-04-11T15:26:53Z
2,617,689
11
2010-04-11T16:17:31Z
[ "python", "django", "django-apps" ]
I am developing a Django application, which is a large system that requires multiple sub-applications to keep things neat. Therefore, I have a top level directory that is a Django app (as it has an empty `models.py` file), and multiple subdirectories, which are also applications in themselves. The reason I have laid m...
You are doing it the right way, since django itself does it that way. The admin app for instance is registered in `INSTALLED_APPS` as `django.contrib.admin`, but to reset it you have to use `manage.py reset admin`, and indeed, `manage.py reset django.contrib.admin` *does not work*. It could be considered as a bug in d...
Slow Python HTTP server on localhost
2,617,615
9
2010-04-11T15:58:15Z
2,617,803
7
2010-04-11T16:49:49Z
[ "python" ]
I am experiencing some performance problems when creating a very simple Python HTTP server. The key issue is that performance is varying depending on which client I use to access it, where the server and all clients are being run on the local machine. For instance, a GET request issued from a Python script (urllib2.url...
This does not sound like a problem with the code. A nifty way of troubleshooting an HTTP server is to connect to it to telnet to it on port 80. Then you can type something like: ``` GET /index.html HTTP/1.1 host: www.blah.com <enter> <enter> ``` and observe the server's response. See if you get a delay using this app...
Slow Python HTTP server on localhost
2,617,615
9
2010-04-11T15:58:15Z
5,273,870
23
2011-03-11T14:03:58Z
[ "python" ]
I am experiencing some performance problems when creating a very simple Python HTTP server. The key issue is that performance is varying depending on which client I use to access it, where the server and all clients are being run on the local machine. For instance, a GET request issued from a Python script (urllib2.url...
The request handler issues a inverse name lookup in order to display the client name in the log. My Windows 7 issues a first DNS lookup that fails with no delay, followed by 2 successive NetBIOS name queries to the HTTP client, and each one run into a 2 sec timeout = 4 seconds delay !! Have a look at <http://www.answe...
Why is this logical expression in python False?
2,617,681
4
2010-04-11T16:16:34Z
2,617,696
9
2010-04-11T16:19:13Z
[ "python", "expression" ]
My question is, why are these expressions False? ``` Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15) [GCC 4.4.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> num = raw_input("Choose a number: ") Choose a number: 5 >>> print num 5 >>> print ( num < 18 ) False >>> print ( num =...
This statement: ``` num = raw_input("Choose a number: ") ``` makes `num` a **string**, not a number, despite its misleading name. It so happens that Python 2 lets you compare strings with numbers, and in your version considers all strings larger than all numbers (the *contents* of the string play no role). Use `num ...
Checking for module availability programmatically in Python?
2,617,704
4
2010-04-11T16:20:47Z
2,617,733
9
2010-04-11T16:30:16Z
[ "python", "module", "python-module" ]
given a list of module names (e.g. mymods = ['numpy', 'scipy', ...]) how can I check if the modules are available? I tried the following but it's incorrect: ``` for module_name in mymods: try: import module_name except ImportError: print "Module %s not found." %(module_name) ``` thanks.
You could use both the `__import__` function, as in @Vinay's answer, **and** a `try`/`except`, as in your code: ``` for module_name in mymods: try: __import__(module_name) except ImportError: print "Module %s not found." %(module_name) ``` Alternatively, to **just** check availability but **without** actu...
Getting last insert id with SQLAlchemy
2,618,714
5
2010-04-11T21:07:06Z
2,619,789
9
2010-04-12T03:52:52Z
[ "python", "sqlalchemy" ]
I'm using SQLAlchemy ``` import hashlib import sqlalchemy as sa from sqlalchemy import orm from allsun.model import meta t_user = sa.Table("users",meta.metadata,autoload=True) class Duplicat(Exception): pass class LoginExistsException(Exception): pass class EmailExistsException(Exception): pass class User(obj...
You can access `user.id` (or whatever name you use for autoincremeted primary key field) after saving `user` object. SQLAlchemy automatically fills fields assigned by database.
Safest python code running
2,618,862
5
2010-04-11T21:59:42Z
2,618,869
9
2010-04-11T22:01:39Z
[ "python", "system" ]
How can I protect my web server, if I run custom users code on server. If any user can submit his python source on my server and run it. Maybe some modules or linux tools for close any network and hardware activity for this script. Thank's all for help!
The concept you're thinking of is sandboxing. Check out the Python wiki page about it: <http://wiki.python.org/moin/SandboxedPython>
Is there a programmatic way to transform a sequence of image files into a PDF?
2,619,071
6
2010-04-11T23:10:43Z
2,619,089
11
2010-04-11T23:15:11Z
[ "python", "documentation", "latex", "pdf-generation", "tex" ]
I have a sequence of JPG images. Each of the scans is already cropped to the exact size of one page. They are sequential pages of a valuable and out of print book. The publishing application requires that these pages be submitted as a single PDF file. I could take each of these images and just past them into a word-pr...
> It occurred to me that there must be a simpler way - so any suggestions? You're right, there is! Try this: ``` sudo apt-get install imagemagick cd ~/rare-book-images convert "*.jpg" rare-book.pdf ``` Note: depending on what shell you're using "\*.jpg" might not work as expected. Try omitting the quotes and seeing ...
How do I do this in my Django URLs? (.json, .xml)
2,619,129
2
2010-04-11T23:28:32Z
2,619,196
8
2010-04-11T23:55:23Z
[ "python", "django", "json", "http", "url" ]
Suppose this is my URL route: ``` (r'^test/?$','hello.life.views.test'), ``` How do I make it so that people can do .json, .xml, and it would pass a variable to my views.test, so that I know to make json or xml?
to add to @ziang's answer, if you really want to emulate file extensions you could just write the regular expression that way. `r'^test\.(?P<extension>(json)|(xml))$'` EDIT: I will add that it's certainly more RESTful to provide the expected return content type as a parameter.
how python http request and response works
2,620,228
6
2010-04-12T06:28:39Z
2,620,378
8
2010-04-12T07:02:31Z
[ "python", "http" ]
I'm newbie for python, I'm having task so I need to scan wifi and send the data to the server, the below is the format which i have to send, this work fine when enter manually in browser url text box, ``` http://223.56.124.58:8080/ppod-web/ProcessRawData?data={"userId":"2220081127-14","timestamp":"2010-04-12 10:54:24"...
Most likely, the issue **with the script you posted in the question** is you cannot directly do: ``` conn=httplib.HTTPConnection("http://223.56.124.58:8080/wireless") ``` The exception is triggered in [`getaddrinfo()`](http://docs.python.org/library/socket.html#socket.getaddrinfo), which calls the C function [`getadd...
Starter question of declarative style SQLAlchemy relation()
2,621,042
5
2010-04-12T09:42:26Z
2,621,118
10
2010-04-12T09:56:36Z
[ "python", "orm", "sqlalchemy", "relation" ]
I am quite new to SQLAlchemy, or even database programming, maybe my question is too simple. Now I have two class/table: ``` class User(Base): __tablename__ = 'users' id = Column(Integer, primary_key=True) name = Column(String(40)) ... class Computer(Base): __tablename__ = 'comps' id = Column(...
The correct syntax should be: ``` buyer = relation(User, backref=backref('buys', order_by=id)) user = relation(User, backref=backref('usings', order_by=id)) ``` P.S. Next time please specify what do you mean by "cannot run" by posting a traceback. **Update**: the traceback in updated question says exactly what you n...
random() in python
2,621,055
4
2010-04-12T09:44:17Z
2,621,082
11
2010-04-12T09:49:11Z
[ "python", "random" ]
In python the function `random()` generates a random float uniformly in the semi-open range [0.0, 1.0). In principle can it ever generate 0.0 (i.e. zero) and 1.0 (i.e. unity)? What is the scenario in practicality?
The `[` indicates that `0.0` *is* included in the range of valid outputs. The `)` indicates `1.0` is *not* in the range of valid outputs.
random() in python
2,621,055
4
2010-04-12T09:44:17Z
2,621,096
13
2010-04-12T09:52:16Z
[ "python", "random" ]
In python the function `random()` generates a random float uniformly in the semi-open range [0.0, 1.0). In principle can it ever generate 0.0 (i.e. zero) and 1.0 (i.e. unity)? What is the scenario in practicality?
`0.0` can be generated; `1.0` cannot (since it isn't within the range, hence the `)` as opposed to `[`). The probability of generating `0.0` is equal to the probability of generating any other number within that range, namely, 1/X where X is the number of different possible results. For a standard unsigned double-prec...
the error "invalid literal for int() with base 10:" keeps coming up
2,621,243
9
2010-04-12T10:18:27Z
2,621,258
7
2010-04-12T10:21:21Z
[ "python", "string", "syntax", "int" ]
I'm trying to write a very simple program, I want to print out the sum of all the multiples of 3 and 5 below 100, but, an error keeps accuring, saying "invalid literal for int() with base 10:" my program is as follows: ``` sum = "" sum_int = int(sum) for i in range(1, 101): if i % 5 == 0: sum += i eli...
Python is not JavaScript: `""` does not automatically convert to `0`, and `0` does not automatically convert to `"0"`. Your program also seems to be confused between printing the sum of all the multiples of three and five and printing a list of all the numbers which are multiples of three and five.
the error "invalid literal for int() with base 10:" keeps coming up
2,621,243
9
2010-04-12T10:18:27Z
2,621,264
10
2010-04-12T10:23:00Z
[ "python", "string", "syntax", "int" ]
I'm trying to write a very simple program, I want to print out the sum of all the multiples of 3 and 5 below 100, but, an error keeps accuring, saying "invalid literal for int() with base 10:" my program is as follows: ``` sum = "" sum_int = int(sum) for i in range(1, 101): if i % 5 == 0: sum += i eli...
The `""` are the cause of these problems. Change ``` sum = "" ``` to ``` sum = 0 ``` and get rid of ``` else: sum += "" ```
Generic List View raises Attribute Error: "'function' object has no attribute '_clone'
2,621,440
6
2010-04-12T10:55:31Z
2,621,558
9
2010-04-12T11:13:53Z
[ "python", "django" ]
An odd error here, perhaps someone can help track down source as it's attempting to extend the Django CMS project & attempts to use uses some logic written as part of that project which I'm not fully clear on. In short, using: ``` urls.py ====================== from django.conf.urls.defaults import * from cmsplugin_fl...
The `_clone` errors are a red herring caused by you passing a function as an argument to a generic view where a `QuerySet` is expected. The version of your code which passes `News.published.all()` to the generic views is correct, as generic views will try to clone the QuerySet they are given, to avoid caching the first...
how to extract elements from a list in python?
2,621,674
11
2010-04-12T11:35:22Z
2,621,685
30
2010-04-12T11:37:42Z
[ "python" ]
I feel suddenly uneasy of not being able to perform this operation easily. It could be that I'm tired, or that there's really no way (google didn't help), but... if you have a list in python, and want to extract element at indices say 1, 2 and 5 into a new list, how do you do ? This is how I did it, but I'm not very ...
Perhaps use this: ``` [a[i] for i in (1,2,5)] # [11, 12, 15] ```
Splitting a string using space delimiters and a maximum length
2,622,572
7
2010-04-12T13:58:15Z
2,622,632
24
2010-04-12T14:06:40Z
[ "python", "string", "split" ]
I'd like to split a string in a similar way to `.split()` (so resulting in a list) but in a more intelligent way: I'd like it to split it into chunks that are up to 15 characters, but are not split mid word so: ``` string = 'A string with words' [splitting process takes place] list = ('A string with','words') ``` T...
``` >>> import textwrap >>> string = 'A string with words' >>> textwrap.wrap(string,15) ['A string with', 'words'] ```
Python: finding lowest integer
2,622,994
9
2010-04-12T14:57:47Z
2,623,002
19
2010-04-12T14:58:49Z
[ "python", "list", "integer" ]
I have the following code: ``` l = ['-1.2', '0.0', '1'] x = 100.0 for i in l: if i < x: x = i print x ``` The code should find the lowest value in my list (-1.2) but instead when i print 'x' it finds the value is still 100.0 Where is my code going wrong?
You aren't comparing integers, you're comparing strings. Strings compare lexicographically -- meaning character by character -- instead of (as you seem to want) by converting the value to a float. Make your list hold numbers (floats or integers, depending on what you want), or convert the strings to floats or integers ...
Python: finding lowest integer
2,622,994
9
2010-04-12T14:57:47Z
2,623,088
25
2010-04-12T15:12:23Z
[ "python", "list", "integer" ]
I have the following code: ``` l = ['-1.2', '0.0', '1'] x = 100.0 for i in l: if i < x: x = i print x ``` The code should find the lowest value in my list (-1.2) but instead when i print 'x' it finds the value is still 100.0 Where is my code going wrong?
To find the minimum value of a list, you might just as well use `min`: ``` x = min(float(s) for s in l) # min of a generator ```
Python: finding lowest integer
2,622,994
9
2010-04-12T14:57:47Z
2,623,098
12
2010-04-12T15:14:03Z
[ "python", "list", "integer" ]
I have the following code: ``` l = ['-1.2', '0.0', '1'] x = 100.0 for i in l: if i < x: x = i print x ``` The code should find the lowest value in my list (-1.2) but instead when i print 'x' it finds the value is still 100.0 Where is my code going wrong?
It looks like you want to convert the list to a list of numbers ``` >>> foo = ['-1.2', '0.0', '1'] >>> bar = map(float, foo) >>> bar [-1.2, 0.0, 1.0] >>> min(bar) -1.2 ``` or if it really is strings you want, that you want to use `min`'s `key` argument ``` >>> foo = ['-1.2', '0.0', '1'] >>> min(foo, key=float) '-1.2...
Is a variable swap guaranteed to be atomic in python?
2,623,086
27
2010-04-12T15:11:52Z
2,623,117
51
2010-04-12T15:16:24Z
[ "python", "multithreading", "atomic", "cpython" ]
With reference to the following link: <http://docs.python.org/faq/library.html#what-kinds-of-global-value-mutation-are-thread-safe> I wanted to know if the following: ``` (x, y) = (y, x) ``` will be guaranteed atomic in cPython. (x and y are both python variables)
Let's see: ``` >>> x = 1 >>> y = 2 >>> def swap_xy(): ... global x, y ... (x, y) = (y, x) ... >>> dis.dis(swap_xy) 3 0 LOAD_GLOBAL 0 (y) 3 LOAD_GLOBAL 1 (x) 6 ROT_TWO 7 STORE_GLOBAL 1 (x) 10 STORE...
How to convert the integer date format into YYYYMMDD?
2,623,156
11
2010-04-12T15:21:37Z
2,623,191
12
2010-04-12T15:26:11Z
[ "python", "matlab", "datetime-format" ]
Python and Matlab quite often have integer date representations as follows: 733828.0 733829.0 733832.0 733833.0 733834.0 733835.0 733836.0 733839.0 733840.0 733841.0 these numbers correspond to some dates this year. Do you guys know which function can convert them back to YYYYMMDD format? thanks a million!
The [`datetime.datetime` class](http://docs.python.org/library/datetime.html#datetime-objects) can help you here. The following works, if those values are treated as integer days (you don't specify what they are). ``` >>> from datetime import datetime >>> dt = datetime.fromordinal(733828) >>> dt datetime.datetime(2010...
How to convert the integer date format into YYYYMMDD?
2,623,156
11
2010-04-12T15:21:37Z
2,623,204
15
2010-04-12T15:27:13Z
[ "python", "matlab", "datetime-format" ]
Python and Matlab quite often have integer date representations as follows: 733828.0 733829.0 733832.0 733833.0 733834.0 733835.0 733836.0 733839.0 733840.0 733841.0 these numbers correspond to some dates this year. Do you guys know which function can convert them back to YYYYMMDD format? thanks a million!
Since Python example was already demonstrated, here is the matlab one: ``` >> datestr(733828, 'yyyymmdd') ans = 20090224 ``` Also, note that while looking similar these are actually different things in Matlab and Python: > Matlab > A serial date number represents the whole and fractional number of days > from a ...
Output without new line
2,623,470
16
2010-04-12T16:05:21Z
2,623,495
22
2010-04-12T16:07:33Z
[ "python", "newline" ]
how can I output text to the console without new line at the end? for example: ``` print 'temp1' print 'temp2' ``` output: ``` temp1 temp2 ``` And I need: ``` temp1temp2 ```
Add a comma after the last argument: ``` print 'temp1', print 'temp2' ``` Alternatively, Call `sys.stdout.write`: ``` import sys sys.stdout.write("Some output") ```
Output without new line
2,623,470
16
2010-04-12T16:05:21Z
2,623,563
16
2010-04-12T16:18:13Z
[ "python", "newline" ]
how can I output text to the console without new line at the end? for example: ``` print 'temp1' print 'temp2' ``` output: ``` temp1 temp2 ``` And I need: ``` temp1temp2 ```
In Python > 2.6 and Python 3: ``` from __future__ import print_function print('temp1', end='') print('temp2', end='') ```
How can I do the multiple replace in python?
2,623,524
5
2010-04-12T16:10:50Z
2,623,545
12
2010-04-12T16:15:04Z
[ "python", "string", "replace" ]
As asked and answered in [this post](http://stackoverflow.com/questions/2595119/python-glob-and-bracket-characters), I need to replace '[' with '[[]', and ']' with '[]]'. I tried to use s.replace(), but as it's not in place change, I ran as follows to get a wrong anwser. ``` path1 = "/Users/smcho/Desktop/bracket/[10,...
``` import re path2 = re.sub(r'(\[|])', r'[\1]', path) ``` Explanation: `\[|]` will match a bracket (opening or closing). Placing it in the parentheses will make it capture into a group. Then in the replacement string, `\1` will be substituted with the content of the group.
What's the __repr__ equivalence in ruby?
2,625,132
4
2010-04-12T20:19:23Z
2,625,174
7
2010-04-12T20:24:59Z
[ "python", "ruby" ]
The `__repr__` function of python is fancy as it is called when print OBJECT is used automatically. Is there a ruby equivalence for it? I thought it was to\_s, but, I had p OBJECT doesn't seem to call the to\_s method. ## Added I got something wrong, p OBJECT seems to call to\_s method as follows. I got some hints f...
``` obj.inspect => string ``` Returns a string containing a human-readable representation of `obj`. **If not overridden, uses the `to_s` method to generate the string.** ``` [ 1, 2, 3..4, 'five' ].inspect #=> "[1, 2, 3..4, \"five\"]" Time.new.inspect #=> "Wed Apr 09 08:54:39 CDT 2003" ``` `...
How do I autoformat some Python code to be correctly formatted?
2,625,294
22
2010-04-12T20:42:57Z
2,625,361
33
2010-04-12T20:53:08Z
[ "python", "formatting" ]
I have some existing code which isn't formatted consistently -- sometimes two spaces are used for indent, sometimes four, and so on. The code itself is correct and well-tested, but the formatting is awful. Is there a place online where I can simply paste a snippet of Python code and have it be indented/formatted autom...
Edit: Nowadays, I would recommend [autopep8](https://github.com/hhatto/autopep8), since it not only corrects indentation problems but also (at your discretion) makes code conform to many other PEP8 guidelines. --- Use `reindent.py`. It should come with the standard distribution of Python, though on Ubuntu you need to...
How do I autoformat some Python code to be correctly formatted?
2,625,294
22
2010-04-12T20:42:57Z
13,761,026
34
2012-12-07T10:14:44Z
[ "python", "formatting" ]
I have some existing code which isn't formatted consistently -- sometimes two spaces are used for indent, sometimes four, and so on. The code itself is correct and well-tested, but the formatting is awful. Is there a place online where I can simply paste a snippet of Python code and have it be indented/formatted autom...
### autopep8 [autopep8](http://pypi.python.org/pypi/autopep8/) would auto-format your python script. not only the code indentation, but also other coding spacing styles. It makes your python script to conform PEP8 Style Guide. ``` pip install autopep8 autopep8 your_script.py # dry-run, only print autopep8 -i your_...
For-loops in Python
2,625,540
5
2010-04-12T21:21:21Z
2,625,558
13
2010-04-12T21:24:04Z
[ "python", "for-loop" ]
What is the best way of doing this in Python? ``` for (v = n / 2 - 1; v >= 0; v--) ``` I actually tried Google first, but as far as I can see the only solution would be to use `while`.
The way to do it is with `xrange()`: ``` for v in xrange(n // 2 - 1, -1, -1): ``` (Or, in Python 3.x, with `range()` instead of `xrange()`.) `//` is flooring division, which makes sure the result is a whole number.
For-loops in Python
2,625,540
5
2010-04-12T21:21:21Z
2,625,846
15
2010-04-12T22:18:06Z
[ "python", "for-loop" ]
What is the best way of doing this in Python? ``` for (v = n / 2 - 1; v >= 0; v--) ``` I actually tried Google first, but as far as I can see the only solution would be to use `while`.
I would do this: ``` for i in reversed(range(n // 2)): # Your code pass ``` It's a bit clearer that this is a reverse sequence, what the lower limit is, and what the upper limit is.
Alternative Python standard library reference
2,625,547
9
2010-04-12T21:21:45Z
2,625,613
10
2010-04-12T21:32:10Z
[ "python", "documentation", "standard-library" ]
I love Python; I absolutely despise its official documentation. Tutorials do not count as library references, but that appears to be what they're attempting. What I really want is the ability to find a class in the standard library and view documentation for all of its properties and methods. Actionscript, MSDN, and J...
The problem isn't with `list` not being a class (it is), but with its interface not being unique to the class. So `list.sort` ends up being documented in the [Mutable Sequence Types](http://docs.python.org/library/stdtypes.html#mutable-sequence-types) section. The kind of information you want is available through the ...
How to copy files to network path or drive using Python
2,625,877
5
2010-04-12T22:24:41Z
2,626,085
8
2010-04-12T23:23:31Z
[ "python", "network-programming", "share", "drive" ]
Mine is similar to this question. [How to copy a file from a network share to local disk with variables?](http://stackoverflow.com/questions/2042342/network-path-and-variables-in-python/2042376) The only difference is my network drive has a password protect with username and password. I need to copy files to a `Samb...
I'd try mapping the share to an unused drive letter by calling the `NET USE` command using `os.system` (assuming you are on Windows): ``` os.system(r"NET USE P: \\ComputerName\ShareName %s /USER:%s\%s" % (password, domain_name, user_name)) ``` After you mapped the share to a drive letter, you can use `shutil.copyfile...
Python sys.argv lists and indexes
2,626,026
15
2010-04-12T23:05:25Z
2,626,052
8
2010-04-12T23:11:18Z
[ "python" ]
In the below code I understand that sys.argv uses lists, however I am not clear on how the index's are used here. ``` def main(): if len(sys.argv) >= 2: name = sys.argv[1] else: name = 'World' print 'Hello', name if __name__ == '__main__': main() ``` If I change ``` name = sys.argv[1] ``` to ``` ...
`sys.argv` is the list of arguments passed to the Python program. The first argument, `sys.argv[0]`, is actually the name of the program as it was invoked. That's not a Python thing, but how most operating systems work. The reason `sys.argv[0]` exists is so you can change your program's behaviour depending on how it wa...
Python sys.argv lists and indexes
2,626,026
15
2010-04-12T23:05:25Z
2,626,634
24
2010-04-13T02:38:56Z
[ "python" ]
In the below code I understand that sys.argv uses lists, however I am not clear on how the index's are used here. ``` def main(): if len(sys.argv) >= 2: name = sys.argv[1] else: name = 'World' print 'Hello', name if __name__ == '__main__': main() ``` If I change ``` name = sys.argv[1] ``` to ``` ...
let's say on the command-line you have: ``` C:\> C:\Documents and Settings\fred\My Documents\Downloads\google-python-exercises \google-python-exercises\hello.py John ``` to make it easier to read, let's just shorten this to: ``` C:\> hello.py John ``` `argv` represents all the items that come along via the command-...
Python dictionary: add or increment entry
2,626,059
40
2010-04-12T23:13:12Z
2,626,062
70
2010-04-12T23:15:12Z
[ "python", "syntax" ]
I'm currently re-engaging with Python after a long absence and loving it. However, I find myself coming across a pattern over and over. I keep thinking that there must be a better way to express what I want and that I'm probably doing it the wrong way. The code that I'm writing is in the following form: ``` # foo is ...
Use a `defaultdict`: ``` from collections import defaultdict foo = defaultdict(int) foo[bar] += 1 ``` In Python >= 2.7, you also have a separate [Counter](http://docs.python.org/dev/py3k/library/collections.html#collections.Counter) class for these purposes. For Python 2.5 and 2.6, you can use its [backported versio...
Python dictionary: add or increment entry
2,626,059
40
2010-04-12T23:13:12Z
2,626,102
56
2010-04-12T23:31:03Z
[ "python", "syntax" ]
I'm currently re-engaging with Python after a long absence and loving it. However, I find myself coming across a pattern over and over. I keep thinking that there must be a better way to express what I want and that I'm probably doing it the wrong way. The code that I'm writing is in the following form: ``` # foo is ...
The `dict`'s [`get()`](http://docs.python.org/library/stdtypes.html#dict.get) method takes an optional second parameter that can be used to provide a default value if the requested key is not found: ``` foo[bar] = foo.get(bar, 0) + 1 ```
python regular expression for domain names
2,626,995
3
2010-04-13T04:35:09Z
2,627,003
7
2010-04-13T04:38:24Z
[ "python", "regex", "url", "dns" ]
I am trying use the following regular expression to extract domain name from a text, but it just produce nothing, what's wrong with it? I don't know if this is suitable to ask this "fix code" question, maybe I should read more. I just want to save some time. Thanks ``` pat_url = re.compile(r''' (?:https?:...
Don't use regex for this. Use the `urlparse` standard library instead. It's far more straightforward and easier to read/maintain. <http://docs.python.org/library/urlparse.html>
What's the pythonic way to use getters and setters?
2,627,002
75
2010-04-13T04:38:23Z
2,627,017
22
2010-04-13T04:42:36Z
[ "python", "getter-setter" ]
I'm doing it like: ``` def set_property(property,value): def get_property(property): ``` or ``` object.property = value value = object.property ``` I'm new to Python, so i'm still exploring the syntax, and i'd like some advice on doing this.
Check out the [`@property` decorator](http://docs.python.org/library/functions.html#property).
What's the pythonic way to use getters and setters?
2,627,002
75
2010-04-13T04:38:23Z
2,627,022
47
2010-04-13T04:43:10Z
[ "python", "getter-setter" ]
I'm doing it like: ``` def set_property(property,value): def get_property(property): ``` or ``` object.property = value value = object.property ``` I'm new to Python, so i'm still exploring the syntax, and i'd like some advice on doing this.
The Pythonic way is to not use them. If you *must* have them then hide them behind a property.
What's the pythonic way to use getters and setters?
2,627,002
75
2010-04-13T04:38:23Z
2,627,032
10
2010-04-13T04:45:45Z
[ "python", "getter-setter" ]
I'm doing it like: ``` def set_property(property,value): def get_property(property): ``` or ``` object.property = value value = object.property ``` I'm new to Python, so i'm still exploring the syntax, and i'd like some advice on doing this.
``` In [1]: class test(object): def __init__(self): self.pants = 'pants' @property def p(self): return self.pants @p.setter def p(self, value): self.pants = value * 2 ....: In [2]: t = test() In [3]: t.p Out[3]: 'pants' In [4]: t.p = 10 In [5]: t.p Out[5]: 20 ```
What's the pythonic way to use getters and setters?
2,627,002
75
2010-04-13T04:38:23Z
2,627,034
229
2010-04-13T04:45:55Z
[ "python", "getter-setter" ]
I'm doing it like: ``` def set_property(property,value): def get_property(property): ``` or ``` object.property = value value = object.property ``` I'm new to Python, so i'm still exploring the syntax, and i'd like some advice on doing this.
Try this: [Python Property](http://docs.python.org/library/functions.html?highlight=property#property) The sample code is: ``` class C(object): def __init__(self): self._x = None @property def x(self): """I'm the 'x' property.""" print "getter of x called" return self._x ...
How do I sanitize LaTeX input?
2,627,135
8
2010-04-13T05:17:51Z
2,627,303
11
2010-04-13T06:03:50Z
[ "python", "latex", "sanitization" ]
I'd like to take user input (sometimes this will be large paragraphs) and generate a LaTeX document. I'm considering a couple of simple regular expressions that replaces all instances of "\" with "\textbackslash " and all instances of "{" or "}" with "\}" or "\{". I doubt this is sufficient. What else do I need to do?...
If your input is plain text and you are in a normal catcode regime, you must do the following substitutions: * `\` → `\textbackslash{}` (note the empty group!) * `{` → `\{` * `}` → `\}` * `$` → `\$` * `&` → `\&` * `#` → `\#` * `^` → `\textasciicircum{}` (requires the `textcomp` package) * `_` → `\_` * ...
Automating HP Quality Center with Python or Java
2,627,419
7
2010-04-13T06:29:14Z
6,098,966
11
2011-05-23T14:57:18Z
[ "java", "python", "quality-center" ]
We have a project that uses HP Quality Center and one of the regular issues we face is people not updating comments on the defect. So I was thinkingif we could come up with a small script or tool that could be used to periodically throw up a reminder and force the user to update the comments. I came across the Open T...
# Example of using Python (win32com) to connect to HP Quality Center via OTA HP Quality Center exposes a com based API called OTA. Documentation on this is downloadable from an QC server (OTA\_API\_Reference.chm) (Weirdly it is very hard to find online) The documentation uses VBScript (The officially supported inter...
How to deserialize an object with PyYAML using safe_load?
2,627,555
5
2010-04-13T06:52:41Z
2,627,732
8
2010-04-13T07:33:36Z
[ "python", "deserialization", "pyyaml" ]
Having a snippet like this: ``` import yaml class User(object): def __init__(self, name, surname): self.name= name self.surname= surname user = User('spam', 'eggs') serialized_user = yaml.dump(user) #Network deserialized_user = yaml.load(serialized_user) print "name: %s, sname: %s" % (deserialized_u...
It appears that safe\_load, by definition, does not let you deserialize your own classes. If you want it to be safe, I'd do something like this: ``` import yaml class User(object): def __init__(self, name, surname): self.name= name self.surname= surname def yaml(self): return yaml.dump(se...
How to deserialize an object with PyYAML using safe_load?
2,627,555
5
2010-04-13T06:52:41Z
2,890,073
13
2010-05-22T23:00:41Z
[ "python", "deserialization", "pyyaml" ]
Having a snippet like this: ``` import yaml class User(object): def __init__(self, name, surname): self.name= name self.surname= surname user = User('spam', 'eggs') serialized_user = yaml.dump(user) #Network deserialized_user = yaml.load(serialized_user) print "name: %s, sname: %s" % (deserialized_u...
Another way exists. From the PyYaml docs: > A python object can be marked as safe and thus be recognized by yaml.safe\_load. To do this, derive it from yaml.YAMLObject [...] and explicitly set its class property yaml\_loader to yaml.SafeLoader. You also have to set the yaml\_tag property to make it work. YAMLObject ...
What kind of client/server protocols python supports out of the box?
2,627,715
2
2010-04-13T07:29:14Z
2,627,748
11
2010-04-13T07:38:11Z
[ "python", "client-server" ]
Without installing third party libraries, what kind of [Client/Server](http://en.wikipedia.org/wiki/Client%E2%80%93server_model) protocols Python supports out of the box ?
* **Basic Web Protocols**: + Downloading from http, ftp and file: with [`urllib`](http://docs.python.org/library/urllib.html), but note that in python 3 that `urllib.urlopen` has moved to `urllib2.urlopen` and is deprecated from python 2.6 + Downloading from https and http with basic proxy and authentication suppor...
Remove items from a list while iterating without using extra memory in Python
2,629,198
9
2010-04-13T11:44:12Z
2,629,230
13
2010-04-13T11:50:03Z
[ "python", "list", "iteration" ]
My problem is simple: I have a long list of elements that I want to iterate through and check every element against a condition. Depending on the outcome of the condition I would like to delete the current element of the list, and continue iterating over it as usual. I have read a few other threads on this matter. Two...
``` li = [ x for x in li if condition(x)] ``` and also ``` li = filter(condition,li) ``` [Thanks to Dave Kirby](http://stackoverflow.com/questions/2629198/python-remove-items-from-a-list-while-iterating-in-python/2629240#2629240)
deciding among subprocess, multiprocessing, and thread in Python?
2,629,680
59
2010-04-13T13:01:31Z
2,629,766
40
2010-04-13T13:14:16Z
[ "python", "multithreading", "parallel-processing" ]
I'd like to parallelize my Python program so that it can make use of multiple processors on the machine that it runs on. My parallelization is very simple, in that all the parallel "threads" of the program are independent and write their output to separate files. I don't need the threads to exchange information but it ...
`multiprocessing` is a great Swiss-army knife type of module. It is more general than threads, as you can even perform remote computations. This is therefore the module I would suggest you use. The `subprocess` module would also allow you to launch multiple processes, but I found it to be less convenient to use than t...
deciding among subprocess, multiprocessing, and thread in Python?
2,629,680
59
2010-04-13T13:01:31Z
16,031,801
85
2013-04-16T08:07:05Z
[ "python", "multithreading", "parallel-processing" ]
I'd like to parallelize my Python program so that it can make use of multiple processors on the machine that it runs on. My parallelization is very simple, in that all the parallel "threads" of the program are independent and write their output to separate files. I don't need the threads to exchange information but it ...
For me this is actually pretty simple: # The *subprocess* option: `subprocess` is **for running other executables** --- it's basically a wrapper around `os.fork()` and `os.execve()` with some support for optional plumbing (setting up PIPEs to and from the subprocesses. (Obviously other OS inter-process communications...
Read a file on App Engine with Python?
2,630,205
32
2010-04-13T14:15:33Z
2,632,039
10
2010-04-13T18:18:08Z
[ "python", "google-app-engine" ]
Is it possible to open a file on GAE just to read its contents and get the last modified tag? I get a IOError: [Errno 13] file not accessible: I know that i cannot delete or update but i believe reading should be possible Has anyone faced a similar problem? ``` os.stat(f,'r').st_mtim ```
You can read files, but they're on Goooogle's wacky GAE filesystem so you have to use a relative path. I just whipped up a quick app with a main.py file and test.txt in the same folder. Don't forget the 'e' on st\_mtime. ``` import os from google.appengine.ext import webapp from google.appengine.ext.webapp import util...
Read a file on App Engine with Python?
2,630,205
32
2010-04-13T14:15:33Z
2,632,751
48
2010-04-13T19:56:37Z
[ "python", "google-app-engine" ]
Is it possible to open a file on GAE just to read its contents and get the last modified tag? I get a IOError: [Errno 13] file not accessible: I know that i cannot delete or update but i believe reading should be possible Has anyone faced a similar problem? ``` os.stat(f,'r').st_mtim ```
You've probably declared the file as static in app.yaml. Static files are not available to your application; if you need to serve them both as static files and read them as application files, you'll need to include 2 copies in your project (ideally using symlinks, so you don't actually have to maintain an actual copy.)...
Python - multi-line array
2,630,211
5
2010-04-13T14:16:32Z
2,630,239
7
2010-04-13T14:20:07Z
[ "python", "arrays" ]
in c++ I can wrote: ``` int someArray[8][8]; for (int i=0; i < 7; i++) for (int j=0; j < 7; j++) someArray[i][j] = 0; ``` And how can I initialize multi-line arrays in python? I tried: ``` array = [[],[]] for i in xrange(8): for j in xrange(8): array[i][j] = 0 ```
``` >>> [[0]*8 for x in xrange(8)] [[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]] >>> ```
Python - multi-line array
2,630,211
5
2010-04-13T14:16:32Z
2,630,639
7
2010-04-13T15:04:41Z
[ "python", "arrays" ]
in c++ I can wrote: ``` int someArray[8][8]; for (int i=0; i < 7; i++) for (int j=0; j < 7; j++) someArray[i][j] = 0; ``` And how can I initialize multi-line arrays in python? I tried: ``` array = [[],[]] for i in xrange(8): for j in xrange(8): array[i][j] = 0 ```
You asked about initializing a list of lists. Its a very useful data structure, but it has an important difference from the 2D array in C++: There are no guarantees that all lines have the same length (i.e, that `len(a[0])==len(a[1])` (while in C++ you do have that guarantee). So another solution that might be handy, ...
Python "Every Other Element" Idiom
2,631,189
32
2010-04-13T16:11:51Z
2,631,222
70
2010-04-13T16:15:58Z
[ "python", "idioms" ]
I feel like I spend a lot of time writing code in Python, but not enough time creating Pythonic code. Recently I ran into a funny little problem that I thought might have an easy, idiomatic solution. Paraphrasing the original, I needed to collect every sequential pair in a list. For example, given the list `[1,2,3,4,5,...
This will do it a bit more neatly: ``` >>> data = [1,2,3,4,5,6] >>> zip(data[0::2], data[1::2]) [(1, 2), (3, 4), (5, 6)] ``` (but it's arguably less readable if you're not familiar with the "stride" feature of ranges). Like your code, it discards the last value where you have an odd number of values.
Python "Every Other Element" Idiom
2,631,189
32
2010-04-13T16:11:51Z
2,631,227
7
2010-04-13T16:16:43Z
[ "python", "idioms" ]
I feel like I spend a lot of time writing code in Python, but not enough time creating Pythonic code. Recently I ran into a funny little problem that I thought might have an easy, idiomatic solution. Paraphrasing the original, I needed to collect every sequential pair in a list. For example, given the list `[1,2,3,4,5,...
How about using the step feature of `range()`: ``` [(l[n],l[n+1]) for n in range(0,len(l),2)] ```
Python "Every Other Element" Idiom
2,631,189
32
2010-04-13T16:11:51Z
2,631,256
45
2010-04-13T16:20:47Z
[ "python", "idioms" ]
I feel like I spend a lot of time writing code in Python, but not enough time creating Pythonic code. Recently I ran into a funny little problem that I thought might have an easy, idiomatic solution. Paraphrasing the original, I needed to collect every sequential pair in a list. For example, given the list `[1,2,3,4,5,...
The one often-quoted is: ``` zip(*[iter(l)] * 2) ```
Python "Every Other Element" Idiom
2,631,189
32
2010-04-13T16:11:51Z
2,631,275
9
2010-04-13T16:23:39Z
[ "python", "idioms" ]
I feel like I spend a lot of time writing code in Python, but not enough time creating Pythonic code. Recently I ran into a funny little problem that I thought might have an easy, idiomatic solution. Paraphrasing the original, I needed to collect every sequential pair in a list. For example, given the list `[1,2,3,4,5,...
I usually copy the `grouper` recipe from the [itertools](http://docs.python.org/library/itertools.html) documentation into my code for this. ``` def grouper(n, iterable, fillvalue=None): "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return izip_longest(fillvalue=fillvalue, *args)...
using a "temporary files" folder in python
2,631,923
2
2010-04-13T17:58:05Z
2,631,947
7
2010-04-13T18:02:57Z
[ "python", "operating-system", "temporary-files", "temporary-directory" ]
I recently wrote a script which queries PyPI and downloads a package; however, the package gets downloaded to a user defined folder. I`d like to modify the script in such a way that my downloaded files go into a temporary folder, if the folder is not specified. The temporary-files folder in \*nix machines is "/tmp" ;...
Python has a built-in module for using temporary files and folders. You probably want [`tempfile.mkdtemp()`](http://docs.python.org/library/tempfile.html#tempfile.mkdtemp).
SQLAlchemy: a better way for update with declarative?
2,631,935
24
2010-04-13T18:00:27Z
2,632,080
9
2010-04-13T18:24:07Z
[ "python", "sqlalchemy", "declarative" ]
I am a SQLAlchemy noob. Let's say I have an user table in declarative mode: ``` class User(Base): __tablename__ = 'user' id = Column(u'id', Integer(), primary_key=True) name = Column(u'name', String(50)) ``` When I know user's id without object loaded into session, I update such user like this: ``` ex =...
You're working on *clause* level here, not on model/entity/object level. Clause level is lower than mapped objects. And yes, something have to be done to convert one terms into others. You could also stay on object level and do: ``` session = Session() u = session.query(User).get(123) u.name = u"Bob Marley" session.c...
SQLAlchemy: a better way for update with declarative?
2,631,935
24
2010-04-13T18:00:27Z
2,632,919
34
2010-04-13T20:19:19Z
[ "python", "sqlalchemy", "declarative" ]
I am a SQLAlchemy noob. Let's say I have an user table in declarative mode: ``` class User(Base): __tablename__ = 'user' id = Column(u'id', Integer(), primary_key=True) name = Column(u'name', String(50)) ``` When I know user's id without object loaded into session, I update such user like this: ``` ex =...
There's also some update capability at the ORM level. It doesn't handle any tricky cases yet but for the trivial case of single row update (or bulk update) it works fine. It even goes over any already loaded objects and applies the update on them also. You can use it like this: ``` session.query(User).filter_by(id=123...
Can Python directory names be keywords? E.g. 'import'?
2,632,179
3
2010-04-13T18:35:32Z
2,632,283
8
2010-04-13T18:47:04Z
[ "python", "module", "keyword" ]
Am I allowed to have a directory named 'import' containing Python code? Or will the import command fail to parse it as a result? Is there any way around that?
You can use the built-in [`__import__` function](http://docs.python.org/library/functions.html#__import__) which accepts any string. Thus you may write: ``` __import__('keyword.submodule') ```
How do I get the path of the current executed file in Python?
2,632,199
124
2010-04-13T18:37:45Z
2,632,297
59
2010-04-13T18:48:28Z
[ "python", "path" ]
This may seem like a newbie question, but it is not. Some common approaches don't work in all cases: # sys.argv[0] This means using `path = os.path.abspath(os.path.dirname(sys.argv[0]))`, but this does not work if you are running from another Python script in another directory, and this can happen in real life. # \_...
You can't directly determine the location of the main script being executed. After all, sometimes the script didn't come from a file at all. For example, it could come from the interactive interpreter or dynamically generated code stored only in memory. However, you can reliably determine the location of a module, sin...
How do I get the path of the current executed file in Python?
2,632,199
124
2010-04-13T18:37:45Z
5,748,583
12
2011-04-21T19:04:27Z
[ "python", "path" ]
This may seem like a newbie question, but it is not. Some common approaches don't work in all cases: # sys.argv[0] This means using `path = os.path.abspath(os.path.dirname(sys.argv[0]))`, but this does not work if you are running from another Python script in another directory, and this can happen in real life. # \_...
I was running into a similar problem, and I think this might solve the problem: ``` def module_path(local_function): ''' returns the module path without the use of __file__. Requires a function defined locally in the module. from http://stackoverflow.com/questions/729583/getting-file-path-of-imported-module'...
How do I get the path of the current executed file in Python?
2,632,199
124
2010-04-13T18:37:45Z
18,489,147
29
2013-08-28T13:19:17Z
[ "python", "path" ]
This may seem like a newbie question, but it is not. Some common approaches don't work in all cases: # sys.argv[0] This means using `path = os.path.abspath(os.path.dirname(sys.argv[0]))`, but this does not work if you are running from another Python script in another directory, and this can happen in real life. # \_...
First, you need to import from `inspect` and `os` ``` from inspect import getsourcefile from os.path import abspath ``` Next, wherever you want to find the source file from you just use ``` abspath(getsourcefile(lambda:0)) ```
How to count the number of files in a directory using Python
2,632,205
64
2010-04-13T18:38:38Z
2,632,251
91
2010-04-13T18:43:35Z
[ "python", "count", "glob" ]
I need to count the number of files in a directory using Python. I guess the easiest way is `len(glob.glob('*'))`, but that also counts the directory as a file. Is there any way to count only the files in a directory?
`os.listdir()` will be slightly more efficient than using `glob.glob`. To test if a filename is an ordinary file (and not a directory or other entity), use `os.path.isfile()`: ``` import os, os.path # simple version for working with CWD print len([name for name in os.listdir('.') if os.path.isfile(name)]) # path joi...
How to count the number of files in a directory using Python
2,632,205
64
2010-04-13T18:38:38Z
8,311,376
31
2011-11-29T13:16:48Z
[ "python", "count", "glob" ]
I need to count the number of files in a directory using Python. I guess the easiest way is `len(glob.glob('*'))`, but that also counts the directory as a file. Is there any way to count only the files in a directory?
``` import os path, dirs, files = os.walk("/usr/lib").next() file_count = len(files) ```
How to count the number of files in a directory using Python
2,632,205
64
2010-04-13T18:38:38Z
14,979,446
9
2013-02-20T12:04:58Z
[ "python", "count", "glob" ]
I need to count the number of files in a directory using Python. I guess the easiest way is `len(glob.glob('*'))`, but that also counts the directory as a file. Is there any way to count only the files in a directory?
``` def directory(path,extension): list_dir = [] list_dir = os.listdir(path) count = 0 for file in list_dir: if file.endswith(extension): # eg: '.txt' count += 1 return count ```
How to count the number of files in a directory using Python
2,632,205
64
2010-04-13T18:38:38Z
16,865,840
8
2013-05-31T20:55:37Z
[ "python", "count", "glob" ]
I need to count the number of files in a directory using Python. I guess the easiest way is `len(glob.glob('*'))`, but that also counts the directory as a file. Is there any way to count only the files in a directory?
This is where fnmatch comes very handy: ``` import fnmatch print len(fnmatch.filter(os.listdir(dirpath), '*.txt')) ``` More details: <http://docs.python.org/2/library/fnmatch.html>
How to count the number of files in a directory using Python
2,632,205
64
2010-04-13T18:38:38Z
24,507,805
7
2014-07-01T10:18:18Z
[ "python", "count", "glob" ]
I need to count the number of files in a directory using Python. I guess the easiest way is `len(glob.glob('*'))`, but that also counts the directory as a file. Is there any way to count only the files in a directory?
``` import os print len(os.listdir(os.getcwd())) ```
Is it possible to do a wx.TextCtrl with no border?
2,632,479
3
2010-04-13T19:14:34Z
2,632,563
13
2010-04-13T19:26:29Z
[ "python", "wxpython" ]
I want to do a wx.TextCtrl with no border usign wxpython :P How can I do it?
How about `wx.BORDER_NONE` as in: ``` t1 = wx.TextCtrl(self, -1, "my text", style=wx.BORDER_NONE) ```
What is the fastest way to send 100,000 HTTP requests in Python?
2,632,520
128
2010-04-13T19:19:50Z
2,632,847
8
2010-04-13T20:09:49Z
[ "python", "http", "concurrency" ]
I am opening a file which has 100,000 url's. I need to send an http request to each url and print the status code. I am using Python 2.6, and so far looked at the many confusing ways Python implements threading/concurrency. I have even looked at the python [concurrence](http://opensource.hyves.org/concurrence) library,...
A good approach to solving this problem is to first write the code required to get one result, then incorporate threading code to parallelize the application. In a perfect world this would simply mean simultaneously starting 100,000 threads which output their results into a dictionary or list for later processing, but...
What is the fastest way to send 100,000 HTTP requests in Python?
2,632,520
128
2010-04-13T19:19:50Z
2,632,885
26
2010-04-13T20:14:08Z
[ "python", "http", "concurrency" ]
I am opening a file which has 100,000 url's. I need to send an http request to each url and print the status code. I am using Python 2.6, and so far looked at the many confusing ways Python implements threading/concurrency. I have even looked at the python [concurrence](http://opensource.hyves.org/concurrence) library,...
Threads are absolutely not the answer here. They will provide both process and kernel bottlenecks, as well as throughput limits that are not acceptable if the overall goal is "the fastest way". A little bit of `twisted` and its asynchronous `HTTP` client would give you much better results.
What is the fastest way to send 100,000 HTTP requests in Python?
2,632,520
128
2010-04-13T19:19:50Z
2,635,066
102
2010-04-14T05:22:43Z
[ "python", "http", "concurrency" ]
I am opening a file which has 100,000 url's. I need to send an http request to each url and print the status code. I am using Python 2.6, and so far looked at the many confusing ways Python implements threading/concurrency. I have even looked at the python [concurrence](http://opensource.hyves.org/concurrence) library,...
Twistedless solution: ``` from urlparse import urlparse from threading import Thread import httplib, sys from Queue import Queue concurrent = 200 def doWork(): while True: url = q.get() status, url = getStatus(url) doSomethingWithResult(status, url) q.task_done() def getStatus(ou...
What is the fastest way to send 100,000 HTTP requests in Python?
2,632,520
128
2010-04-13T19:19:50Z
25,549,675
23
2014-08-28T13:11:46Z
[ "python", "http", "concurrency" ]
I am opening a file which has 100,000 url's. I need to send an http request to each url and print the status code. I am using Python 2.6, and so far looked at the many confusing ways Python implements threading/concurrency. I have even looked at the python [concurrence](http://opensource.hyves.org/concurrence) library,...
A solution using [tornado](http://www.tornadoweb.org) asynchronous networking library ``` from tornado import ioloop, httpclient i = 0 def handle_request(response): print(response.code) global i i -= 1 if i == 0: ioloop.IOLoop.instance().stop() http_client = httpclient.AsyncHTTPClient() for ...
sqlalchemy, select all row
2,633,218
10
2010-04-13T21:09:02Z
26,217,436
11
2014-10-06T13:36:15Z
[ "python", "sqlalchemy", "pylons" ]
I try to get all row from table. in controler i try to ``` meta.Session.query(User).all() ``` But the result is [, ] In this table i heve 2 rows. I get this model for the table: ``` import hashlib import sqlalchemy as sa from sqlalchemy import orm from allsun.model import meta t_user = sa.Table("users",meta.met...
You can easily import your model and run this: ``` from models import User # User is the name of table that has a column name users = User.query.all() for user in users: print user.name ```
Multiple classes in a Python module
2,634,394
22
2010-04-14T01:57:27Z
2,634,441
24
2010-04-14T02:09:42Z
[ "python" ]
I'm very new to Python (I'm coming from a JAVA background) and I'm wondering if anyone could help me with some of the Python standards. Is it a normal or "proper" practice to put multiple class in a module? I have been working with Django and started with the tutorials and they place their database model classes in the...
Here is a useful rule of thumb from what I have seen of typical Java projects: > The bottom-most package in Java should be a file in Python What does that mean? If your Java project was organized: ``` toplevel/ subproject/ Foo.java Bar.java subproject2/ Baz.java Qux.java ``` Th...
How can I run a GAE application on a private server?
2,634,543
5
2010-04-14T02:39:53Z
2,634,745
10
2010-04-14T03:41:13Z
[ "python", "google-app-engine", "hosting" ]
I want to develop a GAE application using python, but I fear that Google will be the only company able to host the code. Is it possible to run a GAE app on a private server or other host? (Note that a previous version of the question incorrectly referred to GWT).
Assuming that by GWT you mean GAE (GWT is for Java and anybody can serve it), [appscale](http://code.google.com/p/appscale/) is probably the best way to host GAE applications anywhere you'd like (including on Amazon EC2 and in your own data center). Anybody can also start a business providing GAE service with AppScale ...
Using __str__ representation for printing objects in containers in Python
2,634,552
7
2010-04-14T02:44:12Z
2,634,723
10
2010-04-14T03:34:34Z
[ "python", "operator-overloading" ]
I've noticed that when an instance with an overloaded `__str__` method is passed to the `print` function as an argument, it prints as intended. However, when passing a container that contains one of those instances to `print`, it uses the `__repr__` method instead. That is to say, `print(x)` displays the correct string...
The problem with the container using the objects' `__str__` would be the total ambiguity -- what would it mean, say, if `print L` showed `[1, 2]`? `L` could be `['1, 2']` (a single item list whose string item contains a comma) or any of four 2-item lists (since each item can be a string or int). The ambiguity of type i...
Easiest way to automatically download required modules in Python?
2,634,874
18
2010-04-14T04:25:19Z
2,634,993
19
2010-04-14T04:57:51Z
[ "python", "module", "setuptools", "python-module" ]
I would like to release a python module I wrote which depends on several packages. What's the easiest way to make it so these packages are programmatically downloaded just in case they are not available on the system that's being run? Most of these modules should be available by easy\_install or pip or something like t...
[pip](https://pip.readthedocs.org/en/latest/) uses [requirements files](https://pip.readthedocs.org/en/latest/user_guide/#requirements-files), which have [a very straightforward format](https://pip.readthedocs.org/en/latest/reference/pip_install/#requirements-file-format). For more Python packaging tooling recommendat...
convert a list of booleans to string
2,635,964
5
2010-04-14T08:40:58Z
2,636,023
10
2010-04-14T08:48:29Z
[ "python" ]
How do I convert this: ``` [True, True, False, True, True, False, True] ``` Into this: ``` 'AB DE G' ``` Note: C and F are missing in the output because the corresponding items in the input list are False.
Assuming your list of booleans is not too long: ``` bools = [True, True, False, True, True, False, True] print ''.join(chr(ord('A') + i) if b else ' ' for i, b in enumerate(bools)) ```
convert a list of booleans to string
2,635,964
5
2010-04-14T08:40:58Z
2,636,299
9
2010-04-14T09:37:32Z
[ "python" ]
How do I convert this: ``` [True, True, False, True, True, False, True] ``` Into this: ``` 'AB DE G' ``` Note: C and F are missing in the output because the corresponding items in the input list are False.
You can use [string.uppercase](http://docs.python.org/library/string.html#string-constants) instead of chr/ord. This will give you locale-dependent results. For ascii you can use string.ascii\_uppercase. ``` >>> import string >>> bools = [True, True, False, True, True, False, True] >>> ''.join(string.uppercase[i] if b...
How to do this in a pythonic way?
2,636,656
3
2010-04-14T10:40:37Z
2,636,663
17
2010-04-14T10:41:52Z
[ "python", "syntax" ]
Consider this Python snippet: ``` for a in range(10): if a == 7: pass if a == 8: pass if a == 9: pass else: print "yes" ``` How can it be written shorter? ``` #Like this or... if a ?????[7,8,9]: pass ```
Use the `in` operator: ``` if a in (7,8,9): pass ```
How to do this in a pythonic way?
2,636,656
3
2010-04-14T10:40:37Z
2,636,669
15
2010-04-14T10:42:42Z
[ "python", "syntax" ]
Consider this Python snippet: ``` for a in range(10): if a == 7: pass if a == 8: pass if a == 9: pass else: print "yes" ``` How can it be written shorter? ``` #Like this or... if a ?????[7,8,9]: pass ```
To test if *a* falls within a range: ``` if 7 <= a <= 9: pass ``` To test if *a* is in a given sequence: ``` if a in [3, 5, 42]: pass ```
How to convert hex string to integer in Python?
2,636,755
4
2010-04-14T11:00:45Z
2,636,769
14
2010-04-14T11:04:23Z
[ "python", "string", "syntax" ]
How to convert ``` x = "0x000000001" # hex number string ``` to ``` y = "1" ```
You can do: ``` y = int("0x000000001", 16) ``` in your case: ``` y = int(x, 16) ``` Looks like you want the int converted to string: ``` y = str(int(x, 16)) ```
Calculating dawn and sunset times using PyEphem
2,637,293
14
2010-04-14T12:29:17Z
2,637,431
12
2010-04-14T12:49:31Z
[ "python", "astronomy", "pyephem" ]
Is it possible to calculate Dawn, Dusk, and sunset times using [PyEphem](http://rhodesmill.org/pyephem/)? I've used PyEphem to produce day and night time, but I didn't find anything on sunset/dusk/dawn
For ***dawn amd dusk***, see [**pyephem documentation regarding twilight**](http://rhodesmill.org/pyephem/rise-set.html#computing-twilight) In a nutshell, dawn and dusk express the time when *the center* of the Sun is at a particular angle below the horizon; the angle used for this calculation varies for the definiti...
Calculating dawn and sunset times using PyEphem
2,637,293
14
2010-04-14T12:29:17Z
18,622,944
18
2013-09-04T20:13:17Z
[ "python", "astronomy", "pyephem" ]
Is it possible to calculate Dawn, Dusk, and sunset times using [PyEphem](http://rhodesmill.org/pyephem/)? I've used PyEphem to produce day and night time, but I didn't find anything on sunset/dusk/dawn
The following script will calculate sunrise, sunset, and twilight times using PyEphem. The comments should be adequate to explain what each part is doing. ``` import ephem #Make an observer fred = ephem.Observer() #PyEphem takes and returns only UTC times. 15:00 is noon in Fredericton fred.date = "2013-09-04 15...
Perl like regex in Python
2,637,592
8
2010-04-14T13:13:14Z
2,637,642
8
2010-04-14T13:20:57Z
[ "python", "regex", "perl" ]
In Perl I would do something like this for taking different fields in a regexp, separating different fields by () and getting them using $ ``` foreach $line (@lines) { $line =~ m/(.*?):([^-]*)-(.*)/; $field_1 = $1 $field_2 = $2 $field_3 = $3 } ``` How could I do something like this in Python?
Python supports regular expressions with the [`re`](http://docs.python.org/library/re.html) module. The `re.search()` method returns a `MatchObject` which has methods like `group()` which you can use to retrieve the "capturing group" information. For example: ``` m = re.search(r'(.*?):([^-]*)-(.*)', line) field_1 = m...
Perl like regex in Python
2,637,592
8
2010-04-14T13:13:14Z
2,637,670
12
2010-04-14T13:25:05Z
[ "python", "regex", "perl" ]
In Perl I would do something like this for taking different fields in a regexp, separating different fields by () and getting them using $ ``` foreach $line (@lines) { $line =~ m/(.*?):([^-]*)-(.*)/; $field_1 = $1 $field_2 = $2 $field_3 = $3 } ``` How could I do something like this in Python?
In Perl, you'd be much better off using an array than suffixing a bunch of scalars with numbers. E.g. ``` foreach my $line ( @lines ) { my @matches = ( $line =~ m/(.*?):([^-]*)-(.*)/ ); ... } ``` In Python, the `re` module returns a match object containing the capture-group information. So you could write: ...
Perl like regex in Python
2,637,592
8
2010-04-14T13:13:14Z
2,638,126
14
2010-04-14T14:21:32Z
[ "python", "regex", "perl" ]
In Perl I would do something like this for taking different fields in a regexp, separating different fields by () and getting them using $ ``` foreach $line (@lines) { $line =~ m/(.*?):([^-]*)-(.*)/; $field_1 = $1 $field_2 = $2 $field_3 = $3 } ``` How could I do something like this in Python?
"Canonical" Python translation of your snippet...: ``` import re myre = re.compile(r'(.*?):([^-]*)-(.*)') for line in lines: mo = myre.search(line) field_1, field_2, field_3 = mo.groups() ``` Importing `re` is a must (imports are normally done at the top of a module, but that's not mandatory). Precompiling t...
How do I match contents of an element in XPath (lxml)?
2,637,760
11
2010-04-14T13:35:16Z
2,637,909
16
2010-04-14T13:54:02Z
[ "python", "xpath", "lxml", "predicate" ]
I want to parse HTML with lxml using XPath expressions. My problem is matching for the contents of a tag: For example given the ``` <a href="http://something">Example</a> ``` element I can match the href attribute using ``` .//a[@href='http://something'] ``` but the given the expression ``` .//a[.='Example'] ``` ...
I would try with: `.//a[text()='Example']` using xpath() method: ``` tree.xpath(".//a[text()='Example']")[0].tag ``` If case you would like to use iterfind(), findall(), find(), findtext(), keep in mind that advanced features like **value comparison and functions** are not available in [ElementPath](http://effbot.o...
sqlalchemy - Mapping self-referential relationship as one to many (declarative form)
2,638,217
21
2010-04-14T14:32:22Z
2,638,384
38
2010-04-14T14:52:40Z
[ "python", "sqlalchemy" ]
I want to map a Tag entity using declarative method with sqlachemy. A tag can have a parent (another Tag). I have: ``` class Tag(Base): __tablename__ = 'tag' id = Column(Integer, primary_key=True) label = Column(String) def __init__(self, label, parentTag=None): self.label = label ``` how c...
You add a foreign key referencing the parent, and then create a relation that specifies the direction via remote side. This is documented under [adjacency list relationships](http://docs.sqlalchemy.org/en/latest/orm/self_referential.html). For declarative you'd do something like this: ``` class Tag(Base): __tablen...
Recursive list comprehension in Python?
2,638,478
27
2010-04-14T15:03:27Z
2,638,524
28
2010-04-14T15:08:09Z
[ "python", "list-comprehension" ]
Is it possible to define a recursive list comprehension in Python? Possibly a simplistic example, but something along the lines of: ``` nums = [1, 1, 2, 2, 3, 3, 4, 4] willThisWork = [x for x in nums if x not in self] # self being the current comprehension ``` Is anything like this possible?
No, there's no (documented, solid, stable, ...;-) way to refer to "the current comprehension". You could just use a loop: ``` res = [] for x in nums: if x not in res: res.append(x) ``` of course this is very costly (O(N squared)), so you can optimize it with an auxiliary `set` (I'm assuming that keeping the ord...
Recursive list comprehension in Python?
2,638,478
27
2010-04-14T15:03:27Z
11,914,759
7
2012-08-11T12:35:10Z
[ "python", "list-comprehension" ]
Is it possible to define a recursive list comprehension in Python? Possibly a simplistic example, but something along the lines of: ``` nums = [1, 1, 2, 2, 3, 3, 4, 4] willThisWork = [x for x in nums if x not in self] # self being the current comprehension ``` Is anything like this possible?
Actually you can! This example with an explanation hopefully will illustrate how. define recursive example to get a number only when it is 5 or more and if it isn't, increment it and call the 'check' function again. Repeat this process until it reaches 5 at which point return 5. ``` print [ (lambda f,v: v >= 5 and v ...
Why the "mutable default argument fix" syntax is so ugly, asks python newbie
2,639,915
26
2010-04-14T18:17:35Z
2,639,948
10
2010-04-14T18:24:17Z
[ "python", "mutable", "names" ]
Now following [my series of "python newbie questions"](http://stackoverflow.com/questions/2634091/python-some-newbie-questions-on-sys-stderr-and-using-function-as-argument/2635912#2635912) and based on [another question](http://stackoverflow.com/questions/575196/python-variable-scope-and-function-calls/575337#575337). ...
This is called the 'mutable defaults trap'. See: <http://www.ferg.org/projects/python_gotchas.html#contents_item_6> Basically, `a_list` is initialized when the program is first interpreted, not each time you call the function (as you might expect from other languages). So you're not getting a new list each time you ca...
Django/Python: Save an HTML table to Excel
2,640,072
5
2010-04-14T18:40:26Z
2,640,183
7
2010-04-14T18:55:44Z
[ "python", "django", "excel", "html-table" ]
I have an HTML table that I'd like to be able to export to an Excel file. I already have an option to export the table into an IQY file, but I'd prefer something that didn't allow the user to refresh the data via Excel. I just want a feature that takes a snapshot of the table at the time the user clicks the link/button...
You can use the excellent [xlwt](http://www.python-excel.org/) module. It is very easy to use, and creates files in xls format (Excel 2003). Here is an (untested!) example of use for a Django view: ``` from django.http import HttpResponse import xlwt def excel_view(request): normal_style = xlwt.easyxf(""" fon...
Preserving the dimensions of a slice from a Numpy 3d array
2,640,147
6
2010-04-14T18:50:40Z
2,640,168
10
2010-04-14T18:54:10Z
[ "python", "numpy", "slice" ]
I have a 3d array, `a`, of shape say `a.shape = (10, 10, 10)` When slicing, the dimensions are `squeezed` automatically i.e. `a[:,:,5].shape = (10, 10)` I'd like to preserve the number of dimensions *but also ensure that the dimension that was squeezed is the one that shows 1* i.e. `a[:,:,5].shape = (10, 10, 1)` I...
``` a[:,:,[5]].shape # (10,10,1) ``` --- `a[:,:,5]` is an example of [basic slicing](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#basic-slicing-and-indexing). `a[:,:,[5]]` is an example of [integer array indexing](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#integer-array-indexing...
Include empty directory with python setup.py sdist
2,640,378
5
2010-04-14T19:26:33Z
2,640,955
7
2010-04-14T20:54:15Z
[ "python", "installation" ]
I have a Python package where I want to include an empty directory as part of the source distribution. I tried adding ``` include empty_directory ``` to the `MANIFEST.in` file, but when I run ``` python setup.py sdist ``` The empty directory is still not included. Any tips on how to do this?
According to [the docs](http://docs.python.org/distutils/commandref.html#sdist-cmd): > * `include pat1 pat2` - *include all > files matching any of the listed > patterns* > * `exclude pat1 pat2` - > *exclude all files matching any of the listed patterns* > * `recursive-include dir pat1 pat2` - *include all files...
JavaScript-like Object in Python standard library?
2,640,806
9
2010-04-14T20:29:35Z
2,641,450
8
2010-04-14T22:15:40Z
[ "python" ]
Quite often, I find myself wanting a simple, "dump" object in Python which behaves like a JavaScript object (ie, its members can be accessed either with `.member` or with `['member']`). Usually I'll just stick this at the top of the `.py`: ``` class DumbObject(dict): def __getattr__(self, attr): return se...
You can try with [attrdict](http://code.activestate.com/recipes/361668/): ``` class attrdict(dict): def __init__(self, *args, **kwargs): dict.__init__(self, *args, **kwargs) self.__dict__ = self a = attrdict(x=1, y=2) print a.x, a.y print a['x'], a['y'] b = attrdict() b.x, b.y = 1, 2 print b.x, ...