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 |
|---|---|---|---|---|---|---|---|---|---|
retrieve links from web page using python and BeautifulSoup | 1,080,411 | 70 | 2009-07-03T18:29:56Z | 22,583,436 | 23 | 2014-03-22T20:52:44Z | [
"python",
"hyperlink",
"beautifulsoup"
] | How can I retrieve the links of a webpage and copy the url address of the links using Python? | For completeness sake, the BeautifulSoup 4 version, making use of the encoding supplied by the server as well:
```
from bs4 import BeautifulSoup
import urllib2
resp = urllib2.urlopen("http://www.gpsbasecamp.com/national-parks")
soup = BeautifulSoup(resp, from_encoding=resp.info().getparam('charset'))
for link in sou... |
Removing the Label From Django's TextArea Widget | 1,080,650 | 5 | 2009-07-03T19:57:55Z | 1,080,735 | 19 | 2009-07-03T20:30:22Z | [
"python",
"django",
"textarea",
"label",
"widget"
] | How do I remove the label that comes attached to the TextArea I am trying to use with Django? I'm trying to find ANY information about this issue but I cannot seem to find anything relating to my problem. This is what I'm doing in my code:
```
class CommentForm(forms.Form):
comment = forms.CharField(widget=forms.T... | This should work with the latest version (trunk) of django:
```
comment = forms.CharField(label="", help_text="", widget=forms.Textarea())
```
Hope that helps! |
Removing the Label From Django's TextArea Widget | 1,080,650 | 5 | 2009-07-03T19:57:55Z | 1,080,736 | 8 | 2009-07-03T20:30:33Z | [
"python",
"django",
"textarea",
"label",
"widget"
] | How do I remove the label that comes attached to the TextArea I am trying to use with Django? I'm trying to find ANY information about this issue but I cannot seem to find anything relating to my problem. This is what I'm doing in my code:
```
class CommentForm(forms.Form):
comment = forms.CharField(widget=forms.T... | The [Django documentation on customizing labels](http://docs.djangoproject.com/en/dev/ref/forms/api/#ref-forms-api-configuring-label) says it could be turned off with `auto_id` argument to Form constructor:
```
f = ContactForm(auto_id=False)
``` |
In Python, how do you change an instantiated object after a reload? | 1,080,669 | 12 | 2009-07-03T20:03:07Z | 1,080,984 | 12 | 2009-07-03T21:59:27Z | [
"python",
"module",
"reload",
"python-import"
] | Let's say you have an object that was instantiated from a class inside a module.
Now, you reload that module.
The next thing you'd like to do is make that reload affect that class.
```
mymodule.py
---
class ClassChange():
def run(self):
print 'one'
myexperiment.py
---
import mymodule
from mymodule import ... | To update all instances of a class, it is necessary to keep track somewhere about those instances -- typically via weak references (weak value dict is handiest and general) so the "keeping track" functionality won't stop unneeded instances from going away, of course!
You'd normally want to keep such a container in the... |
Changes to Python since Dive into Python | 1,080,734 | 12 | 2009-07-03T20:28:33Z | 1,081,252 | 9 | 2009-07-04T01:02:12Z | [
"python"
] | I've been teaching myself Python by working through [Dive Into Python](http://www.diveintopython.net/) by Mark Pilgrim. I thoroughly recommend it, as do [other Stack Overflow users](http://stackoverflow.com/questions/34570/what-is-the-best-quick-read-python-book-out-there/34608#34608).
However, the last update to Dive... | Check out [What's New in Python](http://docs.python.org/whatsnew/). It has all the versions in the 2.x series. Per Alex's comments, you'll want to look at all Python 2.x for x > 2.
Highlights for day-to-day coding:
*Enumeration*: Instead of doing:
```
for i in xrange(len(sequence)):
val = sequence[i]
pass
``... |
Inheriting from instance in Python | 1,081,253 | 8 | 2009-07-04T01:02:45Z | 1,081,271 | 7 | 2009-07-04T01:11:01Z | [
"python",
"inheritance",
"instance",
"overloading"
] | In Python, I would like to construct an instance of the Child's class directly from an instance of the Parent class. For example:
```
A = Parent(x, y, z)
B = Child(A)
```
This is a hack that I thought might work:
```
class Parent(object):
def __init__(self, x, y, z):
print "INITILIZING PARENT"
s... | Once `__new__` in class `Child` returns an instance of `Child`, `Child.__init__` will be called (with the same arguments `__new__` was given) on that instance -- and apparently it just inherits `Parent.__init__`, which does not take well to being called with just one arg (the other `Parent`, `A`).
If there is no other... |
How can I report the API of a class programmatically? | 1,081,392 | 4 | 2009-07-04T02:59:38Z | 1,081,395 | 8 | 2009-07-04T03:03:39Z | [
"python",
"api"
] | My goal is to parse a class and return a data-structure (object, dictionary, etc) that is descriptive of the methods and the related parameters contained within the class. Bonus points for types and returns...
Requirements: Must be Python
For example, the below class:
```
class Foo:
def bar(hello=None):
... | You probably want to check out Python's [inspect](http://docs.python.org/library/inspect.html#inspect.getmembers) module. It will get you most of the way there:
```
>>> class Foo:
... def bar(hello=None):
... return hello
... def baz(world=None):
... return baz
...
>>> import inspect
>>> memb... |
How do you subclass the file type in Python? | 1,082,801 | 13 | 2009-07-04T19:07:22Z | 1,082,817 | 12 | 2009-07-04T19:17:03Z | [
"python",
"file",
"subclass"
] | I'm trying to subclass the built-in `file` class in Python to add some extra features to `stdin` and `stdout`. Here's the code I have so far:
```
class TeeWithTimestamp(file):
"""
Class used to tee the output of a stream (such as stdout or stderr) into
another stream, and to add a timestamp to each message... | Calling `file.__init__` is quite feasible (e.g., on '/dev/null') but no real use because your attempted override of `write` doesn't "take" for the purposes of `print` statements -- the latter internally calls the real `file.write` when it sees that `sys.stdout` is an actual instance of `file` (and by inheriting you've ... |
Does creating separate functions instead of one big one slow processing time? | 1,083,105 | 7 | 2009-07-04T22:41:12Z | 1,083,121 | 27 | 2009-07-04T22:47:33Z | [
"python",
"google-app-engine",
"function",
"performance"
] | I'm working in the Google App Engine environment and programming in Python. I am creating a function that essentially generates a random number/letter string and then stores to the memcache.
```
def generate_random_string():
# return a random 6-digit long string
def check_and_store_to_memcache():
randomstring = g... | Focus on being able to read and easily understand your code.
Once you've done this, if you have a performance problem, then look into what might be causing it.
Most languages, python included, tend to have fairly low overhead for making method calls. Putting this code into a single function is not going to (dramatica... |
Does creating separate functions instead of one big one slow processing time? | 1,083,105 | 7 | 2009-07-04T22:41:12Z | 1,085,128 | 13 | 2009-07-06T02:06:33Z | [
"python",
"google-app-engine",
"function",
"performance"
] | I'm working in the Google App Engine environment and programming in Python. I am creating a function that essentially generates a random number/letter string and then stores to the memcache.
```
def generate_random_string():
# return a random 6-digit long string
def check_and_store_to_memcache():
randomstring = g... | In almost all cases, "inlining" functions to increase speed is like getting a hair cut to lose weight. |
Running JSON through Python's eval()? | 1,083,250 | 17 | 2009-07-05T00:35:10Z | 1,083,262 | 10 | 2009-07-05T00:40:58Z | [
"python",
"json"
] | Best practices aside, is there a compelling reason **not** to do this?
I'm writing a post-commit hook for use with a Google Code project, which provides commit data via a JSON object. GC provides an HMAC authentication token along with the request (outside the JSON data), so by validating that token I gain high confid... | The point of best practices is that in most cases, it's a bad idea to disregard them. If I were you, I'd use a parser to parse JSON into Python. Try out [simplejson](http://undefined.org/python/#simplejson), it was very straightforward for parsing JSON when I last tried it and it claims to be compatible with Python 2.4... |
Running JSON through Python's eval()? | 1,083,250 | 17 | 2009-07-05T00:35:10Z | 1,083,302 | 24 | 2009-07-05T01:28:43Z | [
"python",
"json"
] | Best practices aside, is there a compelling reason **not** to do this?
I'm writing a post-commit hook for use with a Google Code project, which provides commit data via a JSON object. GC provides an HMAC authentication token along with the request (outside the JSON data), so by validating that token I gain high confid... | If you're comfortable with your script working fine for a while, and then randomly failing on some obscure edge case, I would go with eval.
If it's important that your code be robust, I would take the time to add simplejson. You don't need the C portion for speedups, so it really shouldn't be hard to dump a few .py fi... |
Missing datetime.timedelta.to_seconds() -> float in Python? | 1,083,402 | 9 | 2009-07-05T03:28:02Z | 1,083,408 | 12 | 2009-07-05T03:35:44Z | [
"python",
"datetime",
"timedelta"
] | I understand that seconds and microseconds are probably represented separately in `datetime.timedelta` for efficiency reasons, but I just wrote this simple function:
```
def to_seconds_float(timedelta):
"""Calculate floating point representation of combined
seconds/microseconds attributes in :param:`timedelta`... | A Python float has about 15 significant digits, so with seconds being up to 86400 (5 digits to the left of the decimal point) and microseconds needing 6 digits, you could well include the days (up to several years' worth) without loss of precision.
A good mantra is "pi seconds is a nanocentury" -- about 3.14E9 seconds... |
Django Database Caching | 1,084,569 | 3 | 2009-07-05T18:19:09Z | 1,084,583 | 7 | 2009-07-05T18:30:48Z | [
"python",
"django",
"django-cache"
] | I'm working on a small project, and I wanted to provide multiple caching options to the end user. I figured with Django it's pretty simplistic to swap memcached for database or file based caching. My memcached implementation works like a champ without any issues. I placed time stamps on my pages, and curl consistently ... | According to the documentation you're supposed to create the table not by using syncdb but with the following:
```
python manage.py createcachetable cache_table
```
If you haven't done that, try and see if it doesn't work. |
How do I store desktop application data in a cross platform way for python? | 1,084,697 | 37 | 2009-07-05T19:45:44Z | 1,088,459 | 37 | 2009-07-06T18:14:36Z | [
"python",
"desktop-application",
"application-settings"
] | I have a python desktop application that needs to store user data. On Windows, this is usually in `%USERPROFILE%\Application Data\AppName\`, on OSX it's usually `~/Library/Application Support/AppName/`, and on other \*nixes it's usually `~/.appname/`.
There exists a function in the standard library, `os.path.expanduse... | Well, I hate to have been the one to answer my own question, but no one else seems to know. I'm leaving the answer for posterity.
```
APPNAME = "MyApp"
import sys
from os import path, environ
if sys.platform == 'darwin':
from AppKit import NSSearchPathForDirectoriesInDomains
# http://developer.apple.com/DOCUME... |
C++ or Python as a starting point into GUI programming? | 1,084,935 | 7 | 2009-07-05T22:13:19Z | 1,084,958 | 22 | 2009-07-05T22:30:35Z | [
"c++",
"python",
"qt"
] | I have neglected my programming skills since i left school and now i want to start a few things that are running around in my head. Qt would be the toolkit for me to use but i am undecided if i should use Python (looks to me like the easier to learn with a few general ideas about programming) or C++ (the thing to use w... | Being an expert in both C++ and Python, my mantra has long been "Python where I can, C++ where I must": Python is faster (in term of programmer productivity and development cycle) and easier, C++ can give that extra bit of power when I have to get close to the hardware or be extremely careful about every byte or machin... |
Python: How can I import all variables? | 1,084,977 | 18 | 2009-07-05T22:41:16Z | 1,084,984 | 40 | 2009-07-05T22:45:25Z | [
"python",
"variables",
"import",
"module"
] | I'm new to Python and programming in general (a couple of weeks at most).
Concerning Python and using modules, I realise that functions can imported using `from a import *`.
So instead of typing
```
a.sayHi()
a.sayBye()
```
I can say
```
sayHi()
sayBye()
```
which I find simplifies things a great deal. Now, say I... | You gave the solution yourself: `from a import *` will work just fine. Python does not differentiate between functions and variables in this respect.
```
>>> from a import *
>>> if name == "Michael" and age == 15:
... print('Simple!')
...
Simple!
``` |
Python: How can I import all variables? | 1,084,977 | 18 | 2009-07-05T22:41:16Z | 1,084,996 | 7 | 2009-07-05T22:51:08Z | [
"python",
"variables",
"import",
"module"
] | I'm new to Python and programming in general (a couple of weeks at most).
Concerning Python and using modules, I realise that functions can imported using `from a import *`.
So instead of typing
```
a.sayHi()
a.sayBye()
```
I can say
```
sayHi()
sayBye()
```
which I find simplifies things a great deal. Now, say I... | You didn't say this directly, but I'm assuming you're having trouble with manipulating these global variables.
If you manipulate global variables from inside a function, you must declare them global
```
a = 10
def x():
global a
a = 15
print a
x()
print a
```
If you don't do that, then `a = 15` will just creat... |
Python: How can I import all variables? | 1,084,977 | 18 | 2009-07-05T22:41:16Z | 1,086,390 | 21 | 2009-07-06T10:33:08Z | [
"python",
"variables",
"import",
"module"
] | I'm new to Python and programming in general (a couple of weeks at most).
Concerning Python and using modules, I realise that functions can imported using `from a import *`.
So instead of typing
```
a.sayHi()
a.sayBye()
```
I can say
```
sayHi()
sayBye()
```
which I find simplifies things a great deal. Now, say I... | Just for some context, most linters will flag `from module import *` with a warning, because it's prone to namespace collisions that will cause headaches down the road.
Nobody has noted yet that, as an alternative, you can use the
```
from a import name, age
```
form and then use `name` and `age` directly (without t... |
Python: How can I import all variables? | 1,084,977 | 18 | 2009-07-05T22:41:16Z | 1,086,705 | 11 | 2009-07-06T12:28:24Z | [
"python",
"variables",
"import",
"module"
] | I'm new to Python and programming in general (a couple of weeks at most).
Concerning Python and using modules, I realise that functions can imported using `from a import *`.
So instead of typing
```
a.sayHi()
a.sayBye()
```
I can say
```
sayHi()
sayBye()
```
which I find simplifies things a great deal. Now, say I... | Like others have said,
```
from module import *
```
will also import the modules variables.
However, you need to understand that you are *not* importing variables, just references to objects. Assigning something else to the imported names in the importing module **won't** affect the other modules.
Example: assume y... |
Real-time intercepting of stdout from another process in Python | 1,085,071 | 3 | 2009-07-05T23:31:08Z | 1,085,100 | 12 | 2009-07-06T01:51:07Z | [
"python",
"perl",
"process"
] | I'd like to run a system process, intercept the output, and modify it real-time, line by line, in a Python script.
My best attempt, which waits for the process to complete before printing, is:
```
#!/usr/bin/env python
import subprocess
cmd = "waitsome.py"
proc = subprocess.Popen(cmd, shell=True, bufsize=256, stdout... | Looping over a file unavoidably buffers things in pretty large chunks -- a known issue with all Python 2.\* implementations. It works as you intend in Python 3.1, with the final loop being slightly different:
```
for line in proc.stdout:
print(">>> " + str(line.rstrip()))
```
If upgrading to Python 3.1 is impract... |
What's the simplest way to put a python script into the system tray (Windows) | 1,085,694 | 31 | 2009-07-06T06:38:43Z | 1,085,718 | 44 | 2009-07-06T06:49:41Z | [
"python",
"system-tray"
] | What's the simplest way to put a python script into the system tray?
My target platform is Windows. I don't want to see the 'cmd.exe' window. | Those are two questions, actually:
1. Adding a tray icon can be done with Win32 API. Example: [SysTrayIcon.py](http://www.brunningonline.net/simon/blog/archives/SysTrayIcon.py.html)
2. Hiding the `cmd.exe` window is as easy as using `pythonw.exe` instead of `python.exe` to run your scripts. |
Interface for modifying Windows environment variables from Python | 1,085,852 | 15 | 2009-07-06T07:48:40Z | 1,146,404 | 17 | 2009-07-18T01:25:12Z | [
"python",
"windows",
"environment-variables"
] | How can I persistently modify the Windows environment variables from a Python script? (it's the setup.py script)
I'm looking for a standard function or module to use for this. I'm already familiar with the [registry way of doing it](http://code.activestate.com/recipes/416087/), but any comments regarding that are also... | Using setx has few drawbacks, especially if you're trying to append to environment variables (eg. setx PATH %Path%;C:\mypath) This will repeatedly append to the path every time you run it, which can be a problem. Worse, it doesn't distinguish between the machine path (stored in HKEY\_LOCAL\_MACHINE), and the user path,... |
Choosing Java vs Python on Google App Engine | 1,085,898 | 147 | 2009-07-06T08:05:58Z | 1,086,259 | 16 | 2009-07-06T09:48:32Z | [
"java",
"python",
"google-app-engine"
] | Currently Google App Engine supports both Python & Java. Java support is less mature. However, Java seems to have a longer list of libraries and especially support for Java bytecode regardless of the languages used to write that code. Which language will give better performance and more power? Please advise. Thank you!... | Based on experience with running these VMs on other platforms, I'd say that you'll probably get more raw performance out of Java than Python. Don't underestimate Python's selling points, however: The Python language is much more productive in terms of lines of code - the general agreement is that Python requires a thir... |
Choosing Java vs Python on Google App Engine | 1,085,898 | 147 | 2009-07-06T08:05:58Z | 1,087,878 | 113 | 2009-07-06T16:17:10Z | [
"java",
"python",
"google-app-engine"
] | Currently Google App Engine supports both Python & Java. Java support is less mature. However, Java seems to have a longer list of libraries and especially support for Java bytecode regardless of the languages used to write that code. Which language will give better performance and more power? Please advise. Thank you!... | I'm biased (being a Python expert but pretty rusty in Java) but I think the Python runtime of GAE is currently more advanced and better developed than the Java runtime -- the former has had one extra year to develop and mature, after all.
How things will proceed going forward is of course hard to predict -- demand is ... |
Choosing Java vs Python on Google App Engine | 1,085,898 | 147 | 2009-07-06T08:05:58Z | 1,464,516 | 66 | 2009-09-23T07:45:21Z | [
"java",
"python",
"google-app-engine"
] | Currently Google App Engine supports both Python & Java. Java support is less mature. However, Java seems to have a longer list of libraries and especially support for Java bytecode regardless of the languages used to write that code. Which language will give better performance and more power? Please advise. Thank you!... | Watch this app for changes in Python and Java performance:
<http://gaejava.appspot.com/>
Currently, Python and using the low-level API in Java are faster than JDO on Java, **for this simple test**. At least if the underlying engine changes, that app should reflect performance changes. |
Choosing Java vs Python on Google App Engine | 1,085,898 | 147 | 2009-07-06T08:05:58Z | 2,638,859 | 9 | 2010-04-14T15:44:29Z | [
"java",
"python",
"google-app-engine"
] | Currently Google App Engine supports both Python & Java. Java support is less mature. However, Java seems to have a longer list of libraries and especially support for Java bytecode regardless of the languages used to write that code. Which language will give better performance and more power? Please advise. Thank you!... | An important question to consider in deciding between Python and Java is **how you will use the datastore in each language** (and most other angles to the original question have already been covered quite well in this topic).
**For Java**, the standard method is to use JDO or JPA. These are great for portability but a... |
Choosing Java vs Python on Google App Engine | 1,085,898 | 147 | 2009-07-06T08:05:58Z | 18,255,495 | 11 | 2013-08-15T15:00:01Z | [
"java",
"python",
"google-app-engine"
] | Currently Google App Engine supports both Python & Java. Java support is less mature. However, Java seems to have a longer list of libraries and especially support for Java bytecode regardless of the languages used to write that code. Which language will give better performance and more power? Please advise. Thank you!... | **June 2013:** This video is a very good answer by a google engineer:
<http://www.youtube.com/watch?v=tLriM2krw2E>
TLDR; is:
* Pick the language that you and your team is most productive with
* If you want to build something for production: Java or Python (not Go)
* If you have a big team and a complex code base: Ja... |
Boolean value of objects in Python | 1,087,135 | 18 | 2009-07-06T13:59:55Z | 1,087,165 | 29 | 2009-07-06T14:04:57Z | [
"python",
"boolean"
] | As we know, Python has boolean values for objects: If a class has a `__len__` method, every instance of it for which `__len__()` happens to return 0 will be evaluated as a boolean `False` (for example, the empty list).
In fact, every iterable, empty custom object is evaluated as `False` if it appears in boolean expres... | Refer to the Python docs for [`__nonzero__`](https://docs.python.org/2/reference/datamodel.html#object.__nonzero__).
```
class foo(object):
def __nonzero__( self) :
return self.bar % 2 == 0
def a(foo):
if foo:
print "spam"
else:
print "eggs"
def main():
myfoo = foo()
myfoo... |
Boolean value of objects in Python | 1,087,135 | 18 | 2009-07-06T13:59:55Z | 1,087,166 | 31 | 2009-07-06T14:05:09Z | [
"python",
"boolean"
] | As we know, Python has boolean values for objects: If a class has a `__len__` method, every instance of it for which `__len__()` happens to return 0 will be evaluated as a boolean `False` (for example, the empty list).
In fact, every iterable, empty custom object is evaluated as `False` if it appears in boolean expres... | **In Python < 3.0 :**
You have to use [`__nonzero__`](https://docs.python.org/2/reference/datamodel.html#object.__nonzero__) to achieve what you want. It's a method that is called automatically by Python when evaluating an object in a boolean context. It must return a boolean that will be used as the value to evaluate... |
Validate SSL certificates with Python | 1,087,227 | 64 | 2009-07-06T14:17:34Z | 1,088,224 | 25 | 2009-07-06T17:29:48Z | [
"python",
"https",
"ssl-certificate",
"verification"
] | I need to write a script that connects to a bunch of sites on our corporate intranet over HTTPS and verifies that their SSL certificates are valid; that they are not expired, that they are issued for the correct address, etc. We use our own internal corporate Certificate Authority for these sites, so we have the public... | You can use Twisted to verify certificates. The main API is [CertificateOptions](http://twistedmatrix.com/documents/8.2.0/api/twisted.internet.ssl.CertificateOptions.html), which can be provided as the `contextFactory` argument to various functions such as [listenSSL](http://twistedmatrix.com/documents/8.2.0/api/twiste... |
Validate SSL certificates with Python | 1,087,227 | 64 | 2009-07-06T14:17:34Z | 1,441,779 | 8 | 2009-09-17T23:09:19Z | [
"python",
"https",
"ssl-certificate",
"verification"
] | I need to write a script that connects to a bunch of sites on our corporate intranet over HTTPS and verifies that their SSL certificates are valid; that they are not expired, that they are issued for the correct address, etc. We use our own internal corporate Certificate Authority for these sites, so we have the public... | [M2Crypto](http://chandlerproject.org/Projects/MeTooCrypto) can [do the validation](http://www.heikkitoivonen.net/blog/2008/10/14/ssl-in-python-26/). You can also use [M2Crypto with Twisted](http://svn.osafoundation.org/m2crypto/trunk/M2Crypto/SSL/TwistedProtocolWrapper.py) if you like. The [Chandler](http://chandlerpr... |
Validate SSL certificates with Python | 1,087,227 | 64 | 2009-07-06T14:17:34Z | 1,921,551 | 22 | 2009-12-17T12:48:51Z | [
"python",
"https",
"ssl-certificate",
"verification"
] | I need to write a script that connects to a bunch of sites on our corporate intranet over HTTPS and verifies that their SSL certificates are valid; that they are not expired, that they are issued for the correct address, etc. We use our own internal corporate Certificate Authority for these sites, so we have the public... | [PycURL](http://pycurl.sourceforge.net/) does this beautifully.
Below is a short example. It will throw a `pycurl.error` if something is fishy, where you get a tuple with error code and a human readable message.
```
import pycurl
curl = pycurl.Curl()
curl.setopt(pycurl.CAINFO, "myFineCA.crt")
curl.setopt(pycurl.SSL_... |
Validate SSL certificates with Python | 1,087,227 | 64 | 2009-07-06T14:17:34Z | 3,551,700 | 14 | 2010-08-23T21:05:59Z | [
"python",
"https",
"ssl-certificate",
"verification"
] | I need to write a script that connects to a bunch of sites on our corporate intranet over HTTPS and verifies that their SSL certificates are valid; that they are not expired, that they are issued for the correct address, etc. We use our own internal corporate Certificate Authority for these sites, so we have the public... | Here's an example script which demonstrates certificate validation:
```
import httplib
import re
import socket
import sys
import urllib2
import ssl
class InvalidCertificateException(httplib.HTTPException, urllib2.URLError):
def __init__(self, host, cert, reason):
httplib.HTTPException.__init__(self)
... |
Validate SSL certificates with Python | 1,087,227 | 64 | 2009-07-06T14:17:34Z | 3,946,778 | 27 | 2010-10-15T23:06:57Z | [
"python",
"https",
"ssl-certificate",
"verification"
] | I need to write a script that connects to a bunch of sites on our corporate intranet over HTTPS and verifies that their SSL certificates are valid; that they are not expired, that they are issued for the correct address, etc. We use our own internal corporate Certificate Authority for these sites, so we have the public... | I have added a distribution to the Python Package Index which makes the `match_hostname()` function from the Python 3.2 `ssl` package available on previous versions of Python.
<http://pypi.python.org/pypi/backports.ssl_match_hostname/>
You can install it with:
```
pip install backports.ssl_match_hostname
```
Or you... |
Validate SSL certificates with Python | 1,087,227 | 64 | 2009-07-06T14:17:34Z | 18,767,137 | 11 | 2013-09-12T14:32:57Z | [
"python",
"https",
"ssl-certificate",
"verification"
] | I need to write a script that connects to a bunch of sites on our corporate intranet over HTTPS and verifies that their SSL certificates are valid; that they are not expired, that they are issued for the correct address, etc. We use our own internal corporate Certificate Authority for these sites, so we have the public... | Or simply make your life easier by using the [requests](https://pypi.python.org/pypi/requests) library:
```
import requests
requests.get('https://somesite.com', cert='/path/server.crt', verify=True)
```
[A few more words about its usage.](http://docs.python-requests.org/en/latest/user/advanced/#ssl-cert-verification) |
Validate SSL certificates with Python | 1,087,227 | 64 | 2009-07-06T14:17:34Z | 28,325,763 | 8 | 2015-02-04T15:57:34Z | [
"python",
"https",
"ssl-certificate",
"verification"
] | I need to write a script that connects to a bunch of sites on our corporate intranet over HTTPS and verifies that their SSL certificates are valid; that they are not expired, that they are issued for the correct address, etc. We use our own internal corporate Certificate Authority for these sites, so we have the public... | From release version 2.7.9/3.4.3 on, Python **by default** attempts to perform certificate validation.
This has been proposed in PEP 467, which is worth a read: <https://www.python.org/dev/peps/pep-0476/>
The changes affect all relevant stdlib modules (urllib/urllib2, http, httplib).
Relevant documentation:
<https:... |
Use of eval in Python? | 1,087,255 | 15 | 2009-07-06T14:23:07Z | 1,087,265 | 13 | 2009-07-06T14:24:58Z | [
"python",
"dynamic",
"eval"
] | There is an `eval()` function in Python I stumbled upon while playing around. I cannot think of a case when this function is needed, except maybe as syntactic sugar. Can anyone give an example? | The [Wikipedia article on `eval`](http://en.wikipedia.org/wiki/Eval#Uses) is pretty informative, and details various uses.
Some of the uses it suggests are:
* Evaluating mathematical expressions
* [Compiler bootstrapping](http://en.wikipedia.org/wiki/Bootstrapping%5F%28compilers%29)
* Scripting (dynamic languages in ... |
Use of eval in Python? | 1,087,255 | 15 | 2009-07-06T14:23:07Z | 1,087,300 | 11 | 2009-07-06T14:31:22Z | [
"python",
"dynamic",
"eval"
] | There is an `eval()` function in Python I stumbled upon while playing around. I cannot think of a case when this function is needed, except maybe as syntactic sugar. Can anyone give an example? | You may want to use it to allow users to enter their own "scriptlets": **small** expressions (or even small functions), that can be used to customize the behavior of a **complex** system.
In that context, and if you do not have to care too much for the security implications (e.g. you have an educated userbase), then ... |
Use of eval in Python? | 1,087,255 | 15 | 2009-07-06T14:23:07Z | 1,087,625 | 29 | 2009-07-06T15:30:21Z | [
"python",
"dynamic",
"eval"
] | There is an `eval()` function in Python I stumbled upon while playing around. I cannot think of a case when this function is needed, except maybe as syntactic sugar. Can anyone give an example? | `eval` and `exec` are handy quick-and-dirty way to get some source code dynamically, maybe munge it a bit, and then execute it -- but they're hardly ever the best way, especially in production code as opposed to "quick-and-dirty" prototypes &c.
For example, if I had to deal with such dynamic Python sources, I'd reach ... |
Reportlab page x of y NumberedCanvas and Images | 1,087,495 | 4 | 2009-07-06T15:05:23Z | 1,088,029 | 13 | 2009-07-06T16:51:06Z | [
"python",
"reportlab"
] | I had been using the reportlab NumberedCanvas given at <http://code.activestate.com/recipes/546511/> . However, when i try to build a PDF that contains Image flowables, the images do not show, although enough vertical space is left for the image to fit. Is there any solution for this? | See [my new, improved recipe](http://code.activestate.com/recipes/576832/) for this, which includes a simple test with images. Here's an excerpt from the recipe (which omits the test code):
```
from reportlab.pdfgen import canvas
from reportlab.lib.units import mm
class NumberedCanvas(canvas.Canvas):
def __init__... |
Starting and Controlling an External Process via STDIN/STDOUT with Python | 1,087,799 | 4 | 2009-07-06T16:03:57Z | 1,087,883 | 8 | 2009-07-06T16:18:06Z | [
"python",
"subprocess"
] | I need to launch an external process that is to be controlled via messages sent back and forth via stdin and stdout. Using subprocess.Popen I am able to start the process but am unable to control the execution via stdin as I need to.
The flow of what I'm trying to complete is to:
1. Start the external process
2. Iter... | process.communicate(input='\n') is wrong. If you will notice from the Python docs, it writes your string to the stdin of the child, then reads all output from the child until the child exits. From doc.python.org:
> Popen.communicate(input=None) Interact
> with process: Send data to stdin. Read
> data from stdout and s... |
testing python applications that use mysql | 1,088,077 | 5 | 2009-07-06T17:00:00Z | 1,088,090 | 8 | 2009-07-06T17:04:00Z | [
"python",
"mysql",
"unit-testing"
] | I want to write some unittests for an application that uses MySQL. However, I do not want to connect to a real mysql database, but rather to a temporary one that doesn't require any SQL server at all.
Any library (I could not find anything on google)? Any design pattern? Note that DIP doesn't work since I will still h... | There isn't a good way to do that. You want to run your queries against a real MySQL server, otherwise you don't know if they will work or not.
However, that doesn't mean you have to run them against a production server. We have scripts that create a Unit Test database, and then tear it down once the unit tests have r... |
Python: accessing DLL function using ctypes -- access by function *name* fails | 1,088,085 | 5 | 2009-07-06T17:02:09Z | 1,088,142 | 9 | 2009-07-06T17:13:35Z | [
"python",
"dll",
"ctypes",
"attributeerror"
] | `myPythonClient` (below) wants to invoke a `ringBell` function (loaded from a DLL using `ctypes`). However, attempting to access `ringBell` via its *name* results in an `AttributeError`. Why?
`RingBell.h` contains
```
namespace MyNamespace
{
class MyClass
{
public:
static __declspec(dllexport)... | Your C++ compiler is mangling the names of all externally visible objects to reflect (as well as their underlying names) their namespaces, classes, and signatures (that's how overloading becomes possible).
In order to avoid this mangling, you need an `extern "C"` on externally visible names that you want to be visible... |
Adding attributes into Django Model's Meta class | 1,088,431 | 24 | 2009-07-06T18:08:21Z | 1,088,649 | 36 | 2009-07-06T18:50:36Z | [
"python",
"django",
"django-models",
"metadata"
] | I'm writing a mixin which will allow my Models to be easily translated into a deep dict of values (kind of like .values(), but traversing relationships). The cleanest place to do the definitions of these seems to be in the models themselves, a la:
```
class Person(models.Model, DeepValues):
name = models.CharField... | I don't know about elegant, but one pragmatic way is:
```
import django.db.models.options as options
options.DEFAULT_NAMES = options.DEFAULT_NAMES + ('schema',)
```
Obviously, this would break if Django ever added a 'schema' attribute of its own. But hey, it's a thought...you could always pick an attribute name whic... |
Django: Dynamic LOGIN_URL variable | 1,088,913 | 6 | 2009-07-06T19:55:02Z | 1,088,929 | 7 | 2009-07-06T19:58:53Z | [
"python",
"django",
"django-urls"
] | Currently, in my `settings` module I have this:
```
LOGIN_URL = '/login'
```
If I ever decide to change the login URL in `urls.py`, I'll have to change it here as well. Is there any more dynamic way of doing this? | Settings *IS* where you are setting your dynamic login url. Make sure to import `LOGIN_URL` from `settings.py` in your `urls.py` and use that instead.
```
from projectname.settings import LOGIN_URL
``` |
Financial Charts / Graphs in Ruby or Python | 1,089,307 | 12 | 2009-07-06T21:31:21Z | 1,089,435 | 8 | 2009-07-06T22:10:44Z | [
"python",
"ruby",
"charts",
"graph",
"financial"
] | What are my best options for creating a financial open-high-low-close (OHLC) chart in a high level language like Ruby or Python? While there seem to be a lot of options for graphing, I haven't seen any gems or eggs with this kind of chart.
<http://en.wikipedia.org/wiki/Open-high-low-close_chart> (but I don't need the ... | You can use Pylab (`matplotlib.finance`) with Python. Here are some examples: [http://matplotlib.sourceforge.net/examples/pylab\_examples/plotfile\_demo.html](http://matplotlib.sourceforge.net/examples/pylab%5Fexamples/plotfile%5Fdemo.html) . There is some good material specifically on this problem in [Beginning Python... |
Financial Charts / Graphs in Ruby or Python | 1,089,307 | 12 | 2009-07-06T21:31:21Z | 1,089,512 | 16 | 2009-07-06T22:32:49Z | [
"python",
"ruby",
"charts",
"graph",
"financial"
] | What are my best options for creating a financial open-high-low-close (OHLC) chart in a high level language like Ruby or Python? While there seem to be a lot of options for graphing, I haven't seen any gems or eggs with this kind of chart.
<http://en.wikipedia.org/wiki/Open-high-low-close_chart> (but I don't need the ... | You can use [matplotlib](http://matplotlib.sourceforge.net/) and the the optional `bottom` parameter of [matplotlib.pyplot.bar](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.bar). You can then use line `plot` to indicate the opening and closing prices:
For example:
```
#!/usr/bin/env python
... |
Python: Inflate and Deflate implementations | 1,089,662 | 32 | 2009-07-06T23:24:10Z | 1,089,787 | 16 | 2009-07-07T00:12:26Z | [
"c#",
"python",
"compression",
"zlib"
] | I am interfacing with a server that requires that data sent to it is compressed with *Deflate* algorithm (Huffman encoding + LZ77) and also sends data that I need to *Inflate*.
I know that Python includes Zlib, and that the C libraries in Zlib support calls to *Inflate* and *Deflate*, but these apparently are not prov... | You can still use the [`zlib`](https://docs.python.org/2/library/zlib.html) module to inflate/deflate data. The [`gzip`](https://docs.python.org/2/library/gzip.html) module uses it internally, but adds a file-header to make it into a gzip-file. Looking at the [`gzip.py`](http://hg.python.org/cpython/file/8ebda8114e97/L... |
Python: Inflate and Deflate implementations | 1,089,662 | 32 | 2009-07-06T23:24:10Z | 1,090,361 | 13 | 2009-07-07T04:31:48Z | [
"c#",
"python",
"compression",
"zlib"
] | I am interfacing with a server that requires that data sent to it is compressed with *Deflate* algorithm (Huffman encoding + LZ77) and also sends data that I need to *Inflate*.
I know that Python includes Zlib, and that the C libraries in Zlib support calls to *Inflate* and *Deflate*, but these apparently are not prov... | This is an add-on to MizardX's answer, giving some explanation and background.
See <http://www.chiramattel.com/george/blog/2007/09/09/deflatestream-block-length-does-not-match.html>
According to [RFC 1950](http://www.ietf.org/rfc/rfc1950.txt), a zlib stream constructed in the default manner is composed of:
* a 2-byt... |
Is & faster than % when checking for odd numbers? | 1,089,936 | 23 | 2009-07-07T01:26:42Z | 1,089,945 | 53 | 2009-07-07T01:28:58Z | [
"python",
"performance",
"bit-manipulation",
"modulo"
] | To check for odd and even integer, is the lowest bit checking more efficient than using the modulo?
```
>>> def isodd(num):
return num & 1 and True or False
>>> isodd(10)
False
>>> isodd(9)
True
``` | Yep. The `timeit` module in the standard library is how you check on those things. E.g:
```
AmAir:stko aleax$ python -mtimeit -s'def isodd(x): x & 1' 'isodd(9)'
1000000 loops, best of 3: 0.446 usec per loop
AmAir:stko aleax$ python -mtimeit -s'def isodd(x): x & 1' 'isodd(10)'
1000000 loops, best of 3: 0.443 usec per l... |
Is & faster than % when checking for odd numbers? | 1,089,936 | 23 | 2009-07-07T01:26:42Z | 1,089,949 | 23 | 2009-07-07T01:30:52Z | [
"python",
"performance",
"bit-manipulation",
"modulo"
] | To check for odd and even integer, is the lowest bit checking more efficient than using the modulo?
```
>>> def isodd(num):
return num & 1 and True or False
>>> isodd(10)
False
>>> isodd(9)
True
``` | To be totally honest, **I don't think it matters.**
The first issue is readability. What makes more sense to other developers? I, personally, would expect a modulo when checking the evenness/oddness of a number. I would expect that most other developers would expect the same thing. By introducing a different, and unex... |
Is & faster than % when checking for odd numbers? | 1,089,936 | 23 | 2009-07-07T01:26:42Z | 1,090,027 | 10 | 2009-07-07T02:00:48Z | [
"python",
"performance",
"bit-manipulation",
"modulo"
] | To check for odd and even integer, is the lowest bit checking more efficient than using the modulo?
```
>>> def isodd(num):
return num & 1 and True or False
>>> isodd(10)
False
>>> isodd(9)
True
``` | The best optimization you can get is to *not* put the test into a function. '`number % 2`' and 'number & 1' are very common ways of checking odd/evenness, experienced programmers will recognize the pattern instantly, and you can always throw in a comment such as '# if number is odd, then blah blah blah' if you really n... |
Any drawbacks to storing an integer as a string in a database? | 1,090,022 | 13 | 2009-07-07T01:58:05Z | 1,090,065 | 23 | 2009-07-07T02:12:26Z | [
"python",
"mysql",
"database",
"database-design"
] | I have id values for products that I need store. Right now they are all integers, but I'm not sure if the data provider in the future will introduce letters or symbols into that mix, so I'm debating whether to store it now as integer or string.
Are there performance or other disadvantages to saving the values as strin... | Unless you really need the features of an integer (that is, the ability to do arithmetic), then it is probably better for you to store the product IDs as strings. You will never need to do anything like add two product IDs together, or compute the average of a group of product IDs, so there is no need for an actual num... |
Any drawbacks to storing an integer as a string in a database? | 1,090,022 | 13 | 2009-07-07T01:58:05Z | 1,090,100 | 12 | 2009-07-07T02:28:35Z | [
"python",
"mysql",
"database",
"database-design"
] | I have id values for products that I need store. Right now they are all integers, but I'm not sure if the data provider in the future will introduce letters or symbols into that mix, so I'm debating whether to store it now as integer or string.
Are there performance or other disadvantages to saving the values as strin... | Do NOT consider performance. Consider meaning.
ID "numbers" are not numeric except that they are written with an alphabet of all digits.
If I have part number 12 and part number 14, what is the difference between the two? Is part number 2 or -2 meaningful? No.
Part numbers (and anything that doesn't have units of me... |
How does Python store lists internally? | 1,090,104 | 9 | 2009-07-07T02:31:01Z | 1,090,117 | 21 | 2009-07-07T02:35:40Z | [
"python",
"data-structures"
] | How are lists in python stored internally? Is it an array? A linked list? Something else?
Or does the interpreter guess at the right structure for each instance based on length, etc.
If the question is implementation dependent, what about the classic CPython? | from [Core Python Containers: Under the Hood](http://www.pycon.it/media/stuff/slides/core-python-containers-under-hood.ppt)
List Implementation:
Fixed-length array of pointers
\* When the array grows or shrinks, calls realloc() and, if necessary, copies all of the items to the new space
source code: [Include/li... |
Search a folder for files like "/*tmp*.log" in Python | 1,090,651 | 3 | 2009-07-07T06:17:18Z | 1,090,656 | 12 | 2009-07-07T06:18:58Z | [
"python",
"linux",
"file",
"folders"
] | As the title says, I'm using Linux, and the folder could contain more than one file, I want to get the one its name contain `*tmp*.log` (`*` means anything of course!). Just like what I do using Linux command line. | Use the [`glob`](http://docs.python.org/library/glob.html) module.
```
>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']
``` |
Python operators | 1,090,863 | 7 | 2009-07-07T07:37:49Z | 1,090,886 | 15 | 2009-07-07T07:43:50Z | [
"python",
"operators"
] | I am learning Python for the past few days and I have written this piece of code to evaluate a postfix expression.
```
postfix_expression = "34*34*+"
stack = []
for char in postfix_expression :
try :
char = int(char);
stack.append(char);
except ValueError:
if char == '+' :
stack.append(s... | The [`operator`](http://docs.python.org/library/operator.html) module has functions that implement the standard arithmetic operators. With that, you can set up a mapping like:
```
OperatorFunctions = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.div,
# etc
}
```
Then you... |
How to test if a class attribute is an instance method | 1,091,259 | 2 | 2009-07-07T09:23:23Z | 1,091,288 | 8 | 2009-07-07T09:33:55Z | [
"python",
"methods",
"attributes",
"instance"
] | In Python I need to efficiently and generically test whether an attribute of a class is an instance method. The inputs to the call would be the name of the attribute being checked (a string) and an object.
hasattr returns true regardless of whether the attribute is an instance method or not.
Any suggestions?
---
Fo... | ```
def hasmethod(obj, name):
return hasattr(obj, name) and type(getattr(obj, name)) == types.MethodType
``` |
TeamCity for Python/Django continuous integration | 1,091,465 | 9 | 2009-07-07T10:09:26Z | 1,102,217 | 21 | 2009-07-09T06:51:57Z | [
"python",
"django",
"continuous-integration",
"teamcity"
] | I've set up [TeamCity](http://en.wikipedia.org/wiki/TeamCity) on a Linux (Ubuntu) box and would like to use it for some of Python/Django projects.
The problem is that I don't really see what to do next - I tried searching for a Python specific build agent for TeamCity but without much of the success.
How can I manage... | Ok, so there's how to get it working with proper TeamCity integration:
Presuming you have TeamCity installed with at least 1 build agent available
1) Configure your build agent to execute
```
manage.py test
```
2) Download and install this plugin for TC <http://pypi.python.org/pypi/teamcity-messages>
3) You'll hav... |
Programmatic control of python optimization? | 1,092,243 | 5 | 2009-07-07T13:06:14Z | 1,092,266 | 14 | 2009-07-07T13:11:41Z | [
"python",
"optimization",
"pyglet",
"multiplatform"
] | I've been playing with [pyglet](http://www.pyglet.org/index.html). It's very nice. However, if I run my code, which is in an executable file (call it game.py) prefixed with the usual
```
#!/usr/bin/env python
```
by doing
```
./game.py
```
then it's a bit clunky. But if I run it with
```
python -O ./game.py
```
o... | **"On Linux I can easily provide a ./game script to run the file for end users:"**
Correct.
**"but that's not very cross-platform."**
Half-correct. There are exactly two shell languages that matter. Standard Linux "sh" and Non-standard Windows "bat" (a/k/a cmd.exe) and that's all there is nowadays. [When I was a kid... |
Event system in Python | 1,092,531 | 111 | 2009-07-07T14:00:51Z | 1,092,617 | 10 | 2009-07-07T14:19:39Z | [
"python",
"events",
"event-handling",
"dispatcher"
] | What event system for Python do you use? I'm already aware of [pydispatcher](http://pydispatcher.sourceforge.net/), but I was wondering what else can be found, or is commonly used?
I'm not interested in event managers that are part of large frameworks, I'd rather use a small bare-bones solution that I can easily exten... | I use [zope.event](http://pypi.python.org/pypi/zope.event). It's the most bare bones you can imagine. :-)
In fact, here is the complete source code:
```
subscribers = []
def notify(event):
for subscriber in subscribers:
subscriber(event)
```
Note that you can't send messages between processes, for exampl... |
Event system in Python | 1,092,531 | 111 | 2009-07-07T14:00:51Z | 1,094,423 | 58 | 2009-07-07T19:46:51Z | [
"python",
"events",
"event-handling",
"dispatcher"
] | What event system for Python do you use? I'm already aware of [pydispatcher](http://pydispatcher.sourceforge.net/), but I was wondering what else can be found, or is commonly used?
I'm not interested in event managers that are part of large frameworks, I'd rather use a small bare-bones solution that I can easily exten... | We use an EventHook as suggested from Michael Foord in his [Event Pattern](http://www.voidspace.org.uk/python/weblog/arch_d7_2007_02_03.shtml#e616):
Just add EventHooks to your classes with:
```
class MyBroadcaster()
def __init__():
self.onChange = EventHook()
theBroadcaster = MyBroadcaster()
# add a li... |
Event system in Python | 1,092,531 | 111 | 2009-07-07T14:00:51Z | 1,096,614 | 8 | 2009-07-08T07:32:24Z | [
"python",
"events",
"event-handling",
"dispatcher"
] | What event system for Python do you use? I'm already aware of [pydispatcher](http://pydispatcher.sourceforge.net/), but I was wondering what else can be found, or is commonly used?
I'm not interested in event managers that are part of large frameworks, I'd rather use a small bare-bones solution that I can easily exten... | I found this small script on [Valued Lessons](http://www.valuedlessons.com/2008/04/events-in-python.html). It seems to have just the right simplicity/power ratio I'm after. Peter Thatcher is the author of following code (no licensing is mentioned).
```
class Event:
def __init__(self):
self.handlers = set()... |
Event system in Python | 1,092,531 | 111 | 2009-07-07T14:00:51Z | 2,022,629 | 53 | 2010-01-07T18:28:47Z | [
"python",
"events",
"event-handling",
"dispatcher"
] | What event system for Python do you use? I'm already aware of [pydispatcher](http://pydispatcher.sourceforge.net/), but I was wondering what else can be found, or is commonly used?
I'm not interested in event managers that are part of large frameworks, I'd rather use a small bare-bones solution that I can easily exten... | I've been doing it this way:
```
class Event(list):
"""Event subscription.
A list of callable objects. Calling an instance of this will cause a
call to each item in the list in ascending order by index.
Example Usage:
>>> def f(x):
... print 'f(%s)' % x
>>> def g(x):
... print... |
Event system in Python | 1,092,531 | 111 | 2009-07-07T14:00:51Z | 16,192,256 | 59 | 2013-04-24T12:38:55Z | [
"python",
"events",
"event-handling",
"dispatcher"
] | What event system for Python do you use? I'm already aware of [pydispatcher](http://pydispatcher.sourceforge.net/), but I was wondering what else can be found, or is commonly used?
I'm not interested in event managers that are part of large frameworks, I'd rather use a small bare-bones solution that I can easily exten... | Wrapping up the various event systems that are mentioned in the answers here:
The most basic style of event system is the 'bag of handler methods', which is a simple implementation of the [Observer pattern](http://en.wikipedia.org/wiki/Observer_pattern). Basically, the handler methods (callables) are stored in an arra... |
AppEngine server cannot import atom module | 1,092,648 | 3 | 2009-07-07T14:26:49Z | 1,092,753 | 11 | 2009-07-07T14:43:09Z | [
"python",
"google-app-engine"
] | I have gdata library install on my ArchLinux, and a simple application which imports atom library at the beginning, when I run gapp engine and access that web app,
> $ python2.5 ./dev\_appserver.py ~/myapp
It throws exception 'No module named atom'. But when I run 'import atom' in Python2.5 interactive mode, it works... | Add atom.py to the same directory you keep you GAE Python sources in, and make sure it's uploaded to the server when you upload your app. (The upload happens when you do `appcfg.py update myapp/` unless you go out of your way to stop it; use the `--verbose` flag on the command to see exactly what's being uploaded or up... |
How do I check what version of Python is running my script? | 1,093,322 | 524 | 2009-07-07T16:17:49Z | 1,093,331 | 636 | 2009-07-07T16:20:12Z | [
"python",
"version"
] | How can I check what version of the Python Interpreter is interpreting my script? | This information is available in the [sys.version](http://docs.python.org/2/library/sys.html#sys.version) string in the [sys](http://docs.python.org/2/library/sys.html) module:
```
>>> import sys
```
Human readable:
```
>>> print (sys.version) #parentheses necessary in python 3.
2.5.2 (r252:60911, Jul 31 2008... |
How do I check what version of Python is running my script? | 1,093,322 | 524 | 2009-07-07T16:17:49Z | 3,016,171 | 46 | 2010-06-10T16:06:05Z | [
"python",
"version"
] | How can I check what version of the Python Interpreter is interpreting my script? | Your best bet is probably something like so:
```
>>> import sys
>>> sys.version_info
(2, 6, 4, 'final', 0)
>>> if not sys.version_info[:2] == (2, 6):
... print "Error, I need python 2.6"
... else:
... from my_module import twoPointSixCode
>>>
```
Additionally, you can always wrap your imports in a simple try, w... |
How do I check what version of Python is running my script? | 1,093,322 | 524 | 2009-07-07T16:17:49Z | 3,016,198 | 40 | 2010-06-10T16:08:54Z | [
"python",
"version"
] | How can I check what version of the Python Interpreter is interpreting my script? | Put something like:
```
#!/usr/bin/env/python
import sys
if sys.version_info<(2,6,0):
sys.stderr.write("You need python 2.6 or later to run this script\n")
exit(1)
```
at the top of your script.
Note that depending on what else is in your script, older versions of python than the target may not be able to even l... |
How do I check what version of Python is running my script? | 1,093,322 | 524 | 2009-07-07T16:17:49Z | 3,018,075 | 74 | 2010-06-10T20:08:35Z | [
"python",
"version"
] | How can I check what version of the Python Interpreter is interpreting my script? | I like `sys.hexversion` for stuff like this.
<http://docs.python.org/library/sys.html#sys.hexversion>
```
>>> import sys
>>> sys.hexversion
33883376
>>> '%x' % sys.hexversion
'20504f0'
>>> sys.hexversion < 0x02060000
True
``` |
How do I check what version of Python is running my script? | 1,093,322 | 524 | 2009-07-07T16:17:49Z | 17,796,193 | 125 | 2013-07-22T19:50:40Z | [
"python",
"version"
] | How can I check what version of the Python Interpreter is interpreting my script? | From the command line (note the capital 'V'):
```
python -V
```
This is documented in 'man python'. |
How do I check what version of Python is running my script? | 1,093,322 | 524 | 2009-07-07T16:17:49Z | 25,477,839 | 25 | 2014-08-25T01:11:33Z | [
"python",
"version"
] | How can I check what version of the Python Interpreter is interpreting my script? | I found this method somewhere.
```
>>> from platform import python_version
>>> print python_version()
2.7.8
``` |
How do I check what version of Python is running my script? | 1,093,322 | 524 | 2009-07-07T16:17:49Z | 25,631,445 | 9 | 2014-09-02T20:02:50Z | [
"python",
"version"
] | How can I check what version of the Python Interpreter is interpreting my script? | Here's a short commandline version which exits straight away (handy for scripts and automated execution):
```
python -c 'print __import__("sys").version'
```
Or just the major, minor and micro:
```
python -c 'print __import__("sys").version_info[:1]' # (2,)
python -c 'print __import__("sys").version_info[:2]' # (2, ... |
pyserial - How to read the last line sent from a serial device | 1,093,598 | 14 | 2009-07-07T17:16:43Z | 1,093,661 | 9 | 2009-07-07T17:27:56Z | [
"python",
"serial-port",
"arduino",
"pyserial"
] | I have an Arduino connected to my computer running a loop, sending a value over the serial port back to the computer every 100 ms.
I want to make a Python script that will read from the serial port only every few seconds, so I want it to just see the last thing sent from the Arduino.
How do you do this in Pyserial?
... | ```
from serial import *
from threading import Thread
last_received = ''
def receiving(ser):
global last_received
buffer = ''
while True:
# last_received = ser.readline()
buffer += ser.read(ser.inWaiting())
if '\n' in buffer:
last_received, buffer = buffer.split('\n')[... |
pyserial - How to read the last line sent from a serial device | 1,093,598 | 14 | 2009-07-07T17:16:43Z | 1,093,662 | 25 | 2009-07-07T17:28:01Z | [
"python",
"serial-port",
"arduino",
"pyserial"
] | I have an Arduino connected to my computer running a loop, sending a value over the serial port back to the computer every 100 ms.
I want to make a Python script that will read from the serial port only every few seconds, so I want it to just see the last thing sent from the Arduino.
How do you do this in Pyserial?
... | Perhaps I'm misunderstanding your question, but as it's a serial line, you'll have to read everything sent from the Arduino sequentially - it'll be buffered up in the Arduino until you read it.
If you want to have a status display which shows the latest thing sent - use a thread which incorporates the code in your que... |
pyserial - How to read the last line sent from a serial device | 1,093,598 | 14 | 2009-07-07T17:16:43Z | 3,999,994 | 7 | 2010-10-22T18:53:23Z | [
"python",
"serial-port",
"arduino",
"pyserial"
] | I have an Arduino connected to my computer running a loop, sending a value over the serial port back to the computer every 100 ms.
I want to make a Python script that will read from the serial port only every few seconds, so I want it to just see the last thing sent from the Arduino.
How do you do this in Pyserial?
... | These solutions will hog the CPU while waiting for characters.
You should do at least one blocking call to read(1)
```
while True:
if '\n' in buffer:
pass # skip if a line already in buffer
else:
buffer += ser.read(1) # this will block until one more char or timeout
buffer += ser.read(se... |
How to serve any file type with Python's BaseHTTPRequestHandler | 1,094,185 | 7 | 2009-07-07T19:06:36Z | 1,094,237 | 7 | 2009-07-07T19:18:14Z | [
"python",
"httpserver"
] | Consider the following example:
```
import string,cgi,time
from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
try:
if self.path.endswith(".html"):
f = open(curdir + sep + self.path... | Pass binary as a parameter to open(). This:
```
f = open(curdir + sep + self.path, 'rb')
```
Instead of this:
```
f = open(curdir + sep + self.path)
```
UNIX doesn't distinguish between binary and text, but windows does. But if the script executes on UNIX, the "b" will just be ignored so you're safe. |
Wavelet plot with Python libraries | 1,094,655 | 6 | 2009-07-07T20:25:31Z | 1,118,619 | 11 | 2009-07-13T10:03:00Z | [
"python",
"matplotlib",
"scipy",
"wavelet",
"pywt"
] | I know that SciPy has some signal processing tools for wavelets in scipy.signal.wavelets and a chart can be drawn using Matplotlib, but it seems I can't get it right. I have tried plotting a Daubechies wavelet against a linear space, but it's not what I am looking for. I am highly unskilled about wavelets and math in g... | With a recent trunk version of [PyWavelets](http://pybytes.com/pywavelets/), getting approximations of scaling function and wavelet function on x-grid is pretty straightforward:
```
[phi, psi, x] = pywt.Wavelet('db2').wavefun(level=4)
```
Note that x-grid output is not available in v0.1.6, so if you need that you wil... |
Convert a string to integer with decimal in Python | 1,094,717 | 33 | 2009-07-07T20:35:48Z | 1,094,721 | 66 | 2009-07-07T20:36:52Z | [
"python",
"string",
"integer",
"decimal"
] | I have a string in the format: 'nn.nnnnn' in Python, and I'd like to convert it to an integer.
Direct conversion fails:
```
>>> s = '23.45678'
>>> i = int(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '23.45678'
```
I can convert it to... | How about this?
```
>>> s = '23.45678'
>>> int(float(s))
23
```
Or...
```
>>> int(Decimal(s))
23
```
Or...
```
>>> int(s.split('.')[0])
23
```
I doubt it's going to get much simpler than that, I'm afraid. Just accept it and move on. |
Convert a string to integer with decimal in Python | 1,094,717 | 33 | 2009-07-07T20:35:48Z | 1,094,745 | 12 | 2009-07-07T20:41:44Z | [
"python",
"string",
"integer",
"decimal"
] | I have a string in the format: 'nn.nnnnn' in Python, and I'd like to convert it to an integer.
Direct conversion fails:
```
>>> s = '23.45678'
>>> i = int(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '23.45678'
```
I can convert it to... | What sort of rounding behavior do you want? Do you 2.67 to turn into 3, or 2. If you want to use rounding, try this:
```
s = '234.67'
i = int(round(float(s)))
```
Otherwise, just do:
```
s = '234.67'
i = int(float(s))
``` |
Reusable library to get human readable version of file size? | 1,094,841 | 129 | 2009-07-07T20:59:32Z | 1,094,845 | 7 | 2009-07-07T21:00:25Z | [
"python",
"code-snippets",
"filesize"
] | There are various snippets on the web that would give you a function to return human readable size from bytes size:
```
>>> human_readable(2048)
'2 kilobytes'
>>>
```
But is there a Python library that provides this? | One such library is [hurry.filesize](http://pypi.python.org/pypi/hurry.filesize).
```
>>> from hurry.filesize import alternative
>>> size(1, system=alternative)
'1 byte'
>>> size(10, system=alternative)
'10 bytes'
>>> size(1024, system=alternative)
'1 KB'
``` |
Reusable library to get human readable version of file size? | 1,094,841 | 129 | 2009-07-07T20:59:32Z | 1,094,933 | 290 | 2009-07-07T21:15:41Z | [
"python",
"code-snippets",
"filesize"
] | There are various snippets on the web that would give you a function to return human readable size from bytes size:
```
>>> human_readable(2048)
'2 kilobytes'
>>>
```
But is there a Python library that provides this? | Addressing the above "too small a task to require a library" issue by a straightforward implementation:
```
def sizeof_fmt(num, suffix='B'):
for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f... |
Reusable library to get human readable version of file size? | 1,094,841 | 129 | 2009-07-07T20:59:32Z | 10,171,475 | 24 | 2012-04-16T09:16:44Z | [
"python",
"code-snippets",
"filesize"
] | There are various snippets on the web that would give you a function to return human readable size from bytes size:
```
>>> human_readable(2048)
'2 kilobytes'
>>>
```
But is there a Python library that provides this? | Here's my version. It does not use a for-loop. It has constant complexity, O(*1*), and is in theory more efficient than the answers here that use a for-loop.
```
from math import log
unit_list = zip(['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'], [0, 0, 1, 2, 2, 2])
def sizeof_fmt(num):
"""Human friendly file size"""
... |
Reusable library to get human readable version of file size? | 1,094,841 | 129 | 2009-07-07T20:59:32Z | 15,485,265 | 37 | 2013-03-18T19:29:28Z | [
"python",
"code-snippets",
"filesize"
] | There are various snippets on the web that would give you a function to return human readable size from bytes size:
```
>>> human_readable(2048)
'2 kilobytes'
>>>
```
But is there a Python library that provides this? | A library that has all the functionality that it seems you're looking for is [`humanize`](https://pypi.python.org/pypi/humanize). `humanize.naturalsize()` seems to do everything you're looking for. |
Reusable library to get human readable version of file size? | 1,094,841 | 129 | 2009-07-07T20:59:32Z | 25,613,067 | 15 | 2014-09-01T21:23:48Z | [
"python",
"code-snippets",
"filesize"
] | There are various snippets on the web that would give you a function to return human readable size from bytes size:
```
>>> human_readable(2048)
'2 kilobytes'
>>>
```
But is there a Python library that provides this? | While I know this question is ancient, I recently came up with a version that avoids loops, using `log2` to determine the size order which doubles as a shift and an index into the suffix list:
```
from math import log2
_suffixes = ['bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']
def file_size(size):... |
Is there a Python language specification? | 1,094,961 | 24 | 2009-07-07T21:23:25Z | 1,094,987 | 21 | 2009-07-07T21:27:30Z | [
"python",
"specifications"
] | Is there anything in Python akin to Java's JLS or C#'s spec? | There's no specification per se. The closest thing is the [Python Language Reference](http://docs.python.org/reference/), which details the syntax and semantics of the language. |
Matrix from Python to MATLAB | 1,095,265 | 25 | 2009-07-07T22:55:08Z | 1,095,324 | 40 | 2009-07-07T23:13:52Z | [
"python",
"matlab",
"file-io",
"import",
"matrix"
] | I'm working with Python and MATLAB right now and I have a 2D array in Python that I need to write to a file and then be able to read it into MATLAB as a matrix. Any ideas on how to do this?
Thanks! | If you use numpy/scipy, you can use the `scipy.io.savemat` function:
```
import numpy, scipy.io
arr = numpy.arange(10)
arr = arr.reshape((3, 3)) # 2d array of 3x3
scipy.io.savemat('c:/tmp/arrdata.mat', mdict={'arr': arr})
```
Now, you can load this data into MATLAB using File -> Load Data. Select the file and the ... |
Matrix from Python to MATLAB | 1,095,265 | 25 | 2009-07-07T22:55:08Z | 1,095,505 | 7 | 2009-07-08T00:13:44Z | [
"python",
"matlab",
"file-io",
"import",
"matrix"
] | I'm working with Python and MATLAB right now and I have a 2D array in Python that I need to write to a file and then be able to read it into MATLAB as a matrix. Any ideas on how to do this?
Thanks! | I think [ars](http://stackoverflow.com/questions/1095265/matrix-from-python-to-matlab/1095324#1095324) has the most straight-forward answer for saving the data to a .mat file from Python (using [savemat](http://docs.scipy.org/doc/scipy/reference/generated/scipy.io.savemat.html)). To add just a little to their answer, y... |
Get __name__ of calling function's module in Python | 1,095,543 | 54 | 2009-07-08T00:30:47Z | 1,095,621 | 80 | 2009-07-08T01:03:42Z | [
"python",
"stack-trace",
"introspection"
] | Suppose `myapp/foo.py` contains:
```
def info(msg):
caller_name = ????
print '[%s] %s' % (caller_name, msg)
```
And `myapp/bar.py` contains:
```
import foo
foo.info('Hello') # => [myapp.foo] Hello
```
I want `caller_name` to be set to the `__name__` attribute of the calling functions' module (which is 'myap... | Check out the inspect module:
`inspect.stack()` will return the stack information.
Inside a function, `inspect.stack()[1]` will return your caller's stack. From there, you can get more information about the caller's function name, module, etc.
See the docs for details:
<http://docs.python.org/library/inspect.html>
... |
Get __name__ of calling function's module in Python | 1,095,543 | 54 | 2009-07-08T00:30:47Z | 5,071,539 | 12 | 2011-02-21T21:35:29Z | [
"python",
"stack-trace",
"introspection"
] | Suppose `myapp/foo.py` contains:
```
def info(msg):
caller_name = ????
print '[%s] %s' % (caller_name, msg)
```
And `myapp/bar.py` contains:
```
import foo
foo.info('Hello') # => [myapp.foo] Hello
```
I want `caller_name` to be set to the `__name__` attribute of the calling functions' module (which is 'myap... | Confronted with a similar problem, I have found that **sys.\_current\_frames()** from the sys module contains interesting information that can help you, without the need to import inspect, at least in specific use cases.
```
>>> sys._current_frames()
{4052: <frame object at 0x03200C98>}
```
You can then "move up" usi... |
Find module name of the originating exception in Python | 1,095,601 | 9 | 2009-07-08T00:55:16Z | 1,096,213 | 8 | 2009-07-08T05:19:23Z | [
"python",
"exception",
"logging",
"stack-trace",
"introspection"
] | Example:
```
>>> try:
... myapp.foo.doSomething()
... except Exception, e:
... print 'Thrown from:', modname(e)
Thrown from: myapp.util.url
```
In the above example, the exception was actually thrown at myapp/util/url.py module. Is there a way to get the `__name__` of that module?
My intention is to use this ... | This should work:
```
import inspect
try:
some_bad_code()
except Exception, e:
frm = inspect.trace()[-1]
mod = inspect.getmodule(frm[0])
print 'Thrown from', mod.__name__
```
EDIT: Stephan202 mentions a corner case. In this case, I think we could default to the file name.
```
import inspect
try:
... |
Does get_or_create() have to save right away? (Django) | 1,095,663 | 33 | 2009-07-08T01:17:30Z | 1,095,706 | 34 | 2009-07-08T01:29:09Z | [
"python",
"django"
] | I need to use something like get\_or\_create() but the problem is that I have a lot of fields and I don't want to set defaults (which don't make sense anyway), and if I don't set defaults it returns an error, because it saves the object right away apparently.
I can set the fields to null=True, but I don't want null fi... | You can just do:
```
try:
obj = Model.objects.get(**kwargs)
except Model.DoesNotExist:
obj = Model(**dict((k,v) for (k,v) in kwargs.items() if '__' not in k))
```
which is pretty much what [`get_or_create`](https://github.com/django/django/blob/master/django/db/models/query.py#L454) does, sans commit. |
where does django install in ubuntu | 1,095,725 | 29 | 2009-07-08T01:38:33Z | 1,095,862 | 86 | 2009-07-08T02:26:58Z | [
"python",
"django",
"ubuntu"
] | I am looking for the **init**.py file for django. I tried whereis and find, but I get a lot of dirs. | you can just print it out.
```
>>> import django
>>> print django.__file__
/var/lib/python-support/python2.5/django/__init__.pyc
>>>
```
or:
```
import inspect
import django
print inspect.getabsfile(django)
``` |
what next after 'dive into python' | 1,095,768 | 10 | 2009-07-08T01:50:19Z | 1,095,787 | 7 | 2009-07-08T01:57:04Z | [
"python"
] | I've been meaning to learn another language than java. So I started to poke around with python. I've gone over 'dive into python' so I have a decent knowledge about python now.
where do you suggest I go from here? I dont want to go through another advanced book again and would like to use the python knowledge towards ... | You can try my [Building Skills in OO Design](http://homepage.mac.com/s%5Flott/books/oodesign.html).
<http://homepage.mac.com/s_lott/books/oodesign.html> |
what next after 'dive into python' | 1,095,768 | 10 | 2009-07-08T01:50:19Z | 1,095,809 | 12 | 2009-07-08T02:05:48Z | [
"python"
] | I've been meaning to learn another language than java. So I started to poke around with python. I've gone over 'dive into python' so I have a decent knowledge about python now.
where do you suggest I go from here? I dont want to go through another advanced book again and would like to use the python knowledge towards ... | That really kind of depends on what you enjoy, or would like to build. Since you haven't said, I'll recommend something I enjoyed instead. [Programming Collective Intelligence](http://rads.stackoverflow.com/amzn/click/0596529325 "Programming Collective Intelligence") by Toby Segaran is a fun book, and the examples are ... |
Override namespace in Python | 1,096,216 | 13 | 2009-07-08T05:20:31Z | 1,096,220 | 17 | 2009-07-08T05:22:28Z | [
"python",
"python-import"
] | Say there is a folder, '/home/user/temp/a40bd22344'. The name is completely random and changes in every iteration. I need to be able to import this folder in Python using a fixed name, say 'project'. I know I can add this folder to sys.path to enable import lookup, but is there a way to replace 'a40bd22344' with 'proje... | Sure, `project = __import__('a40bd22344')` after `sys.path` is set properly will just work.
Suppose you want to do it in a function taking the full path as an argument and setting the *global* import of `project` properly (as well as magically making `import project` work afterwards in other modules). Piece of cake:
... |
Override namespace in Python | 1,096,216 | 13 | 2009-07-08T05:20:31Z | 1,096,247 | 21 | 2009-07-08T05:33:14Z | [
"python",
"python-import"
] | Say there is a folder, '/home/user/temp/a40bd22344'. The name is completely random and changes in every iteration. I need to be able to import this folder in Python using a fixed name, say 'project'. I know I can add this folder to sys.path to enable import lookup, but is there a way to replace 'a40bd22344' with 'proje... | Here's one way to do it, without touching sys.path, using the `imp` module in Python:
```
import imp
f, filename, desc = imp.find_module('a40bd22344', ['/home/user/temp/'])
project = imp.load_module('a40bd22344', f, filename, desc)
project.some_func()
```
Here is a link to some good documentation on the `imp` modul... |
Override namespace in Python | 1,096,216 | 13 | 2009-07-08T05:20:31Z | 1,097,237 | 19 | 2009-07-08T10:21:15Z | [
"python",
"python-import"
] | Say there is a folder, '/home/user/temp/a40bd22344'. The name is completely random and changes in every iteration. I need to be able to import this folder in Python using a fixed name, say 'project'. I know I can add this folder to sys.path to enable import lookup, but is there a way to replace 'a40bd22344' with 'proje... | You first import it with **import**:
```
>>> __import__('temp/a40bd22344')
<module 'temp/a40bd22344' from 'temp/a40bd22344/__init__.py'>
```
Then you make sure that this module gets known to Python as `project`:
```
>>> import sys
>>> sys.modules['project'] = sys.modules.pop('temp/a40bd22344')
```
After this, anyth... |
How to make urllib2 requests through Tor in Python? | 1,096,379 | 41 | 2009-07-08T06:22:08Z | 2,015,649 | 19 | 2010-01-06T19:37:37Z | [
"python",
"tor"
] | I'm trying to crawl websites using a crawler written in Python. I want to integrate Tor with Python meaning I want to crawl the site anonymously using Tor.
I tried doing this. It doesn't seem to work. I checked my IP it is still the same as the one before I used tor. I checked it via python.
```
import urllib2
proxy_... | You are trying to connect to a SOCKS port - Tor rejects any non-SOCKS traffic. You can connect through a middleman - Privoxy - using Port 8118.
Example:
```
proxy_support = urllib2.ProxyHandler({"http" : "127.0.0.1:8118"})
opener = urllib2.build_opener(proxy_support)
opener.addheaders = [('User-agent', 'Mozilla/5.0'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.