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 |
|---|---|---|---|---|---|---|---|---|---|
Encode file path properly using python | 5,960,751 | 5 | 2011-05-11T07:32:50Z | 5,960,893 | 10 | 2011-05-11T07:47:11Z | [
"python",
"url-encoding"
] | I am trying to open files by getting the path from a dictionary. Some of the file names have commas (,) and other such characters which when used give a "no such file found error"
For instance the following file path will not open: foo,%20bar.mp3
If characters like commas exist then it should be encoded as : foo%2C%2... | You may need [urllib.pathname2url](http://docs.python.org/library/urllib.html#urllib.pathname2url)
```
>>> from urllib import pathname2url
>>> pathname2url('foo, bar.mp3')
'foo%2C%20bar.mp3'
``` |
Python: How to pack different types of data into a string buffer using struct.pack_into | 5,961,407 | 9 | 2011-05-11T08:34:35Z | 5,961,539 | 11 | 2011-05-11T08:45:49Z | [
"python",
"c",
"struct"
] | I'm trying to pack some unsigned int data into a string buffer created using `ctypes.create_string_buffer`.
Here is the following code segment, and a running example showing the error [on codepad](http://codepad.org/S8nUWMcW):
```
import struct
import ctypes
import binascii
buf = ctypes.create_string_buffer(16)
stru... | You're not supposed to prefix every output specifier with the '=' code. Just say it once:
```
struct.pack_into("=III", buf, 0, 1, 2, 3)
```
This yields:
```
01000000020000000300000000000000
``` |
python try/exception help | 5,961,864 | 2 | 2011-05-11T09:14:21Z | 5,961,925 | 9 | 2011-05-11T09:19:11Z | [
"python",
"exception-handling"
] | I'm trying to support repetition where the user inputs a filename, then inputs two integers. So if an exception is thrown, I want the user to be prompted with input again.
My problem is if a valid file is entered but an invalid integer is entered it will ask for the file again instead of just the integer. How can I fi... | Try use multiple `while` loops:
```
while True:
fileName = raw_input("Enter name of file: ")
try:
# more code here to detect or open the file
break
except Exception: # can be IOError or something else
print ("error msg")
while True:
try:
integer = int(raw_input("Enter ... |
Check if a function is a method of some object | 5,963,729 | 9 | 2011-05-11T11:49:09Z | 5,963,773 | 16 | 2011-05-11T11:52:04Z | [
"python",
"function",
"methods"
] | How to check if a function is a method of some object?
For example:
```
def check_method(f):
...
check_method(lambda x: x + 1) # >>> False
check_method(SomeClass().some_method) # >>> True
```
There are some special attributes in methods in my 'helloworld' example (e.g. 'im\_self', '\_\_self\_\_' etc)... | Use [`inspect.ismethod()`](http://docs.python.org/library/inspect.html#inspect.ismethod).
The documentation states:
> Return true if the object is a bound method written in Python.
This means that it will work as you intend for classes that you define in Python. However, for methods of built-in classes like `list` o... |
How to get twitter followers using Twython? | 5,963,792 | 4 | 2011-05-11T11:53:23Z | 6,000,878 | 16 | 2011-05-14T09:12:47Z | [
"python",
"twitter",
"twitter-oauth",
"twython"
] | I want to get a list of twitter followers/following of a particular user, when their screenname or user.id is specified. Can anyone please give the code snippet for it? Thanks. | I'm the author of Twython. There's two different methods you can use for this; one that returns just follower IDs (get\_followers\_ids), and one that returns the statuses/etc of a follower set (get\_followers\_list).
Some example code for one would be like the following:
```
from twython import Twython
twitter = Twy... |
Python's profile module: <string>:1(?) | 5,964,126 | 13 | 2011-05-11T12:21:58Z | 5,965,887 | 13 | 2011-05-11T14:27:41Z | [
"python",
"profiling",
"profiler",
"profile"
] | I am using Python's (v2.4) `profile` module to profile a `numpy` script, and the following entry appears to account for the bulk of the execution time:
```
ncalls tottime percall cumtime percall filename:lineno(function)
256/1 0.000 0.000 7.710 7.710 <string>:1(?)
```
Unfortunately, its appearance ma... | Ignore this line. It is an artifact of how the profiler is implemented. It is not telling you anything useful. Look at the "tottime" value for it: 0.000. "tottime" is the amount of time spent executing "<string>:1(?)" excluding time spent executing children of it. So, no time is spent here. "cumtime" and "percall" are ... |
Python: Cannot Assign Function Call | 5,964,927 | 3 | 2011-05-11T13:19:49Z | 5,965,035 | 8 | 2011-05-11T13:27:21Z | [
"python"
] | I am having a "can't assign to call function"
`invest()` is another defined function that works.
```
def profile(initial_amount,startyear,endyear):
subsequent_amount = 0
for year in range(startyear,endyear-1):
if year == startyear:
print """<table border="1">"""
print "<tr>"
... | Syntactically, this line makes no sense:
```
invest(initial_amount,top_company(5,year,year+1)) = subsequent_amount
```
You are attempting to assign a value to a function call, as the error says. What are you trying to accomplish? If you're trying set `subsequent_amount` to the value of the function call, switch the o... |
Use scipy.integrate.quad to integrate complex numbers | 5,965,583 | 19 | 2011-05-11T14:08:20Z | 5,966,088 | 30 | 2011-05-11T14:40:58Z | [
"python",
"numpy",
"scipy",
"complex-numbers"
] | I'm using right now the scipy.integrate.quad to successfully integrate some real integrands. Now a situation appeared that I need to integrate a complex integrand. quad seems not be able to do it, as the other scipy.integrate routines, so I ask: is there any way to integrate a complex integrand using scipy.integrate, w... | What's wrong with just separating it out into real and imaginary parts? `scipy.integrate.quad` requires the integrated function return floats (aka real numbers) for the algorithm it uses.
```
import scipy
from scipy.integrate import quad
def complex_quadrature(func, a, b, **kwargs):
def real_func(x):
retu... |
Communication between PHP and Python | 5,965,655 | 8 | 2011-05-11T14:12:09Z | 5,966,240 | 7 | 2011-05-11T14:50:33Z | [
"php",
"python",
"ajax",
"ipc"
] | I'm trying to build a web interface for some python scripts. The thing is I have to use PHP (and not CGI) and some of the scripts I execute take quite some time to finish: 5-10 minutes. Is it possible for PHP to communicate with the scripts and display some sort of progress status? This should allow the user to use the... | You want *inter-process communication*. Sockets are the first thing that comes to mind; you'd need to set up a socket to *listen* for a connection (on the same machine) in PHP and set up a socket to *connect* to the listening socket in Python and *send* it its status.
Have a look at [this socket programming overview](... |
Start creating websites by using Python | 5,966,059 | 4 | 2011-05-11T14:38:31Z | 5,966,101 | 10 | 2011-05-11T14:42:13Z | [
"python"
] | I am basically a PHP guy. now moving towards python. I am starting to learn python.
How do I install it and start working it, and develop websites .
I got totally confused with the alternative implementations in the download section of the Python site. Can you tell me what "alternative implementations" means?.
I mean... | Just as a disclaimer, I interpret you saying "run Python in a browser" as "making a website with Python."
If you want to start writing web applications in Python, you can either use CGI or use one of its many [web app frameworks](http://wiki.python.org/moin/WebFrameworks). Python is not like PHP in the sense that you ... |
Python distutils not using correct version of gcc | 5,967,065 | 5 | 2011-05-11T15:49:02Z | 5,968,410 | 14 | 2011-05-11T17:48:12Z | [
"python",
"gcc",
"distutils"
] | I am trying to compile a package on Mac OSX 10.6.5. The package's install script relies on distutils. The problem is that the computer's default gcc is version 4.2 (I determined this by just running gcc --version in a terminal window) but when I run 'python setup.py build', I see from the output that the distutils is c... | To force distutils to use a separate compiler, you can redefine a few variables via the environment. First, find out what distutils is using as defaults:
```
>>> from distutils import sysconfig
>>> sysconfig.get_config_var('LDSHARED')
'gcc-4.0 -Wl,-F. -bundle -undefined dynamic_lookup'
>>> sysconfig.get_config_var('CC... |
How to execute multi-line statements within Python's own debugger (PDB) | 5,967,241 | 72 | 2011-05-11T16:01:28Z | 5,967,631 | 15 | 2011-05-11T16:33:08Z | [
"python",
"debugging",
"multiline",
"pdb"
] | So I am running a Python script within which I am calling Python's debugger, PDB by writing:
```
import ipdb; ipdb.set_trace()
```
(iPython's version of PDB, though for the matter I don't think it makes a difference; I use it for the colored output only).
Now, when I get to the debugger I want to execute a multi-lin... | Inside the Python (2.7.1) interpreter or debugger (import pdb), you can execute a multi-line statement with the following syntax.
```
for i in range(5): print("Hello"); print("World"); print(i)
```
Note: When I'm inside the interpreter, I have to hit return twice before the code will execute. Inside the debugger, how... |
How to execute multi-line statements within Python's own debugger (PDB) | 5,967,241 | 72 | 2011-05-11T16:01:28Z | 8,387,484 | 120 | 2011-12-05T15:16:03Z | [
"python",
"debugging",
"multiline",
"pdb"
] | So I am running a Python script within which I am calling Python's debugger, PDB by writing:
```
import ipdb; ipdb.set_trace()
```
(iPython's version of PDB, though for the matter I don't think it makes a difference; I use it for the colored output only).
Now, when I get to the debugger I want to execute a multi-lin... | You could do this while in pdb to launch a temporary interactive Python session with all the local variables available:
```
(pdb) !import code; code.interact(local=vars())
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(Int... |
Python bytearray ignoring encoding? | 5,969,014 | 3 | 2011-05-11T18:42:11Z | 5,969,242 | 8 | 2011-05-11T19:00:22Z | [
"python"
] | I've got a chunk of code that reads binary data off a string buffer (`StringIO` object), and tries to convert it to a `bytearray` object, but it's throwing errors when the value is greater than 127, which the ascii encoding can't handle, even when I'm trying to override it:
```
file = open(filename, 'r+b')
file.seek(o... | When converting a string to another encoding, its original encoding is taken to be ASCII if it is a `str` or Unicode if it is a `unicode` object. When creating the `bytearray`, the `encoding` parameter is required only if the string is `unicode`. Just don't specify an encoding and you will get the results you want. |
How to SWIG in VS2010? | 5,969,173 | 5 | 2011-05-11T18:53:43Z | 6,117,641 | 11 | 2011-05-24T22:24:09Z | [
"c++",
"python",
"visual-studio-2010",
"swig"
] | Hey Everybody,
I'm trying to SWIG a multi file project that I made in VS2010 (c++) to python. I've managed to link the Python26.lib file, and have SWIG generating a wrapper .cpp file for my main .cpp file. I've set my code to build a .dll with the extension .pyd.
This is the .i file I have currently:
```
%module Hive... | Ok, I'm using swig and VS2010 with no problems...
In your case, it looks more like you have problems with linking. Beyond the check of libraries, dont forget to check 32-64 bit libraries you are linking. Try to link all as x86 target as fail-safe. And don't use **AnyCpu**.
---
**How to use SWIG under VS2010.**
lets... |
Print all properties of a Python Class | 5,969,806 | 60 | 2011-05-11T19:51:36Z | 5,969,930 | 117 | 2011-05-11T20:01:40Z | [
"python",
"oop"
] | I have a class Animal with several properties like:
```
class Animal(object):
def __init__(self):
self.legs = 2
self.name = 'Dog'
self.color= 'Spotted'
self.smell= 'Alot'
self.age = 10
self.kids = 0
#many more...
```
I now want to print all these properties... | In this simple case you can use [`vars()`](https://docs.python.org/2/library/functions.html#vars):
```
an = Animal()
attrs = vars(an)
# {'kids': 0, 'name': 'Dog', 'color': 'Spotted', 'age': 10, 'legs': 2, 'smell': 'Alot'}
# now dump this in some way or another
print ', '.join("%s: %s" % item for item in attrs.items())... |
Print all properties of a Python Class | 5,969,806 | 60 | 2011-05-11T19:51:36Z | 5,970,005 | 18 | 2011-05-11T20:09:05Z | [
"python",
"oop"
] | I have a class Animal with several properties like:
```
class Animal(object):
def __init__(self):
self.legs = 2
self.name = 'Dog'
self.color= 'Spotted'
self.smell= 'Alot'
self.age = 10
self.kids = 0
#many more...
```
I now want to print all these properties... | Maybe you are looking for something like this?
```
>>> class MyTest:
def __init__ (self):
self.value = 3
>>> myobj = MyTest()
>>> myobj.__dict__
{'value': 3}
``` |
Print all properties of a Python Class | 5,969,806 | 60 | 2011-05-11T19:51:36Z | 5,970,022 | 27 | 2011-05-11T20:10:30Z | [
"python",
"oop"
] | I have a class Animal with several properties like:
```
class Animal(object):
def __init__(self):
self.legs = 2
self.name = 'Dog'
self.color= 'Spotted'
self.smell= 'Alot'
self.age = 10
self.kids = 0
#many more...
```
I now want to print all these properties... | Another way is to call the [`dir()`](https://docs.python.org/2/library/functions.html#dir "dir") function (see [https://docs.python.org/2/library/functions.html#dir](https://docs.python.org/2/library/functions.html#dir "dir")).
```
a = Animal()
dir(a)
>>>
['__class__', '__delattr__', '__dict__', '__doc__', '__forma... |
Removing redundancy when adding items to Python dictionaries | 5,970,161 | 3 | 2011-05-11T20:24:37Z | 5,970,193 | 8 | 2011-05-11T20:27:03Z | [
"python"
] | Suppose you have a dictionary like:
```
my_dict = {'foo' : {'bar' : {}}}
```
And you want to make the following sequence of assignments:
```
my_dict['foo']['bar']['first'] = 1
my_dict['foo']['bar']['second'] = 2
```
Clearly there is some redundancy in the fact that `my_dict['foo']['bar']` is repeated. Is there any ... | Not really, save of course the obvious intermediate variable:
```
foo_bar = my_dict['foo']['bar']
foo_bar['first'] = 1
foo_bar['second'] = 2
```
How is Python supposed to know you want to refer to the same dictionary twice unless you tell it like this? |
How to set environment variables in Python | 5,971,312 | 172 | 2011-05-11T22:25:11Z | 5,971,326 | 210 | 2011-05-11T22:27:16Z | [
"python",
"environment-variables"
] | I need to set some environment variables in the python script and I want all the other scripts that are called from python (shell scripts) which will be child process to see the environment variables set. The value is a number.
If I do `os.environ["DEBUSSY"] = 1`, it complains saying that `1` has to be string.
I also ... | Environment variables must be strings, so use
```
os.environ["DEBUSSY"] = "1"
```
to set the variable `DEBUSSY` to the string `1`. To access this variable later, simply use
```
print os.environ["DEBUSSY"]
```
Child processes automatically inherit the environment of the parent process -- no special action on your pa... |
How to set environment variables in Python | 5,971,312 | 172 | 2011-05-11T22:25:11Z | 5,971,328 | 7 | 2011-05-11T22:27:31Z | [
"python",
"environment-variables"
] | I need to set some environment variables in the python script and I want all the other scripts that are called from python (shell scripts) which will be child process to see the environment variables set. The value is a number.
If I do `os.environ["DEBUSSY"] = 1`, it complains saying that `1` has to be string.
I also ... | What about `os.environ["DEBUSSY"] = '1'`? Environment variables are always strings. |
How to set environment variables in Python | 5,971,312 | 172 | 2011-05-11T22:25:11Z | 5,971,334 | 9 | 2011-05-11T22:28:30Z | [
"python",
"environment-variables"
] | I need to set some environment variables in the python script and I want all the other scripts that are called from python (shell scripts) which will be child process to see the environment variables set. The value is a number.
If I do `os.environ["DEBUSSY"] = 1`, it complains saying that `1` has to be string.
I also ... | > if i do os.environ["DEBUSSY"] = 1, it
> complains saying that 1 has to be
> string.
Then do
```
os.environ["DEBUSSY"] = "1"
```
> I also want to know how to read the
> environment variables in python(in the
> later part of the script) once i set
> it.
Just use `os.environ["DEBUSSY"]`, as in
```
some_value = os.e... |
How to set environment variables in Python | 5,971,312 | 172 | 2011-05-11T22:25:11Z | 5,977,987 | 58 | 2011-05-12T12:29:26Z | [
"python",
"environment-variables"
] | I need to set some environment variables in the python script and I want all the other scripts that are called from python (shell scripts) which will be child process to see the environment variables set. The value is a number.
If I do `os.environ["DEBUSSY"] = 1`, it complains saying that `1` has to be string.
I also ... | You may need to consider some further aspects for code robustness;
when you're storing an integer-valued variable as an environment variable, try
```
os.environ['DEBUSSY'] = str(myintvariable)
```
then for retrieval, consider that to avoid errors, you should try
```
os.environ.get('DEBUSSY', 'Not Set')
```
possibl... |
.write not working in Python | 5,972,277 | 9 | 2011-05-12T01:04:18Z | 5,972,298 | 20 | 2011-05-12T01:08:55Z | [
"python",
"file"
] | I'm fairly new to Python so hopefully I'm just missing something obvious here, but it has me stumped. Snippet of my program below:
```
outFile = open('P4Output.txt', 'w')
outFile.write(output)
print output
print "Output saved to \"P4Output.txt\"\n"
```
output prints correctly to the console, but if I go open up the f... | Did you do f.close() at the end of your program? |
.write not working in Python | 5,972,277 | 9 | 2011-05-12T01:04:18Z | 5,972,302 | 26 | 2011-05-12T01:09:30Z | [
"python",
"file"
] | I'm fairly new to Python so hopefully I'm just missing something obvious here, but it has me stumped. Snippet of my program below:
```
outFile = open('P4Output.txt', 'w')
outFile.write(output)
print output
print "Output saved to \"P4Output.txt\"\n"
```
output prints correctly to the console, but if I go open up the f... | Due to buffering, the string may not actually show up in the file until you call `flush()` or `close()`. So try to call `f.close()` after `f.write()`. Also using `with` with file objects is recommended, it will automatically close the file for you even if you break out of the `with` block early due to an exception or `... |
.write not working in Python | 5,972,277 | 9 | 2011-05-12T01:04:18Z | 5,976,560 | 7 | 2011-05-12T10:22:06Z | [
"python",
"file"
] | I'm fairly new to Python so hopefully I'm just missing something obvious here, but it has me stumped. Snippet of my program below:
```
outFile = open('P4Output.txt', 'w')
outFile.write(output)
print output
print "Output saved to \"P4Output.txt\"\n"
```
output prints correctly to the console, but if I go open up the f... | You need to do a
```
outFile.flush()
```
if you want the buffered contents to be written to the disk.
If you're done writing to the file, a `file.close` call will implicitly flush the buffered data before closing the file. |
Python twisted: iterators and yields/inlineCallbacks | 5,972,664 | 18 | 2011-05-12T02:20:16Z | 5,979,862 | 12 | 2011-05-12T14:48:51Z | [
"python",
"twisted"
] | Folks,
Am thoroughly confused, so it's possible I am not even asking things correctly, but here goes:
I have a twisted application using inlineCallbacks. Now I need to define an iterator which will mean a generator is returned to the caller. However, the iterator cannot be inlineCallbacks decorated, can it be? If not,... | You're right that you can't express what you want to express in `cacheiter`. The `inlineCallbacks` decorator won't let you have a function that returns an iterator. If you decorate a function with it, then the result is a function that always returns a `Deferred`. That's what it is for.
Part of what makes this difficu... |
how to insert some text in all django context using django middleware | 5,973,276 | 9 | 2011-05-12T04:25:26Z | 5,973,587 | 20 | 2011-05-12T05:19:26Z | [
"python",
"django",
"templates"
] | this my middleware code :
```
from django.conf import settings
from django.template import RequestContext
class BeforeFilter(object):
def process_request(self, request):
settings.my_var = 'Hello World'
request.ss = 'ssssssssss'
return None
def process_response(self, request, response):... | To meet your initial goal, I do not think the **BeforeFilter** middle ware is required. What we need is just a [template context processor](https://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors).
Write a context processor as following:
```
#file: context_processors.py
def sample_context_pro... |
Bulkloader CSV size error | 5,973,363 | 10 | 2011-05-12T04:39:40Z | 5,973,638 | 8 | 2011-05-12T05:26:59Z | [
"python",
"google-app-engine",
"bulkloader"
] | Bulkloader raises the following error when importing a CSV file with large cells:
```
[ERROR ] Error in data source thread: field larger than field limit (131072)
```
This is a common problem for the csv module, which can be fixed with:
```
csv.field_size_limit(sys.maxint)
```
How can I make bulkloader execute th... | Try this:
In bulkloader.yaml add:
```
python_preamble:
- import: csv_fix
... # the rest of your imports
```
In csv\_fix.py add:
```
import csv, sys
csv.field_size_limit(sys.maxint)
``` |
SQLAlchemy ordering by count on a many to many relationship | 5,973,553 | 15 | 2011-05-12T05:12:20Z | 5,975,375 | 25 | 2011-05-12T08:33:39Z | [
"python",
"orm",
"sqlalchemy",
"flask",
"flask-sqlalchemy"
] | This is a simplified example of my current models *(I'm using the [Flask SQLAlchemy extension](http://packages.python.org/Flask-SQLAlchemy/))*:
```
like = db.Table(
'like',
db.Column('uid', db.Integer, db.ForeignKey('users.id')),
db.Column('pid', db.Integer, db.ForeignKey('posts.id'))
)
class User(db.Mode... | I haven't used SQLAlchemy much so I figured I'd give it a shot. I didn't try to use your models, I just wrote some new ones (similar enough though):
```
likes = db.Table('likes',
db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
db.Column('post_id', db.Integer, db.ForeignKey('post.id'))
)
class User... |
Python - Avoid passing logger reference between functions? | 5,974,273 | 26 | 2011-05-12T06:42:17Z | 5,974,391 | 23 | 2011-05-12T06:54:36Z | [
"python",
"logging"
] | I have a simple Python script that uses the in-built `logging`.
I'm configuring logging inside a function. Basic structure would be something like this:
```
#!/usr/bin/env python
import logging
import ...
def configure_logging():
logger = logging.getLogger("my logger")
logger.setLevel(logging.DEBUG)
# Fo... | You can either use the root (default) logger, and thus the module level functions `logging.debug`, ... or get your logger in the function using it.
Indeed, the `getLogger` function is a factory-like function with a registery (singleton like), i.e. it always returns the same instance for the given logger name.
You can t... |
Python - Avoid passing logger reference between functions? | 5,974,273 | 26 | 2011-05-12T06:42:17Z | 5,974,475 | 8 | 2011-05-12T07:04:21Z | [
"python",
"logging"
] | I have a simple Python script that uses the in-built `logging`.
I'm configuring logging inside a function. Basic structure would be something like this:
```
#!/usr/bin/env python
import logging
import ...
def configure_logging():
logger = logging.getLogger("my logger")
logger.setLevel(logging.DEBUG)
# Fo... | You can just do :
```
logger = logging.getLogger("my logger")
```
in your `count_parrots()` method. When you pass the name that was used earlier (i.e. "my logger") the logging module would return the same instance that was created corresponding to that name.
Update: From the [logging tutorial](http://docs.python.org... |
Testing Python Scripts | 5,974,557 | 9 | 2011-05-12T07:13:41Z | 5,975,668 | 8 | 2011-05-12T09:01:42Z | [
"python",
"unit-testing",
"tdd"
] | How do I test the STDOUT output of a Python script with a testing framework like doctest, unittest, nose, etc? For example, say running my script "todo.py --list" should return "take out the garbage". I've read someone who separates out the STDOUT printing part of the script from the part that generates the output to b... | I see two ways :
1. Redirect stdout during the unittest:
```
class YourTest(TestCase):
def setUp(self):
self.output = StringIO()
self.saved_stdout = sys.stdout
sys.stdout = self.output
def tearDown(self):
self.output.close()
sys.stdout = self... |
Download all the links(related documents) on a webpage using Python | 5,974,595 | 10 | 2011-05-12T07:17:06Z | 5,976,423 | 16 | 2011-05-12T10:08:06Z | [
"python"
] | I have to download a lot of documents from a webpage. They are wmv files, PDF, BMP etc. Of course, all of them have links to them. So each time, I have to RMC a file, select 'Save Link As' Then save then as type All Files. Is it possible to do this in Python? I search the SO DB and folks have answered question of how t... | Here is an example of how you could download some chosen files from <http://pypi.python.org/pypi/xlwt>
you will need to install mechanize first: <http://wwwsearch.sourceforge.net/mechanize/download.html>
```
import mechanize
from time import sleep
#Make a Browser (think of this as chrome or firefox etc)
br = mechaniz... |
Bring the current Python program to background | 5,975,124 | 17 | 2011-05-12T08:09:37Z | 5,975,185 | 12 | 2011-05-12T08:16:24Z | [
"python",
"linux",
"background"
] | A python script prints information to screen and then should go to background.
How to do that from within the script itself? | Since the shell is waiting for your process to finish, the main process must terminate. You can use `os.fork()` to fork off a child process and `sys.exit()` from the parent process:
```
if os.fork():
sys.exit()
# Child code goes here
``` |
Bring the current Python program to background | 5,975,124 | 17 | 2011-05-12T08:09:37Z | 5,976,352 | 18 | 2011-05-12T10:01:52Z | [
"python",
"linux",
"background"
] | A python script prints information to screen and then should go to background.
How to do that from within the script itself? | Copying related code from [Creating a daemon the Python way](http://code.activestate.com/recipes/278731-creating-a-daemon-the-python-way/); please read the comments as to why that code is quite thought-out.
```
def createDaemon():
"""Detach a process from the controlling terminal and run it in the
background as ... |
nosetests is capturing the output of my print statements. How to circumvent this? | 5,975,194 | 97 | 2011-05-12T08:16:51Z | 5,975,555 | 146 | 2011-05-12T08:49:49Z | [
"python",
"nosetests"
] | When I type
```
$ nosetests -v mytest.py
```
all my print outputs are captured when all tests pass.
I want to see print outputs even everything passes.
So what I'm doing is to force an assertion error to see the output, like this.
```
class MyTest(TestCase):
def setUp(self):
self.debug = False
def... | Either:
```
$ nosetests --nocapture mytest.py
```
Or:
```
$ NOSE_NOCAPTURE=1 nosetests mytests.py
```
(it can also be specified in the `nose.cfg` file, see `nosetests --help`) |
nosetests is capturing the output of my print statements. How to circumvent this? | 5,975,194 | 97 | 2011-05-12T08:16:51Z | 18,977,760 | 8 | 2013-09-24T09:30:37Z | [
"python",
"nosetests"
] | When I type
```
$ nosetests -v mytest.py
```
all my print outputs are captured when all tests pass.
I want to see print outputs even everything passes.
So what I'm doing is to force an assertion error to see the output, like this.
```
class MyTest(TestCase):
def setUp(self):
self.debug = False
def... | Use
```
--nologcapture
```
it worked for me |
How to extract HTTP message body in BaseHTTPRequestHandler.do_POST()? | 5,975,952 | 17 | 2011-05-12T09:27:55Z | 5,976,905 | 42 | 2011-05-12T10:52:03Z | [
"python",
"http",
"post",
"basehttpserver",
"basehttprequesthandler"
] | In the `do_POST()` method of `BaseHTTPRequestHandler` I can access the headers of the POST request simply via the property `self.headers`. But I can't find a similar property for accessing the body of the message. How do I then go about doing that? | You can access POST body in `do_POST` method like this:
```
content_len = int(self.headers.getheader('content-length', 0))
post_body = self.rfile.read(content_len)
``` |
How to install lxml for python without administative rights on linux? | 5,976,030 | 5 | 2011-05-12T09:36:07Z | 5,981,037 | 12 | 2011-05-12T16:12:34Z | [
"python",
"linux",
"lxml"
] | I just need some packages which dont present at the host machine (and I and linux... we... we didn't spend much time together...).
I used to install them like:
```
# from the source
python setup.py install --user
```
or
```
# with easy_install
easy_install prefix=~/.local package
```
But it doesn't work with lxml.... | If you have no admin rights, and cannot convince the administrator to install the relevant packages for you, you have two options:
**Option 1** - Download sources for [`libxml2` and `libxslt`](ftp://xmlsoft.org/libxml2/) and compile and install them under your `$HOME` somewhere, then build python-lxml against those co... |
Is there a convenient way to map a file uri to os.path? | 5,977,576 | 14 | 2011-05-12T11:56:10Z | 5,977,628 | 13 | 2011-05-12T12:00:25Z | [
"python",
"uri",
"filepath"
] | A subsystem which I have no control over insists on providing filesystem paths in the form of a uri. Is there a python module/function which can convert this path into the appropriate form expected by the filesystem in a platform independent manner? | The [urlparse](http://docs.python.org/library/urlparse.html) module provides the path from the URI:
```
import os, urlparse
p = urlparse.urlparse('file://C:/test/doc.txt')
finalPath = os.path.abspath(os.path.join(p.netloc, p.path))
``` |
Is there a convenient way to map a file uri to os.path? | 5,977,576 | 14 | 2011-05-12T11:56:10Z | 15,048,213 | 10 | 2013-02-24T03:04:04Z | [
"python",
"uri",
"filepath"
] | A subsystem which I have no control over insists on providing filesystem paths in the form of a uri. Is there a python module/function which can convert this path into the appropriate form expected by the filesystem in a platform independent manner? | For future readers. The solution from @Jakob Bowyer doesn't convert URL characters to ascii. After a bit of digging I found this solution:
```
>>> import urllib, urlparse
>>> urllib.url2pathname(urlparse.urlparse('file:///home/user/some%20file.txt').path)
'/home/user/some file.txt'
```
EDIT:
Here's what I ended up u... |
Association between naming classes and naming their files in python (convention?) | 5,978,557 | 28 | 2011-05-12T13:18:40Z | 5,978,618 | 32 | 2011-05-12T13:23:30Z | [
"python",
"naming-conventions",
"filenames",
"classname"
] | In python (and some other languages) I have learned, that the name of a class should be written in small letters except for the first letter, which should be a capital letter. Example:
```
class FooBar:
...
```
A class should go in a file, named the same as the class. In this example it would be a file `foobar.py... | What you have presented is the standard convention.
> ## Package and Module Names
>
> Modules should have short, all-lowercase names. Underscores can
> be used in the module name if it improves readability. Python packages
> should also have short, all-lowercase names, although the use of underscores
> is discouraged.... |
Association between naming classes and naming their files in python (convention?) | 5,978,557 | 28 | 2011-05-12T13:18:40Z | 5,978,659 | 8 | 2011-05-12T13:25:55Z | [
"python",
"naming-conventions",
"filenames",
"classname"
] | In python (and some other languages) I have learned, that the name of a class should be written in small letters except for the first letter, which should be a capital letter. Example:
```
class FooBar:
...
```
A class should go in a file, named the same as the class. In this example it would be a file `foobar.py... | PEP 8 says:
> Modules should have short, all-lowercase names. Underscores can be used
> in the module name if it improves readability. Python packages should
> also have short, all-lowercase names, although the use of underscores
> is discouraged.
I'll also note that you shouldn't necessarily have on only one class p... |
Python: detect duplicates using a set | 5,979,071 | 7 | 2011-05-12T13:54:11Z | 5,979,102 | 11 | 2011-05-12T13:56:52Z | [
"python",
"python-3.x",
"set"
] | I have a large number of objects I need to store in memory for processing in Python. Specifically, I'm trying to remove duplicates from a large set of objects. I want to consider two objects "equal" if a certain instance variable in the object is equal. So, I assumed the easiest way to do this would be to insert all my... | You forgot to *also* [define `__eq__()`](http://docs.python.org/reference/datamodel.html#object.__hash__).
> If a class does not define a `__cmp__()` or `__eq__()` method it should not define a `__hash__()` operation either; if it defines `__cmp__()` or `__eq__()` but not `__hash__()`, its instances will not be usable... |
Python - manually install package using virtualenv | 5,979,513 | 53 | 2011-05-12T14:26:37Z | 5,979,776 | 76 | 2011-05-12T14:42:38Z | [
"python",
"installation",
"virtualenv",
"pip",
"virtualenvwrapper"
] | I have a python program I want to install into my virtualenv - it's a zip package that I need to unzip and then run a setup.py program - but my question is more regarding how to get these unzipped files into my virtualenv so that the package gets installed into the virtualenv's site-packages folder?
I can also install... | I typically would extract the program to a temporary folder, then from that folder, run the setup.py using the direct path to the virtualenv python instance. eg if your virtualenv is in /home/username/virtualpy, use this (from your temporary folder)
```
/home/username/virtualpy/bin/python setup.py install
```
This sh... |
Python: Retrieve items from a set | 5,979,861 | 6 | 2011-05-12T14:48:46Z | 5,980,019 | 8 | 2011-05-12T15:00:19Z | [
"python",
"python-3.x",
"set"
] | In general, Python sets don't seem to be designed for retrieving items by key. That's obviously what dictionaries are for. But is there anyway that, given a key, you can retrieve an instance from a set which is equal to the key?
Again, I know this is exactly what dictionaries are for, but as far as I can see, there ar... | I'd definitely use a dictionary here. Reusing the `firstname` instance variable as a dictionary key won't copy it -- the dictionary will simply use the same object. I doubt a dictionary will use significantly more memory than a set.
To actually save memory, add a `__slots__` attribute to your classes. This will preven... |
How to implement the --verbose or -v option into a script? | 5,980,042 | 48 | 2011-05-12T15:01:39Z | 5,980,173 | 52 | 2011-05-12T15:09:31Z | [
"python",
"option"
] | I know the `--verbose` or `-v` from several tools and I'd like to implement this into some of my own scripts and tools.
I thought of placeing
```
if verbose:
print ...
```
through my source code, so that if a user passes the `-v` option, the variable `verbose` will be set to `True` and the text will be printed.
... | My suggestion is to use a function. But rather than putting the `if` in the function, which you might be tempted to do, do it like this:
```
if verbose:
def verboseprint(*args):
# Print each argument separately so caller doesn't need to
# stuff everything to be printed into a single string
... |
How to implement the --verbose or -v option into a script? | 5,980,042 | 48 | 2011-05-12T15:01:39Z | 5,980,220 | 7 | 2011-05-12T15:12:22Z | [
"python",
"option"
] | I know the `--verbose` or `-v` from several tools and I'd like to implement this into some of my own scripts and tools.
I thought of placeing
```
if verbose:
print ...
```
through my source code, so that if a user passes the `-v` option, the variable `verbose` will be set to `True` and the text will be printed.
... | What I do in my scripts is check at runtime if the 'verbose' option is set, and then set my logging level to debug. If it's not set, I set it to info. This way you don't have 'if verbose' checks all over your code. |
How to implement the --verbose or -v option into a script? | 5,980,042 | 48 | 2011-05-12T15:01:39Z | 15,412,863 | 37 | 2013-03-14T15:04:53Z | [
"python",
"option"
] | I know the `--verbose` or `-v` from several tools and I'd like to implement this into some of my own scripts and tools.
I thought of placeing
```
if verbose:
print ...
```
through my source code, so that if a user passes the `-v` option, the variable `verbose` will be set to `True` and the text will be printed.
... | Use the `logging` module:
```
import logging as log
â¦
args = p.parse_args()
if args.verbose:
log.basicConfig(format="%(levelname)s: %(message)s", level=log.DEBUG)
log.info("Verbose output.")
else:
log.basicConfig(format="%(levelname)s: %(message)s")
log.info("This should be verbose.")
log.warning("This ... |
How to print a linebreak in a python function? | 5,982,206 | 30 | 2011-05-12T17:52:20Z | 5,982,228 | 86 | 2011-05-12T17:53:54Z | [
"python",
"line-breaks"
] | I have a list of strings in my code;
```
A = ['a1', 'a2', 'a3' ...]
B = ['b1', 'b2', 'b3' ...]
```
and I want to print them separated by a linebreak, like this:
```
>a1
b1
>a2
b2
>a3
b3
```
I've tried:
```
print '>' + A + '/n' + B
```
But /n isn't recognized like a line break. | You have your slash backwards, it should be `"\n"` |
How to print a linebreak in a python function? | 5,982,206 | 30 | 2011-05-12T17:52:20Z | 5,982,229 | 19 | 2011-05-12T17:53:55Z | [
"python",
"line-breaks"
] | I have a list of strings in my code;
```
A = ['a1', 'a2', 'a3' ...]
B = ['b1', 'b2', 'b3' ...]
```
and I want to print them separated by a linebreak, like this:
```
>a1
b1
>a2
b2
>a3
b3
```
I've tried:
```
print '>' + A + '/n' + B
```
But /n isn't recognized like a line break. | The newline character is actually `'\n'`. |
How to print a linebreak in a python function? | 5,982,206 | 30 | 2011-05-12T17:52:20Z | 5,982,471 | 7 | 2011-05-12T18:16:09Z | [
"python",
"line-breaks"
] | I have a list of strings in my code;
```
A = ['a1', 'a2', 'a3' ...]
B = ['b1', 'b2', 'b3' ...]
```
and I want to print them separated by a linebreak, like this:
```
>a1
b1
>a2
b2
>a3
b3
```
I've tried:
```
print '>' + A + '/n' + B
```
But /n isn't recognized like a line break. | ```
for pair in zip(A, B):
print ">"+'\n'.join(pair)
``` |
matplotlib basic question | 5,982,774 | 2 | 2011-05-12T18:40:15Z | 5,983,004 | 9 | 2011-05-12T18:58:05Z | [
"python",
"matplotlib"
] | Please forgive my simple question. I have just started to use Matplotlib and I am having some difficulty.
I can run the following with the interpretor without problems:
```
>>> from pylab import *
>>> plot([1,2,3])
>>> show()
```
The above code generates a beautiful graph.
However, if I place the following code... | Looks like you have a file on your Desktop that is shadowing the standard Python `new` module:
```
>>> import new
>>> new
<module 'new' from '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/new.pyc'>
```
Rename or remove `$HOME/Desktop/new.py` and try again. |
python multiprocessing arguments: deep copy? | 5,983,159 | 9 | 2011-05-12T19:10:19Z | 5,983,362 | 7 | 2011-05-12T19:25:22Z | [
"python",
"multiprocessing",
"deep-copy"
] | ```
from multiprocessing import Process
# c is a container
p = Process(target = f, args = (c,))
p.start()
```
I assume a deep copy of `c` is passed to function `f` because shallow copy would make no sense in the case of a new process (the new process doesn't have access to the data from the calling process).
But how ... | When you create a `Process` instance, under the hood Python issues a `fork()`. This creates a child process whose memory space is an exact copy of its parent -- so *everything existing at the time of the fork is copied*.
On Linux this is made efficient through "copy-on-write". From the [fork man page](http://linux.die... |
Eggs in path before PYTHONPATH environment variable | 5,984,523 | 11 | 2011-05-12T21:10:01Z | 5,987,359 | 11 | 2011-05-13T04:52:29Z | [
"python",
"setuptools",
"easy-install"
] | If I have packages installed from *easy\_install*, the eggs are prepended to `sys.path` before the items in the `PYTHONPATH` variable.
For example, if I have an egg package called *foo* installed as well as a package called *foo* in the current directory, and then do this:
```
PYTHONPATH="." python
>>> import foo
```... | Unfortunately this is done with a hard-coded template deep inside `setuptools/command/easy_install.py`. You could create a patched setuptools with an edited template, but I've found no clean way to extend easy\_install from the outside.
Each time easy\_install runs it will regenerate the file `easy_install.pth`. Here ... |
python re.sub group: number after \number | 5,984,633 | 59 | 2011-05-12T21:22:24Z | 5,984,688 | 108 | 2011-05-12T21:28:30Z | [
"python",
"regex",
"numbers",
"group"
] | How can I replace 'foobar' to 'foo123bar'?
This doesn't work:
```
>>> re.sub(r'(foo)', r'\1123', 'foobar')
'J3bar'
```
This works:
```
>>> re.sub(r'(foo)', r'\1hi', 'foobar')
'foohibar'
```
I think it's a common issue: number after \number. Anyone can give me a point on how to handle this? | The answer is:
```
re.sub(r'(foo)', r'\g<1>123', 'foobar')
```
Relevant excerpt from the docs:
> In addition to character escapes and
> backreferences as described above,
> \g will use the substring
> matched by the group named name, as
> defined by the (?P...) syntax.
> \g uses the corresponding
> group number; \g<... |
Python distutils gcc path | 5,986,256 | 7 | 2011-05-13T01:10:24Z | 5,986,692 | 14 | 2011-05-13T02:33:49Z | [
"python",
"compilation",
"distutils"
] | I'm trying to cross-compile the pycrypto package, and I'm getting closer and closer however, I've hit an issue I just can't figure out.
I want distutils to use the cross-compile specific gcc- so I set the CC env var and it seems to respect the setting for the first invocation of the compiler, but thats it.
```
export... | This sounds similar to another answer I recently gave for [customizing the distutils compiler](http://stackoverflow.com/questions/5967065/python-distutils-not-using-correct-version-of-gcc/5968410#5968410). You'll also need to define `LDSHARED` which is the command used to produce the final shared object. See if this wo... |
function is not defined error in Python | 5,986,860 | 9 | 2011-05-13T03:05:17Z | 5,986,866 | 15 | 2011-05-13T03:07:47Z | [
"python",
"function"
] | I am trying to define a basic function in python but I always get the following error when I run a simple test program;
```
>>> pyth_test(1, 2)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
pyth_test(1, 2)
NameError: name 'pyth_test' is not defined
```
Here is the code I am using f... | Yes, but in what file is `pyth_test`'s definition declared in? Is it also located before it's called?
Edit:
To put it into perspective, create a file called `test.py` with the following contents:
```
def pyth_test (x1, x2):
print x1 + x2
pyth_test(1,2)
```
Now run the following command:
```
python test.py
```... |
Should I return an empty dict instead of None? | 5,987,011 | 12 | 2011-05-13T03:36:23Z | 5,987,027 | 15 | 2011-05-13T03:41:33Z | [
"python"
] | I have a method that currently returns `None` or a `dict`.
```
result,error = o.apply('grammar')
```
The caller currently has to check for the existence of two keys to decide what kind of object was returned.
```
if 'imperial' in result:
# yay
elif 'west' in result:
# yahoo
else:
# something wrong?
```
... | Yes I think returning an empty dict (or where applicable an empty list) is preferable to returning None as this avoids an additional check in the client code.
EDIT:
Adding some code sample to elaborate:
```
def result_none(choice):
mydict = {}
if choice == 'a':
mydict['x'] = 100
mydict['y'] ... |
Missing expected output | 5,987,143 | 3 | 2011-05-13T04:10:41Z | 5,987,159 | 8 | 2011-05-13T04:13:47Z | [
"python"
] | I am trying to run this file from the ebook *Learning Python The Hard Way* with the "python ex18.py" command, but it is not outputting anything. What's wrong?
```
# this one is like your scripts with argv
def print_two(*args):
arg1, arg2 = args
print "arg1: %r, arg2: %r" % (arg1, arg2)
# ok, that *args is act... | Because that file doesn't actually *call* any functions, there's nothing to output.
That file just defines four functions and then does nothing with them. :)
Try adding *calls* to `print_none`, `print_one`, and so forth:
```
print_none()
print_one("hello")
print_two("hello", "world")
print_two_again("hello", "world"... |
Python 3.2 question | 5,988,295 | 9 | 2011-05-13T06:52:11Z | 5,988,381 | 9 | 2011-05-13T07:00:05Z | [
"python",
"urllib"
] | I am using Python 3.2. I can import "urllib" library just like with 2.x version. But I can't find methods such as urlopen, urlretrieve, etc. What gives? How do I retrieve a webpage on v3.2?
I have tried to import urllib2 and urllib3 libraries. But my machine says it can't find those modules so not importable. Why thes... | You should use `urllib.request`. Example [here](http://docs.python.org/py3k/library/urllib.request.html#examples). |
PyCharm: DJANGO_SETTINGS_MODULE is undefined | 5,988,597 | 12 | 2011-05-13T07:23:23Z | 10,640,950 | 14 | 2012-05-17T17:55:38Z | [
"python",
"django",
"environment-variables",
"pycharm"
] | I am using PyCharm IDE and when I run any `file.py` I get this error:
> ..raise ImportError("Settings cannot be imported, because environment
> variable %s is undefined." % ENVIRONMENT\_VARIABLE) ImportError:
> Settings cannot be imported, because environment variable
> DJANGO\_SETTINGS\_MODULE is undefined.
How to c... | I had the same problem. The settings of my django support was empty:
 |
How vertical bars literal determine the formal regular expression in python? | 5,988,617 | 5 | 2011-05-13T07:25:31Z | 5,988,678 | 7 | 2011-05-13T07:30:51Z | [
"python",
"regex"
] | According to the python doc, vertical bars literal are used as an 'or' operator. It matches A|B,where A and B can be arbitrary REs.
For example, if the regular expression is as following:
ABC|DEFï¼it matches strings like these:
"ABC", "DEF"
But what if I want to match strings as following:
"ABCF", "ADEF"
Perhaps ... | These will work:
```
A(BC|DE)F
A(?:BC|DE)F
```
The difference is the number of groups generated: 1 with the first, 0 with the second.
Yours will match either `ABC` or `DEF`, with 2 groups, one containing nothing and the other containing the matched fragment (`BC` or `DE`). |
Pipe character in Python | 5,988,665 | 34 | 2011-05-13T07:29:26Z | 5,988,687 | 38 | 2011-05-13T07:31:33Z | [
"python",
"pipe",
"bitwise-operators"
] | I see a "pipe" character (`|`) used in a function call:
```
res = c1.create(go, come, swim, "", startTime, endTime, "OK", ax|bx)
```
What is the meaning of the pipe in `ax|bx`? | It is a *bitwise OR* of integers. For example, if one or both of `ax` or `bx` are `1`, this evaluates to `1`, otherwise to `0`. It also works on other integers, for example `15 | 128 = 143`, i.e. `00001111 | 10000000 = 10001111` in binary. |
Pipe character in Python | 5,988,665 | 34 | 2011-05-13T07:29:26Z | 5,988,712 | 8 | 2011-05-13T07:33:59Z | [
"python",
"pipe",
"bitwise-operators"
] | I see a "pipe" character (`|`) used in a function call:
```
res = c1.create(go, come, swim, "", startTime, endTime, "OK", ax|bx)
```
What is the meaning of the pipe in `ax|bx`? | [Bitwise OR](http://docs.python.org/reference/expressions.html#binary-bitwise-operations). |
Pipe character in Python | 5,988,665 | 34 | 2011-05-13T07:29:26Z | 9,559,187 | 54 | 2012-03-04T21:54:46Z | [
"python",
"pipe",
"bitwise-operators"
] | I see a "pipe" character (`|`) used in a function call:
```
res = c1.create(go, come, swim, "", startTime, endTime, "OK", ax|bx)
```
What is the meaning of the pipe in `ax|bx`? | This is also the union set operator
```
set([1,2]) | set([2,3])
``` |
django forms: change attribute of formfield dynamically | 5,989,293 | 5 | 2011-05-13T08:33:58Z | 5,989,322 | 14 | 2011-05-13T08:36:58Z | [
"python",
"django",
"django-forms"
] | I have a form like the one below:
```
class ConsentFormTpl(forms.Form):
title = forms.CharField()
message = forms.CharField(widget=EditorWidget,label='Description')
acknowledge = forms.BooleanField(label="Require acknowledgement?")
deadline = forms.DateField(widget=CalendarTimeWidget,label="Acknowledg... | The fields aren't available as attributes on the form instance. They're available as dictionary elements in `self.fields`. So:
```
self.fields['acknowledge'].required = False
```
and so on. |
numpy on multicore hardware | 5,991,014 | 15 | 2011-05-13T11:09:00Z | 5,996,170 | 7 | 2011-05-13T18:28:41Z | [
"python",
"performance",
"numpy",
"multicore",
"linear-algebra"
] | What's the state of the art with regards to getting `numpy` to use mutliple cores (on Intel hardware) for things like inner and outer vector products, vector-matrix multiplications etc?
I am happy to rebuild `numpy` if necessary, but at this point I am looking at ways to speed things up without changing my code.
For ... | You should probably start by checking whether the Atlas build that numpy is using has been built with multi-threading. You can build and run this to inspect the Atlas configuration (straight from the Atlas FAQ):
```
main()
/*
* Compile, link and run with something like:
* gcc -o xprint_buildinfo -L[ATLAS lib dir]... |
Is it possible to have multiple PyPlot windows? Or am I limited to subplots? | 5,993,206 | 11 | 2011-05-13T14:13:39Z | 5,993,463 | 17 | 2011-05-13T14:33:00Z | [
"python",
"matplotlib"
] | I'm not sure how to word my question more clearly. Basically, is PyPlot limited to one instance/window? Any hack or workaround I try either causes my program to freeze or for the second pyplot window to be queued until the first one is closed. | Sure, just open a new figure:
```
import matplotlib.pyplot as plt
plt.plot(range(10))
plt.figure()
plt.plot(range(10), 'ro-')
plt.show()
```
If you're running this in the default python interpreter, this won't work, as each figure needs to enter the gui's mainloop. If you want to run things in an interactive shell... |
Fastest way to search a list in python | 5,993,621 | 8 | 2011-05-13T14:45:38Z | 5,993,659 | 29 | 2011-05-13T14:47:53Z | [
"python",
"list",
"search",
"find",
"set"
] | When you do something like `"test" in a` where `a` is a list does python do a sequential search on the list or does it create a hash table representation to optimize the lookup? In the application I need this for I'll be doing a lot of lookups on the list so would it be best to do something like `b = set(a)` and then `... | > Also note that the list of values I'll have won't have duplicate data and I don't actually care about the order it's in; I just need to be able to check for the existence of a value.
Don't use a list, use a [`set()`](http://docs.python.org/library/stdtypes.html#set-types-set-frozenset) instead. It has exactly the pr... |
Fastest way to search a list in python | 5,993,621 | 8 | 2011-05-13T14:45:38Z | 5,993,671 | 7 | 2011-05-13T14:48:50Z | [
"python",
"list",
"search",
"find",
"set"
] | When you do something like `"test" in a` where `a` is a list does python do a sequential search on the list or does it create a hash table representation to optimize the lookup? In the application I need this for I'll be doing a lot of lookups on the list so would it be best to do something like `b = set(a)` and then `... | `"test" in a` with a list `a` will do a linear search. Setting up a hash table on the fly would be much more expensive than a linear search. `"test" in b` on the other hand will do an amoirtised O(1) hash look-up.
In the case you describe, there doesn't seem to be a reason to use a list over a set. |
MySQLdb is extremely slow with large result sets | 5,994,363 | 7 | 2011-05-13T15:42:59Z | 5,994,545 | 12 | 2011-05-13T15:56:08Z | [
"python",
"mysql-python"
] | I executed the following query both in phpMyAdmin & MySQLdb (python).
```
SELECT *, (SELECT CONCAT(`id`, '|', `name`, '|', `image_code`)
FROM `model_artist` WHERE `id` = `artist_id`) as artist_data,
FIND_IN_SET("metallica", `searchable_words`) as find_0
FROM `model_song` HAVING find_0
```
phpMyAdmin said the query t... | If you expect an SQL query to have a large result set which you then plan to iterate over record-by-record, then you may want to consider using the [MySQLdb SSCursor](http://mysql-python.sourceforge.net/MySQLdb-1.2.2/public/MySQLdb.cursors.SSCursor-class.html) instead of the default cursor. The default cursor stores th... |
Changing South Migration Directory | 5,994,420 | 9 | 2011-05-13T15:46:38Z | 5,997,223 | 11 | 2011-05-13T20:11:01Z | [
"python",
"django",
"django-orm",
"django-south"
] | How do you change the location where South looks for an app's migrations?
By default, South assumes an app's migrations are in /migrations. However, I've migrated the model of a third-party package which is installed at /usr/local/lib/python-2.6/dist-packages/, so South is looking for migrations there, instead of the ... | In settings.py:
```
SOUTH_MIGRATION_MODULES = {
'books': 'myproject.app_name.migrations',
}
``` |
How to change the user and group permissions for a directory, by name? | 5,994,840 | 28 | 2011-05-13T16:18:58Z | 5,995,007 | 66 | 2011-05-13T16:31:27Z | [
"python",
"operating-system",
"chown"
] | [os.chown](http://docs.python.org/library/os.html#os.chown) is exactly what I want, but I want to specify the user and group by name, not ID (I don't know what they are). How can I do that? | ```
import pwd
import grp
import os
uid = pwd.getpwnam("nobody").pw_uid
gid = grp.getgrnam("nogroup").gr_gid
path = '/tmp/f.txt'
os.chown(path, uid, gid)
``` |
How to change the user and group permissions for a directory, by name? | 5,994,840 | 28 | 2011-05-13T16:18:58Z | 28,145,810 | 9 | 2015-01-26T06:53:37Z | [
"python",
"operating-system",
"chown"
] | [os.chown](http://docs.python.org/library/os.html#os.chown) is exactly what I want, but I want to specify the user and group by name, not ID (I don't know what they are). How can I do that? | Since Python 3.3
<https://docs.python.org/3.3/library/shutil.html#shutil.chown>
```
import shutil
shutil.chown(path, user=None, group=None)
```
Change owner user and/or group of the given path.
user can be a system user name or a uid;
the same applies to group.
At least one argument is required.
Availability: Unix... |
Backpropagation through time | 5,995,485 | 18 | 2011-05-13T17:16:42Z | 5,996,614 | 11 | 2011-05-13T19:08:11Z | [
"java",
".net",
"python",
"f#",
"neural-network"
] | Does anyone know of a library with a working implementation of backpropagation through time?
Any of Java/Python/C#/VB.NET/F# (preferably the last one) will do! | Assuming you're already using some library for BP, it should be (TM) rather straightforward to implement BPTT using BP as a step in the process.
The Wikipedia entry for BPTT [1] includes relevant pseudo code.
My own starting point, about 18 years ago, was "The Truck Backer-Upper: An Example of Self-Learning in Neural... |
Python underscore variable | 5,995,572 | 2 | 2011-05-13T17:24:43Z | 5,995,581 | 8 | 2011-05-13T17:25:24Z | [
"python",
"variables",
"underscores"
] | In interactive python, there is the 'continuation variable', the underscore.
```
>>> import netlib
>>> netdev = netlib.netface('eth1')
>>> if netdev.getIP():
... print _
...
10.80.22.100
>>>
```
But using this in a script, it is undefined so this fails:
```
if netdev.getIP(): SetValue('ipaddress', _)
```
Is the... | No. It is only available within the Python REPL. |
Cannot append to a returned list? | 5,996,439 | 2 | 2011-05-13T18:53:03Z | 5,996,456 | 10 | 2011-05-13T18:54:28Z | [
"python"
] | ```
def f():
lst = ['a', 'b', 'c']
return lst[1:]
```
why is `f().append('a') is None == True` even though `f().__class__` is `<type 'list'>` and `f() == ['b', 'c']` | Because `append()` returns `None` and not the list object. Use
```
l = f()
l.append('a')
...
``` |
Efficient way to delete lines from a file in python (and keep the same file name)? | 5,996,616 | 3 | 2011-05-13T19:08:29Z | 5,996,677 | 8 | 2011-05-13T19:14:52Z | [
"python",
"file"
] | My program is keeping a log for the user. If the log ever gets bigger than a set amount, I want to delete the first 20% of lines.
From similar questions, I've seen suggestions to do read in the old file, and write out all the lines I want to keep into a new file. However, my files might be too large to be constantly r... | The general method to achieve this for logfiles is 'rotation' - when the logfiles gets older or hits a certain size, you rename it and start writing a new one.
If you are using [logging](http://docs.python.org/library/logging.html) module, there is even a preconfigured one - [RotatingFileHandler](http://docs.python.org... |
how to make pyinotify to run a program on any modification over a file? | 5,996,768 | 3 | 2011-05-13T19:24:32Z | 5,997,080 | 7 | 2011-05-13T19:53:55Z | [
"python",
"pyinotify"
] | I have to watch for any input given to or any changes that made in the present content over a file, upon any modification i need to run a python program which is located in the same folder.
I tried my best to understand but i'm not able to get any good result.
It would be of great help, if anyone can help me through t... | ```
import pyinotify,subprocess
def onChange(ev):
cmd = ['/bin/echo', 'File', ev.pathname, 'changed']
subprocess.Popen(cmd).communicate()
wm = pyinotify.WatchManager()
wm.add_watch('file.watched', pyinotify.IN_MODIFY, onChange)
notifier = pyinotify.Notifier(wm)
notifier.loop()
```
Replace `cmd` with the comman... |
How to limit a number to be within a specified range? (Python) | 5,996,881 | 24 | 2011-05-13T19:34:57Z | 5,996,939 | 35 | 2011-05-13T19:40:39Z | [
"python",
"max",
"min"
] | I want to limit a number to be within a certain range. Currently, I am doing the following:
```
minN = 1
maxN = 10
n = something() #some return value from a function
n = max(minN, n)
n = min(maxN, n)
```
This keeps it within `minN` and `maxN`, but it doesn't look very nice. How could I do it better?
PS: FYI, I am us... | If you want to be cute, you can do:
```
n = sorted([minN, n, maxN])[1]
``` |
How to limit a number to be within a specified range? (Python) | 5,996,881 | 24 | 2011-05-13T19:34:57Z | 5,996,949 | 32 | 2011-05-13T19:41:14Z | [
"python",
"max",
"min"
] | I want to limit a number to be within a certain range. Currently, I am doing the following:
```
minN = 1
maxN = 10
n = something() #some return value from a function
n = max(minN, n)
n = min(maxN, n)
```
This keeps it within `minN` and `maxN`, but it doesn't look very nice. How could I do it better?
PS: FYI, I am us... | ```
def clamp(n, minn, maxn):
return max(min(maxn, n), minn)
```
or functionally equivalent:
```
clamp = lambda n, minn, maxn: max(min(maxn, n), minn)
```
now, you use:
```
n = clamp(n, 7, 42)
```
or make it perfectly clear:
```
n = minn if n < minn else maxn if n > maxn else n
```
even clearer:
```
def cla... |
How to limit a number to be within a specified range? (Python) | 5,996,881 | 24 | 2011-05-13T19:34:57Z | 24,755,898 | 20 | 2014-07-15T10:32:06Z | [
"python",
"max",
"min"
] | I want to limit a number to be within a certain range. Currently, I am doing the following:
```
minN = 1
maxN = 10
n = something() #some return value from a function
n = max(minN, n)
n = min(maxN, n)
```
This keeps it within `minN` and `maxN`, but it doesn't look very nice. How could I do it better?
PS: FYI, I am us... | Simply use `numpy.clip()` ([doc](http://docs.scipy.org/doc/numpy/reference/generated/numpy.clip.html)):
```
n = np.clip(n, minN, maxN)
```
It also works for whole arrays:
```
my_array = np.clip(my_array, minN, maxN)
``` |
Sort a list of files using Python | 5,997,006 | 2 | 2011-05-13T19:46:22Z | 5,997,091 | 7 | 2011-05-13T19:55:25Z | [
"python",
"sorting",
"pdf-generation"
] | I need to combine a folder full of pdfs into one file. However they must be combined in a certain order. A sample of the file names is:
```
WR_Mapbook__1.pdf
WR_Mapbook__1a.pdf
WR_Mapbook__2.pdf
WR_Mapbook__2a.pdf
WR_Mapbook__3.pdf
WR_Mapbook__3a.pdf
etc...
```
The way that they are sorted in windows expl... | try putting () after pdfList.sort as in:
```
pdfList.sort()
```
The way you've got it written it won't actually sort the list. I grabbed your list of file names stuck them in an array and they sorted in the order you show them. |
Escape double quotes for JSON in Python | 5,997,029 | 19 | 2011-05-13T19:48:35Z | 5,997,083 | 9 | 2011-05-13T19:54:21Z | [
"python",
"string"
] | How can I replace double quotes with a backslash and double quotes in Python?
```
>>> s = 'my string with "double quotes" blablabla'
>>> s.replace('"', '\\"')
'my string with \\"double quotes\\" blablabla'
>>> s.replace('"', '\\\"')
'my string with \\"double quotes\\" blablabla'
```
I would like to get the following:... | ```
>>> s = 'my string with \\"double quotes\\" blablabla'
>>> s
'my string with \\"double quotes\\" blablabla'
>>> print s
my string with \"double quotes\" blablabla
>>>
```
When you just ask for 's' it escapes the \ for you, when you print it, you see the string a more 'raw' state. So now...
```
>>> s = """my strin... |
Escape double quotes for JSON in Python | 5,997,029 | 19 | 2011-05-13T19:48:35Z | 5,997,098 | 50 | 2011-05-13T19:56:51Z | [
"python",
"string"
] | How can I replace double quotes with a backslash and double quotes in Python?
```
>>> s = 'my string with "double quotes" blablabla'
>>> s.replace('"', '\\"')
'my string with \\"double quotes\\" blablabla'
>>> s.replace('"', '\\\"')
'my string with \\"double quotes\\" blablabla'
```
I would like to get the following:... | You should be using the [`json`](http://docs.python.org/library/json.html) module. `json.dumps(string)`. It can also serialize other python data types.
```
import json
>>> s = 'my string with "double quotes" blablabla'
>>> json.dumps(s)
<<< '"my string with \\"double quotes\\" blablabla"'
``` |
Escape double quotes for JSON in Python | 5,997,029 | 19 | 2011-05-13T19:48:35Z | 18,691,212 | 8 | 2013-09-09T03:43:29Z | [
"python",
"string"
] | How can I replace double quotes with a backslash and double quotes in Python?
```
>>> s = 'my string with "double quotes" blablabla'
>>> s.replace('"', '\\"')
'my string with \\"double quotes\\" blablabla'
>>> s.replace('"', '\\\"')
'my string with \\"double quotes\\" blablabla'
```
I would like to get the following:... | Note that you can escape a json array / dictionary by doing json.dumps twice and json.loads twice:
```
>>> a = {'x':1}
>>> b = json.dumps(json.dumps(a))
>>> b
'"{\\"x\\": 1}"'
>>> json.loads(json.loads(b))
{u'x': 1}
``` |
Strange python for syntax, how does this work, whats it called? | 5,997,540 | 4 | 2011-05-13T20:41:17Z | 5,997,557 | 9 | 2011-05-13T20:43:03Z | [
"python",
"generator-expression"
] | ```
print max(3 for i in range(4))
#output is 3
```
Using Python 2.6
The 3 is throwing me off, heres my attempt at explaining whats going on.
for i in range(4) makes a loop that loops 4 times, incrementing i from 0 to 3 at the start of each loop. [no idea what the 3 means in this context...] max() returns the bigges... | This evaluates to:
```
print max([3,3,3,3])
```
... which is an elaborate way to say `print 3`.
`expr for x in xs` is a generator expression. Typically, you would use `x` in `expr`. For example:
`[2*i for i in range(4)] #=> [0, 2, 4, 6]` |
Strange python for syntax, how does this work, whats it called? | 5,997,540 | 4 | 2011-05-13T20:41:17Z | 5,997,566 | 14 | 2011-05-13T20:43:55Z | [
"python",
"generator-expression"
] | ```
print max(3 for i in range(4))
#output is 3
```
Using Python 2.6
The 3 is throwing me off, heres my attempt at explaining whats going on.
for i in range(4) makes a loop that loops 4 times, incrementing i from 0 to 3 at the start of each loop. [no idea what the 3 means in this context...] max() returns the bigges... | `3 for i in range(4)` is a generator that yields 3 four times in a row and `max` takes an iterable and returns the element with the highest value, which is, obviously, three here. |
Is There An Operator To Calculate Percentage In Python? | 5,997,987 | 19 | 2011-05-13T21:30:56Z | 5,998,002 | 13 | 2011-05-13T21:32:17Z | [
"python",
"python-3.x"
] | I've recently learned that the " % " sign is used to calculate the remainder of an integer in Python. However I was unable to determine if there's another operator or method to calculate percent in Python. Like with " / " which will give you the quotient, if you just use a float for one of the integers it will actually... | There is no such operator in Python, but it is trivial to implement on your own. In practice in computing, percentages are not nearly as useful as a modulo, so no language that I can think of implements one. |
Is There An Operator To Calculate Percentage In Python? | 5,997,987 | 19 | 2011-05-13T21:30:56Z | 5,998,010 | 66 | 2011-05-13T21:33:22Z | [
"python",
"python-3.x"
] | I've recently learned that the " % " sign is used to calculate the remainder of an integer in Python. However I was unable to determine if there's another operator or method to calculate percent in Python. Like with " / " which will give you the quotient, if you just use a float for one of the integers it will actually... | You could just divide your two numbers and multiply by 100. Note that this will throw an error if "whole" is 0, as asking what percentage of 0 a number is does not make sense:
```
def percentage(part, whole):
return 100 * float(part)/float(whole)
```
Or if the question you wanted it to answer was "what is 5% of 20"... |
Get current time in milliseconds in Python? | 5,998,245 | 173 | 2011-05-13T22:02:54Z | 5,998,359 | 256 | 2011-05-13T22:21:39Z | [
"python",
"datetime",
"time"
] | How can I get the current time in milliseconds in Python? | For what I needed, here's what I did, based on @samplebias' comment above:
```
import time
millis = int(round(time.time() * 1000))
print millis
```
Quick'n'easy. Thanks all, sorry for the brain fart.
For reuse:
```
import time
current_milli_time = lambda: int(round(time.time() * 1000))
```
Then:
```
>>> current_... |
Get current time in milliseconds in Python? | 5,998,245 | 173 | 2011-05-13T22:02:54Z | 13,200,235 | 35 | 2012-11-02T17:26:33Z | [
"python",
"datetime",
"time"
] | How can I get the current time in milliseconds in Python? | time.time() may only give resolution to the second, the preferred approach for milliseconds is datetime
```
from datetime import datetime
dt = datetime.now()
dt.microsecond
``` |
Get current time in milliseconds in Python? | 5,998,245 | 173 | 2011-05-13T22:02:54Z | 21,858,377 | 7 | 2014-02-18T15:36:20Z | [
"python",
"datetime",
"time"
] | How can I get the current time in milliseconds in Python? | ```
def TimestampMillisec64():
return int((datetime.datetime.utcnow() - datetime.datetime(1970, 1, 1)).total_seconds() * 1000)
``` |
Python - convert comma separated string into reducing string list | 5,998,569 | 7 | 2011-05-13T23:00:16Z | 5,998,672 | 24 | 2011-05-13T23:16:41Z | [
"python"
] | Given a Python string like this:
```
location_in = 'London, Greater London, England, United Kingdom'
```
I would like to convert it into a list like this:
```
location_out = ['London, Greater London, England, United Kingdom',
'Greater London, England, United Kingdom',
'England, United... | ```
location_in = 'London, Greater London, England, United Kingdom'
locations = location_in.split(', ')
location_out = [', '.join(locations[n:]) for n in range(len(locations))]
``` |
Python: Anyway to use map to get first element of a tuple | 5,998,835 | 9 | 2011-05-13T23:47:00Z | 5,998,844 | 13 | 2011-05-13T23:49:09Z | [
"python",
"map-function"
] | I have a tuple of tuples and I want to put the first value in each of the tuples into a set. I thought using map() would be a good way of doing this the only thing is I can't find an easy way to access the first element in the tuple. So for example I have the tuple `((1,), (3,))`. I'd like to do something like `set(map... | Use a list comprehension:
```
data = ((1,), (3,))
print [x[0] for x in data]
``` |
Python: Anyway to use map to get first element of a tuple | 5,998,835 | 9 | 2011-05-13T23:47:00Z | 5,998,894 | 10 | 2011-05-13T23:57:10Z | [
"python",
"map-function"
] | I have a tuple of tuples and I want to put the first value in each of the tuples into a set. I thought using map() would be a good way of doing this the only thing is I can't find an easy way to access the first element in the tuple. So for example I have the tuple `((1,), (3,))`. I'd like to do something like `set(map... | ```
from operator import itemgetter
map(itemgetter(0), ((1,), (3,)))
```
While the list comprehensions are generally more readable, itemgetter is closest to what he asked for.
Timing information:
```
>>> from timeit import Timer
>>> mapped = Timer(setup='from operator import itemgetter\nlst=( ("a",), ("b",), (1,), (... |
Beautifulsoup = extract content within a tag | 5,999,407 | 11 | 2011-05-14T02:15:56Z | 5,999,439 | 13 | 2011-05-14T02:26:53Z | [
"python",
"beautifulsoup"
] | I'd like to extract the content "Hello world". Please note that there are multiples `<table>` and similar `<td colspan="2">` on the page as well.
i tried the following:
```
hello = soup.find(text='Name: ')
hello.findPreviousSiblings
```
But it returned nothing.
Here's the snippet of the code:
```
<table border="0"... | use next instead
```
>>> s = '<table border="0" cellspacing="2" width="800"><tr><td colspan="2"><b>Name: </b>Hello world</td></tr><tr>'
>>> soup = BeautifulSoup(s)
>>> hello = soup.find(text='Name: ')
>>> hello.next
u'Hello world'
```
*next* and *previous* let you move through the document elements in the order they ... |
Can't have a function as a class attribute in Python | 5,999,575 | 9 | 2011-05-14T03:12:57Z | 5,999,599 | 18 | 2011-05-14T03:19:01Z | [
"python",
"class"
] | I want to have a plain old function as a class constant. However, Python "helpfully" turns it into a method for me:
```
class C(object):
a = 17
b = (lambda x : x+1)
print C.a # Works fine for int attributes
print C.b # Uh-oh... is a <unbound method C.<lambda>> now
print C.b(1) # TypeError: unbound me... | staticmethod:
```
class C(object):
a = 17
@staticmethod
def b(x):
return x+1
```
Or:
```
class C(object):
a = 17
b = staticmethod(lambda x : x+1)
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.