text
stringlengths 226
34.5k
|
---|
Why does my socket.makefile object block even after a close?
Question: If I use
[socket.makefile](http://docs.python.org/library/socket.html#socket.socket.makefile)
and then close the file object as well as the underlying socket, then
subsequent calls to `read` will throw an exception, just as I'd want it to.
For example, the following code works as I'd expect:
import socket
from time import sleep
from threading import Thread
ADDR = ("localhost", 4321)
def listener(sock):
client,addr = sock.accept()
sleep(1)
client.close()
sock.close()
server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_sock.bind(ADDR)
server_sock.listen(1)
Thread(target=listener, args=[server_sock]).start()
sock = socket.create_connection(ADDR)
f = sock.makefile("r+b", bufsize=0)
f.close()
sock.close()
f.read(8) # throws an exception, as I'd expect
However, if I make a call to `read` while the file/socket are still open then
that call will block, and **then** if I close the socket, the read method
still doesn't return. In fact, it hangs indefinitely until the socket is
closed on the other end. The following code demonstrates this distressing
behavior:
import socket
from time import sleep
from threading import Thread
ADDR = ("localhost", 4321)
def reader(f):
print("about to read")
print("we read %r" % f.read(8))
print("finished reading")
def listener(sock):
client, addr = sock.accept()
sleep(3)
client.close()
sock.close()
server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_sock.bind(ADDR)
server_sock.listen(1)
Thread(target=listener, args=[server_sock]).start()
sock = socket.create_connection(ADDR)
f = sock.makefile("r+b", bufsize=0)
Thread(target=reader, args=[f]).start()
sleep(1)
print("closing pseudo-file and socket")
f.close()
sock.close()
sleep(1)
print("we still haven't finished reading!")
This is a serious problem for me, since I'd like to make a blocking call to
`f.read` in a thread, but then still be able to close the socket and have the
thread return from that call (possibly by throwing an exception) and exit.
However, all that happens is that the call blocks forever so long as the other
side never closes the socket.
So is there any way for `Thread1` to call `read` on the file-like object
created by `socket.makefile` and then have `Thread2` shut down the socket in a
way that causes `Thread1` to stop blocking on its `read` call?
**EDIT:** I tried re-writing my program to entirely use `gevent` and its
socket and Greenlet approach to multithreading, but my program still does
exactly the same thing:
from gevent import sleep, socket, spawn
ADDR = ("localhost", 4321)
def reader(f):
print("about to read")
print("we read %r" % f.read(8))
print("finished reading")
def listener(sock):
client, addr = sock.accept()
sleep(3)
client.close()
sock.close()
server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_sock.bind(ADDR)
server_sock.listen(1)
spawn(listener, server_sock)
sock = socket.create_connection(ADDR)
f = sock.makefile("r+b", bufsize=0)
spawn(reader, f)
sleep(1)
print("closing pseudo-file and socket")
f.close()
sock.close()
sleep(1)
print("we still haven't finished reading!")
sleep(2)
I was surprised to learn that even using `gevent` sockets, calls to `read`
will block even after the underlying socket is closed. If there's no way to
prevent this, I'll probably just have to accept Thomas' depressing "this is
not possible" answer :(
Answer: In situations like this, I've had success using
[eventlet](http://eventlet.net/ "eventlet") and nowadays,
[gevent](http://www.gevent.org/ "gevent") is doing the same types of things:
'monkey patching' the socket library to use non blocking I/O. Here's an
example of what you could try:
>>> from gevent import monkey; monkey.patch_socket()
>>> import socket
and see how that'd affect your results
|
Python clist widget not returning expected list, returns only the first character of each item
Question: I wrote a simple program to print out all non-hidden files and subdirectories
in a given directory.
I am now trying to migrate my code into a clist widget example I found on
Google. Other than ripping out some unneeded buttons, all I changed was the
top portion to integrate my code, and it partially works except that it only
returns the first character of each file and subdirectory. So I expected this:
Desktop
Downloads
Scripts
textfile.txt
pron.avi
But instead got this:
D
D
S
t
p
Here is the example with the code I changed (really just the first def)
import gtk, os
class CListExample:
# this is the part Thraspic changed (other than safe deletions)
# User clicked the "Add List" button.
def button_add_clicked(self, data):
dirList=os.listdir("/usr/bin")
for item in dirList:
if item[0] != '.':
data.append(item)
data.sort()
return
def __init__(self):
self.flag = 0
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_size_request(250,150)
window.set_title("GtkCList Example")
window.connect("destroy", gtk.mainquit)
vbox = gtk.VBox(gtk.FALSE, 5)
vbox.set_border_width(0)
window.add(vbox)
vbox.show()
scrolled_window = gtk.ScrolledWindow()
scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_ALWAYS)
vbox.pack_start(scrolled_window, gtk.TRUE, gtk.TRUE, 0)
scrolled_window.show()
clist = gtk.CList(1)
# What however is important, is that we set the column widths as
# they will never be right otherwise. Note that the columns are
# numbered from 0 and up (to an anynumber of columns).
clist.set_column_width(0, 150)
# Add the CList widget to the vertical box and show it.
scrolled_window.add(clist)
clist.show()
hbox = gtk.HBox(gtk.FALSE, 0)
vbox.pack_start(hbox, gtk.FALSE, gtk.TRUE, 0)
hbox.show()
button_add = gtk.Button("Add List")
hbox.pack_start(button_add, gtk.TRUE, gtk.TRUE, 0)
# Connect our callbacks to the three buttons
button_add.connect_object("clicked", self.button_add_clicked,
clist)
button_add.show()
# The interface is completely set up so we show the window and
# enter the gtk_main loop.
window.show()
def main():
gtk.mainloop()
return 0
if __name__ == "__main__":
CListExample()
main()
Answer: When you adding data to CList through append method, you must pass a sequence.
Rewrite your code:
def button_add_clicked(self, data):
dirList = os.listdir("/usr/bin")
for item in dirList:
if not item.startswith('.'):
data.append([item])
data.sort()
When you creating CList instance you passes to the constructor number of
collumns. In your example you created CList with one collumn, that's why you
can see only first element (first character) of passed sequence in the append
method.
|
What are some examples of thread-unsafe Python code?
Question: What are some examples of Python code that is not safe to run in a threaded
environment? Examples need not be framework-related -- simple Python examples
and caveats are preferred. Thanks!
Answer: The following function may write to the file / overwrite the file in an
unpredictable way.
import threading
fp = open('f','w')
def work1():
for x in range(10000):
fp.write('1')
def work2():
for x in range(10000):
fp.write('2')
t1 = threading.Thread(target = work1)
t1.daemon = True
t2 = threading.Thread(target = work2)
t2.daemon = True
t1.start()
t2.start()
t1.join()
t2.join()
On the other hand, the locking mechanism here will prevent the file output
from getting mixed up.
import threading
lock = threading.Lock()
fp = open('f','w')
def work1():
with lock:
for x in range(10000):
fp.write('1')
def work2():
with lock:
for x in range(10000):
fp.write('2')
t1 = threading.Thread(target = work1)
t1.daemon = True
t2 = threading.Thread(target = work2)
t2.daemon = True
t1.start()
t2.start()
t1.join()
t2.join()
|
Ordering by a custom model field in django
Question: I am trying to add an additional custom field to a django model. I have been
having quite a hard time figuring out how to do the following, and **I will be
awarding a 150pt bounty for the first fully correct answer** when it becomes
available (after it is available -- see as a reference [Improving
Python/django view code](http://stackoverflow.com/questions/6245755/improving-
python-django-view-code)).
I have the following model, with a custom def that returns a video count for
each user --
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
positions = models.ManyToManyField('Position', through ='PositionTimestamp', blank=True)
def count(self):
from django.db import connection
cursor = connection.cursor()
cursor.execute(
"""SELECT (
SELECT COUNT(*)
FROM videos_video v
WHERE v.uploaded_by_id = p.id
OR EXISTS (
SELECT NULL
FROM videos_videocredit c
WHERE c.video_id = v.id
AND c.profile_id = p.id
)
) AS Total_credits
FROM userprofile_userprofile p
WHERE p.id = %d"""%(int(self.pk))
)
return int(cursor.fetchone()[0])
I want to be able to order by the count, i.e.,
`UserProfile.objects.order_by('count')`. Of course, I can't do that, which is
why I'm asking this question.
Previously, I tried adding a custom model Manager, but the problem with that
was I also need to be able to filter by various criteria of the UserProfile
model: Specifically, I need to be able to do:
`UserProfile.objects.filter(positions=x).order_by('count')`. In addition, I
need to stay in the ORM (cannot have a raw sql output) and I do not want to
put the filtering logic into the SQL, because there are various filters, and
would require several statements.
How exactly would I do this? Thank you.
Answer: My reaction is that you're trying to take a bigger bite than you can chew.
Break it into bite size pieces by giving yourself more primitives to work
with.
You want to create these two pieces separately so you can call on them:
* Does this user get credit for this video? return boolean
* For how many videos does this user get credit? return int
Then use a combination of @property, model managers, querysets, and methods
that make it easiest to express what you need.
For example you might attach the "credit" to the video model taking a user
parameter, or the user model taking a video parameter, or a "credit" manager
on users which adds a count of videos for which they have credit.
It's not trivial, but shouldn't be too tricky if you work for it.
|
lxml.etree.iterparse closes input file handler?
Question: filterous is
[using](https://github.com/l0b0/filterous/blob/cc172cc54bd068a5f1de231e3567f4fe0bb5d2d1/filterous/filterous.py#L262)
`iterparse` to parse a simple [XML `StringIO`
object](https://github.com/l0b0/filterous/blob/cc172cc54bd068a5f1de231e3567f4fe0bb5d2d1/tests/tests.py#L56)
in a [unit
test](https://github.com/l0b0/filterous/blob/cc172cc54bd068a5f1de231e3567f4fe0bb5d2d1/tests/tests.py#L139).
However, when trying to access the `StringIO` object afterwards, Python exits
with a "`ValueError: I/O operation on closed file`" message. According to the
[`iterparse` documentation](http://lxml.de/parsing.html#iterparse-and-
iterwalk), "Starting with lxml 2.3, the .close() method will also be called in
the error case," but I get no error message or `Exception` from `iterparse`.
My IO-foo is obviously not up to speed, so does anyone have suggestions?
The command and (hopefully) relevant code:
$ python2.6 setup.py test
setup.py:
from setuptools import setup
from filterous import filterous as package
setup(
...
test_suite = 'tests.tests',
tests/tests.py:
from cStringIO import StringIO
import unittest
from filterous import filterous
XML = '''<posts tag="" total="3" ...'''
class TestSearch(unittest.TestCase):
def setUp(self):
self.xml = StringIO(XML)
self.result = StringIO()
...
def test_empty_tag_not(self):
"""Empty tag; should get N results."""
filterous.search(
self.xml,
self.result,
{'ntag': [u'']},
['href'],
False)
self.assertEqual(
len(self.result.getvalue().splitlines()),
self.xml.getvalue().count('<post '))
filterous/filterous.py:
from lxml import etree
...
def search(file_pointer, out, terms, includes, human_readable = True):
...
context = etree.iterparse(file_pointer, tag='posts')
Traceback:
ERROR: Empty tag; should get N results.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/victor/dev/filterous/tests/tests.py", line 149, in test_empty_tag_not
self.xml.getvalue().count('<post '))
ValueError: I/O operation on closed file
PS: The tests all ran fine on
[2010-07-27](http://pypi.python.org/pypi?%3aaction=display&name=Filterous&version=0.8.2).
Answer: Seems to work fine with `StringIO`, try using that instead of `cStringIO`. No
idea why it's getting closed.
|
python array error
Question: hello I am trying to load coordinates for plotting from a text file and I keep
getting an error I don't understand. The coordinates look like this in the
file `(0.1, 0.0, 0.0), (0.613125, 0.52202, 0.19919)` Here is the code I am
trying to run:
from visual import *
with open ('/Desktop/Coordlist2.txt','r') as open_file:
rightFace = curve(pos=[(1,-1,-1), (1,-1,1), (1,-1,-1),(1,1,-1),(1,1,-1),(1,1,1),(1,1,1),(1,-1,1)], radius=0.01, color=color.cyan)
backFace = curve(pos=[(1,-1,-1), (-1,-1,-1), (-1,-1,-1),(-1,1,-1),(-1,1,-1),(1,1,-1)], radius=0.01, color=color.cyan)
leftFace = curve(pos=[(-1,-1,-1), (-1,-1,1), (-1,-1,1),(-1,1,1),(-1,1,1),(-1,1,-1)], radius=0.01, color=color.cyan)
frontFace = curve(pos=[(-1,-1,1), (1,-1,1), (1,1,1),(-1,1,1)], radius=0.01, color=color.cyan)
for line in open_file.readlines():
coords = line
points(pos=[coords], size=1, color=color.yellow)
This is the error message I am getting:
Traceback (most recent call last):
File "/Users/Graphs.py", line 15, in <module>
points(pos=[coords], size=1, color=color.yellow)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/vis/primitives.py", line 84, in __init__
self.process_init_args_from_keyword_dictionary( keywords )
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/vis/primitives.py", line 212, in process_init_args_from_keyword_dictionary
setattr(self, key, value)
ValueError: Object cannot be converted to array.
Any help would be greatly appreciated
Answer: The problem is here:
for line in open_file.readlines():
coords = line
When you read a line from a file, you always get a string. You then have to
process that string to produce whatever data structure you need. So if you
have a line that looks like this (for example)
l = '(5, 6, 7)'
you have to explicitly break it up and create a tuple from it:
l_tuple = tuple(int(n) for n in l.strip('()').split(','))
Also, as agf reminded me, you should probably just do `for line in open_file`;
`open_file.readlines` creates a copy of the file in memory, while `for line in
open_file` just iterates over the lines individually, without copying the
entire file into memory.
Just to be as complete as possible, to convert a string that looks like this:
s = '(0.1, 0.0, 0.0), (0.613125, 0.52202, 0.19919)'
You can do this:
>>> numbers = tuple(float(n.strip('( )')) for n in s.split(','))
>>> t1, t2 = numbers[:3], numbers[3:]
This works as long as there are always two tuples of 3 per line.
agf's solution in his comment works too, but it's a bit more brittle, since
the tuples _must_ be separated by `'), ('` exactly. To tell the truth,
Ignacio's solution is really the best. :)
|
How do I iterate over a SQLite database using the Python API?
Question: Basically I want to be able to choose an amount of numbers using for x...in
range(y amount of numbers) and inject them into an SQLite database. However I
receive the following error:
line 17, in <module>
values (?)""") (number)
sqlite3.ProgrammingError: Incorrect number of bindings supplied.
The current statement uses 1, and there are 0 supplied.
Here is my non functioning code. All input is appreciated.:
import sqlite3
conn = sqlite3.connect("usernames.sqlite")
c = conn.cursor()
c.execute('''create table numbers (number)''')
for number in range(21):
# Insert a row of data
c.execute("""insert into numbers
values (?)"""),(number)
# Save (commit) the changes
conn.commit()
# We can also close the cursor if we are done with it
c.close()
Answer: execute takes a tuple of values in the case of "?" parameters, so you need to
write:
c.execute("""insert into numbers values (?)""", (number,))
`(number,)` is a way to define a tuple with one element.
And by the way, you can do this more efficiently using the
[executemany](http://docs.python.org/library/sqlite3.html#sqlite3.Cursor.executemany)
method:
c.executemany(
"""insert into numbers values (?)""",
[(number,) for number in range(21)]
)
|
problem in installing pypol
Question: I have been trying to install pypol in cygwin. But when I do setup where I
have to type python setup.py install then it displays an error as the
following:
Traceback (most recent call last):
File "setup.py", line 1, in
from setuptools import find_packages, setup, Command
File "/cygdrive/c/pypol_-0.4/setuptools/**init**.py", line 2, in
from setuptools.extension import Extension, Library
File "/cygdrive/c/pypol_-0.4/setuptools/extension.py", line 2, in
from setuptools.dist import _get_unpatched
File "/cygdrive/c/pypol_-0.4/setuptools/dist.py", line 6, in
from setuptools.command.install import install
File "/cygdrive/c/pypol_-0.4/setuptools/command/**init**.py", line 8, in
from setuptools.command import install_scripts
File "/cygdrive/c/pypol_-0.4/setuptools/command/install_scripts.py", line 3,
in
from pkg_resources import Distribution, PathMetadata, ensure_directory
ImportError: No module named pkg_resourceserror
Its clear that some of the modules are missing in my setuptools but I
installed the setuptools again and they are still not there. How do I get out
of this problem? Please help. Thank you.
Answer: [What is causing ImportError: No module named pkg_resources after upgrade of
Python on os X?](http://stackoverflow.com/questions/1756721/what-is-causing-
importerror-no-module-named-pkg-resources-after-upgrade-of-pytho)
is informative. It suggests that you're invoking the wrong version of
`python`. Do you already have `python` installed under Windows?
If you **do** have another version of Python (you can probably check under
cygwin with `which python`) make sure that you're invoking the right one,
which is most easily done by putting its binary path at the beginning of your
`PATH` environmental variable in your `~/.bashrc` or similar.
Then, re-install `setuptools` with the correct python, and everything should
go smoothly.
Really, the linked answer tells you all you need to know, except it's talking
about multiple versions on OSX rather than Windows.
I see that none of your previous questions have an accepted answer, please
click the check mark next to the best answer to your question.
|
flask "hello world" can not run in debug model
Question: I followed official document, installed virtualenv and flask, and then `python
hello.py` But there is something wrong:
* Running on http://127.0.0.1:5000/
* Restarting with reloader: inotify events
Traceback (most recent call last):
File "hello.py", line 9, in <module>
app.run(debug=True)
File "/home/aa/prj/env/lib/python2.7/site-packages/Flask-0.7.2-py2.7.egg/flask/app.py", line 553, in run
return run_simple(host, port, self, **options)
File "/home/aa/prj/env/lib/python2.7/site-packages/Werkzeug-0.7-py2.7.egg/werkzeug/serving.py", line 609, in run_simple
run_with_reloader(inner, extra_files, reloader_interval)
File "/home/aa/prj/env/lib/python2.7/site-packages/Werkzeug-0.7-py2.7.egg/werkzeug/serving.py", line 528, in run_with_reloader
reloader_loop(extra_files, interval)
File "/home/aa/prj/env/lib/python2.7/site-packages/Werkzeug-0.7-py2.7.egg/werkzeug/serving.py", line 436, in reloader_loop
reloader(fnames, interval=interval)
File "/home/aa/prj/env/lib/python2.7/site-packages/Werkzeug-0.7-py2.7.egg/werkzeug/serving.py", line 464, in _reloader_inotify
mask = reduce(lambda m, a: m | getattr(EventsCodes, a), mask, 0)
File "/home/aa/prj/env/lib/python2.7/site-packages/Werkzeug-0.7-py2.7.egg/werkzeug/serving.py", line 464, in <lambda>
mask = reduce(lambda m, a: m | getattr(EventsCodes, a), mask, 0)
AttributeError: type object 'EventsCodes' has no attribute 'IN_DELETE_SELF'
my hello.py:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return "Hello World!"
if __name__ == '__main__':
app.run(debug=True)
but if without debug that's ok? why? my /env/lib/python2.7/site-packages:
distribute-0.6.10-py2.7.egg
Jinja2-2.6-py2.7.egg
Werkzeug-0.7-py2.7.egg
easy-install.pth
pip-0.7.2-py2.7.egg
Answer: This seems to be a bug triggered by a change in pyinotify's API, which you
must also have installed. You could remove pyinotify or use a dirty hack to
force it to use stat() instead of pyinotify. To line 496 of
`werkzeug/serving.py` try adding (below the part where it attempts to import
pyinotify):
# dirty hack
reloader = _reloader_stat_loop
reloader_name = "stat() polling"
Make sure to also report the bug to the [werkzeug](http://werkzeug.pocoo.org/)
developers.
|
save the image in the clipboatd - in Python/Tkinter
Question: the subject says it all: is it possible to take an image present in the
clipboard and save it to file under Tkinter?
Answer: Here is a script that should get let you get arbitrary clipboard data on
windows.
import win32clipboard as clip
# The standard windows clipboard formats
formats = ['CF_OEMTEXT', 'CF_PALETTE', 'CF_TEXT', 'CF_ENHMETAFILE', 'CF_UNICODETEXT',
'CF_BITMAP', 'CF_METAFILEPICT', 'CF_DIB', 'CF_DIBV5']
def getFromClipboard(format):
'""Returns a given type of data from the clipboard.'
data = None
clip.OpenClipboard(0)
if clip.IsClipboardFormatAvailable(format):
data = clip.GetClipboardData(format)
clip.CloseClipboard()
return data
good_formats = []
clip.OpenClipboard(0)
for format in formats:
if clip.IsClipboardFormatAvailable(format):
good_formats.append(format)
clip.CloseClipboard()
# choose among the good formats here
print good_formats
# use the one you picked here
data = getFromClipboard(good_formats[0])
Then `data` will be the raw image data and you can just save it to a file
normally.
<http://msdn.microsoft.com/en-us/library/ms649013%28v=VS.85%29.aspx>
<http://docs.activestate.com/activepython/2.4/pywin32/win32clipboard__GetClipboardData_meth.html>
Provide some information, more is out there.
|
python asynchat: how to store information on individual connections, and how to know when a client disconnects
Question: For fun, I'm writing a minimal IRC server with asynchat. I'm trying to clear
up a few fundamentals (my specific questions follow the code). I've decided
not to use anything in Twisted just so I can implement a little more myself.
First, the code I have:
import asyncore,asynchat
import socket
class Connection(asynchat.async_chat):
def __init__(self, server, sock, addr):
asynchat.async_chat.__init__(self, sock)
self.set_terminator('\n')
self.data = ""
print "client connecting:",addr
# do some IRC protocol initialization stuff here
def collect_incoming_data(self, data):
self.data = self.data + data
def found_terminator(self):
print self.data
self.data = ''
class Server(asyncore.dispatcher):
def __init__(self, host, port):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.bind((host, port))
self.listen(5)
def handle_accept(self):
conn, addr = self.accept()
Connection(self, conn, addr)
def handle_close(self):
self.close()
s = Server('127.0.0.1',5006)
asyncore.loop()
So, in my mind, this code structure is similar to a Twisted client factory:
the `Server` class is initialized once and basically instantiates `Connection`
every time a client connects. First question: is the best way to keep track of
all connected clients by storing all of the Connections in a list within
`Server`?
Also, I don't understand how I am to know when a specific client closes their
connection to my socket? `Connection` implements asynchat (and by extension
asyncore) but adding the handle_close() callback to the `Connection` class
doesn't fire when a client disconnects. It seems to be only for when the bound
socket on the server is destroyed. I don't see any methods for this purpose.
This socket always stays open, whether or not clients connect, right?
Answer: to handle client side closed connections check the handle_error method, does
your client issue a clean close connection? handle_error() :Called when an
exception is raised and not otherwise handled. The default version prints a
condensed traceback.
hope it helps.
|
Untarring in python, interactive vs script call
Question: I am trying to untar a tar file via `popen` (`from platform import popen`) and
am running into problems. The command runs if I use the interactive script,
but does not if I put it in a .py file and run it.
Basically, I change to to that directory and run `popen("tar xvf
the_tar.tar")`
Why would these be different? How come it does not run in the script?
Identical code between the interactive session and the script!
Edit:
The exact script is as follows
import os, time
from platform import popen
os.chdir("C:/testing/")
popen("tar -xvf the_tar.tar")
Answer: You should use the `tarfile` library:
from tarfile import TarFile
tar = TarFile("the_tar.tar")
tar.extractall()
|
Issue with decorator and keyword arguments
Question: I'm using the [decorator](http://pypi.python.org/pypi/decorator) module to
decorate some functions. I want the decorator to be quite general, so I'm
allowing it to have any number of arguments and keyword arguments (as long as
there are more than two arguments):
from decorator import decorator
def wrap(f):
return decorator(_wrap, f)
def _wrap(function, t, f, *args, **kwargs):
print 't=', t
print 'f=', f
print 'args=', args
print 'kwargs=', kwargs
@wrap
def read(a, b, c=False, d=True):
pass
read(1, 2, d=True)
The issue is that the above return:
t= 1
f= 2
args= (False, True)
kwargs= {}
but the `False` and `True` come from `c=` and `d=`, so shouldn't they be in
`kwargs`, i.e.:
t= 1
f= 2
args= (,)
kwargs= {'c':False, 'd':True}
?
Answer: `c` and `d` _are_ positional arguments. Their names are included in the
function object's metadata (because you use `decorator`, it's also preserved
on the wrapper) and therefore you can refer to their names when calling the
function, but they're still positional arguments and specifying them by their
names merely leads to them being put into the correct positions in `args`. And
it works as expected, so why is it an issue?
|
NameError: global name 'thing' is not defined
Question: I don't think there is quite the need for the continued downvoting, I am just
trying to learn here!
One.py
from two import *
ADooDah = Doodah()
something = Thing(ADooDah)
something.DoThis()
something.DoThat
something.DoAnother
if (something.has_done_stuff() == True)
self.SomeFunction
Two.py
class Thing(var):
def __init__(self, var)
self.SomeVar = var
def has_done_stuff(self):
while True:
id, newMessage = SomeVar.get_next_message()
if id == 0:
return true
else:
return false
I get...
Traceback (most recent call last):
File "C:\One.py", line 9, in <module>
has_done_stuff = thing.HasDoneStuff()
NameError: global name 'thing' is not defined
EDITS: The code was indeed peppered with errors. I was trying to show my
situation rather than any real code. Rush typing causes foolish typing. Even
I'm not that bad! Well, most of the time ;) .
I hope the edits make it all make more sense and you fine people can stop
focusing on the crazy syntax errors and explain a bit more about my scope (I
assume) problem. I'm fairly new to Python/IronPython and the rules around
implicit types and scoping I am still in the process of learning!
I have solved my problem though. Thanks. It was fairly unrelated to the above
as it turns out.
Answer:
Something = Thing(ADooDah)
thing.DoThis()
Your `thing` is called `Something`. Also, your class `Thing` has none of the
methods you are calling/not calling (missing parens). This is pretty much non-
sense code.
|
Python File Concatenation
Question: I have a data folder, with subfolders for each subject that ran through a
program. So, for example, in the data folder, there are folders for Bob, Fred,
and Tom. Each one of those folders contains a variety of files and subfolders.
However, I am only interested in the 'summary.log' file contained in each
subject's folder.
I want to concatenate the 'summary.log' file from Bob, Fred, and Tom into a
single log file in the data folder. In addition, I want to add a column to
each log file that will list the subject number.
Is this possible to do in Python? Or is there an easier way to do it? I have
tried a number of different batches of code, but none of them get the job
done. For example,
#!/usr/bin/python
import sys, string, glob, os
fls = glob.glob(r'/Users/slevclab/Desktop/Acceptability Judgement Task/data/*');
outfile = open('summary.log','w');
for x in fls:
file=open(x,'r');
data=file.read();
file.close();
outfile.write(data);
outfile.close();
Gives me the error,
Traceback (most recent call last):
File "fileconcat.py", line 8, in <module>
file=open(x,'r');
IOError: [Errno 21] Is a directory
I think this has to do with the fact that the data folder contains subfolders,
but I don't know how to work around it. I also tried this, but to no avail:
from glob import iglob
import shutil
import os
PATH = r'/Users/slevclab/Desktop/Acceptability Judgement Task/data/*'
destination = open('summary.log', 'wb')
for filename in iglob(os.path.join(PATH, '*.log'))
shutil.copyfileobj(open(filename, 'rb'), destination)
destination.close()
This gives me an "invalid syntax" error at the "for filename" line, but I'm
not sure what to change.
Answer: The syntax is not related to the use of glob. You forget the ":" at the end of
the for statement:
for filename in iglob(os.path.join(PATH, '*.log')):
^--- missing
But the following pattern works :
PATH = r'/Users/slevclab/Desktop/Acceptability Judgement Task/data/*/*.log'
destination = open('summary.log', 'wb')
for filename in iglob(PATH):
shutil.copyfileobj(open(filename, 'rb'), destination)
destination.close()
|
google app engine, python , unicode, email, mail api
Question: I'm using an open source web service python application to send email through
GAE but if the name or email body contains Arabic or Hebrew characters the
application throws some errors (e.g "The indicated parameters are not valid").
Therefore I need to know how to fix this issue. I have to note that I'm a
Python beginner (one week since I started playing with Python).
#
import cgi
import os
import logging
import contextlib
from xml.dom import minidom
from xml.dom.minidom import Document
import exceptions
import warnings
import imghdr
from google.appengine.api import images
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
from google.appengine.api import mail
import wsgiref.handlers
# START Constants
CONTENT_TYPE_HEADER = "Content-Type"
CONTENT_TYPE_TEXT = "text/plain"
XML_CONTENT_TYPE = "application/xml"
XML_ENCODING = "utf-8"
"""
Allows you to specify IP addresses and associated "api_key"s to prevent others from using your app.
Storage and Manipulation methods will check for this "api_key" in the POST/GET params.
Retrieval methods don't use it (however you could enable them to use it, but maybe rewrite so you have a "read" key and a "write" key to prevent others from manipulating your data).
Set "AUTH = False" to disable (allowing anyone use your app and CRUD your data).
To generate a hash/api_key visit https://www.grc.com/passwords.htm
To find your ip visit http://www.whatsmyip.org/
"""
AUTH = False
# END Constants
# START Exception Handling
class Error(StandardError):
pass
class Forbidden(Error):
pass
logging.getLogger().setLevel(logging.DEBUG)
@contextlib.contextmanager
def mailExcpHandler(ctx):
try:
yield {}
except (ValueError), exc:
xml_error_response(ctx, 400 ,'app.invalid_parameters', 'The indicated parameters are not valid: ' + exc.message)
except (Forbidden), exc:
xml_error_response(ctx, 403 ,'app.forbidden', 'You don\'t have permission to perform this action: ' + exc.message)
except (Exception), exc:
xml_error_response(ctx, 500 ,'system.other', 'An unexpected error in the web service has happened: ' + exc.message)
def xml_error_response(ctx, status, error_id, error_msg):
ctx.error(status)
doc = Document()
errorcard = doc.createElement("error")
errorcard.setAttribute("id", error_id)
doc.appendChild(errorcard)
ptext = doc.createTextNode(error_msg)
errorcard.appendChild(ptext)
ctx.response.headers[CONTENT_TYPE_HEADER] = XML_CONTENT_TYPE
ctx.response.out.write(doc.toxml(XML_ENCODING))
# END Exception Handling
# START Helper Methods
def isAuth(ip = None, key = None):
if AUTH == False:
return True
elif AUTH.has_key(ip) and key == AUTH[ip]:
return True
else:
return False
# END Helper Methods
# START Request Handlers
class Send(webapp.RequestHandler):
def post(self):
"""
Sends an email based on POST params. It will queue if resources are unavailable at the time.
Returns "Success"
POST Args:
to: the receipent address
from: the sender address (must be a registered GAE email)
subject: email subject
body: email body content
"""
with mailExcpHandler(self):
# check authorised
if isAuth(self.request.remote_addr,self.request.POST.get('api_key')) == False:
raise Forbidden("Invalid Credentials")
# read data from request
mail_to = str(self.request.POST.get('to'))
mail_from = str(self.request.POST.get('from'))
mail_subject = str(self.request.POST.get('subject'))
mail_plain = str(self.request.POST.get('plain'))
mail_html = str(self.request.POST.get('html'))
message = mail.EmailMessage()
message.sender = mail_from
message.to = mail_to
message.subject = mail_subject
message.body = mail_plain
if mail_html != None and mail_html != "":
message.html = mail_html
message.send()
self.response.headers[CONTENT_TYPE_HEADER] = CONTENT_TYPE_TEXT
self.response.out.write("Success")
# END Request Handlers
# START Application
application = webapp.WSGIApplication([
('/send', Send)
],debug=True)
def main():
run_wsgi_app(application)
if __name__ == '__main__':
main()
# END Application
Answer:
mail_to = str(self.request.POST.get('to'))
mail_from = str(self.request.POST.get('from'))
mail_subject = str(self.request.POST.get('subject'))
mail_plain = str(self.request.POST.get('plain'))
mail_html = str(self.request.POST.get('html'))
I doubt you need to convert them to strings. Try without str(), it could work.
|
improve this very-simple dictionary generator in python
Question: I'm trying to make a simple dict generator. It works but it isn't very
functional yet.
I'd like to improve it by being able to change the max size of the output
without touching the code.
letr='abcdefghijklmnopqrstuvwxyz'
for i in range(len(letr)):
t=letr[i]
print t
for t2 in letr:
print t+t2
for t3 in letr:
print t+t2+t3
for t4 in letr:
print t+t2+t3+t4
for t5 in letr:
print t+t2+t3+t4+t5
Answer:
import itertools
def dict_gen(n):
letr = 'abcdefghijklmnopqrstuvwxyz'
return itertools.chain(''.join(j) for i in range(n)
for j in itertools.product(letr, repeat=i+1))
Usage:
for word in dict_gen(n): # replace n with the max word length you want
print word
Unlike some of the other answers this will include duplicates like your
example ('aa', 'bb', etc).
`dict_gen()` will return a generator, but you can always just pass it into
`list()` if you need to access elements by index:
>>> words = list(dict_gen(5))
>>> len(words) == 26 + 26**2 + 26**3 + 26**4 + 26**5 # verify correct length
True
>>> words[20:30] # transition from one letter to two letters
['u', 'v', 'w', 'x', 'y', 'z', 'aa', 'ab', 'ac', 'ad']
>>> words[-10:] # last 10 elements
['zzzzq', 'zzzzr', 'zzzzs', 'zzzzt', 'zzzzu', 'zzzzv', 'zzzzw', 'zzzzx', 'zzzzy', 'zzzzz']
|
Is there a simple way to match a value in a csv file using python?
Question: Is there a simple way to match a value in a given field of a csv file using
python without using a regex? I have a field in a csv file that contains text.
I wish to write a python script to do stuff to all the fields that contain the
text 'eagle' in a file called file.csv.
For example:
import csv
with open('file.csv', mode='r') as infile:
reader = csv.reader(infile)
for row in reader:
match = row[3]
if match == 'eagle':
DO STUFF
The above code does not work. How can I DO STUFF with all the row[3] values
that match the string 'eagle'? Thanks for the help!
EDIT: here are some examples lines from 'file.csv'
tree,rock,10000,eagle
plant,stone,500,owl
seed,boulder,7000,crane
fruit,pebble,60000000,hawk
I wish to match row[3] from line 1 and 4, then DO STUFF.
Answer: It works on my machine.
bash-4.1$ cat > file.csv
tree,rock,10000,eagle
plant,stone,500,owl
seed,boulder,7000,crane
fruit,pebble,60000000,hawk
bash-4.1$ python
Python 2.7 (r27:82500, Sep 16 2010, 18:03:06)
[GCC 4.5.1 20100907 (Red Hat 4.5.1-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import csv
>>>
>>> with open('file.csv', mode='r') as infile:
... reader = csv.reader(infile)
... for row in reader:
... match = row[3]
... if match == 'eagle':
... print(repr(match))
...
'eagle'
|
Parent resides in datastore, assign children uploaded using CSV bulkloader
Question: Presently I have a `Team` residing in the datastore:
team = Team.get_by_key_name('Plants')
And I have the following CSV file in my local computer:
name,level
Pea Shooter,1
Threepeater,3
Melon-pult,20
My `bulkloader.yaml` looks like this:
python_preamble:
- import: models
- import: my_transforms
transformers:
- kind: Character
connector: csv
property_map:
- property: name
external_name: name
- property: level
external_name: level
import_transform: my_transforms.transform_integer
I wrote a `models.py` that looks like this:
from google.appengine.ext import db
class Team(db.Model):
name = db.StringProperty()
class Character(db.Model):
name = db.StringProperty()
level = db.IntegerProperty()
I also wrote a `my_transforms.py`:
def transform_integer(integer_string):
return int(integer_string)
**Question:** How do I upload the CSV file so that when the `Character`s enter
the datastore, their `parent` properties are assigned to `team`?
Answer: The first answer lacks detail but I was able to glean some information from
it.
I added another column to my CSV file named `Character.csv`:
team,name,level
Plants,Pea Shooter,1
Plants,Threepeater,3
Plants,Melon-pult,20
The `bulkloader.yaml` now looks like this:
python_preamble:
- import: models
- import: my_transforms
transformers:
- kind: Character
connector: csv
property_map:
- property: __key__
external_name: team
import_transform: transform.create_deep_key(('Team', 'team', False),
('Character', 'name', False))
- property: name
external_name: name
- property: level
external_name: level
import_transform: my_transforms.transform_integer
Then I do the following in the Terminal:
$ cd /path/to/app
$ appcfg.py upload_data --config_file=bulkloader.yaml \
--filename=Character.csv \
--kind=Character \
--url=http://localhost:8082/_ah/remote_api
|
Boost.Python: Calling virtual functions from C++
Question: I'm not looking for help on _exposing_ virtual functions to Python, I would
like to know how I can call the said virtual functions from the C++ side.
Consider this...
// ====================
// C++ code
// --------------------
struct Base
{
virtual void func() {
cout << "Hello from C++!";
}
};
BOOST_PYTHON_MODULE(name)
{
// Expose the class and its virtual function here
}
// ====================
// Python code
// --------------------
from name import Base
class Deriv(Base):
def func():
print('Hello from Python!')
Any advice on how I might grab a `Base*` to the derived type such that when I
do `base->func()`, the Python function is called? The Boost docs only describe
how to expose the virtual functions to Python, not how to call their
redefinitions from C+.
Answer: I think you just call `extract<Base*>(obj)` where `obj` is `python::object`.
|
Python - Rewrite multiple lines in the Console
Question: I know it is possible to consistently rewrite the last line displayed in the
terminal with "\r", but I am having trouble figuring out if there is a way to
go back and edit previous lines printed in the console.
What I would like to do is reprint multiple lines for a text-based RPG,
however a friend was also wondering about this for an application which had
one line dedicated to a progress bar, and another describing the download.
i.e. the console would print:
Moving file: NameOfFile.txt
Total Progress: [######## ] 40%
and then update appropriately (to both lines) as the program was running.
Answer: On Unix, use the [curses](http://docs.python.org/howto/curses.html) module.
On Windows, there are several options:
* PDCurses: <http://www.lfd.uci.edu/~gohlke/pythonlibs/>
* The HOWTO linked above recommends the [Console](http://effbot.org/zone/console-index.htm) module
* <http://newcenturycomputers.net/projects/wconio.html>
* <http://docs.activestate.com/activepython/2.7/pywin32/win32console.html>
Simple example using curses (I am a total curses n00b):
import curses
import time
def report_progress(filename, progress):
"""progress: 0-10"""
stdscr.addstr(0, 0, "Moving file: {0}".format(filename))
stdscr.addstr(1, 0, "Total progress: [{1:10}] {0}%".format(progress * 10, "#" * progress))
stdscr.refresh()
if __name__ == "__main__":
stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
try:
for i in range(10):
report_progress("file_{0}.txt".format(i), i+1)
time.sleep(0.5)
finally:
curses.echo()
curses.nocbreak()
curses.endwin()
|
Need an alternative to Solr which can run on most shared hosts
Question: I got a rude shock when I discovered that my company's hosts host python, but
**never JSP** under our current plans.
I developed a search program in **python (not Django)** which uses Solr. I
made use of these features (roughly in order of importance):
* Solr CEL (inbuilt indexer for DOC,PDFs etc)
* faceted search
* highlighting
* "more like this" searches
* flexible relevance
* returning data in very friendly formats (python objects in this case)
* composing complex queries easily (just manipulation of text)
Could you reccomend an alternative that closely matches these features and
actually work with most shared hosts? Our hosts are Hostgator and ResellerClub
(shared).
I **shortlisted Xapian** as it has these features (but I am open to more
options). Can it be deployed in a shared environment? Is the python support
well documented and as easy?
Footnote: This problem was caused by a newb (me) to the company and a
miscommunication with my boss. The JSP part went under the radar until too
lare. And sorry if I sound rude and unhelpful. I am just nervous.
Answer: How about using a [hosted Solr
solution](http://stackoverflow.com/questions/2168634/hosted-full-text-search-
solutions)? They're not free of course, but migrating to another search engine
will likely be a lengthy, complex, costly task. Not to mention that the
alternative search engine probably won't be as powerful as Solr. Or get an EC2
instance or a VPS somewhere.
Either way, it _is_ going to cost time and money, so it's a matter of figuring
out what solution is easiest and cheapest.
|
Embed a function from a Matlab MEX file directly in Python
Question: I am using a proprietary Matlab MEX file to import some simulation results in
Matlab (no source code available of course!). The interface with Matlab is
actually really simple, as there is a single function, returning a Matlab
struct. I would like to know if there is any way to call this function in the
MEX file directly from Python, without having to use Matlab?
What I have in mind is for example using something like SWIG to import the C
function into Python by providing a custom Matlab-wrapper around it... By the
way, I know that with scipy.io.loadmat it is already possible to read Matlab
binary *.mat data files, but I don't know if the data representation in a mat
file is the same as the internal representation in Matlab (in which case it
might be useful for the MEX wrapper).
The idea would be of course to be able to use the function provided in the MEX
with no Matlab installation present on the system.
Thanks.
Answer: Unless I'm misunderstanding something about how Matlab works or about your
question, it is very highly unlikely to be possible. From a technical point of
view any solution would need to be a full, binary compatible, bug for bug,
feature for feature reimplementation of the Matlab C library, (implementing
mxGetPr, mxGetN and so on) but binding to Python.
Let me edit my own answer to say the following: If you do have a MATLAB
license available there is the excellent package [MLAB
wrap](http://mlabwrap.sourceforge.net) which does at least part of what you
want.
|
Does anyone have a Categorized XML Corpus Reader for NLTK?
Question: Has anyone written a Categorized XML Corpus reader for NLTK?
I'm working with the Annotated NYTimes corpus. It's an XML corpus. I can read
the files with
[XMLCorpusReader](http://stackoverflow.com/questions/6837566/can-nltks-
xmlcorpusreader-be-used-on-a-multi-file-corpus) but I'd like to use some of
NLTK's category functionality. There's a [nice
tutorial](https://www.packtpub.com/article/python-text-processing-
nltk-20-creating-custom-corpora) for subclassing NLTK readers. I'll can go
ahead and write this but was hoping to save some time if someone's already
done this.
If not I'll post what I've written.
Answer: Here's a Categorized XML Corpus Reader for NLTK. It's based on [this
tutorial.](https://www.packtpub.com/article/python-text-processing-
nltk-20-creating-custom-corpora) This lets you use NLTK's category-based
features on XML Corpora like the New York Times Annotated Corpus.
Call this file CategorizedXMLCorpusReader.py and import this as:
import imp
CatXMLReader = imp.load_source('CategorizedXMLCorpusReader','PATH_TO_THIS_FILE/CategorizedXMLCorpusReader.py')
You can then use this like any other NLTK Reader. For instance,
CatXMLReader = CatXMLReader.CategorizedXMLCorpusReader('.../nltk_data/corpora/nytimes', file_ids, cat_file='PATH_TO_CATEGORIES_FILE')
I'm still figuring NLTK out so any corrections or suggestions are welcome.
# Categorized XML Corpus Reader
from nltk.corpus.reader import CategorizedCorpusReader, XMLCorpusReader
class CategorizedXMLCorpusReader(CategorizedCorpusReader, XMLCorpusReader):
def __init__(self, *args, **kwargs):
CategorizedCorpusReader.__init__(self, kwargs)
XMLCorpusReader.__init__(self, *args, **kwargs)
def _resolve(self, fileids, categories):
if fileids is not None and categories is not None:
raise ValueError('Specify fileids or categories, not both')
if categories is not None:
return self.fileids(categories)
else:
return fileids
# All of the following methods call the corresponding function in ChunkedCorpusReader
# with the value returned from _resolve(). We'll start with the plain text methods.
def raw(self, fileids=None, categories=None):
return XMLCorpusReader.raw(self, self._resolve(fileids, categories))
def words(self, fileids=None, categories=None):
#return CategorizedCorpusReader.words(self, self._resolve(fileids, categories))
# Can I just concat words over each file in a file list?
words=[]
fileids = self._resolve(fileids, categories)
# XMLCorpusReader.words works on one file at a time. Concatenate them here.
for fileid in fileids:
words+=XMLCorpusReader.words(self, fileid)
return words
# This returns a string of the text of the XML docs without any markup
def text(self, fileids=None, categories=None):
fileids = self._resolve(fileids, categories)
text = ""
for fileid in fileids:
for i in self.xml(fileid).getiterator():
if i.text:
text += i.text
return text
# This returns all text for a specified xml field
def fieldtext(self, fileids=None, categories=None):
# NEEDS TO BE WRITTEN
return
def sents(self, fileids=None, categories=None):
#return CategorizedCorpusReader.sents(self, self._resolve(fileids, categories))
text = self.words(fileids, categories)
sents=nltk.PunktSentenceTokenizer().tokenize(text)
return sents
def paras(self, fileids=None, categories=None):
return CategorizedCorpusReader.paras(self, self._resolve(fileids, categories))
|
How do I make a PATCH request in Python?
Question: Is there a way to make a request using PATCH http method in Python?
I tried using httplib, but it doesn't accept PATCH as method param.
Answer: With [Requests](http://python-requests.org), making [PATCH
requests](http://docs.python-requests.org/en/latest/api/#requests.patch) is
very simple:
import requests
r = requests.patch('http://httpbin.org/patch')
|
Virtualenv __future__ module works on command line, but not while running dev_appserver.py
Question: I'm running into a strange error when running App Engine from within my
**virtualenv**. Here is the error:
File "/home/matthew/dev/sdks/google_appengine_1.5.2/google/appengine/tools/dev_appserver.py", line 2318, in LoadModuleRestricted description)
File "/home/matthew/dev/projects/webapp2/project/src/webapp2.py", line 11, in <module>
from __future__ import with_statement
ImportError: No module named __future__
* If I run python in my virtualenv and type `import __future__`, it imports.
* If I deactivate my virtualenv and run **dev_appserver.py** , the app works.
* But if my virtualenv is active AND I run dev_appserver.py (even though #1 is true), the app does not work and I get the error above.
Why would `__future__` be available while running the Python interpreter, but
not dev_appserver.py?
Answer: This is [bug
4339](http://code.google.com/p/googleappengine/issues/detail?id=4339). Make
sure you use the SDK version 1.6.0, then do:
$ cd /usr/local/google_appengine/google/appengine/tools
$ wget "http://googleappengine.googlecode.com/issues/attachment?aid=43390029000&name=dev_appserver_import_hook.patch&token=974d9f138a5604dc7eb0526156b26cc7" -O dev_appserver.patch
$ patch -p1 < dev_appserver.patch
|
How to have logarithmic bins in a Python histogram
Question: As far as I know the option Log=True in the histogram function only refers to
the y-axis.
P.hist(d,bins=50,log=True,alpha=0.5,color='b',histtype='step')
I need the bins to be equally spaced in log10. Is there something that can do
this?
Answer: use logspace() to create a geometric sequence, and pass it to bins parameter.
And set the scale of xaxis to log scale.
import pylab as pl
import numpy as np
data = np.random.normal(size=10000)
pl.hist(data, bins=np.logspace(0.1, 1.0, 50))
pl.gca().set_xscale("log")
pl.show()

|
django_auth_ldap no module named ldap
Question: I am trying to get the django_auth_module working but I don't think I managed
to install it properly.
I downloaded the package and ran setup.py install. Then in my settings.py file
I tried to import the module ldap and it gave me the following error :
ImportError: no module named ldap
I am working on a CentOS 6 server.
Maybe it has to do with where I should install the module? The folder is in
the directory just above my site folder, but maybe that's wrong...
RESOLVED : Ok, I just needed to install the module python-ldap... problem
solved!
Answer: Install missing module:
pip install python-ldap
To install python-ldap with pip on Ubuntu: (some libraries are needed)
sudo apt-get install python-dev libldap2-dev libsasl2-dev libssl-dev
|
how to distinguish between a method and an attribute in python by name
Question: Sometimes, I find it hard to distinguish between a method and an attribute by
it's name without appending parentheses.
For example:
there're `keys()` method and `text` attribute in
`xml.etree.ElementTree.Element` class.
`text`:The text attribute can be used to hold additional data associated with
the element.
`keys()`:Returns the elements attribute names as a list.
* * *
Is there some basic rules/conventions to make `text` an attribute, but
`keys()` a method?
If I make `text()` a method, and `keys` an attribute. It still seems OK.
Answer: The only real distinction is that one is callable and one is not, so you can
use the builtin function
[`callable()`](http://docs.python.org/library/functions.html#callable) with
the actual object (not a string with the name of it) to determine whether or
not it is callable.
In your case:
>>> from xml.etree import ElementTree
>>> elt = ElementTree.Element("")
>>> callable(elt.keys)
True
>>> callable(elt.text)
False
|
Python 3, let json object accept bytes or let urlopen output strings
Question: With Python3 I am requesting from some url a json document.
response = urllib.request.urlopen(request)
The `response` object is a file like object with read, readline functions.
Normally a json object can be created with a file (opened in textmode)
obj = json.load(fp)
What I would like to do is:
obj = json.load(response)
this however does not work as urlopen returns a file object in binary mode.
A work around is of course:
str_response = response.readall().decode('utf-8')
obj = json.loads(str_response)
but this feels bad...
Is there a better way that I can transform a byte file object to a string file
object? Or am I missing any parameters for either `urlopen` or `json.load` to
give an encoding?
This would look to me as a common use case so I'm confident I'm missing some
usefull function.
Answer: Python’s wonderful standard library to the rescue…
import codecs
reader = codecs.getreader("utf-8")
obj = json.load(reader(response))
Works with both py2 and py3.
|
YAML parsing and Python?
Question: What is the best way to parse a YAML file into a Python object?
For example, this YAML:
Person:
name: XYZ
To this Python class:
class Person(yaml.YAMLObject):
yaml_tag = 'Person'
def __init__(self, name):
self.name = name
I am using PyYAML by the way.
Answer: If your YAML file looks like this:
# tree format
treeroot:
branch1:
name: Node 1
branch1-1:
name: Node 1-1
branch2:
name: Node 2
branch2-1:
name: Node 2-1
And you've installed `PyYAML` like this:
pip install PyYAML
And the Python code looks like this:
import yaml
f = open('tree.yaml')
# use safe_load instead load
dataMap = yaml.safe_load(f)
f.close()
The variable `dataMap` now contains a dictionary with the tree data. If you
print `dataMap` using PrettyPrint, you will get something like:
{'treeroot': {'branch1': {'branch1-1': {'name': 'Node 1-1'},
'name': 'Node 1'},
'branch2': {'branch2-1': {'name': 'Node 2-1'},
'name': 'Node 2'}}}
So, now we have seen how to get data into our Python program. Saving data is
just as easy:
f = open('newtree.yaml', "w")
yaml.dump(dataMap, f)
f.close()
You have a dictionary, and now you have to convert it to a Python object:
class Struct:
def __init__(self, **entries):
self.__dict__.update(entries)
Then you can use:
>>> args = your YAML dictionary
>>> s = Struct(**args)
>>> s
<__main__.Struct instance at 0x01D6A738>
>>> s...
and follow "[Convert Python dict to
object](http://stackoverflow.com/questions/1305532/convert-python-dict-to-
object)".
For more information you can look at [pyyaml.org](http://pyyaml.org/) and
[this](http://web.archive.org/web/20130809020433/http://mikkel.elmholdt.dk/?p=4).
|
Python - Have parent thread handle child threads Exception
Question: Is there a way to have the parent that spawned a new thread catch the spawned
threads exception? Below is a real basic example of what I am trying to
accomplish. It should stop counting when Exception is raised, but I don't know
how to catch it. Are exceptions thread safe? I would love to be able to use
the `Subprocess` module, but I am stuck using Python 2.3 and am not sure how
else to do this. Possibly using the `threading` module?
import time
import thread
def test():
try:
test = thread.start_new_thread(watchdog, (5,))
count(10)
except:
print('Stopped Counting')
def count(num):
for i in range(num):
print i
time.sleep(1)
def watchdog(timeout):
time.sleep(timeout)
raise Exception('Ran out of time')
if __name__ == '__main__':
test()
**UPDATE**
My original code was a little misleading. It am really looking for something
more like this:
import time
import thread
import os
def test():
try:
test = thread.start_new_thread(watchdog, (5,))
os.system('count_to_10.exe')
except:
print('Stopped Counting')
def watchdog(timeout):
time.sleep(timeout)
raise Exception('Ran out of time')
if __name__ == '__main__':
test()
I am trying to create a watchdog to kill the os.system call if the program
hangs up for some reason.
Answer: > stuck using Python 2.3
Python 2.3 is like 10 years old now. Why are you still using it?
> Possibly using the threading module
You should be using threading anyway.
You are probably thinking about the problem wrong though. You should probably
create some classes and rethink the approach to your problem.
Also if you're creating a watchdog, it probably doesn't make much sense to
have it in the same process as what you're doing. time.sleep() is a system
call that a regular python `Exception` won't cancel anyway.
|
Invalid command 'py2exe'
Question: I have python 2.5 and 2.6 installed. I'm running my project on 2.6. First I
had py2exe for 2.5 installed but it didn't work so I installed py2exe for 2.6
and deleted the other version but then the module wasn't found. Now I changed
the sys path:
import sys
sys.path.append('F:\Program Files\Python26\Lib\site-packages\py2exe')
from build_exe import py2exe
from distutils.core import setup
setup(
name =...
When i type into the console: path\setup.py py2exe I get "error: invalid
command 'py2exe'"
EDIT: I changed the path to 'F:/Program Files/Python26/Lib/site-
packages/py2exe' with correct slashes. Console looks like this:
E:\Eclipse Workspace\...\src>setup.py py2exe
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: setup.py --help [cmd1 cmd2 ...]
or: setup.py --help-commands
or: setup.py cmd --help
error: invalid command 'py2exe'
Answer: Here is your problem:
sys.path.append('F:\Program Files\Python26\Lib\site-packages\py2exe')
A backslash (`\`) is an [escape
character](http://en.wikipedia.org/wiki/Escape_character "escape character")
and interperted in a special way by almost all programming languages,
including Python.
It's unfortunate that DOS (And by extension Windows) also uses the backslash
as a directory separator instead of a a slash. [There is a bit of history
behind this](http://superuser.com/questions/176388/why-does-windows-use-
backslashes-for-paths-and-unix-forward-slashes "there is a bit of history
behind this")...
In any case, you have a few options:
Use slashes. Python will convert them to backslashes internally.
d = 'C:/Program Files/'
Use two backslahes, this will escape the backslashes and insert a single
backslashes.
d = 'C:\\Program Files\\'
Use a "raw" string which doesn't interpret escape character. Do this by adding
a `r` before the string.
d = r'C:\Program Files\'
I personally prefer the first solution. But I've seen the other two being used
quite a bit too. Note that this also works the other way around, so if you use
backslashes Python will convert it to slashes on UNIX and Linux systems.
As a free bonus hint, this may also be a good place to point out the
[os.path.join()](http://docs.python.org/library/os.path.html#os.path.join
"os.path.join\(\)") function :)
|
ImportError exception encountered while trying to use Fabric
Question: I am using Ubuntu and virtualenv, and I am having this recurring problem,
while attempting to use Fabric to create a deployment script. Fabric depends
on paramiko, which depends on PyCrypto.
Each time I try to use Fabric, or PyCrypto directly, I get this error:
ImportError: cannot import name Random
I have tried reinstalling with pip install -U PyCrypto. I have also tried
installing the python-crypto and python-crypto-dbg packages with Aptitude, to
no avail. I still get the same error. Anyone have any ideas that might help me
solve this problem? Thanks in advance!
Answer: It's possible that there's a file name collision in your the directory from
which you're running Fabric. Do you have a file called `Crypto.py` in your
project?
Can you get Crypto.Random to import from outside of your project directory?
(but still using your virtualenv. Ipython is a big help here.)
|
How does django handle multiple memcached servers?
Question: In the django documentation it says this:
> ...
>
> One excellent feature of Memcached is its ability to share cache over
> multiple servers. This means you can run Memcached daemons on multiple
> machines, and the program will treat the group of machines as a single
> cache, without the need to duplicate cache values on each machine. To take
> advantage of this feature, include all server addresses in LOCATION, either
> separated by semicolons or as a list.
>
> ...
[Django's cache framework -
Memcached](https://docs.djangoproject.com/en/1.3/topics/cache/#memcached)
How exactly does this work? I've read some answers on this site that suggest
this is accomplished by sharding across the servers based on hashes of the
keys.
[Multiple memcached servers
question](http://stackoverflow.com/questions/4717559/multiple-memcached-
servers-question)
[How does the MemCacheStore really work with multiple
servers?](http://stackoverflow.com/questions/5733972/how-does-the-
memcachestore-really-work-with-multiple-servers)
That's fine, but I need a much more specific and detailed answer than that.
Using django with pylibmc or python-memcached how is this sharding actually
performed? Does the order of IP addresses in the configuration setting matter?
What if two different web servers running the same django app have two
different settings files with the IP addresses of the memcached servers in a
different order? Will that result in each machine using a different sharding
strategy that causes duplicate keys and other inefficiencies?
What if a particular machine shows up in the list twice? For example, what if
I were to do something like this where 127.0.0.1 is actually the same machine
as 172.19.26.240?
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': [
'127.0.0.1:11211',
'172.19.26.240:11211',
'172.19.26.242:11211',
]
}
}
What if one of the memcached servers has more capacity than the others? If
machine one has as 64MB memcached and machine 2 has a 128MB, Will the sharding
algorithm take that into account and give machine 2 a greater proportion of
the keys?
I've also read that if a memcached server is lost, then those keys are lost.
That is obvious when sharding is involved. What's more important is what will
happen if a memcached server goes down and I leave its IP address in the
settings file? Will django/memcached simply fail to get any keys that would
have been sharded to that failed server, or will it realize that server has
failed and come up with a new sharding strategy? If there is a new sharding
strategy, does it intelligently take the keys that were originally intended
for the failed server and divide them among the remaining servers, or does it
come up with a brand new strategy as if the first server didn't exist and
result in keys being duplicated?
I tried reading the source code of python-memcached, and couldn't figure this
out at all. I plan to try reading the code of libmemcached and pylibmc, but I
figured asking here would be easier if someone already knew.
Answer: It's the actual memcached client who does the sharding. Django only passes the
configuration from `settings.CACHES` to the client.
The order of the servers doesn't matter*, but (at least for python-memcached)
you can specify a 'weight' for each of the servers:
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': [
('cache1.example.org:11211', 1),
('cache2.example.org:11211', 10),
],
}
I think that a quick look at `memcache.py` (from python-memcached) and
especially `memcached.Client._get_server` should answer the rest of your
questions:
def _get_server(self, key):
if isinstance(key, tuple):
serverhash, key = key
else:
serverhash = serverHashFunction(key)
for i in range(Client._SERVER_RETRIES):
server = self.buckets[serverhash % len(self.buckets)]
if server.connect():
#print "(using server %s)" % server,
return server, key
serverhash = serverHashFunction(str(serverhash) + str(i))
return None, None
I would expect that the other memcached clients are implemented in a similar
way.
* * *
**Clarification by @Apreche:** The order of servers does matter in one case.
If you have multiple web servers, and you want them all to put the same keys
on the same memcached servers, you need to configure them with the same server
list in the same order with the same weights
|
Mac to Windows Python
Question: I have recently moved a set of near identical programs from my mac to my
school's windows, and while the paths appear to be the same (or the tail end
of them), they will not run properly.
import glob
import pylab
from pylab import *
def main():
outfnam = "igdata.csv"
fpout = open(outfnam, "w")
nrows = 0
nprocessed = 0
nbadread = 0
filenames = [s.split("/")[1] for s in glob.glob("c/Cmos6_*.IG")]
dirnames = "c an0 an1 an2 an3 an4".split()
for suffix in filenames:
nrows += 1
row = []
row.append(suffix)
for dirnam in dirnames:
fnam = dirnam+"/"+suffix
lines = [l.strip() for l in open(fnam).readlines()]
nprocessed += 1
if len(lines)<5:
nbadread += 1
print "warning: file %s contains only %d lines"%(fnam, len(lines))
tdate = "N/A"
irrad = dirnam
Ig_zeroVds_largeVgs = 0.0
else:
data = loadtxt(fnam, skiprows=5)
tdate = lines[0].split(":")[1].strip()
irrad = lines[3].split(":")[1].strip()
# pull out last column (column "-1") from second-to-last row
Ig_zeroVds_largeVgs = data[-2,-1]
row.append(irrad)
row.append("%.3e"%(Ig_zeroVds_largeVgs))
fpout.write(", ".join(row) + "\n")
print "wrote %d rows to %s"%(nrows, outfnam)
print "processed %d input files, of which %d had missing data"%( \
nprocessed, nbadread)`
This program worked fine for a mac, but for windows I keep getting for :
print "wrote %d rows to %s"%(nrows, outfnam)
print "processed %d input files, of which %d had missing data"%( \
nprocessed, nbadread)
wrote 0 row to file name processed 0 input files, of which o had missing data
on my mac i go 144 row to file...
does any one have any suggestions?
Answer: If the script doesn't raise any errors, this piece of code is most likely
returning an empty list.
glob.glob("c/Cmos6_*.IG")
Seeing as glob.glob works perfectly fine with forward slashes on Windows, the
problem is most likely that it's not finding the files, which most likely
means that the string you provided has an error somewhere in it. Make sure
there isn't any error in `"c/Cmos6_*.IG"`.
If the problem isn't caused by this, then unfortunately, I have no idea why it
is happening.
Also, when I tried it, filenames returned by glob.glob have backslashes in
them on Windows, so you should probably split by `"\\"` instead.
|
Is there a way to autogenerate valid arithmetic expressions?
Question: I'm currently trying to create a Python script that will autogenerate space-
delimited arithmetic expressions which are valid. However, I get sample output
that looks like this: `( 32 - 42 / 95 + 24 ( ) ( 53 ) + ) 21`
While the empty parentheses are perfectly OK by me, I can't use this
autogenerated expression in calculations since there's no operator between the
24 and the 53, and the + before the 21 at the end has no second argument.
What I want to know is, is there a way to account for/fix these errors using a
Pythonic solution? (And before anyone points it out, I'll be the first to
acknowledge that the code I posted below is probably the worst code I've
pushed and conforms to...well, very few of Python's core tenets.)
import random
parentheses = ['(',')']
ops = ['+','-','*','/'] + parentheses
lines = 0
while lines < 1000:
fname = open('test.txt','a')
expr = []
numExpr = lines
if (numExpr % 2 == 0):
numExpr += 1
isDiv = False # Boolean var, makes sure there's no Div by 0
# isNumber, isParentheses, isOp determine whether next element is a number, parentheses, or operator, respectively
isNumber = random.randint(0,1) == 0 # determines whether to start sequence with number or parentheses
isParentheses = not isNumber
isOp = False
# Counts parentheses to ensure parentheses are matching
numParentheses = 0
while (numExpr > 0 or numParentheses > 0):
if (numExpr < 0 and numParentheses > 0):
isDiv = False
expr.append(')')
numParentheses -= 1
elif (isOp and numParentheses > 0):
rand = random.randint(0,5)
expr.append(ops[rand])
isDiv = (rand == 3) # True if div op was just appended
# Checks to see if ')' was appended
if (rand == 5):
isNumber = False
isOp = True
numParentheses -= 1
# Checks to see if '(' was appended
elif (rand == 4):
isNumber = True
isOp = False
numParentheses += 1
# All other operations go here
else:
isNumber = True
isOp = False
# Didn't add parentheses possibility here in case expression in parentheses somehow reaches 0
elif (isNumber and isDiv):
expr.append(str(random.randint(1,100)))
isDiv = False
isNumber = False
isOp = True
# If a number's up, decides whether to append parentheses or a number
elif (isNumber):
rand = random.randint(0,1)
if (rand == 0):
expr.append(str(random.randint(0,100)))
isNumber = False
isOp = True
elif (rand == 1):
if (numParentheses == 0):
expr.append('(')
numParentheses += 1
else:
rand = random.randint(0,1)
expr.append(parentheses[rand])
if rand == 0:
numParentheses += 1
else:
numParentheses -= 1
isDiv = False
numExpr -= 1
fname.write(' '.join(expr) + '\n')
fname.close()
lines += 1
Answer: Yes, you can generate random arithmetic expressions in a Pythonic way. You
need to change your approach, though. Don't try to generate a string and count
parens. Instead generate a random _expression tree_ , then output that.
By an expression tree, I mean an instance of a class called, say, `Expression`
with subclasses `Number`, `PlusExpression,`MinusExpression`,
'TimesExpression`, `DivideExpression`, and `ParenthesizedExpression`. Each of
these, except `Number` will have fields of type `Expression`. Give each a
suitable `__str__` method. Generate some random expression objects and just
print the "root."
Can you take it from here or would you like me to code it up?
**ADDENDUM** : Some sample starter code. Doesn't generate random expressions
(yet?) but this can be added....
# This is just the very beginning of a script that can be used to process
# arithmetic expressions. At the moment it just defines a few classes
# and prints a couple example expressions.
# Possible additions include methods to evaluate expressions and generate
# some random expressions.
class Expression:
pass
class Number(Expression):
def __init__(self, num):
self.num = num
def __str__(self):
return str(self.num)
class BinaryExpression(Expression):
def __init__(self, left, op, right):
self.left = left
self.op = op
self.right = right
def __str__(self):
return str(self.left) + " " + self.op + " " + str(self.right)
class ParenthesizedExpression(Expression):
def __init__(self, exp):
self.exp = exp
def __str__(self):
return "(" + str(self.exp) + ")"
e1 = Number(5)
print e1
e2 = BinaryExpression(Number(8), "+", ParenthesizedExpression(BinaryExpression(Number(7), "*", e1)))
print e2
** ADDENDUM 2 **
Getting back into Python is really fun. I couldn't resist implementing the
random expression generator. It is built on the code above. SORRY ABOUT THE
HARDCODING!!
from random import random, randint, choice
def randomExpression(prob):
p = random()
if p > prob:
return Number(randint(1, 100))
elif randint(0, 1) == 0:
return ParenthesizedExpression(randomExpression(prob / 1.2))
else:
left = randomExpression(prob / 1.2)
op = choice(["+", "-", "*", "/"])
right = randomExpression(prob / 1.2)
return BinaryExpression(left, op, right)
for i in range(10):
print(randomExpression(1))
Here is the output I got:
(23)
86 + 84 + 87 / (96 - 46) / 59
((((49)))) + ((46))
76 + 18 + 4 - (98) - 7 / 15
(((73)))
(55) - (54) * 55 + 92 - 13 - ((36))
(78) - (7 / 56 * 33)
(81) - 18 * (((8)) * 59 - 14)
(((89)))
(59)
Ain't tooooo pretty. I think it puts out too many parents. Maybe change the
probability of choosing between parenthesized expressions and binary
expressions might work well....
|
python stop selenium standalone server
Question: How would I stop the selenium-server-standalone. I know you can start it by
`java -jar selenium-server-standalone.jar` But how would you stop it? Also, is
there a simple way to script it in python to start and stop it as I am running
tests.I feel like this is pretty simple. But am unable to find the answer to
my question.
Answer: You can start the server with `subprocess.Popen`, and shut it down with
`sel.shut_down_selenium_server()`:
import selenium
import socket
import subprocess
import shlex
import sys
import time
# CHANGE path='/path/to/selenium-server.jar' AS NEEDED:
def start_server(path='/path/to/selenium-server.jar'):
null=open('/dev/null')
proc=subprocess.Popen(shlex.split('java -jar {p}'.format(p=path)),
stdout=null,stderr=null)
return proc
def shutdown_server(sel):
sel.shut_down_selenium_server()
def start_selenium(host="localhost",
port=4444,
browserStartCommand="*firefox",
browserURL="http://www.google.com/webhp"):
sel=selenium.selenium(host,port,browserStartCommand,browserURL)
try:
sel.start()
except socket.error as err:
proc=start_server()
time.sleep(1)
try:
sel.start()
except socket.error as err:
sys.exit(err)
return sel
if __name__=='__main__':
sel=start_selenium()
time.sleep(1)
sel.stop()
shutdown_server(sel)
|
How to render a python dict as an html table with vertical columns
Question: I've got a python dict with where each key corresponds to a heading, and the
list associated with each heading contains an arbitrary number of values:
data = {
"heading1": ['h1-val1', 'h1-val2', 'h1-val3', ],
"heading2": ['h2-val1', ],
"heading3": ['h3-val1', 'h3-val2', 'h3-val3', 'h3-val4', ],
}
I need to render this in a Django template as a table, where the values are
listed vertically beneath each heading, with any missing values rendered as an
empty table cell:
<table>
<thead>
<tr>
<th>heading1</th>
<th>heading2</th>
<th>heading3</th>
</tr>
</thead>
<tbody>
<tr>
<td>h1-val1</td>
<td>h2-val1</td>
<td>h3-val1</td>
</tr>
<tr>
<td>h1-val2</td>
<td></td>
<td>h3-val2</td>
</tr>
<tr>
<td>h1-val3</td>
<td></td>
<td>h3-val3</td>
</tr>
<tr>
<td></td>
<td></td>
<td>h3-val4</td>
</tr>
</tbody>
</table>
What's the best way to achieve this?
My first inclination is to rearrange the original dict into a 2D matrix, and
just pass that into the template. I'm sure I'm not the first to run into this
kind of problem, though, and I'm curious how others have solved this problem.
**UPDATE:** Just for reference, here's my original solution to this problem
(which I'm not very happy with).
# Using the data dict from the question:
size = max(len(data['heading1']), len(data['heading2']), len(data['heading3']))
matrix = [[None, None, None] for i in range(size)] # initialize an empty matrix
# manually copy the data into the appropriate column :(
i = 0
for item in data['heading1']:
matrix[i][0] = item
i += 1
i = 0
for item in data['heading2']:
matrix[i][1] = item
i += 1
i = 0
for item in data['heading3']:
matrix[i][2] = item
i += 1
I then passed the matrix into the template which looked like this:
<table>
<thead><tr>
<th>heading1</th>
<th>heading2</th>
<th>heading3</th>
</tr></thead>
<tbody>
{% for row in matrix %}
<tr>
{% for col in row %}
<td>{% if col %}{{ col }}{% else %} {% endif %}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
Answer: If we change the game a little bit, it's actually a snap to turn this around
(so long as your lists are None filled...)
from django.template import Context, Template
data = {
"heading1": ['h1-val1', 'h1-val2', 'h1-val3', ],
"heading2": ['h2-val1', ],
"heading3": ['h3-val1', 'h3-val2', 'h3-val3', 'h3-val4', ],
}
# we'll need to split the headings from the data
# rather than using keys() I'm just hard coding so I can control the order
headings = ["heading1", "heading2", "heading3"]
columns = [data[heading] for heading in headings]
# get the length of the longest column
max_len = len(max(columns, key=len))
for col in columns:
# padding the short columns with None
col += [None,] * (max_len - len(col))
# Then rotate the structure...
rows = [[col[i] for col in columns] for i in range(max_len)]
dj_template ="""
<table>
{# headings #}
<tr>
{% for heading in headings %}
<th>{{ heading }}</th>
{% endfor %}
</tr>
{# data #}
{% for row in data %}
<tr>
{% for val in row %}
<td>{{ val|default:'' }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
"""
# finally, the code I used to render the template:
tmpl = Template(dj_template)
tmpl.render(Context(dict(data=rows, headings=headings)))
For me, this produces the following (blank lines stripped):
<table>
<tr>
<th>heading1</th>
<th>heading2</th>
<th>heading3</th>
</tr>
<tr>
<td>h1-val1</td>
<td>h2-val1</td>
<td>h3-val1</td>
</tr>
<tr>
<td>h1-val2</td>
<td></td>
<td>h3-val2</td>
</tr>
<tr>
<td>h1-val3</td>
<td></td>
<td>h3-val3</td>
</tr>
<tr>
<td></td>
<td></td>
<td>h3-val4</td>
</tr>
</table>
|
Python - Pycrypto - Sending encrypted data over network
Question: I am trying to get 2 programs to share encrypted data over a network using
public keys, but I am stuck with a difficult problem : the information that is
shared (the keys and/or the encrypted data) seems to get modified. I am hoping
to keep the encrypted data format as well as the format of the keys as simple
as possible in order to allow compatibility with other languages. To break
down the problem, I have created 2 programs : Keyreceive and Keysend. They
execute in this order :
1. Keyreceive starts up and waits to receive the encrypted data
2. Keysend starts up and generates an RSA key, saving the exported private key to a file
3. Keysend encrypts a piece of data and sends it to Keyreceive over the network
4. Keyreceive imports the private key from the same file, and uses it to decrypt the encrypted data
5. Keysend also decrypts the encrypted data to verify the result
**Keysend.py**
import socket
import os
from Crypto.PublicKey import RSA
from Crypto import Random
rng = Random.new().read
RSAkey = RSA.generate(1024, rng)
privatekey = RSAkey
publickey = RSAkey.publickey()
print(privatekey.exportKey()) #export under the 'PEM' format (I think)
print(publickey.exportKey())
file = open("Keys.txt", "w")
file.write(privatekey.exportKey()) #save exported private key
file.close()
data = "hello world"
enc_data = publickey.encrypt(data, 16) #encrypt message with public key
print(str(enc_data))
host = "localhost"
port = 12800
connexion = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connexion.connect((host, port))
connexion.send(str(enc_data)) # send encrypted data, this appears to be the source of the problem
dec_data = RSAkey.decrypt(enc_data) # test decryption
print(dec_data)
os.system("pause")
**Keyreceive.py**
import socket
import os
from Crypto.PublicKey import RSA
from Crypto import Random
host = ''
port = 12800
connexion = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connexion.bind((host, port))
connexion.listen(5)
clientconnexion, connexioninfo = connexion.accept()
enc_data = clientconnexion.recv(1024) # receive encrypted data
print(enc_data)
file = open("Keys.txt", "r")
privatestr = file.read() # retrieve exported private key from file
file.close()
print(privatestr)
privatekey = RSA.importKey(privatestr) # import private key
data = privatekey.decrypt(enc_data) # decrypt sent encrypted data
print(data)
os.system("pause")
After both files have finished decrypting the encrypted data, Keysender
outputs the original message : "hello world", whereas Keyreceiver outputs
gibberish. If there is "hidden" information in the encrypted data and key
formats, would there be some way of writing them in a "pure" text format?
Answer: You're right about which line is the source of the problem.
connexion.send(str(enc_data))
`enc_data` here is a _tuple_ , the first (and in fact only) element of which
is a string containing the actual ciphertext. When you are calling `str` on
it, you're getting Python's attempt to convert the tuple to a string, which is
not what you want. If you change it to this:
connexion.send(enc_data[0])
then it should do what you want.
|
Does python's glob function support wildcards with variable depth?
Question: I'm writing a python script that uses this awkward glob syntax.
import glob
F = glob.glob('./www.dmoz.org/Science/Environment/index.html')
F += glob.glob('./www.dmoz.org/Science/Environment/*/index.html')
F += glob.glob('./www.dmoz.org/Science/Environment/*/*/index.html')
F += glob.glob('./www.dmoz.org/Science/Environment/*/*/*/index.html')
F += glob.glob('./www.dmoz.org/Science/Environment/*/*/*/*/index.html')
Seems like there ought to be a way to wrap this is one line:
F = glob.glob('./www.dmoz.org/Science/Environment/[super_wildcard]/index.html')
But I don't know what the appropriate super wildcard would be. Does such a
thing exist?
Answer: Sorry - it does not. You will have to probably write few lines of code using
[os.walk](http://docs.python.org/library/os.html#os.walk):
for root, dirs, files in os.walk('/starting/path/'):
for myFile in files:
if myFile == "index.html":
print os.path.join(root, myFile)
|
python Django model indentation error
Question:
from django.db import models
class Category(models.Model):
title = models.CharField(max_length=250)
slug = models.SlugField(unique=True)
description = models.TextField()
class Meta:
verbose_name_plural = "Categories"
def __unicode__(self):
return self.title
I am getting this error
>
> verbose_name_plural = "Categories"
> ^ IndentationError: expected an indented block
>
I am using gedit with use spaces as option for tabs ( also tried altering tab
width)..I am almost certain that the code is correct..but some problem with
spacing and tabs..
Answer:
class Meta:
verbose_name_plural = "Categories"
You are not indenting correctly after `class Meta:`.
|
Plotting lines with gnuplot python
Question: I have a list:
x = [1,2,3,4]
Now using gnuplot, I have plotted the points as `(0,1), (1,2), ...`
Here is the syntax I used:
g = Gnuplot.Gnuplot()
g.plot(x)
Now I have my required set of points but I want to join these points by a
line. How do I do that?
Answer: Does the following work for you?
>>> import Gnuplot
>>> x = [1,2,3,4]
>>> gp = Gnuplot.Gnuplot()
>>> gp.title('My title')
>>> gp('set style data linespoints')
>>> gp.plot(x)
You can pass whatever options you want in the 5th command.
|
PyQt or PySide - which one to use
Question: I started learning a bit of python and would now like to toy around a bit with
gui-building. Qt seems to be a good choice because of its cross-
platformishness.
Now there seem to be two bindings available: PyQt by Riverbank Computing and
PySide, originally developed by Nokia.
So which one should I choose? All I can find are two year old feature
comparisons, but what differences are there nowadays?
Which one is easier to use, has more/better documentation? Are both still in
active development?
Licensing isn't of much concern to me since I don't intend to write commercial
applications.
Answer: Both toolkits are actively maintained, and by now more or less equal in
features and quality. There are only few, rather unimportant differences.
Still, I'd recommend PySide for Python 2. It has a more reasonable API, mainly
it doesn't expose Qt types, which have a direct equivalent in Python (e.g.
QString, QList, etc.) or which are completely superfluous due to Python's
dynamic nature, like QVariant. This avoids many tedious conversions to and
from Qt types, and thus eases programming and avoids many errors.
PyQt also supports this modern API, and uses it by default for Python 3, but
not for Python 2 to maintain backwards compatibility.
|
How to find the last occurrence of an item in a Python list
Question: Say I have this list:
li = ["a", "b", "a", "c", "x", "d", "a", "6"]
As far as help showed me, there is not a builtin function that returns the
last occurrence of a string (like the reverse of `index`). So basically, how
can I find the last occurrence of `"a"` in the given list?
Answer: If you are actually using just single letters like shown in your example, then
`''.join(li).rfind('a')` would work nicely. It will return `-1` if 'a' is not
in the list.
For the general case you could use:
len(li) - 1 - li[::-1].index('a')
It will raise `ValueError` if `'a'` is not in the list.
For the case where `li` is a very long list, it may be performant to do this
with a 'lazy' approach using itertools:
import itertools as it
indices = xrange(len(li) - 1, 0, -1)
gen = it.izip(indices, reversed(li))
next(i for i,value in gen if value == 'a')
Here are some timing comparisons on python 2.7.6:
>>> li = list(string.ascii_lowercase * 100)
>>> timeit ''.join(li).rfind('a')
10000 loops, best of 3: 23.9 µs per loop
>>> timeit (len(li) - 1) - li[::-1].index('a')
100000 loops, best of 3: 6.02 µs per loop
>>> timeit next(i for i,v in it.izip(xrange(len(li)-1, 0, -1), reversed(li)) if v == 'a')
100000 loops, best of 3: 2.52 µs per loop
Timings on python 3.4.3, where we don't actually need itertools:
>>> timeit ''.join(li).rfind('a')
100000 loops, best of 3: 19 µs per loop
>>> timeit (len(li) - 1) - li[::-1].index('a')
100000 loops, best of 3: 5.52 µs per loop
>>> timeit next(i for i,v in zip(range(len(li)-1, 0, -1), reversed(li)) if v == 'a')
100000 loops, best of 3: 2.96 µs per loop
|
Python byte buffer object?
Question: Is there a byte buffer object in Python to which I can append values of
specific types? _(preferably with specifiable endianess)_
For example:
buf.add_int(4) # should add a 4 byte integer
buf.add_short(10) # should add a 2 byte short
buf.add_byte(24) # should add a byte
I know that I could just use `struct.pack` but this approach just seems
easier. Ideally it should be like the `DataOutputStream` and `DataInputStream`
objects in **Java** which do this exact task.
Answer: You can always use [bitstring](http://code.google.com/p/python-bitstring/). It
is capable of doing all the things you ask and more.
>>> import bitstring
>>> stream=bitstring.BitStream()
>>> stream.append("int:32=4")
>>> stream.append("int:16=10")
>>> stream.append("int:8=24")
>>> stream
BitStream('0x00000004000a18')
>>> stream.bytes
'\x00\x00\x00\x04\x00\n\x18'
Here is a link to the
[documentation](http://packages.python.org/bitstring/#documentation).
|
which one should I use: os.sep or os.path.sep?
Question: They are same, but which one should I use?
<http://docs.python.org/library/os.html>:
> `os.sep`
>
>> The character used by the operating system to separate pathname components.
This is '/' for POSIX and '\' for Windows. Note that knowing this is not
sufficient to be able to parse or concatenate pathnames — use os.path.split()
and os.path.join() — but it is occasionally useful. Also available via
os.path.
Answer: I'd use `os.path.sep` to make it very clear that it's the path separator… But
consistency is more important, so if one is already being used, use that.
Otherwise, pick one and use it all the time.
**Edit** : Just to make sure you're not reinventing the wheel, though, the
`path` module already has `join`, `split`, `dirname`, and `basename`
functions… So you should rarely need to use `path.sep`:
>>> os.path.join("foo", "bar", "baz")
'foo/bar/baz'
>>> os.path.split(_)
('foo/bar', 'baz')
|
Split numpy array object into two different size vectors using C
Question: I have
X as input --- this is dtype object this is of following structure
x=[[1,2,3,4...n elements],[1 element],[1,2,...m elements],[1 element]]
To mimic the input...
>>> from numpy import *
>>> x=array([array([1,2,3,4,5]),array([1]),array([1,2,3,4,5,6,7,8]),array([1])],dtype=object)
>>> x
array([[1 2 3 4 5], [1], [1 2 3 4 5 6 7 8], [1]], dtype=object)
I passing X as an argument to my Python C extension as PyArray_Object
static PyObject* samp(PyObject *self, PyObject *args) {
PyArrayObject *array,*p1,*p2;
int n,j;
if (!PyArg_ParseTuple(args, "O!",&PyArray_Type, &array))
return NULL;
n=array->nd;
if(n!=1 || array->descr->type_num!=PyArray_OBJECT) {
PyErr_SetString(PyExc_ValueError, "array must be one-dimensional and of Object type");
return NULL;
}
j=array->dimensions[0];
/* ...... */
}
Now I am stuck here as I m not sure how to split this into 4 objects Please
kindly can anyone give me few pointers on this...
Answer: Originally you had an array of four arrays. The following line extracts it
into four array variables:
`a,b,c,d=x[0],x[1],x[2],x[3]`
If you need native Python objects instead of numpy arrays, use list
comprehension:
`objs = [y for y in a]`
|
Encoding mail subject (SMTP) in Python with non-ASCII characters
Question: I am using Python module `MimeWriter` to construct a message and smtplib to
send a mail constructed message is:
file msg.txt:
-----------------------
Content-Type: multipart/mixed;
from: me<[email protected]>
to: [email protected]
subject: 主題
Content-Type: text/plain;charset=utf-8
主題
I use the code below to send a mail:
import smtplib
s=smtplib.SMTP('smtp.abc.com')
toList = ['[email protected]']
f=open('msg.txt') #above msg in msg.txt file
msg=f.read()
f.close()
s.sendmail('[email protected]',toList,msg)
I get mail body correctly but subject is not proper,
subject: some junk characters
主題 <- body is correct.
Please suggest? Is there any way to specify the decoding to be used for the
subject also, as being specified for the body. How can I get the subject
decoded correctly?
Answer: From <http://docs.python.org/library/email.header.html>
from email.message import Message
from email.header import Header
msg = Message()
msg['Subject'] = Header('主題', 'utf-8')
print msg.as_string()
> Subject: =?utf-8?b?5Li76aGM?=
more simple:
from email.header import Header
print Header('主題', 'utf-8').encode()
> =?utf-8?b?5Li76aGM?=
|
multiprocessing.Pool seems to work in Windows but not in ubuntu?
Question: SOLVED: The problem was Wingware Python IDE. I guess the natural question now
is how it is possible and how this could be fixed.
I asked a question yesterday ( [Problem with multiprocessing.Pool in
Python](http://stackoverflow.com/questions/6900244/problem-with-
multiprocessing-pool-in-python) ) and this question is almost the same but I
have figured out that it seems to work on a Windows computer and not in my
ubuntu. At the end of this post I will post a slightly different version of
the code that does the same thing.
Short summary of my problem: When using multiprocessing.Pool in Python I am
not always able to get the amount of workers that I am asking for. When this
happens, the program just stalls.
I have been working for a solution all day, and then I came to think about
Noahs' comment on my previous question. He said that it worked on his machine
so I gave the code to my colleague who runs a Windows machine with Enthoughts
64-bit Python 2.7.1 distribution. I have the same with the big difference that
mine runs on ubuntu. I also mention that we both have Wingware Python IDE, but
I doubt that this is of any importance?
There are two problems with my code that don't arise when my colleague runs
the code on his machine.
1. I am not always able to get the four workers I am asking for (Although my machine has 12 workers). When this happens, the process just stalls and does not continue. No exception or Error is raised.
2. When I am able to get the four workers I ask for (which happens approximately 1 out 5 times or so), the figures that are produced (plain random numbers) are EXACTLY the same for all four pictures. This is not the case for my colleague.
Something is very fishy and I am very thankful for any kind of help you guys
can offer.
The code:
import multiprocessing as mp
import scipy as sp
import scipy.stats as spstat
import pylab
def testfunc(x0, N):
print 'working with x0 = %s' % x0
x = [x0]
for i in xrange(1,N):
x.append(spstat.norm.rvs(size = 1)) # stupid appending to make it slower
if i % 10000 == 0:
print 'x0 = %s, i = %s' % (x0, i)
return sp.array(x)
def testfuncParallel(fargs):
return testfunc(*fargs)
# Define Number of tasks.
nTasks = 4
N = 100000
if __name__ == '__main__':
"""
Try number 1. Using multiprocessing.Pool together with Pool.map_async
"""
pool = mp.Pool(processes = nTasks) # I have 12 threads (six cores) available so I am suprised that it does not get access to nTasks = 4 amount of workers
# Define tasks:
tasks = [(x, n) for x, n in enumerate(nTasks*[N])] # nTasks different tasks
# Compute parallel: async - asynchronically, i.e. not necessary in order.
result = pool.map_async(testfuncParallel, tasks)
pool.close() # These are needed if map_async is used
pool.join()
# Get results:
sim = sp.zeros((N, nTasks))
for nn, res in enumerate(result.get()):
sim[:, nn] = res
pylab.figure()
for i in xrange(nTasks):
pylab.subplot(nTasks,1, i + 1)
pylab.plot(sim[:, i])
pylab.show()
Thanks in advance.
Sincerely, Matias
Answer: I don't have a solution for your first problem. In fact, I can run your code
repeatedly without fail on my 64-bit Ubuntu box with Enthought's Python 2.7.1
[EPD 7.0-2 (64-bit)]. **edit** : It turns out the problem was being caused by
your IDE (Wingware). The obvious workaround is to run the script from outside
the IDE.
As to the second question, what happens is that on Unix every worker process
inherits the same state of the random number generator from the parent
process. This is why they generate identical pseudo-random sequences. All you
have to do to fix this is call `scipy.random.seed` at the top of `testfunc`:
def testfunc(x0, N):
sp.random.seed()
print 'working with x0 = %s' % x0
...
|
python webkit with proxy support
Question: I am writing a python script for scraping a webpage. I have created a webkit
webview object and used the open method for loading the url. But I want to
load the url through a proxy. How can i done this ? How to integrate webkit
with proxy? which webkit class support proxy?
Answer: try below code snippets. (reference from
[url](http://code.google.com/p/pywebkitgtk/issues/detail?id=53))
import gtk, webkit
import ctypes
libgobject = ctypes.CDLL('/usr/lib/libgobject-2.0.so.0')
libwebkit = ctypes.CDLL('/usr/lib/libsoup-2.4.so.1')
libsoup = ctypes.CDLL('/usr/lib/libsoup-2.4.so.1')
libwebkit = ctypes.CDLL('/usr/lib/libwebkit-1.0.so')
proxy_uri = libsoup.soup_uri_new('http://127.0.0.1:8000') # set your proxy url
session = libwebkit.webkit_get_default_session()
libgobject.g_object_set(session, "proxy-uri", proxy_uri, None)
w = gtk.Window()
s = gtk.ScrolledWindow()
v = webkit.WebView()
s.add(v)
w.add(s)
w.show_all()
v.open('http://www.google.com')
Hope, it could help you.
|
Calling methods of the main program from run time loaded Dll
Question: I have a (big and complex) C++ program with its own classes and
methods.(obviously)
I would like to load at runtime a dll. From the main program i want to call a
function inside the dll passing a class instance , and this function will use
the method of this class.
In pseudo code
Main program:
class MyClass{
myattr1();
myattr2();
mymethod1();
mymethod2();
}
void main(){
MyClass* object = &(new MyClass())
handle_of_the_dll = *some function that load the dll*
dllfunc = getfunc(handle_of_the_dll, "interesting_function")
dllfunc(object)
[...etc...]
and the dll
#ifdef __cplusplus
extern C {
#endif
#ifdef BUILD_DLL
#define EXPORT __declspec(dllexport)
#else
#define EXPORT __declspec(dllimport)
#endif
#include all the needed headers from main program, where the class is defined
EXPORT void interesting_functionn(MyClass object){
object.mymethod1();
}
#ifdef __cplusplus
}
#endif
Is this valid/doable/right?
# EDIT:
i know that this would be a poor design for a general program, but this method
is intended to give the users the ability to use their custom dll that can
access the api of the main program. Something like Cpython modules
Answer: It is valid and doable. Generate a sample DLL in visual C++ and the code will
have all the bases covered. Replace the static linking in the client with
`LoadLibrary` and `GetProcAdress`.
Name mangling could be an issue,
[DependencyWalker](http://www.dependencywalker.com/) will help you there.
Keep a low profile with emory management. For example, if you use a memory
manager on one side but not on the other, your begging for trouble.
|
Python, checksum of a dict
Question: I'm thinking to create a checksum of a dict to know if it was modified or not
For the moment i have that:
>>> import hashlib
>>> import pickle
>>> d = {'k': 'v', 'k2': 'v2'}
>>> z = pickle.dumps(d)
>>> hashlib.md5(z).hexdigest()
'8521955ed8c63c554744058c9888dc30'
Perhaps a better solution exists?
_Note: I want to create an unique id of a dict to create a good Etag._
**EDIT:** I can have abstract data in the dict.
Answer: Something like this:
reduce(lambda x,y : x^y, [hash(item) for item in d.items()])
Take the hash of each (key, value) tuple in the dict and XOR them alltogether.
@katrielalex If the dict contains unhashable items you could do this:
hash(str(d))
or maybe even better
hash(repr(d))
|
How do I import a module from a parent directory? (unittest purposes)
Question: I have just finished writing the core section of a project I am working on and
I want to write test for it using unittest before I continue. I am aware that
I should have done this before, but when I started I didn't know Python, so..
whatever..
What I would like to achieve: I have a sub-package of the main package which
contains all the modules I want to test inside it. I want to put a
subsubpackage inside that called 'tests' or something which then contains all
of my test cases, which I'd like to be able to aggregate into a test suite
from outside the package so eventually I can run all the test for the entire
project in one go.
The structure is something like this:
/projectPackage
/projectPackage/package
/projectPackage/package/\__init__.py (empty)
/projectPackage/package/someModule.py
/projectPackage/package/... (more modules)
/projectPackage/package/testing.py (runs all the tests in /tests/)
/projectPackage/package/tests
/projectPackage/package/tests/\__init__.py (empty)
/projectPackage/package/tests/someModuleTests.py
Problem I am having:
someModuleTests has to import someModule from the parent package so it can
test its methods. This doesn't seem to work. I get various errors like:
Attempted relative import beyond toplevel package
Anyway, I expect it's just because I am a Python noob! I have my own ideas on
how I am going to do it for this project, because of course each is different,
but any general advice on the structuring of medium-large python projects is
also appreciated.
Answer: Run the unit test from the parent directory so the directory is in your
PYTHONPATH (the current working directory always is). This is done by
executing the test file from your parent directory or by using something like
nosetest which recursively looks for all tests in your package.
Don't use relative imports, they cause things like this. Don't hack your
PYTHONPATH and/or sys.path to try and fix it either.
|
How to prevent a process from terminating on a KeyboardInterrupt?
Question: I've been messing around with a Django project. What I want to achieve is the
Django project starting up in another process while the parent process
initiates a load of arbitary code I have written (the backend of my project).
Obviously, the Django process and parent processes communicate. I'd like a
dictionary to be read and written to by the processes.
I have the following code, based upon examples from
[here](http://docs.python.org/library/multiprocessing.html#sharing-state-
between-processes):
#!/usr/bin/env python
from multiprocessing import Process, Manager
import os
import time
from dj import manage
def django(d, l):
print "starting django"
d[1] = '1'
d['2'] = 2
d[0.25] = None
l.reverse()
manage.start()
def stop(d, l):
print "stopping"
print d
print l
if (__name__ == '__main__'):
os.system('clear')
print "starting backend..."
time.sleep(1)
print "backend start complete."
manager = Manager()
d = manager.dict()
l = manager.list(range(10))
p = Process(target=django, args=(d, l))
p.start()
try:
p.join()
except KeyboardInterrupt:
print "interrupt detected"
stop(d, l)
When I hit CTRL+C to kill the Django process, I'm seeing the Django server
shut down, and `stop()` being called. Then what I want to see is the
dictionary, `d`, and list, `l`, being printed.
Output is:
starting backend...
backend start complete.
starting django
Validating models...
0 errors found
Django version 1.3, using settings 'dj.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
^Cinterrupt detected
stopping
<DictProxy object, typeid 'dict' at 0x141ae10; '__str__()' failed>
<ListProxy object, typeid 'list' at 0x1425090; '__str__()' failed>
It can't find the dictionary or list after the CTRL+C event. Has the Manager
process been terminated when the SIGINT is issued? If it is, is there anyway
to stop it from terminating there and terminating with the main process?
I hope this makes sense. Any help greatly receieved.
Answer: Ok, as far I see no possibility to simply ignore exception. When you rise one,
you always go straight into a "except" block if there is one. What I'm
proposing here is something what will restart your django application on each
^C, but note, that there should be added some back door for leaving.
In theory, you can wrap each line with a `try..except..` block and that would
act like a restart of each line, what will not be as visible as restart of
whole script. If anyone finds a really-working solution, I will be the first
one to upvote him.
You can set all inside your `if (__name__ == '__main__'):` into o `main`
function and leave something like this:
def main():
#all the code...
if (__name__ == '__main__'):
while True:
try:
main()
except KeyboardInterrupt:
pass
|
Resume FTP download after timeout
Question: I'm downloading files from a flaky FTP server that often times out during file
transfer and I was wondering if there was a way to reconnect and resume the
download. I'm using python's ftplib. Here is the code that I am using:
#! /usr/bin/python
import ftplib
import os
import socket
import sys
#--------------------------------#
# Define parameters for ftp site #
#--------------------------------#
site = 'a.really.unstable.server'
user = 'anonymous'
password = '[email protected]'
root_ftp_dir = '/directory1/'
root_local_dir = '/directory2/'
#---------------------------------------------------------------
# Tuple of order numbers to download. Each web request generates
# an order numbers
#---------------------------------------------------------------
order_num = ('1','2','3','4')
#----------------------------------------------------------------#
# Loop through each order. Connect to server on each loop. There #
# might be a time out for the connection therefore reconnect for #
# every new ordernumber #
#----------------------------------------------------------------#
# First change local directory
os.chdir(root_local_dir)
# Begin loop through
for order in order_num:
print 'Begin Proccessing order number %s' %order
# Connect to FTP site
try:
ftp = ftplib.FTP( host=site, timeout=1200 )
except (socket.error, socket.gaierror), e:
print 'ERROR: Unable to reach "%s"' %site
sys.exit()
# Login
try:
ftp.login(user,password)
except ftplib.error_perm:
print 'ERROR: Unable to login'
ftp.quit()
sys.exit()
# Change remote directory to location of order
try:
ftp.cwd(root_ftp_dir+order)
except ftplib.error_perm:
print 'Unable to CD to "%s"' %(root_ftp_dir+order)
sys.exit()
# Get a list of files
try:
filelist = ftp.nlst()
except ftplib.error_perm:
print 'Unable to get file list from "%s"' %order
sys.exit()
#---------------------------------#
# Loop through files and download #
#---------------------------------#
for each_file in filelist:
file_local = open(each_file,'wb')
try:
ftp.retrbinary('RETR %s' %each_file, file_local.write)
file_local.close()
except ftplib.error_perm:
print 'ERROR: cannot read file "%s"' %each_file
os.unlink(each_file)
ftp.quit()
print 'Finished Proccessing order number %s' %order
sys.exit()
The error that I get: socket.error: [Errno 110] Connection timed out
Any help is greatly appreciated.
Answer: Resuming a download through FTP using only standard facilities (see
[RFC959](http://tools.ietf.org/html/rfc959)) requires use of the block
transmission mode (section 3.4.2), which can be set using the `MODE B`
command. Although this feature is technically required for conformance to the
specification, I'm not sure all FTP server software implements it.
In the block transmission mode, as opposed to the stream transmission mode,
the server sends the file in chunks, each of which has a marker. This marker
may be re-submitted to the server to restart a failed transfer (section 3.5).
The specification says:
> [...] a restart procedure is provided to protect users from gross system
> failures (including failures of a host, an FTP-process, or the underlying
> network).
However, AFAIK, the specification does not define a required lifetime for
markers. It only says the following:
> The marker information has meaning only to the sender, but must consist of
> printable characters in the default or negotiated language of the control
> connection (ASCII or EBCDIC). The marker could represent a bit-count, a
> record-count, or any other information by which a system may identify a data
> checkpoint. The receiver of data, if it implements the restart procedure,
> would then mark the corresponding position of this marker in the receiving
> system, and return this information to the user.
It should be safe to assume that servers implementing this feature will
provide markers that are valid between FTP sessions, but your mileage may
vary.
|
CouchDB stops with socket error 54 partway through first indexing
Question: I'm trying to sort ~13,000 documents on my Mac's local CouchDB database by
date, but it gets hung up on document 5407 each time. I've tried increasing
the time-out tolerance on Futon but to no avail. This is the error message I'm
getting:
for row in db.view('index15/by_date_time', startkey=start, endkey=end): File
"/Library/Python/2.6/site-packages/CouchDB-0.8-py2.6.egg/couchdb/client.py",
line 984, in **iter** File "/Library/Python/2.6/site-
packages/CouchDB-0.8-py2.6.egg/couchdb/client.py", line 1003, in rows File
"/Library/Python/2.6/site-packages/CouchDB-0.8-py2.6.egg/couchdb/client.py",
line 990, in _fetch File "/Library/Python/2.6/site-
packages/CouchDB-0.8-py2.6.egg/couchdb/client.py", line 880, in _exec File
"/Library/Python/2.6/site-packages/CouchDB-0.8-py2.6.egg/couchdb/http.py",
line 393, in get_json File "/Library/Python/2.6/site-
packages/CouchDB-0.8-py2.6.egg/couchdb/http.py", line 374, in get File
"/Library/Python/2.6/site-packages/CouchDB-0.8-py2.6.egg/couchdb/http.py",
line 419, in _request File "/Library/Python/2.6/site-
packages/CouchDB-0.8-py2.6.egg/couchdb/http.py", line 239, in request File
"/Library/Python/2.6/site-packages/CouchDB-0.8-py2.6.egg/couchdb/http.py",
line 205, in _try_request_with_retries socket.error: 54
incidentally, this is the same error message that is produced when I have a
typo in my script.
I'm using couchpy to create the view as follows:
def dateTimeToDocMapper(doc):
from dateutil.parser import parse
from datetime import datetime as dt
if doc.get('Date'):
# [year, month, day, hour, min, sec]
_date = list(dt.timetuple(parse(doc['Date']))[:-3])
yield (_date, doc)
while this is running, I can open a python shell and using server.tasks() I
can see that the indexing is indeed taking place.
> > > >>> server.tasks()
>>>
>>> [{u'status': u'Processed 75 of 13567 changes (0%)', u'pid': u'<0.451.0>',
u'task': u'gmail2 _design/index11', u'type': u'View Group Indexer'}]
but each time it gets stuck on process 5407 of 13567 changes (it takes ~8
minutes to get this far). I have examined what I believe to be document 5407
and it doesn't appear to be anything out of the ordinary.
Incidentally, if I try to restart the process after it stops, I get this
response from server.tasks()
> > > >>> server.tasks()
>>>
>>> [{u'status': u'Processed 0 of 8160 changes (0%)', u'pid': u'<0.1224.0>',
u'task': u'gmail2 _design/index11', u'type': u'View Group Indexer'}]
in other words, couchDB seems to have recognized that it's already processed
the first 5407 of the 13567 changes and now has only 8160 left.
but then it almost immediately quits and gives me the same socket.error: 54
I have been searching the internet for the last few hours to no avail. I have
tried initiating the indexing from other locations, such as Futon. As I
mentioned, one of my errors was an OS timeout error, and increasing the
time_out thresholds in Futon's configuration seemed to help with that.
Please, if anyone could shed light on this issue, I would be very very
grateful. I'm wondering if there's a way to restart the process once its
already indexed 5407 documents, or better yet if there's a way to prevent the
thing from quitting 1/3 of the way through in the first place.
Thanks so much.
Answer: From what I gather, CouchDB builds your view contents by sending all documents
to your couchpy view server, which runs your Python code on that document. If
that code fails for any reason, CouchDB will be notified that something went
wrong, which will stop the update of the view contents.
So, there is something wrong with document 5408 that causes your Python code
to misbehave. If you need more help, I suggest you post that document here.
Alternatively, look into the logs for your couchpy view server: they might
contain information about how your code failed.
|
Build/Parse an XML document from a socketstream in Python
Question: I have an issue parsing a continuous stream of (multiple) xml documents sent
by a third party over a socket. A sample of the xml stream sent over the
socket is:
<?xml version="1.0"?><event><user id="1098"/><viewpage>109958</viewpage></event>
<?xml version="1.0"?><event><user id="1482"/><actions><edit>102865</edit><commit>1592356</commit></actions></event>
etc.
Here's the code I'm using:
import socket
import xml.etree.cElementTree as etree
from StringIO import StringIO
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "IP.IP.IP.IP"
port = "8080"
addr = (host,port)
s.connect(addr)
def iparse(packet):
for _, element in etree.iterparse(packet):
print ("%s, %s" %(element.tag, element.text))
element.clear()
#if complete <event> node received, publish node
data = "<feeds>"
while 1:
chunk = s.recv(1024)
#replace the xml doc declarations as comments
data += (chunk.replace("<?","<!--")).replace("?>","-->")
iparse(StringIO(data))
Things work just fine...however, the `for` loop in `iparse` iterates through
the entire doc each time. Is it possible for `iparse` to build and iterate
through one well-formed tag node (event) as it appears over the stream
instead? Note that there is no way in which I can set the chunk size to read a
well-formed packet. I could use a buffer, then build the packet and only send
to `iparse` once the packet is well-formed, but that would likely introduce
unwanted latency? Is there a better way to handle this?
**EDIT:**
Each event is distinct but contains arbitrary nodes under the root `<event>`.
`iparse` is expected to publish the latest event to an arbitrary number of
subscribers within a real-time analytics graphing system.
Answer: You could have a look at the [feed parsing](http://lxml.de/parsing.html#the-
feed-parser-interface) in `lxml.etree`. However, you're still going to run
into problems as your document is continually growing.
Are the XML blobs separated by new line characters? If so I suggest that you
buffer until you hit a new line and then send each line to an xml parser. Á la
[Twisted's
LineReceiver](http://twistedmatrix.com/trac/browser/tags/releases/twisted-11.0.0/twisted/protocols/basic.py#L509).
Actually, if it was me, I'd probably write this application in
[Twisted](http://twistedmatrix.com/trac/). Gluing together network services is
a common use case for it for me.
|
set python recursion limit for a function
Question: I have 2 solutions to a recursion problem that I need for a function (actually
a method). I want it to be recursive, but I want to set the recursion limit to
10 and reset it after the function is called (or not mess with recursion limit
at all). Can anyone think of a better way to do this or recommend using one
over the others? I'm leaning towards the context manager because it keeps my
code cleaner and no setting the tracebacklimit, but there might be caveats?
import sys
def func(i=1):
print i
if i > 10:
import sys
sys.tracebacklimit = 1
raise ValueError("Recursion Limit")
i += 1
func(i)
class recursion_limit(object):
def __init__(self, val):
self.val = val
self.old_val = sys.getrecursionlimit()
def __enter__(self):
sys.setrecursionlimit(self.val)
def __exit__(self, *args):
sys.setrecursionlimit(self.old_val)
raise ValueError("Recursion Limit")
def func2(i=1):
"""
Call as
with recursion_limit(12):
func2()
"""
print i
i += 1
func2(i)
if __name__ == "__main__":
# print 'Running func1'
# func()
with recursion_limit(12):
func2()
I do see some odd behavior though with the context manager. If I put in main
with recursion_limit(12):
func2()
It prints 1 to 10. If I do the same from the interpreter it prints 1 to 11. I
assume there is something going on under the hood when I import things?
EDIT: For posterity this is what I have come up with for a function that knows
its call depth. I doubt I'd use it in any production code, but it gets the job
done.
import sys
import inspect
class KeepTrack(object):
def __init__(self):
self.calldepth = sys.maxint
def func(self):
zero = len(inspect.stack())
if zero < self.calldepth:
self.calldepth = zero
i = len(inspect.stack())
print i - self.calldepth
if i - self.calldepth < 9:
self.func()
keeping_track = KeepTrack()
keeping_track.func()
Answer: You shouldn't change the system recursion limit at all. You should code your
function to know how deep it is, and end the recursion when it gets too deep.
The reason the recursion limit seems differently applied in your program and
the interpreter is because they have different tops of stack: the functions
invoked in the interpreter to get to the point of running your code.
|
Search for a string in a line using regex
Question: I am searching for a string in the format XXXXX_XXXXX or XXXXXX_XXXXX or
XXXXXX in a line, where X is alphanumeric.
So the string before "_" is 5 or 6 characters long and the string after "_" is
always five or may be just 6 characters long without any underscore. I am
coding in Python.
Any help will be much appreciated.
Answer: Howabout this?
([a-zA-Z0-9]{5,6}_[a-zA-Z0-9]{5})|[a-zA-Z0-9]{6}
Full code example:
import re
pat = re.compile(r'^(([a-zA-Z0-9]{5,6}_[a-zA-Z0-9]{5})|[a-zA-Z0-9]{6})$')
print pat.match('xxxxx_xxxxx') is not None # True, 5 chars, underscore, 5 chars
print pat.match('xxxxxx_xxxxx') is not None # True, 6 chars, underscore, 5 chars
print pat.match('xxxxxx') is not None # True, 6 chars
**NOTE:** I previously wrote this, not realizing python doesn't support POSIX
character classes
([[:alnum:]]{5,6}_[[:alnum:]]{5})|[[:alnum:]]{6}
|
Python logging: reverse effects of disable()
Question: The [logging
docs](http://docs.python.org/library/logging.html#logging.disable) say that
calling the `logging.disable(lvl)` method can "temporarily throttle logging
output down across the whole application," but I'm having trouble finding the
"temporarily." Take, for example, the following script:
import logging
logging.disable(logging.CRITICAL)
logging.warning("test")
# Something here
logging.warning("test")
So far, I haven't been able to find the `Something here` that will re-enable
the logging system as a whole and allow the second `warning` to get through.
Is there a reverse to `disable()`?
Answer:
logging.disable(logging.NOTSET)
|
While Loops Problem with Python Twitter Crawler
Question: I'm continuing writing my twitter crawler and am running into more problems.
Take a look at the code below:
from BeautifulSoup import BeautifulSoup
import re
import urllib2
url = 'http://mobile.twitter.com/NYTimesKrugman'
def gettweets(soup):
tags = soup.findAll('div', {'class' : "list-tweet"})#to obtain tweet of a follower
for tag in tags:
print tag.renderContents()
print ('\n\n')
def are_more_tweets(soup):#to check whether there is more than one page on mobile
links = soup.findAll('a', {'href': True}, {id: 'more_link'})
for link in links:
b = link.renderContents()
test_b = str(b)
if test_b.find('more'):
return True
else:
return False
def getnewlink(soup): #to get the link to go to the next page of tweets on twitter
links = soup.findAll('a', {'href': True}, {id : 'more_link'})
for link in links:
b = link.renderContents()
if str(b) == 'more':
c = link['href']
d = 'http://mobile.twitter.com' +c
return d
def checkforstamp(soup): # the parser scans a webpage to check if any of the tweets are
times = soup.findAll('a', {'href': True}, {'class': 'status_link'})
for time in times:
stamp = time.renderContents()
test_stamp = str(stamp)
if test_stamp.find('month'):
return True
else:
return False
response = urllib2.urlopen(url)
html = response.read()
soup = BeautifulSoup(html)
gettweets(soup)
stamp = checkforstamp(soup)
tweets = are_more_tweets(soup)
print 'stamp' + str(stamp)
print 'tweets' +str (tweets)
while (not stamp) and tweets:
b = getnewlink(soup)
print b
red = urllib2.urlopen(b)
html = red.read()
soup = BeautifulSoup(html)
gettweets(soup)
stamp = checkforstamp(soup)
tweets = are_more_tweets(soup)
print 'done'
The code works in the following way: For a single user NYTimesKrugman -I
obtain all tweets on a single page(gettweets) -provided more tweets exist(are
more tweets) and that I haven't obtained a month of tweets yet(checkforstamp),
I get the link for the next page of tweets -I go to the next page of tweets
(entering the while loop) and continue the process until one of the above
conditions is violated
However, I have done extensive testing and determined that I am not actually
able to enter the while loop. Rather, the program is not doing so. This is
strange, because my code is written such that tweets are true and stamp should
yield false. However, I'm getting the below results: I am truly baffled!
<div>
<span>
<strong><a href="http://mobile.twitter.com/nytimeskrugman">NYTimeskrugman</a></strong>
<span class="status">What Would I Have Done? <a rel="nofollow" href="http://nyti.ms/nHxb8L" target="_blank" class="twitter_external_link">http://nyti.ms/nHxb8L</a></span>
</span>
<div class="list-tweet-status">
<a href="/nytimeskrugman/status/98046724089716739" class="status_link">3 days ago</a>
</div>
<div class="list-tweet-actions">
</div>
</div>
stampTrue
tweetsTrue
done
>>>
If someone could help that'd be great. Why can I not get more than 1 page of
tweets? Is my parsing in checkstamp being done incorrectly? Thanx.
Answer: Your `checkforstamp` function returns non-empty, defined strings:
return 'True'
So `(not stamp)` will always be false.
Change it to return booleans like `are_more_tweets` does:
return True
and it should be fine.
For reference, see the [boolean
operations](http://docs.python.org/reference/expressions.html#boolean-
operations) documentation:
> In the context of Boolean operations, and also when expressions are used by
> control flow statements, the following values are interpreted as false:
> False, None, numeric zero of all types, and empty strings and containers
> (including strings, tuples, lists, dictionaries, sets and frozensets). **All
> other values are interpreted as true.**
>
> ...
>
> The operator **not** yields True if its argument is false, False otherwise.
Edit:
Same problem with the `if` test in `checkforstamp`. Since `find('substr')`
returns `-1` when the substring is not found, `str.find('substr')` in boolean
context will be `True` if there is no match according to the rules above.
That is not the only place in your code where this problem appears. Please
review all your tests.
|
SciPy LeastSq Dfun Usage
Question: I'm trying to get my Jacobian to work with SciPy's Optimize library's leastsq
function.
I have the following code:
#!/usr/bin/python
import scipy
import numpy
from scipy.optimize import leastsq
#Define real coefficients
p_real=[3,5,1]
#Define functions
def func(p, x): #Function
return p[0]*numpy.exp(-p[1]*x)+p[2]
def dfunc(p, x, y): #Derivative
return [numpy.exp(-p[1]*x),-x*p[0]*numpy.exp(-p[1]*x), numpy.ones(len(x))]
def residuals(p, x, y):
return y-func(p, x)
#Generate messy data
x_vals=numpy.linspace(0,10,30)
y_vals=func(p_real,x_vals)
y_messy=y_vals+numpy.random.normal(size=len(y_vals))
#Fit
plsq,cov,infodict,mesg,ier=leastsq(residuals, [10,10,10], args=(x_vals, y_vals), Dfun=dfunc, col_deriv=1, full_output=True)
print plsq
Now, when I run this, I get `plsq=[10,10,10]` as my return. When I take out
`Dfun=dfunc, col_deriv=1`, then I get something close to `p_real`.
Can anyone tell me what gives? Or point out a better source of documentation
than what SciPy provides?
Incidentally, I'm using the Jacobian because I have the (perhaps misguided)
belief that it will lead to faster convergence.
Answer: Change `residuals` to its negative:
def residuals(p, x, y):
return func(p, x)-y
and you get
[ 3. 5. 1.]
Hope this helps :)
|
Why do `print("Hello, World!")` and `print("Hello", "World!")` produce different outputs?
Question: I just installed Python 2.7.2 on Windows XP with the idea of learning how to
program. Several of the tutorial books I'm using give examples of print
commands which, when I try them, I get different answers.
I expected both of these to return the same thing -
>>> print("Hello, World!")
Hello, World!
>>> print("Hello", "World")
('Hello', 'World')
>>>
I've tried searching around for answers, but I'm not even sure how to explain
where I'm going wrong.
Answer: Since `print` is a statement in Python 2.x, you're getting expected behavior.
`(a,b)` is a tuple, so `print (a,b)` will print it as a tuple.
On the other hand, `print` is a function in Python 3.x, so
print("hello world")
and
print("hello", "world")
will yield the same answer.
This is one breaking change when going from Python 2.x to 3.x. Understanding
the difference is important. Type `help()` in your interpreter and then
`print`. You will get different descriptions based on your Python version.
I'd suggest checking out [this
page](http://docs.python.org/release/3.0.1/whatsnew/3.0.html), which describes
in a quick and nice way what worked before and what works now.
|
Python module generator for github
Question: I'm newbie to python and it's philosophy. I'm trying to develop a module on
github. Is there any Ruby's gem generator like tool for developing module? How
to develop a module? Thank you for any advise.
Answer: You don't need a tool to create a python module, any filename ending in `.py`
is sufficient. A _package_ , which is a collection of modules, is similarly
created by the presence of a file named `__init__.py` in the same folder as
other modules (and possibly other packages). The `__init__.py` file can be
empty or not, your choice.
Best practices dictate that importing a module should have no side effects; It
should define classes and functions, but take no action. python modules should
start with a docstring explaining the purpose of the module and how it should
be used.
|
SWIG: 'module' object has no attribute 'Decklist'
Question: I'm having one hell of a time with SWIG, due in part to the lack of good C++
examples to learn from. I finally got my first program to compile with SWIG,
but am having troubles running it. Let me just get right to the code...
setup.py:
#!/usr/bin/env python
"""
setup.py file for SWIG example
"""
from distutils.core import setup, Extension
decklist_module = Extension('_decklist',
sources=['decklist_wrap.cxx', 'decklist.cpp'],
)
setup (name = 'decklist',
version = '0.1',
author = "Me",
description = """Testing!""",
ext_modules = [decklist_module],
py_modules = ["decklist"],
)
decklist.hpp:
#include <boost/unordered_map.hpp>
class DeckList{
private:
boost::unordered_map<std::string, int> mainBoard;
boost::unordered_map<std::string, int> sideBoard;
public:
void addCard(std::string name, int cardCount);
int getCount(std::string cardName);
DeckList();
~DeckList();
};
decklist.cpp:
#ifndef DECKLIST_H
#define DECKLIST_H
#include "decklist.hpp"
#include <stdio.h>
DeckList::DeckList(){
}
void DeckList::addCard(std::string cardName, int cardCount){
mainBoard[cardName] = cardCount;
}
int DeckList::getCount(std::string cardName){
return mainBoard[cardName];
}
#endif
decklist.i:
//decklist.i
%module decklist
%{
#include "decklist.hpp"
%}
#include "decklist.hpp"
Now on the terminal (I am on Ubuntu Natty Narwhal), I run the following two
commands:
swig -python -c++ decklist.i
python setup.py build_ext --inplace
The second gives me the following response:
running build_ext
building '_decklist' extension
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.7 -c decklist_wrap.cxx -o build/temp.linux-x86_64-2.7/decklist_wrap.o
cc1plus: warning: command line option "-Wstrict-prototypes" is valid for Ada/C/ObjC but not for C++
gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.7 -c decklist.cpp -o build/temp.linux-x86_64-2.7/decklist.o
cc1plus: warning: command line option "-Wstrict-prototypes" is valid for Ada/C/ObjC but not for C++
g++ -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions build/temp.linux-x86_64-2.7/decklist_wrap.o build/temp.linux-x86_64-2.7/decklist.o -o /home/aespiel1/deck/_decklist.so
But I wind up with:
decklist.cpp
decklist.hpp
decklist.i
decklist.py
decklist.pyc
_decklist.so
decklist_wrap.cxx
setup.py
and a build folder with `.o` files for both the `decklist_wrap` and `decklist`
files.
If I run python in idle and switch into this directory and:
import decklist
I get:
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
import decklist
ImportError: No module named decklist
Strangely, if I run it from the terminal, I can `import decklist`. But then a
command like:
dl = decklist.DeckList()
gives:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'DeckList'
What am I doing wrong? I am so frustrated.
Answer: change decklist.i as following:
//decklist.i
%module decklist
%{
#include "decklist.hpp"
%}
%include "decklist.hpp" // <-- *** use % in *.i ***
or you can declare your classes & functions here that you want to export.
|
Mean subtraction of patches in python nympy scipy
Question: I have a numpy array of 3 dimension, it's a grid of patches of 8x8 images.
What is the best way to subtract from each patch it's average, in other words
each patch has a unique mean and I want to subtract it. I tried the following
with no success obviously because both arrays are not equal in shape
patches=- patches.mean(axis = 2).mean(axis = 1)
I thought of using the repeat function, something like:
patches=- np.repeat(np.repeat(patches.mean(axis =2).mean(axis =1).reshape((n_patches, 8, 8)), 1, 1))
Put I think that following this route would lead to an inefficient solution.
Any thoughts or solution on this?
Answer:
import numpy as np
a = np.random.rand(10,8,8)
mean = a.mean(axis=2).mean(axis=1)
b = a - mean[:, np.newaxis, np.newaxis] # reshape the mean as (10, 1, 1)
|
How to check if webpage are alive with python with multiproccessing
Question: I have a list of urls (about 25k) and I am trying to check if they are alive
(200 response). want to do these checks in parallel using the multiprocessing
library for Python. I wrote the following (largely based on the Python doc
example) but it seems to run pretty slowly. Is there any way I can make this
script run faster?
import urllib2
import time
import random
from multiprocessing import Process, Queue, current_process, freeze_support
class HeadRequest(urllib2.Request):
def get_method(self):
return "HEAD"
#
# Function run by worker processes
#
def worker(input, output):
for args in iter(input.get, 'STOP'):
result = alive(args)
output.put(result)
#
# Functions referenced by tasks
#
def alive(x):
x = x.strip()
try:
return x, ":", urllib2.urlopen(HeadRequest(x)).getcode()
except urllib2.HTTPError as e:
return x, ":", e.code
except:
return x, ": Error"
#
#
#
def check():
NUMBER_OF_PROCESSES = 500
text_file = open("url.txt", "r")
TASKS1 = text_file.readlines()
# Create queues
task_queue = Queue()
done_queue = Queue()
# Submit tasks
for task in TASKS1:
task_queue.put(task)
# Start worker processes
for i in range(NUMBER_OF_PROCESSES):
Process(target=worker, args=(task_queue, done_queue)).start()
# Get and print results
for i in range(len(TASKS1)):
print done_queue.get()
# Tell child processes to stop
for i in range(NUMBER_OF_PROCESSES):
task_queue.put('STOP')
if __name__ == '__main__':
freeze_support()
check()
Any help is appreciated
Answer: There is an easy way:
<http://scrapy.org/>
Scrapy provides web crawler framework for Python: you can give it a list of
URLs to crawl (in your case it doesn't need to follow links) and it will
automatically scale to several crawlers within the process/thread limitations
you give to it - you don't need to go to the details of multiprocess
communications and scaling yourself.
<http://doc.scrapy.org/topics/scrapyd.html#topics-scrapyd>
The only thing left for your own code is to analyze the results.
|
How in Python check if two files ( String and file ) have same content?
Question: I am very new to Python and have question. How in Python check if two files (
String and file ) have same content ? I need to download some stuffs and
rename, but I don't want to save same stuff with two or more different names
(same stuff can be on different ip addresses ).
Answer: If the file is large, I would consider reading it in chunks like this:
compare.py:
import hashlib
teststr = "foo"
filename = "file.txt"
def md5_for_file(f, block_size=2**20):
md5 = hashlib.md5()
while True:
data = f.read(block_size)
if not data:
break
md5.update(data.encode('utf8'))
return md5.digest()
md5 = hashlib.md5()
md5.update((teststr + "\n").encode('utf8'))
digest = md5.digest()
f = open(filename, 'r')
print(md5_for_file(f) == digest)
file.txt:
foo
This program prints True if the string and file match
|
How to add builtin functions
Question: I am new to python programming. How can I add new built-in functions and
keywords to python interpreter using C or C++?
Answer: In short, it is _technically_ possible to add things to Python's builtins†,
but it is almost never necessary (and generally considered a very bad idea).
In longer, it's obviously possible to modify Python's source and add new
builtins, keywords, etc… But the process for doing that is a bit out of the
scope of the question as it stands.
If you'd like more detail on how to modify the Python source, how to write C
functions which can be called from Python, or something else, please edit the
question to make it more specific.
If you are new to Python programming and you feel like you _should_ be
modifying the core language in your day-to-day work, that's probably an
indicator you should simply be learning more about it. Python is used,
unmodified, for a huge number of different problem domains (for example,
[numpy](http://numpy.scipy.org/) is an extension which facilitates scientific
computing and [Blender](http://www.blender.org/) uses it for 3D animation), so
it's likely that the language can handle your problem domain too.
†: you _can_ modify the `__builtin__` module to “add new builtins”… But this
is almost certainly a bad idea: any code which depends on it will be very
difficult (and confusing) to use anywhere outside the context of its original
application. Consider, for example, if you add a `greater_than_zero`
“builtin”, then use it somewhere else:
$ cat foo.py
__builtin__.greater_than_zero = lambda x: x > 0
def foo(x):
if greater_than_zero(x):
return "greater"
return "smaller"
Anyone who tries to read that code will be confused because they won't know
where `greater_than_zero` is defined, and anyone who tries to use that code
from an applicaiton which hasn't snuck `greater_than_zero` into `__builtin__`
won't be able to use it.
A better method is to use Python's existing `import` statement:
<http://docs.python.org/tutorial/modules.html>
|
Write frames from camera to a single image in OpenCV
Question: I am trying to grab frames from camera and add them into a single image to get
the effect as in this image:
<http://www.danheller.com/images/California/DeathValley/Nite/tent-star-
trails.jpg>
But my image turns white after a couple of seconds. Here is the code:
#!/usr/bin/python
import cv
stream = cv.CaptureFromCAM(0)
cv.NamedWindow("Stream",1)
out = cv.CreateImage((640, 480), 8, 3)
while True:
frame = cv.QueryFrame(stream)
cv.Add(frame, out, out, None)
cv.ShowImage("Stream", out)
cv.WaitKey(25)
Can anyone help?
Answer: Yes, your image will turn white after a few frames because adding images pixel
by pixel increases the brightness by quite a lot. You'll have to come up with
a better algorithm to merge the images together.
One way you can do that is add the two images then normalize the resulting
image before adding more images on, or if you're adding lots of frames, add
only a small multiple (0.01) of the pixel value of the image to the resulting
image each frame, but again, normalize the resulting image so dark pixels stay
dark. This effectively simulates the long exposure effect that is created
using real cameras.
Real cameras create that effect by having a very low exposure setting so only
a few photons enter the lens at once, so when you leave the camera stationary
for a while, more and more photos hit the film and eventually brightens up the
picture. If you left the camera long enough. If you left the camera out for
too long, the same thing will happen to the picture, it will go white. Adding
pictures together directly is like having a very high exposure, lots of light
enters the lens at once and the picture turns white.
|
iterate through unicode strings and compare with unicode in python dictionary
Question:
I have two python dictionaries containing information about japanese words and
characters:
1. vocabDic : contains vocabulary, key: word, value: dictionary with information about it
2. kanjiDic : contains kanji ( single japanese character ), key: kanji, value: dictionary with information about it
Now I would like to iterate through each character of each word in the
vocabDic and look up this character in the kanji dictionary. My goal is to
create a csv file which I can then import into a database as join table for
vocabulary and kanji.
My Python version is 2.6
My code is as following:
kanjiVocabJoinWriter = csv.writer(open('kanjiVocabJoin.csv', 'wb'), delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
kanjiVocabJoinCount = 1
#loop through dictionary
for key, val in vocabDic.iteritems():
if val['lang'] is 'jpn': # only check japanese words
vocab = val['text']
print vocab
# loop through vocab string
for v in vocab:
test = kanjiDic.get(v)
print v
print test
if test is not None:
print str(kanjiVocabJoinCount)+','+str(test['id'])+','+str(val['id'])
kanjiVocabJoinWriter([str(kanjiVocabJoinCount),str(test['id']),str(val['id'])])
kanjiVocabJoinCount = kanjiVocabJoinCount+1
If I print the variables to the command line, I get:
vocab : works, prints in japanese
v ( one character of the vocab in the for loop ) : �
test ( character looked up in the kanjiDic ) : None
To me it seems like the for loop messes the encoding up.
I tried various functions ( decode, encode.. ) but no luck so far.
Any ideas on how I could get this working?
Help would be very much appreciated.
Answer: From your description of the problem, it sounds like `vocab` is an encoded
`str` object, not a `unicode` object.
For concreteness, suppose `vocab` equals `u'債務の天井'` encoded in `utf-8`:
In [42]: v=u'債務の天井'
In [43]: vocab=v.encode('utf-8') # val['text']
Out[43]: '\xe5\x82\xb5\xe5\x8b\x99\xe3\x81\xae\xe5\xa4\xa9\xe4\xba\x95'
If you loop over the encoded `str` object, you get one byte at a time: `\xe5`,
then `\x82`, then `\xb5`, etc.
However if you loop over the unicode object, you'd get one unicode character
at a time:
In [45]: for v in u'債務の天井':
....: print(v)
債
務
の
天
井
Note that the first unicode character, encoded in `utf-8`, is 3 bytes:
In [49]: u'債'.encode('utf-8')
Out[49]: '\xe5\x82\xb5'
That's why looping over the bytes, printing one byte at a time, (e.g. `print
\xe5`) fails to print a recognizable character.
So it looks like you need to decode your `str` objects and work with `unicode`
objects. You didn't mention what encoding you are using for your `str`
objects. If it is `utf-8`, then you'd decode it like this:
vocab=val['text'].decode('utf-8')
If you are not sure what encoding `val['text']` is in, post the output of
print(repr(vocab))
and maybe we can guess the encoding.
|
File operations in Python
Question: I have a piece of code which extracts a string that lies between two
strings.However,this script performs this operation only on a line.I want to
perform this operation on a complete file and get a list of all the words
lying between those two words.
Note:The two words are fixed.For ex:If my code is something like
'const int variablename=1'
then I want a list of all the words in the file lying between `'int'` and
`'='`. Here is the current script:
s='const int variablename = 1'
k=s[s.find('int')+4:s.find('=')]
print k
Answer: If the file fits comfortably into memory, you can get this with a single regex
call:
import re
regex = re.compile(
r"""(?x)
(?<= # Assert that the text before the current location is:
\b # word boundary
int # "int"
\s # whitespace
) # End of lookbehind
[^=]* # Match any number of characters except =
(?<!\s) # Assert that the previous character isn't whitespace.
(?= # Assert that the following text is:
\s* # optional whitespace
= # "="
) # end of lookahead""")
with open(filename) as fn:
text = fn.read()
matches = regex.findall(text)
If there can be only one word between `int` and `=`, then the regex is a bit
more simple:
regex = re.compile(
r"""(?x)
(?<= # Assert that the text before the current location is:
\b # word boundary
int # "int"
\s # whitespace
) # End of lookbehind
[^=\s]* # Match any number of characters except = or space
(?= # Assert that the following text is:
\s* # optional whitespace
= # "="
) # end of lookahead""")
|
Question about timeit module in python
Question: I have a question about the timeit module in python, which is used to
determine the time it takes for a piece of code to execute.
t = timeit.Timer("foo","from __main__ import foo")
str(t.timeit(1000))
What is the meaning of the argument 1000 in the above code ?
Answer: From the
[documentation](http://docs.python.org/library/timeit.html#timeit.Timer.timeit):
>
> Timer.timeit([number=1000000])
>
>
> Time `number` executions of the main statement. This executes the setup
> statement once, and then returns the time it takes to execute the main
> statement a number of times, measured in seconds as a float. The argument is
> the number of times through the loop, defaulting to one million. The main
> statement, the setup statement and the timer function to be used are passed
> to the constructor.
|
Installing h5py on OS X
Question: I've spent the day trying to get the `h5py` module of python working, but
without success. I've installed HDF5 shared libraries, followed the
instructions I could find on the web to get it right. But it doesn't work,
below is the error message I get when trying to import the module into python.
I tried installing through MacPorts too but again it wouldnt work.
I'm using Python27 32 bits (had too for another module, and thus installed the
i386 HDF5 library... if that's right?)
Any help very welcome !
Thank you !
import h5py
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/h5py/__init__.py", line 1, in <module>
from h5py import _errors
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/h5py/_errors.so, 2): Symbol not found: _H5E_ALREADYEXISTS_g
Referenced from: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/h5py/_errors.so
Expected in: flat namespace
in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/h5py/_errors.so
Answer: Check that you are not inside the h5py installation directory.
|
Get socket for urllib2.urlopen return value for HTTP
Question: I'm trying to do asynchronous downloading of files using urllib2 but have no
succeeded in finding out the socket (or its fileno) to wait for new data for
for HTTP requests. Here's what I've already tried.
>>> from urllib2 import urlopen
>>> from select import select
>>> r = urlopen('http://stackoverflow.com/')
>>> select([r], [], [])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/socket.py", line 307, in fileno
return self._sock.fileno()
AttributeError: HTTPResponse instance has no attribute 'fileno'
>>> r.fileno()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/socket.py", line 307, in fileno
return self._sock.fileno()
AttributeError: HTTPResponse instance has no attribute 'fileno'
>>> r.fp.fileno()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/socket.py", line 307, in fileno
return self._sock.fileno()
AttributeError: HTTPResponse instance has no attribute 'fileno'
>>> select([r.fp], [], [])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/socket.py", line 307, in fileno
return self._sock.fileno()
AttributeError: HTTPResponse instance has no attribute 'fileno'
>>>
Answer: See <http://www.velocityreviews.com/forums/t512553-re-urllib2-urlopen-
broken.html>.
> The problem is that urlib2 was changed to wrap an HTTPResponse object in a
> socket._fileobject to get a few more file methods. Except (as reported
> above) HTTPResponse doesn't have a fileno() method, so when _fileobject
> tries to use it, it blows up.
The solution
Adding an appropriate method to HTTPResponse:
def fileno(self):
return self.fp.fileno()
Or, alternatively, use `urllib.urlopen` instead of `urrlib2.urlopen`.
There is a [bug report](http://bugs.python.org/issue1327971) for this issue;
it was fixed in Python 3 and in Python 2.7.
|
opencv getImage() error
Question: I wrapped opencv today with simplecv python interface. After going through the
official [SimpleCV Cookbook](http://simplecv.org/doc/cookbook.html) I was able
to successfully [Load, Save](http://simplecv.org/doc/cookbook.html#loading-
and-saving-images), and
[Manipulate](http://simplecv.org/doc/cookbook.html#image-manipulation) images.
Thus, I know the library is being loaded properly.
However, under the [Using a Camera, Kinect, or Virtual
Camera](http://simplecv.org/doc/cookbook.html#using-a-camera-kinect-or-
virtualcamera) heading I was unsuccessful in running some commands. In
particular, `mycam = Camera()` worked, but `img = mycam.getImage()` produced
the following error:
In [35]: img = mycam.getImage().save()
OpenCV Error: Bad argument (Array should be CvMat or IplImage) in cvGetSize, file /home/jordan/OpenCV-2.2.0/modules/core/src/array.cpp, line 1237
---------------------------------------------------------------------------
error Traceback (most recent call last)
/home/simplecv/<ipython console> in <module>()
/usr/local/lib/python2.7/dist-packages/SimpleCV-1.1-py2.7.egg/SimpleCV/Camera.pyc in getImage(self)
332
333 frame = cv.RetrieveFrame(self.capture)
--> 334 newimg = cv.CreateImage(cv.GetSize(frame), cv.IPL_DEPTH_8U, 3)
335 cv.Copy(frame, newimg)
336 return Image(newimg, self)
error: Array should be CvMat or IplImage
I'm running Ubuntu Natty on a HP TX2500 tablet. It has a built in webcam,
(CyberLink Youcam?) Has anybody seen this error before? I've been all over the
web today looking for a solution, but nothing seems to be doing the trick.
**Update 1** : I tested cv.QueryFrame(capture) using the code found here [in a
separate Stack Overflow
question](http://stackoverflow.com/questions/4929721/opencv-python-grab-
frames-from-a-video-file) and it worked; so I've pretty much nailed this down
to a webcam issue.
**Update 2** : In fact, I get the exact same errors on a machine that doesn't
even have a webcam! It's looking like the TX2500 is not compatible...
Answer: since the error raised from Camera.py of SimpleCV, you need to debug the
getImage() method. If you can edit it:
def getImage(self):
if (not self.threaded):
cv.GrabFrame(self.capture)
frame = cv.RetrieveFrame(self.capture)
import pdb # <-- add this line
pdb.set_trace() # <-- add this line
newimg = cv.CreateImage(cv.GetSize(frame), cv.IPL_DEPTH_8U, 3)
cv.Copy(frame, newimg)
return Image(newimg, self)
then run your program, it will be paused as pdb.set_trace(), here you can
inspect the type of frame, and try to figure out how get the size of frame.
Or you can do the capture in your code, and inspect the frame object:
mycam = Camera()
cv.GrabFrame(mycam.capture)
frame = cv.RetrieveFrame(mycam.capture)
|
How to pull specific information from an output in Python
Question: So I have a code that gives an output, and what I need to do is pull the
information out in between the commas, assign them to a variable that changes
dynamically when called... here is my code:
import re
data_directory = 'Z:/Blender_Roto/'
data_file = 'diving_board.shape4ae'
fullpath = data_directory + data_file
print("====init=====")
file = open(fullpath)
for line in file:
current_line = line
# massive room for optimized code here.
# this assumes the last element of the line containing the words
# "Units Per Second" is the number we are looking for.
# this is a non float number, generally.
if current_line.find("Units Per Second") != -1:
fps = line_split = float(current_line.split()[-1])
print("Frames Per Second:", fps)
# source dimensions
if current_line.find("Source Width") != -1:
source_width = line_split = int(current_line.split()[-1])
print("Source Width:", source_width)
if current_line.find("Source Height") != -1:
source_height = line_split = int(current_line.split()[-1])
print("Source Height:", source_height)
# aspect ratios
if current_line.find("Source Pixel Aspect Ratio") != -1:
source_px_aspect = line_split = int(current_line.split()[-1])
print("Source Pixel Aspect Ratio:", source_px_aspect)
if current_line.find("Comp Pixel Aspect Ratio") != -1:
comp_aspect = line_split = int(current_line.split()[-1])
print("Comp Pixel Aspect Ratio:", comp_aspect)
# assumption, ae file can contain multiple mocha shapes.
# without knowing the exact format i will limit the script
# to deal with one mocha shape being animated N frames.
# this gathers the shape details, and frame number but does not
# include error checking yet.
if current_line.find("XSpline") != -1:
# record the frame number.
frame = re.search("\s*(\d*)\s*XSpline", current_line)
if frame.group(1) != None:
frame = frame.group(1)
print("frame:", frame)
# pick part the part of the line that deals with geometry
match = re.search("XSpline\((.+)\)\n", current_line)
line_to_strip = match.group(1)
points = re.findall('(\(.*?\))', line_to_strip)
print(len(points))
for point in points:
print(point)
print("="*40)
file.close()
This gives me the output:
====init=====
Frames Per Second: 24.0
Source Width: 2048
Source Height: 778
Source Pixel Aspect Ratio: 1
Comp Pixel Aspect Ratio: 1
frame: 20
5
(0.793803,0.136326,0,0.5,0)
(0.772345,0.642332,0,0.5,0)
(0.6436,0.597615,0,0.5,0)
(0.70082,0.143387,0,0.5,0.25)
(0.70082,0.112791,0,0.5,0)
========================================
So what I need for example is to be able to assign (0.793803, 0.136326, 0,
0.5, 0) to (1x,1y,1z,1w,1s), (0.772345,0.642332,0,0.5,0) to (2x, 2y, 2z, 2w,
2s) etc so that no matter what numbers are filling those positions they will
take on that value.
here is the code I need to put those numbers into:
#-------------------------------------------------------------------------------
# Name: Mocha Rotoscoping Via Blender
# Purpose: Make rotoscoping more efficient
#
# Author: Jeff Owens
#
# Created: 11/07/2011
# Copyright: (c) jeff.owens 2011
# Licence: Grasshorse
#-------------------------------------------------------------------------------
#!/usr/bin/env python
import sys
import os
import parser
sys.path.append('Z:\_protomotion\Prog\HelperScripts')
import GetDir
sys.path.append('Z:\_tutorials\01\tut01_001\prod\Blender_Test')
filename = 'diving_board.shape4ae'
infile = 'Z:\_tutorials\01\tut01_001\prod\Blender_Test'
import bpy
from mathutils import Vector
#below are taken from mocha export
x_width =2048
y_height = 778
z_depth = 0
frame = 20
def readText():
text_file = open('diving_board.shape4ae', 'r')
lines = text_file.readlines()
print (lines)
print (len.lines)
for line in lines:
print (line)
##sets points final x,y,z value taken from mocha export for blender interface
point1x = (0.642706 * x_width)
point1y = (0.597615 * y_height)
point1z = (0 * z_depth)
point2x = (0.770557 * x_width)
point2y = (0.647039 * y_height)
point2z = (0 * z_depth)
point3x = (0.794697 * x_width)
point3y = (0.0869024 * y_height)
point3z = (0 * z_depth)
point4x = (0.707973* x_width)
point4y = (0.0751348 * y_height)
point4z = (0 * z_depth)
w = 1 # weight
listOfVectors = [Vector((point1x,point1y,point1z)),Vector((point2x,point2y,point2z)),Vector((point3x,point3 y,point3z)),Vector((point4x,point4y,point4z)), Vector((point1x,point1y,point1z))]
def MakePolyLine(objname, curvename, cList):
curvedata = bpy.data.curves.new(name=curvename, type='CURVE')
curvedata.dimensions = '3D'
objectdata = bpy.data.objects.new(objname, curvedata)
objectdata.location = (0,0,0) #object origin
bpy.context.scene.objects.link(objectdata)
polyline = curvedata.splines.new('POLY')
polyline.points.add(len(cList)-1)
for num in range(len(cList)):
x, y, z = cList[num]
polyline.points[num].co = (x, y, z, w)
MakePolyLine("NameOfMyCurveObject", "NameOfMyCurve", listOfVectors)
So where I have my vector I would like to be able to place (p.x,
p.y,0.z,p.w,p.s) then (p2.x,p2.y,p2.zp2.wp2.s) etc so that it can change per
the number given
Any help will be great.. thank you in advance!
-jeff
Answer: Instead of _printing_ each output, you can create point objects and index them
by name. For example:
>>> class Point:
... def __init__(self, t):
... (self.x,self.y,self.z,self.w,self.s) = t
...
>>> p = Point( (3,4,5,3,1) )
>>> p.w
3
You can place these point objects in an array, then access components by
myPoints[3].x
**ADDENDUM**
If it is important to you _not_ to pull the points from an array, but rather
use actual variable names, you _can_ do the following, where `points` is your
**array of tuples** :
(p0x,p0y,p0z,p0w,p0s) = points[0]
(p1x,p1y,p1z,p1w,p1s) = points[1]
(p2x,p2y,p2z,p2w,p2s) = points[2]
...
and so on.
Do consider whether this is an appropriate approach though. Having a point
class allows you to have any number of points. With defined variable names,
creating an unbounded number of these things on the fly is possible but almost
always a bad idea. Here is a caveat about doing so:
<http://mail.python.org/pipermail/tutor/2005-January/035232.html>.
When you have an array of point objects you do what you want much better! For
example you can do the following:
myPoints[i].y = 12
thereby changing the y-coordinate of the ith point. This is next to impossible
when you have fixed the variable names. Hope that helps! (And hope I
understand your clarification! Let me know if not....)
|
why is python script failing to download webpages through a proxy
Question: i am new to python and am trying my luck at sockets. So i wrote a simple http
client but to my surprise it is failing to access webpages that firefox can
access, yet they use the same headers
import socket
clientsocket= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(("213.229.83.205",80))#connect to proxy at given address
print "connected to 213.229.83.205"
sdata= """GET http://google.co.ug/ HTTP/1.1
Host: google.co.ug
User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:6.0) Gecko/20100101 Firefox/6.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Proxy-Connection: keep-alive
Cookie: cookie <-- Real cookie deleted
"""
print "sending request"
clientsocket.send(sdata);
rdata=clientsocket.recv(10240)
if not rdata: print "no data found"
else:
print "receiving data !"
myfile=open("c:/users/markdenis/desktop/google.html","w")
myfile.write(str(rdata))
myfile.close()
print "data written to file on desktop"
clientsocket.close()
raw_input()#system(pause)
When i run it, it shows:
connected to 213.229.83.205
sending request
no data found
Answer: The HTTP protocol requires `\r\n` at the end of each header and an extra on a
blank line at the end of the HTTP headers. You aren't explicit about the line
endings in your `sdata` buffer, and therefore your buffer ends up with just
`\n` line endings.
Tested on Windows, Linux and OS X, to be sure:
>>> x = """a
b
c"""
>>> x
'a\\nb\\nc\\n'
Where you need:
>>> x = "a\r\nb\r\nc\r\n"
>>> x
'a\\r\\nb\\r\\nc\\r\\n'
Add `\r\n`s and give it a shot. Doing it directly in the buffer will get you
an extra set of `\n`, so split it up:
sdata = "GET http://google.co.ug/ HTTP/1.1\r\n"
sdata += "Host: google.co.ug\r\n"
sdata += "User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:6.0) Gecko/20100101 Firefox/6.0\r\n"
sdata += "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n"
sdata += "Accept-Language: en-us,en;q=0.5\r\n"
sdata += "Accept-Encoding: gzip, deflate\r\n"
sdata += "Proxy-Connection: keep-alive\r\n"
sdata += "\r\n"
|
Possible to Simplify These Python Regular Expressions?
Question:
patterns = {}
patterns[1] = re.compile("[A-Z]\d-[A-Z]\d")
patterns[2] = re.compile("[A-Z]\d-[A-Z]\d\d")
patterns[3] = re.compile("[A-Z]\d\d-[A-Z]\d\d")
patterns[4] = re.compile("[A-Z]\d\d-[A-Z]\d\d\d")
patterns[5] = re.compile("[A-Z]\d\d\d-[A-Z]\d\d\d")
patterns[6] = re.compile("[A-Z][A-Z]\d-[A-Z][A-Z]\d")
patterns[7] = re.compile("[A-Z][A-Z]\d-[A-Z][A-Z]\d\d")
patterns[8] = re.compile("[A-Z][A-Z]\d\d-[A-Z][A-Z]\d\d")
patterns[9] = re.compile("[A-Z][A-Z]\d\d-[A-Z][A-Z]\d\d\d")
patterns[10] = re.compile("[A-Z][A-Z]\d\d\d-[A-Z][A-Z]\d\d\d")
def matchFound(toSearch):
for items in sorted(patterns.keys(), reverse=True):
matchObject = patterns[items].search(toSearch)
if matchObject:
return items
return 0
then I use the following code to look for matches:
while matchFound(toSearch) > 0:
I have 10 different regular expressions but I feel like they could be replaced
by one, well written, more elegant regular expression. Do you guys think it's
possible?
EDIT: FORGOT TWO MORE EXPRESSIONS:
patterns[11] = re.compile("[A-Z]\d-[A-Z]\d\d\d")
patterns[12] = re.compile("[A-Z][A-Z]\d-[A-Z][A-Z]\d\d\d")
EDIT2: I ended up with the following. I realize I COULD get extra results but
I don't think they're possible in the data I'm parsing.
patterns = {}
patterns[1] = re.compile("[A-Z]{1,2}\d-[A-Z]{1,2}\d{1,3}")
patterns[2] = re.compile("[A-Z]{1,2}\d\d-[A-Z]{1,2}\d{2,3}")
patterns[3] = re.compile("[A-Z]{1,2}\d\d\d-[A-Z]{1,2}\d\d\d")
Answer: Sean Bright gave you the answer you need. Here's just a general tip:
Python has wonderful documentation. In this case, you could read it with the
"help" command:
import re
help(re)
And if you read through the help, you would see:
{m,n} Matches from m to n repetitions of the preceding RE.
It also helps to use Google. "Python regular expressions" found these links
for me:
<http://docs.python.org/library/re.html>
<http://docs.python.org/howto/regex.html>
Both are worth reading.
|
How to draw an ordered tree in python?
Question: I have an XML file whose underlying structure is an ordered tree. I use
digraph in networks representing this tree and then I want to draw this tree.
Suppose the digraph is G, then I write the following code:
map = dict(zip(id,tag)) # map from id to label
pos = nx.pydot_layout(G,prog = 'dot')
labels = nx.draw_networkx_labels(G, pos, map)
nx.draw_networkx(G, pos, False, node_size = 1000, node_color = color)
plt.show()
but i cannot get a ordered tree. the order of silbing nodes are not in their
original order.
I want to know how can I plot an ordered tree in python, thanks,
Answer: Don't call a variable `map`, there is a builtin called `map`.
You can use an
[OrderedDict](http://docs.python.org/library/collections.html#collections.OrderedDict)
to keep the items in order:
from collections import OrderedDict
from itertools import izip
themap = OrderedDict(izip(id,tag)) # map from id to label
You can also [get it from PyPI](http://pypi.python.org/pypi/ordereddict) if
you have an older version of Python than 2.7 / 3.2.
|
Trouble using pyopengl in Python 2.6.6
Question: What I'm trying to do is code a basic OpenGL 2.0 window, when I run the code
from a file, it works for the first couple of runs, then it dumps errors. If I
run the same exact code from the IDLE GUI, I get a window every time. The
following is first a list of added Python 2.6.6 packages, the code and the
errors. Am I using any conflicting packages? Am I missing a package? My
imports work in the IDLE GUI. Any help would be great!!
Date: Aug 1, 2011 Time: 03:20:00 AM
This is the listing of packages installed for Python 2.6.6.
This file was created manually and is meant to be used as a
reference to show what packages were added in which order
python-2.6.6.msi
setuptools-0.6c11-win32-py26.exe
numpy-1.6.0-win32-superpack-python26.exe
PIL-1.1.7-win32-py26.exe
wxPython2.8-win32-unicode-2.8.12.0-py26.exe
wxPython2.8-win32-docs-demos-2.8.12.0.exe
pyglet-1.1.4.msi
pywin32-216-win32.py32.exe
PyOpenGL-3.0.1.win32.exe
PyOpenGL-accelerate-3.0.1-win32-py26.exe
Pygame-1.9.1-win32-py26.msi
py2exe-0.6.9-win32-py2.6.exe
psyco (using c:\python26\scripts\easy_install psyco)
#import sys #redundant(used to eval errors)
#import OpenGL #redundant(used to eval errors)
#import numpy #redundant(used to eval errors)
#From here down is the original code, with gl imports listed as GLUT/GL/GLU
#Page 26 PyOpenGL.pdf by Stan Blank, Ph.D
from OpenGL.GL import * #These 3 imports are called in a layered format
from OpenGL.GLU import * #Fron the simplest to the most complex(complete)
from OpenGL.GLUT import *
def draw():
glClear(GL_COLOR_BUFFER_BIT)
glutWireTeapot(0.5)
glFlush()
glutInit(sys.argv)
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB)
glutInitWindowSize(250, 250)
glutInitWindowPosition(100, 100)
glutCreateWindow("Python OGL Program")
glutDisplayFunc(draw)
glutMainLoop()
IDLE error listings
Traceback (most recent call last):
File "C:\Code\Python\PyOpenGL\ogl_01.py", line 7, in
from OpenGL.GL import *
File "C:\Python26\lib\site-packages\pyopengl-3.0.1-py2.6-win32.egg\OpenGL\GL\__init__.py", line 2, in
from OpenGL.raw.GL import *
File "C:\Python26\lib\site-packages\pyopengl-3.0.1-py2.6-win32.egg\OpenGL\raw\GL\__init__.py", line 6, in
from OpenGL.raw.GL.constants import *
File "C:\Python26\lib\site-packages\pyopengl-3.0.1-py2.6-win32.egg\OpenGL\raw\GL\constants.py", line 7, in
from OpenGL import platform, arrays
File "C:\Python26\lib\site-packages\pyopengl-3.0.1-py2.6-win32.egg\OpenGL\arrays\__init__.py", line 22, in
formathandler.FormatHandler.loadAll()
File "C:\Python26\lib\site-packages\pyopengl-3.0.1-py2.6-win32.egg\OpenGL\arrays\formathandler.py", line 37, in loadAll
cls.loadPlugin( entrypoint )
File "C:\Python26\lib\site-packages\pyopengl-3.0.1-py2.6-win32.egg\OpenGL\arrays\formathandler.py", line 44, in loadPlugin
plugin_class = entrypoint.load()
File "C:\Python26\lib\site-packages\pyopengl-3.0.1-py2.6-win32.egg\OpenGL\plugins.py", line 14, in load
return importByName( self.import_path )
File "C:\Python26\lib\site-packages\pyopengl-3.0.1-py2.6-win32.egg\OpenGL\plugins.py", line 28, in importByName
module = __import__( ".".join(moduleName), {}, {}, moduleName)
File "C:\Python26\lib\site-packages\pyopengl-3.0.1-py2.6-win32.egg\OpenGL\arrays\numpymodule.py", line 25, in
from OpenGL_accelerate.numpy_formathandler import NumpyHandler
File "numpy.pxd", line 30, in OpenGL_accelerate.numpy_formathandler (src\numpy_formathandler.c:3543)
ValueError: numpy.dtype does not appear to be the correct type object
Sorry for the length of the post, I just wanted to fully document the problem.
The Py install is running on Win XP SP3, IDLE header:
Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32
Answer: The numpy Cython extension for OpenGL was probably built with numpy 1.3.x. So
either you recompile OpenGL (especially the Cython extension) with your new
numpy version or you downgrade numpy to 1.3.x. (if this does not help try to
downgrade to 1.4.x and 1.5.x as well - as I do not exactly know what changed
in what version).
|
Program doesn't work completely when run outside eclipse
Question: I have a small python application, which uses pyttsx for some text to speech.
How it works: simply say whatever is there in the clipboard.
The program works as expected inside eclipse. But if run on cmd.exe it only
works partly if the text on the clipboard is too large(a few paras). Why ?
when run from cmd, it prints statements , but the actual 'talking' doesn't
work(if the clipboard text is too large
Here is a of the program part which actually does the talking: As can be seen
the 'talking' part is handled inside a thread.
def saythread(queue , text , pauselocation, startingPoint):
saythread.pauselocation = pauselocation
saythread.pause = 0
saythread.engine = pyttsx.init()
saythread.pausequeue1 = False
def onWord(name, location, length):
saythread.pausequeue1 = queue.get(False)
saythread.pause = location
saythread.pauselocation.append(location)
if saythread.pausequeue1 == True :
saythread.engine.stop()
def onFinishUtterance(name, completed):
if completed == True:
os._exit(0)
def engineRun():
if len(saythread.pauselocation) == 1:
rate = saythread.engine.getProperty('rate')
print rate
saythread.engine.setProperty('rate', rate-30)
textMod = text[startingPoint:]
saythread.engine.say(text[startingPoint:])
token = saythread.engine.connect("started-word" , onWord )
saythread.engine.connect("finished-utterance" , onFinishUtterance )
saythread.engine.startLoop(True)
engineRun()
if saythread.pausequeue1 == False:
os._exit(1)
def runNewThread(wordsToSay, startingPoint):
global queue, pauselocation
e1 = (queue, wordsToSay, pauselocation, startingPoint)
t1 = threading.Thread(target=saythread,args=e1)
t1.start()
#wordsToSay = CLIPBOARD CONTENTS
runNewThread(wordsToSay,0)
Thanks
Edit: I have checked than the python version used is the same 2.7 . The
command used to run the program in cmd : `python
d:\python\play\speech\speechplay.py`
Answer: Checked that the problem is not in the code that reads the text from the
clipboard.
You should check if your eclipse setup specifies custom environment variables
for the project which do not exist outside Eclipse. Especially:
* PYTHONPATH (and also additional projects on which your program could depend in your setup)
* PATH
Use
import os
print os.environ['PATH']
print os.environ['PYTHONPATH']
at the beginning of your program to compare both settings.
Misc stylistic advices:
* don't use `os._exit`, prefer `sys.exit` (you should only use `os._exit` in a child process after a call to `os.fork`, which is not available on Windows)
* I think a `threading.Event` would be more appropriate than a `queue.Queue`
* I'd use a subclass approach for the thread with methods rather than a function with inner functions
For example:
import threading
import sys
import pyttsx
class SayThread(threading.Thread):
def __init__(self, queue, text, pauselocation, startingPoint, debug=False):
threading.Thread.__init__(self)
self.queue = queue
self.text = text
self.pauselocation = pauselocation
self.startingPoint = startingPoint
self.pause = 0
self.engine = pyttsx.init(debug=debug)
self.pausequeue1 = False
def run(self):
if len(self.pauselocation) == 1:
rate = self.engine.getProperty('rate')
print rate
self.engine.setProperty('rate', rate-30)
textMod = self.text[self.startingPoint:]
self.engine.say(self.text[self.startingPoint:])
self.engine.connect("started-word", self.onWord )
self.engine.connect("finished-utterance", self.onFinishUtterance )
self.engine.startLoop(True)
if self.pausequeue1 == False:
sys.exit(1)
def onWord(self, name, location, length):
self.pausequeue1 = self.queue.get(False)
self.pause = location
self.pauselocation.append(location)
if self.pausequeue1 == True :
self.engine.stop()
def onFinishUtterance(self, name, completed):
if completed == True:
sys.exit(0)
def runNewThread(wordsToSay, startingPoint):
global queue, pauselocation
t1 = SayThread(queue, wordsToSay,
pauselocation, startingPoint)
t1.start()
#wordsToSay = CLIPBOARD CONTENTS
runNewThread(wordsToSay,0)
|
How to automate shell input with python?
Question: I am automating some tasks with python, but have hit a bit of a roadblock. One
of the tasks I am automating requires user input in the shell.
The requirement is that you to run the command with an email address as a
parameter (simple enough), and then you are asked to authenticate with the
password for that email address. How can you simulate user input to provide
the password?
There are also some menus afterwards which ask options, for which the input
need just be to repeatedly hit enter. How is this simulated? Keeping in mind
that this window will not always have focus..
Answer: I'm not sure what you're asking in the second part, but subprocesses can be
controlled with the `pexpect` module. For example:
#!/usr/bin/env python
import pexpect
import sys
# Get email and password somehow
#email = ...
#password = ...
# Start the subprocess
child = pexpect.spawn('mycommand %s' % email)
# redirect output to stdout
child.logfile_read = sys.stdout
# Assumes the prompt is "password:"
child.expect('password:')
child.sendline(password)
# Wait for the process to close its output
child.expect(pexpect.EOF)
|
python locale for gtk does not work on windows
Question: I have python 2.7 and pygtk. I am trying to set locale language for gtk in my
application but no luck. My windows is in slovak language and I would like to
have button labels in my app in english. How to solve it?
I tried this but no luck (all labels are still in slovak): `
import os
os.environ['LANGUAGE'] = 'en_US' #tried en_UK as well
os.environ['LANG'] = 'en_US'
os.putenv('en_US', 'LANG')
import locale
locale.setlocale(locale.LC_ALL, 'English_United Kingdom.1252' )
`
but when I make cmd file this works:
set LANG=en_US
something.exe
what am I doing wrong?
Answer: This is becoming a common question these days and should probably become a
PyGTK FAQ. See for example this PyGTK [bug
report](https://bugzilla.gnome.org/show_bug.cgi?id=574520)
In short, there's a whole lot of details you're missing. For example:
1) Starting with Python 2.4, on Windows, assigning values to os.environ only
changes the copy of the environment variables Python manages and no longer has
any effect on the copy maintained by the C library (msvcr90 for Python, msvcrt
for the various GTK+ related dll's).
2) Once you take care of the above you also need to take special care of
configuring libintl. That means you'll need to bindtextdomain() and
bind_textdomain_codeset() both intl.dll and Python's gettext module.
There's probably more that I don't remember right now, but you could take a
look at my
[elib.intl](https://github.com/dieterv/elib.intl/blob/master/lib/elib/intl/__init__.py)
module written specifically for what you're trying to do (and more). When you
have it working, you can simply set the LANGUAGE environment variable to C to
have the default American English.
You can do that either from a .bat or .cmd file or by using
os.environ['LANGUAGE'] = 'C' befory you import elib.intl.
|
Getting python to print in UTF8 on Windows XP with the console
Question: I would like to configure my console on Windows XP to support UTF8 and to have
python detect that and work with it.
So far, my attempts:
C:\Documents and Settings\Philippe>C:\Python25\python.exe
Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> print u'é'
é
>>> import sys
>>> sys.stdout.encoding
'cp437'
>>> quit()
So, by default I am in cp437 and python detects that just fine.
C:\Documents and Settings\Philippe>chcp 65001
Active code page: 65001
C:\Documents and Settings\Philippe>python
Python 2.5.2 (r252:60911, Feb 21 2008, 13:11:45) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.stdout.encoding
'cp65001'
>>> print u'é'
C:\Documents and Settings\Philippe>
It seems like printing in UTF8 makes python crash now...
Answer: > I would like to configure my console on Windows XP to support UTF8
I don't think it's going to happen.
The 65001 code page is buggy; some stdio calls behave incorrectly and break
many tools. Whilst you can register cp65001 as an encoding manually:
def cp65001(name):
if name.lower()=='cp65001':
return codecs.lookup('utf-8')
codecs.register(cp65001)
and this allows you to `print u'some unicode string'`, it doesn't allow you to
write non-ASCII characters in that Unicode string. You get the same odd errors
(IOError 0 et al) that you do when you try to write non-ASCII UTF-8 sequences
directly as byte strings.
Unfortunately UTF-8 is a second-class citizen under Windows. NT's Unicode
model was drawn up before UTF-8 existed and consequently you're expected to
use two-byte-per-code-unit encodings (UTF-16, originally UCS-2) anywhere you
want consistent Unicode. Using byte strings, like many portable apps and
languages (such as Python) written with C's `stdio`, doesn't fit that model.
And rewriting Python to use the Windows Unicode console calls (like
WriteConsoleW) instead of the portable C stdio ones doesn't play well with
shell tricks like piping and redirecting to a file. (Not to mention that you
still have to change from the default terminal font to a TTF one before you
can see the results working at all...)
Ultimately if you need a command line with working UTF-8 support for stdio-
based apps, you'd probably be better off using an alternative to the Windows
Console that deliberately supports it, such as Cygwin's, or Python's IDLE or
pywin32's PythonWin.
|
Getting contents of title tags with Python script
Question: I want to make a really script in Python that gets the contents from the title
tags of a specified web page and then puts them into a MySQL database.
I have very (and I mean very) little experience with Python but this needs to
be done for my project. How can I do this in the simplest way possible?
I hope you are able to understand what I'm trying to ask.
Answer: 1. Study [urllib2](http://docs.python.org/library/urllib2.html#examples) to see how to download the webpage.
2. Study [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/documentation.html) to parse the HTML and pull out the title.
3. Study the [Python Database API Specification](http://www.python.org/dev/peps/pep-0249/) to insert rows into the MySQL database.
* * *
Here is some example code to get you started:
import urllib2
import BeautifulSoup
import MySQLdb
f = urllib2.urlopen('http://www.python.org/')
soup=BeautifulSoup.BeautifulSoup(f.read())
title=soup.find('title')
print(title.string)
connection=MySQLdb.connect(
host='HOST',user='USER',
passwd='PASS',db='MYDB')
cursor=connection.cursor()
sql='''CREATE TABLE IF NOT EXISTS foo (
fooid int(11) NOT NULL AUTO_INCREMENT,
title varchar(100) NOT NULL,
PRIMARY KEY (fooid)
)'''
cursor.execute(sql)
sql='INSERT INTO foo (title) VALUES (%s)'
args=[title.string]
cursor.execute(sql,args)
cursor.close()
connection.close()
|
Let Tkinter continue to process next event without closing current pop-up window
Question: I am using tkinter to write a simple GUI program to plot figure of some data,
the plot function is realized using matplotlib module, here is my simplified
code:
#!/usr/bin/env python
import Tkinter, tkFileDialog, tkMessageBox
from plot_core import berplot
class BerPlotTk(Tkinter.Frame):
def __init__ (self, master = None):
Tkinter.Frame.__init__(self, master, width = 500, height = 200)
self.fullfilenames = [] # filename with path
self.master = master
self.CreateWidgets()
def CreateWidgets(self):
# other widgets...
# Buttons
self.button_sel = Tkinter.Button(self, text = "Open", command = self.Open)
self.button_sel.grid(column = 0, row = 7, sticky = "EW")
self.button_plot = Tkinter.Button(self, text = "Plot", command = self.Plot)
self.button_plot.grid(column = 2, row = 7, sticky = "EW")
self.button_exit = Tkinter.Button(self, text = "Exit", command = self.top.quit)
self.button_exit.grid(column = 3, row = 7, sticky = "EW")
def Open(self):
input_filenames = tkFileDialog.askopenfilename(parent = self.master,
title = "Select the log file")
self.fullfilenames = list(self.tk.splitlist(input_filenames))
def Plot(self):
berplot(self.fullfilenames)
if __name__ == "__main__":
root = Tkinter.Tk()
app = BerPlotTk(root)
root.mainloop()
root.destroy()
berplot() is a function in another python module as:
from matplotlib.pyplot import *
def berplot(filelist):
# retrieve data x, y from the log file
# ...
ber = semilogy(x, y)
# ...
show()
return 1
The program can work, when I open the data file and click "Plot" button, it
will create a figure window(by the matplotlib), but the GUI can not continue
to process before I close the figure window. However, I want to continue to
draw next figure while keeping current one, How can I realize this?
Answer: you can embed matplotlib figure in to Tk GUI:
import matplotlib
matplotlib.use('TkAgg')
from numpy import arange, sin, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
import Tkinter as Tk
class TkPlot(Tk.Frame):
def __init__ (self, master = None):
Tk.Frame.__init__(self, master, width = 500, height = 200)
self.CreateWidgets()
def CreateWidgets(self):
self.button = Tk.Button(root, text="Plot", command=self.Plot)
self.button.pack()
self.figure = Figure(figsize=(5,4), dpi=100)
canvas = FigureCanvasTkAgg(self.figure, master=root)
canvas.show()
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
toolbar = NavigationToolbar2TkAgg( canvas, root )
toolbar.update()
canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
def Plot(self):
a = self.figure.add_subplot(111)
t = arange(0.0,3.0,0.01)
s = sin(2*pi*t)
a.plot(t,s)
self.figure.canvas.draw()
if __name__ == "__main__":
root = Tk.Tk()
app = TkPlot(root)
root.mainloop()
<http://matplotlib.sourceforge.net/examples/user_interfaces/index.html>
|
Applying different commands at different location
Question: I am working in Ubuntu. I have a bunch of commands (say 10 commands like cmd1,
cmd2, cmd3..............cmd10)
I want to write a python script, which can achieve the following:
It should traverse through the directory structure and apply a command at
particular directory path. The location and the commands are already known to
me.
Here is the example how, I want the script to operate.
/local/mnt/myspace/sample1$ cmd1
/local/mnt/myspace/sample2$ cmd2
/local/mnt/myspace$ cmd3
/local/mnt$cmd4
/local/mnt/myspace/sample9$ cmd 8
/local/mnt/myspace/sample3$ cmd10
can someone please help on this.
Answer: Maybe something like this:
import subprocess
import os
jobs=[
('/local/mnt/myspace/sample1', 'cmd1'),
('/local/mnt/myspace/sample2', 'cmd2'),
('/local/mnt/myspace', 'cmd3'),
('/local/mnt', 'cmd4'),
('/local/mnt/myspace/sample9', 'cmd', '8'),
('/local/mnt/myspace/sample3', 'cmd10'),
]
for job in jobs:
print "In", job[0], "executing", job[1:]
os.chdir(job[0])
subprocess.Popen(job[1:]).wait()
(just a quick shot)
Look how I have "abused" the apparent mistake at cmd 8 to show how to call
programs which take parameters.
|
Sending message via Python + xmpppy: AttributeError in minimal example
Question: I found in a related question a minimal example to send a message via
xmpp(py); see below. But when I execute the script I get the following error:
client = xmpp.Client('gmail.com')
AttributeError: 'module' object has no attribute 'Client'
I'm working with Eclipse and PyDev, and xmpppy should definitely be installed.
The Interpreter includes /usr/local/lib/python2.7/dist-packages/ and when
looking there I find
/usr/local/lib/python2.7/dist-packages/xmpppy-0.5.0rc1-py2.7.egg
/usr/local/lib/python2.7/dist-packages/xmpppy-0.5.0rc1-py2.7.egg/xmpp
help('modules') also shows me the xmpp module. When using the autocomplete
function (CTRL + SPACE) in Eclipse/PyDev I can actually 'see' the client.
Still, I get the AttributeError. I guess I'm missing something really stupid
here.
Thanks,
Christian
import xmpp
username = 'username'
passwd = 'password'
to='[email protected]'
msg='hello :)'
client = xmpp.Client('gmail.com')
client.connect(server=('talk.google.com',5223))
client.auth(username, passwd, 'botty')
client.sendInitPresence()
message = xmpp.Message(to, msg)
message.setAttr('type', 'chat')
client.send(message)
Answer: You've named a script `xmpp.py`. You're accidentally `import`ing it instead of
the real `xmpp` module.
Rename the script and everything should work fine.
|
importing MySQL in django
Question: I downloaded The SQL API from here <http://www.djangoproject.com/r/python-
mysql/> (the official site) the problem is I don't know how to import it in
django. for example whrn I type this:
from django.shortcuts import render_to_response
import MySQLdb
....
...
..
I get the following error:
Traceback (most recent call last):
File "<console>", line 1, in <module>
ImportError: No module named MySQLdb
where should I extract the files, and what do I have to change to make it work
?
Answer: When you extract it , cd into where you extracted it and run the setup.py file
` python setup.py install `
|
Is there a library for splitting sentence into a list of words in it?
Question: I'm looking at nltk for python, but it splits(tokenize) `won't` as
`['wo',"n't"]`. Are there libraries that do this more robustly?
I know i can build a regex of some sort to solve this problem, but I'm looking
for a library/tool because it would be a more directed approach. For example,
after a basic regex with periods and commas, I realized words like 'Mr. ' will
break the system.
(@artsiom)
If the sentence was "you won't?", split() will give me ["you", "won't?"]. So
there's an extra '?' that I have to deal with. I'm looking for a tried and
tested method which do away with the kinks like the above mentioned and also
the lot many exceptions that I'm sure exist. Of course, I'll resort to a
split(regex) if I don't find any.
Answer: [The Natural Language Toolkit](http://www.nltk.org/) (NLTK) is probably what
you need.
>>> from nltk.tokenize import word_tokenize
>>> word_tokenize("'Hello. This is a test. It works!")
["'Hello", '.', 'This', 'is', 'a', 'test', '.', 'It', 'works', '!']
>>> word_tokenize("I won't fix your computer")
['I', 'wo', "n't", 'fix', 'your', 'computer']
[`nltk.tokenize.word_tokenize`](http://www.nltk.org/api/nltk.tokenize.html?highlight=word_tokenize#nltk.tokenize.word_tokenize)
by default use the
[`TreebankWordTokenizer`](http://www.nltk.org/api/nltk.tokenize.html?highlight=treebankwordtokenizer#nltk.tokenize.treebank.TreebankWordTokenizer),
a word tokenizer that tokenizes sentences with the [Penn
Treebank](http://www.cis.upenn.edu/~treebank/tokenization.html) conventions.
Note that this tokenizer assumes that the text has already been segmented into
sentences.
You can test some of the various tokenizers provided by NLTK (i.e.
[`WordPunctTokenizer`](http://www.nltk.org/api/nltk.tokenize.html?highlight=wordpuncttokenizer#nltk.tokenize.regexp.WordPunctTokenizer),
[`WhitespaceTokenizer`](http://www.nltk.org/api/nltk.tokenize.html?highlight=whitespacetokenizer#nltk.tokenize.regexp.WhitespaceTokenizer)...)
on this [page](http://text-processing.com/demo/tokenize/).
|
Why a procedure is so much faster when put into a function?
Question: Here is what I did, I created 2 procedures, one in a function and one in the
python file itself. The one on the python file itself run almost 2 times
slower even if it's exactly the same. WHY ?
Bellow is an example with 2 procedures that are just loops on P element
I have the following python file :
from time import *
P=1000000 #range of the 2 loops
def loop(N):
for k in range(N):
continue
start=time()
loop(P)
stop1=time()
for k in range(P):
continue
stop2=time()
print "time with function ",stop1-start
print "time without function ",stop2-stop1
Here is what I get (I tried it with one thousand samples and the result is the
following) :
time with function 0.0950000286102
time without function 0.15700006485
with xrange instead of range I get :
time with function 0.0460000038147
time without function 0.107999843597
So it's like 0.05 second in used to build the list
I know it's may be a useless question, but If someone know why is this going
so much faster I would be happy to know
Answer: The only significant difference is that the version in the function is only
updating the local variable for that function, whereas the version not in a
function is updating a _global_ variable `k`.
As mentioned
[here](http://wiki.python.org/moin/PythonSpeed/PerformanceTips#Local_Variables):
> The final speedup available to us for the non-map version of the for loop is
> to use local variables wherever possible. If the above loop is cast as a
> function, append and upper become local variables. **Python accesses local
> variables much more efficiently than global variables.**
|
Python AttributeError: 'module' object has no attribute 'init'
Question: I was running a simple python file:
from livewires import games
games.init(screen_width = 640, screen_height = 480, fps = 50)
games.screen.mainloop()
When I run this in IDLE, I get the error printed in the title. I copy and
pasted this code from a book. I'm at the early stages of a beginner, so I
don't know much. I'm fairly sure that I installed livewires properly as i've
already run other programs with its modules. (gosh, I know that that is
probably not the right terminology at all, sorry.) I'm not exactly looking for
a way to fix this, (although that'd be nice, too) I'm just hoping someone
could explain exactly what the problem is. I copied the code from a book so I
don't understand what I did wrong. I'm 100% positive that there are no typos,
too.
Answer: Well, searching around, it seems that this is the livewires website:
[Livewires Home Page](http://www.livewires.org.uk/python/home) where one can
download their livewires package.
Also, some code from this: [Chapter
11](http://docs.google.com/viewer?a=v&q=cache%3aZJ_gR284T4gJ%3amendel.informatics.indiana.edu/~yye/lab/teaching/fall2011-I210/CH11-game.ppt%20python%20old%20livewires%201.0&hl=en&gl=ca&pid=bl&srcid=ADGEESi_RxkDDp3D4RCDcmJss5zXXwccsbWuFzAJPPikP87WbvrO6YaTL7hwnuhSQIANCuuxD5IQmvegLHepBIlVnOYYz62abQUd5s3OzFzjbXOPLU61rQIgHlnnptYj0gxdl6Sce2CI&sig=AHIEtbQM5-j4ux2HLpcWTZY4Csr5voR2Ug)
looks like what he's posted here ("The Pizza Panic Game").
Downloading and unpacking livewires shows that there is indeed no `init`
function in the games module (as the comments already mentioned).
Either this book has non-working examples (doubtful, given the depth it
explains this example with); or **the livewires package has changed between
when the book was written and now** (much more likely).
The livewires website has other examples on it which I think you'll have much
more success with.
I'd recommend you ditch the book, since it's likely you'll keep running into
roadblocks like this. A Google search will turn up a number of other free
python tutorials which are more up-to-date, and will be easier to follow.
This page has a few links for beginners: [Beginners
Guide](http://wiki.python.org/moin/BeginnersGuide/NonProgrammers)
|
Algorithm: Stop invalid entries into a Competition in python script
Question: I have an Android Mobile App that is really just a calendar & you can click a
certain date & a secret code pops up. The user uses that code to enter a
competition - they follow the link to the competition HTML page(python script
really) & enter their details to enter the competition. There are 100 minor
prizes & 3 major prizes. A code can either be a non-winning code or it can win
the user a prize(either the minor or major).
So they will be redirected to: <http://mycompetition.com/comp.py?code=ABCDEF>
Then they enter their age, code & image captcha(avoiding spammers) & click
enter competition.
**My Problem:** I am having difficulty coming up with an algorithm to ensure
that people just don't type in the above URL & put a random code value for the
CGI 'code' value & accidentally win a prize if they guess a correct code(or
they use a bot to keep trying).
**Can you come up with any ideas to avoid someone who has not purchased the
app just going to the url above & typing in a random code & accidently winning
the prize?**
My algorithms/ideas:
\- Have the code 12 characters long which makes the probability of guessing
the code very slim but still possible. I am bad with maths & probability so if
I use 26 char & 10 digits as potential chars in the code does that mean the
probability of guesing correct 1 out of (36 chars * 12 pass length * 103
prizes)? Does that probability leave only supercomputers(not that I believe
anyones going to devote a super computer to my comp :P) able to guess the
code?
\- Dont associate a prize with a code. Instead just have the android app
randomly generate some code that means nothing & when they enter the
competition I just give them a random 1/10000 (I dont expect anywhere near
10000 entries into the comp) of winning a prize. To enter the competition you
have to enter your age & the code & then enter a captcha to avoid spammers.
\- Is there any easier algorithm you know of that avoids users who haven't
purchased the app getting a prize?
**EDIT:** \- What about whenever the App is downloaded I look at their
phones(wireless part) MAC address. On 1st run of the app I upload that MAC
address to my server that contains a list of MAC addresses of users of my app.
When/If they discover the secret code, they clikc enter competition & are
redirected to
[http://mycompetition.com/comp.py?code=RANDOMMEANINGLESSGENERATEDCODE&uniqueID=USERSMACADDRESS](http://mycompetition.com/comp.py?code=RANDOMMEANINGLESSGENERATEDCODE&uniqueID=USERSMACADDRESS).
In my script I check that the uniqueID is in my list of users who downloaded
my app, if it isn't I dont proceed, if it is they have 1/10000 chance of
winning a prize. Can you see any flaws in this algorithm?
Answer: Use an [HMAC](http://en.wikipedia.org/wiki/Hmac) to generate the code based on
a secret you share between the Android app and the site. As the text for the
HMAC, you can use a random value, which you include in the resulting code, or
something unique to the user, such as their email address (meaning that each
user can only have one valid code). If the length of the code is important,
you can truncate the hash produced by the HMAC, but bear in mind that the
shorter you truncate it, the more practical a brute-force attack is.
As long as your users cannot discover the shared secret, this will be secure
insofar as an attacker would have to guess at random, or attempt to determine
the secret by brute force. Since the code runs on user-owned devices, though,
there's no way to prevent them from extracting the code from your app. A user
with a rooted phone and a disassembler could do this relatively easily. To
combat that, you could obfuscate the code, and release new versions of the
app, updating the secret key there and on the site, whenever you suspect it's
been compromised.
Ultimately, because the device is in the user's control, there's no way to
totally prevent users from generating their own codes, but using an approach
such as the one above, you can make it much more difficult for them, and
easier for you to recover from it.
|
Python: exe file from script, significant performance decrese
Question: I am testing a C++ code compiled to exe (O errors, 0 warnings). The code
represents a console application. I run the apllication in the following ways:
a) from the windows7 command line: average time 497sec
b) from Python script using
subprocess.call ()
with the average time 1201 sec!
**Results:**
The application runs almost 3 tines longer from Python script than from
command line... Is this significant performance decrease normal ?
Answer: Are you measuring from the point that `subprocess.call()` is executed or from
the point that you load the Python script? I would imagine that a large
portion of that time arises from waiting for the Python interpreter to load,
the `subprocess` module to load, any other modules you import, etc. If your
Python script which calls the program will end up being large then I think
this will become insignificant. If it will be short, you may be better off
creating a Windows batch (.bat) file to call the program (assuming those still
exist in Win7...I haven't used Windows in a while).
|
Convert string into datetime type
Question: > **Possible Duplicate:**
> [Convert Date String to DateTime Object in
> Python](http://stackoverflow.com/questions/2721782/convert-date-string-to-
> datetime-object-in-python)
Is there an easy way to convert the string the string `10/22/1984` into a
datetime.date object?
Answer: You can use datetime.strptime method for this purpose:
from datetime import datetime
dVal = datetime.strptime('10/22/1984', '%m/%d/%Y')
You can read more using the [following link that describes python strptime
behavior](http://docs.python.org/library/datetime.html?highlight=datetime.strptime#strftime-
strptime-behavior).
|
javascript/python time processing fails in chrome
Question: I am writing a timer web app,which records start time and stop time.It uses
`javascript,jquery1.4.2` for the front end and `python` for backend code.When
a start button is clicked ,start time is saved in a javascript variable.when
the button is clicked again, stop time is saved in another variable.These
values are passed as hidden parameters to the python code which gets the
start,stop values from `django`'s `request` parameter.
I expect the start/stop parameters values to be in the following format
"07:16:03 PM"
so that it can be parsed using `'%I:%M:%S %p'`format string. I am getting this
correctly in `mozilla firefox`.But when I use `chrome`,I only get
"19:16:03"
This causes value error when I try to parse it with the above format string.
import time
...
def process_input(request,...):
start_time=request.POST[u'timerstarted']
...
fmtstr='%I:%M:%S %p'
start_time_list = list(time.strptime(start_time,fmtstr)[3:6])
I tried putting `alert('start time set as'+start_time)` in javascript to find
what values are set in the page's hiddenfields
With firefox ,I got
start time set as08:03:09 PM
stop time set as08:03:43 PM
but with chrome
start time set as20:04:21
stop time set as20:04:32
My knowledge of javascript,jquery is minimal.Why is the script behaving
differently in these two browsers? Below is the javascript snippet
$(document).ready(function(){
var changeBtnStatus=function(){
var timebtnvalue=$('#timebtn').attr("value");
if (timebtnvalue =="start"){
...
var start_date=new Date();
var str_time=start_date.toLocaleTimeString();
var timerstartedfield =$('#timerstarted');
timerstartedfield.attr("value",str_time);
alert('start time set as'+str_time);
}
else if (timebtnvalue=="stop"){
...
var stop_date=new Date();
var stp_time=stop_date.toLocaleTimeString();
var timerstoppedfield =$('#timerstopped');
timerstoppedfield.attr("value",stp_time);
alert('stop time set as'+stp_time);
}
};
var timerBtnClicked=function(){
...
changeBtnStatus();
};
$('#timebtn').click(timerBtnClicked);
...
}
);
Answer: You don't want the string of the time in locale, using the toString method you
can provide your own format, or use toUTCString().
toLocaleTimeString is especially meant to display the time as the user is used
to, you want it in a set format.
So instead of start_date.toLocaleTimeString(), you want to use
start_date.[toUTCString](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/toUTCString)().
|
Plotting directly to movie with numpy and mencoder
Question: So, this should be a comment to [this
thread](http://stackoverflow.com/questions/4092927/generating-movie-from-
python-without-saving-individual-frames-to-files), but it's apparently closed,
so here it goes. I've been playing around quite successfully with matplotlib
and numpy and mencoder, as has been suggested around here. I have since
adopted [Voki Codder buffer to stdin
solution](https://github.com/vokimon/freenect_python_processing/blob/master/src/videosink.py),
which speeds the whole process up considerably. The thing is, I couldn't find
any documentation on the -format="bgra" part of the command. This means that
the bytes are from right to left blue green red alpha, right. Do they have to
be uint32, or something else. The problem is I'm plotting colormaps of floats,
so I'm trying to convert them to grayscale, but I'm getting lots of weird
patterns which make me strongly believe I'm doing something wrong. I wrote
this function to convert from floats to uint32 within a range. But the result
is not why I expected, am I doing something terribly stupid?
def grayscale(x, min, max):
return np.uint32((x-min)/(max-min)*0xffffff)
Answer: I think you're getting confused on what the `uint32` represents. It's 4 bands
of `uint8` integers.
If you have floating point data, and want to represent it in grayscale, you
don't want to rescale it to a full 32 bit range, you want to rescale it to an
8-bit range, and repeat that for the red, green, and blue bands (and then
presumably put in a constant alpha band).
You could also just use a different byteorder. `Y8` is just a single
grayscale, 8-bit band, and `Y16` is a single, grayscale 16-bit band. (Have a
look at the output of `mencoder -rawvideo format=help` for a full (though
somewhat confusing) listing.)
Just to illustrate using numpy for view a 32-bit integer as four bands of
8-bit integers:
import numpy as np
height, width = 20,20
# Make an array with 4 bands of uint8 integers
image = np.zeros((height, width, 4), dtype=np.uint8)
# Filling a single band (red)
b,g,r,a = image.T
r.fill(255)
# Fill the image with yellow and leave alpha alone
image[...,:3] = (255, 255, 0)
# Then when we want to view it as a single, 32-bit band:
image32bit = image.reshape(-1).view(np.uint32).reshape(height, width)
# (Note that this is a view. In other words, we could change "b" above
# and it would change "image32bit")
In your case, however, you probably want to do something more like this:
import numpy as np
from videosink import VideoSink
height, width = 20,20
numframes = 1000
data = np.random.random((height, width, numframes))
# Rescale your data into 0-255, 8-bit integers
# (This could be done in-place if you need to conserve memory)
d ata_rescaled = 255.0 / (data.max() - data.min()) * (data - data.min())
data_rescaled = data_rescaled.astype(np.uint8)
# The key here is the "Y8" format. It's 8-bit grayscale.
video = VideoSink((height,width), "test", rate=20, byteorder="Y8")
# Iterate over last axis
for frame in data.T:
video.run(frame.T)
video.close()
|
Do Sets exist in Go? (like in Python)
Question: Is there any Go collection similar to 'Set's in python?
alternatives:
* Is there an easy way of implementing Sets in Go?
* Is there any method to eliminate duplicates in a slice?
Answer: You could just have a `map[whatevertype]bool` and set the value to `true`. You
could add every element in a slice as a map key, then use a `range` to get
only the unique ones back out.
package main
import "fmt"
func main() {
m := make(map[string]bool)
s := make([]string, 0)
s = append(s, "foo")
s = append(s, "foo")
s = append(s, "foo")
s = append(s, "bar")
s = append(s, "bar")
for _, r := range s {
m[r] = true
}
s = make([]string, 0)
for k, _ := range m {
s = append(s, k)
}
fmt.Printf("%v\n", s)
}
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.