text
stringlengths 226
34.5k
|
---|
write two values to csv row in python
Question: So I have a solved problem, but I don't like the solution :)
with open(outfile, 'a') as file:
writer = csv.writer(file) #opens a csv writer
#inserts ID to front of wordList
wordList.insert(0,ID)
writer.writerow(wordList)
#removes ID
wordList.remove(ID)
Right now it successfully writes an ID and a list of words into csv form (as
far as I can tell-- I don't actually have excel on my computer). The part I
don't like is that I have to insert and remove the ID, because I don't want it
included later. This seems lame. Can I somehow do a double insert to the same
row, easily?
I tried:
writer.writerow([ID,wordList])
but it gave undesirable square brackets
This is for 2.7, if that matters! Thanks !
Answer:
writer.writerow([ID] + wordList)
or
from itertools import chain
writer.writerow(chain([ID], wordList))
|
how to enable transparency in vte.Terminal
Question: i am creating a simple terminal in python using vte.Terminal. i want to have a
certain level of transparency in the terminal background but the set_opacity
doesn't work. but it works in terminator and other terminals.
window.set_opacity makes the whole window transparent but i dont want the
title bat to be transparent. here's the code.
#!/usr/bin/env python
import vte
import gtk
import pango
import os
import signal
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.connect('destroy', lambda w: gtk.main_quit())
# initial window size
window.resize(640, 480)
terminal = vte.Terminal()
terminal.connect("child-exited", lambda w: gtk.main_quit())
# here you can set backscroll buffer
terminal.set_scrollback_lines(5000)
# encoding for console
terminal.set_encoding("UTF-8")
terminal.set_cursor_blinks(False)
# here you can set background image
#terminal.set_background_image_file("some/background/picture/here")
# transparency
terminal.set_opacity (45000)
# font for terminal
font = pango.FontDescription()
font.set_family("Ubuntu Mono")
# font size
font.set_size(11 * pango.SCALE)
font.set_weight(pango.WEIGHT_NORMAL)
font.set_stretch(pango.STRETCH_NORMAL)
terminal.set_font_full(font, True)
child_pid = terminal.fork_command()
scroll = gtk.ScrolledWindow()
scroll.set_policy(0,1)
scroll.add_with_viewport(terminal)
window.add(scroll)
window.show_all()
# This must be here! before gtk.main()
# here you can set columns count (first param)
terminal.set_size(500,0)
try:
gtk.main()
except KeyboardInterrupt:
pass
Answer: The following snippet solved this problem.
colormap = window.get_screen().get_rgba_colormap()
if colormap == None:
colormap = window.get_screen().get_rgb_colormap()
gtk.widget_set_default_colormap(colormap)

although i endded up using Vala for the program and it had a simple function
called [set_visual](http://valadoc.org/#!api=gtk+-3.0/Gtk.Widget.set_visual).
Hope this helps
|
Inconsistent MySQL information using django data models
Question: I've been grappling with what appears to be a bug between Django/MySQL, but is
perhaps just my own misunderstanding in the nuances of threaded applications,
etc.
First, a bit of information on my application. I have a multithreaded
application programmed in python that is using Django's models. There are
three different types of threads that supply information down a pipeline
through the use of Queues. Thread one pulls a bunch of objects from the
database and throws them into a queue. The next thread (the main workhorse)
takes the item off the queue and pulls an HTTP request and throws that onto a
queue for the third thread. The third thread does some processing on the html
and updates some database values.
Here's the weird part. I have a mysql column called "level." The first thread
pulls rows where level = 0. After parsing the HTTP response the final thread
is supposed to update the row in the database with level = 1 along with all
manner of data that is parsed out of the HTTP. Well at full speed the script
_says_ it's processing about 1,000 a minute. But the number of rows with level
= 1 increases at about 1/3 of that. Here's some excerpt from the problem when
going slowly.
[a picture of program output showing correct
output](http://i.imgur.com/7WcXX.png)
The important part is the lines that say "Updating level one entry." The
numbers at the end are displaying the number of level 1 rows in the database,
followed by the current "level" status of the working data object. This output
is when it is functioning correctly. It is produced by this code block:
# update our current record to reflect having run here
current.update = datetime.now()
# this prints out the "updating level one" text with debugging information
self.send_message(304, str(Scrape.objects.filter(level=1).count()) + ":" + str(current.level))
current.level = 1
current.save()
# and after saving the information to the db, prints it out again
self.send_message(304, str(Scrape.objects.filter(level=1).count()) + ":" + str(current.level))
self.send_message(308, str(current.asin)) # send out a consuming message
However, after running for a little while I will get output that is basically
identical, except the count for number of objects at level = 1 will not
increase. This makes absolutely no sense to me. If the value was = 0 before,
and is = 1 now, then it should increase the number of level = 1 entries!
I don't believe this is merely caching but more likely either an error that
I've made or some sort of unexpected behavior out of the components I'm using.
Any advice from more experienced eyes would be greatly appreciated.
Answer: My immediate guess would be a transaction issue. Since these are running in
separate threads, they'll have their own transactions, and therefore will be
subject to transaction isolation. Even if the thread doing the updating
commits its transaction and starts a new one, the thread outputting the count
will not necessarily see that update until it too starts a new transaction.
|
Twisted adbapi errors and log.err
Question: I'm debugging the 'MySQL server has gone away' errors. There is a proposed
solution, which more or less works:
from twisted.enterprise import adbapi
from twisted.python import log
import MySQLdb
class ReconnectingConnectionPool(adbapi.ConnectionPool):
"""Reconnecting adbapi connection pool for MySQL.
This class improves on the solution posted at
http://www.gelens.org/2008/09/12/reinitializing-twisted-connectionpool/
by checking exceptions by error code and only disconnecting the current
connection instead of all of them.
Also see:
http://twistedmatrix.com/pipermail/twisted-python/2009-July/020007.html
"""
def _runInteraction(self, interaction, *args, **kw):
try:
return adbapi.ConnectionPool._runInteraction(self, interaction, *args, **kw)
except MySQLdb.OperationalError, e:
if e[0] not in (2006, 2013):
raise
log.msg("RCP: got error %s, retrying operation" %(e))
conn = self.connections.get(self.threadID())
self.disconnect(conn)
# try the interaction again
return adbapi.ConnectionPool._runInteraction(self, interaction, *args, **kw)
Taken from here: <http://www.gelens.org/2009/09/13/twisted-connectionpool-
revisited/>
However, the exception gets caught no only in our ReconnectingConnectionPool,
but in _runInteraction itself too. And it triggers log.err, which (apparently)
does two things:
* print the error - although our application works fine
* what's worse, it makes trial fail, so the tests fail. I'm not really sure this is log.err problem, but it happens nonetheless.
I could hack adbapi, but that's probably not the best idea. Are there any
better ways to handle this?
Answer: Are you asking how to make a unit test pass even if an error is logged? Try
[flushLoggedErrors](http://twistedmatrix.com/documents/current/api/twisted.trial.unittest.TestCase.html#flushLoggedErrors).
If you're asking something else, please clarify.
|
python byRef // copy
Question: I am new to Python (and dont know much about programming anyway), but I
remember reading that python generally does not copy values so any statement a
= b makes b point to a. If I run
a = 1
b = a
a = 2
print(b)
gives the result 1. Should that not be 2?
Answer: No, the result should be 1.
Think of the assignment operator ( `=` ) as the assignment of a reference.
a = 1 #a references the integer object 1
b = a #b and a reference the same object
a = 2 #a now references a new object (2)
print b # prints 1 because you changed what a references, not b
This whole distinction really is most important when dealing with _mutable_
objects such as `lists` as opposed to _immutable_ objects like `int`,`float`
and `tuple`.
Now consider the following code:
a=[] #a references a mutable object
b=a #b references the same mutable object
b.append(1) #change b a little bit
print a # [1] -- because a and b still reference the same object
# which was changed via b.
|
Why won't .png files download with Python script while it works for other image types?
Question: I am trying to search the source code of a webpage, and download various files
from it using Python. This script searches the source code for .jpg files and
downloads them all as expected. However, upon modifying the script (changing
".jpg" to ".png", as shown below), I get the error:
Traceback (most recent call last):
File "img.py", line 19, in <module> urllib.urlretrieve(images[z], "image"+str(z)+".png")
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 91, in urlretrieve
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 237, in retrieve
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 205, in open
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 461, in open_file
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib.py", line 475, in open_local_file
IOError: [Errno 2] No such file or directory: '/images/adapt-icon-search.png?1342791397'
Here is the script I am using:
import urllib
import urllib2
import re
print "enter url of site (such as 'dribbble.com')"
url = raw_input()
fullurl = "http://"+url
src = urllib2.urlopen(fullurl)
src = src.read()
images = re.findall('src="(.*\.png[^"]*)', src)
z=0
while z < len(images):
urllib.urlretrieve(images[z], "image"+str(z)+".png")
print "done"
z+=1
Insight as to why this script doesn't work for .png files would be much
appreciated. Many thanks in advance.
UPDATE: below is a sample of the source I am wanting to search through:
<span rel="tipsy" title="This shot has rebounds." class="rebound-mark has-rebounds">1</span>
</a>
</div>
</div>
<h2>
<a href="/Dash" class="url" rel="contact" title="Dash"><img alt="Avatar-new" class="photo fn" src="http://dribbble.s3.amazonaws.com/users/107759/avatars/original/avatar-new.png?1339961321" /> Dash</a>
<a href="/account/pro" class="badge-link">
<span class="badge badge-pro">Pro</span>
</a>
</h2>
Answer: So the error you are getting is this:
> IOError: [Errno 2] No such file or directory: '/images/adapt-icon-
> search.png?1342791397'
What's happening is that the web page you're scraping has some PNG references
that do not include the domain name included in the URL. When you try to fetch
them in your `while` loop, it fails because you're only providing the location
on the remote host: `/images/adapt-icon-search.png?1342791397`.
You need to extend your code to detect those kinds of URLs (which are
perfectly legal, and in fact, very common). For the kind you're hitting here,
you'll just need to prepend the matched URL with the host name of the server
(e.g. `http://dribble.com/`).
You will probably also want to handle relative URLs, which also exclude the
hostname, but start without a `/` character. Those will need to be prepended
with the previous page's path, if there was one. So if you were scraping
`http://dribble.com/foo/bar.html`, you'd need to prepend a relative URL with
`http://dribble.com/foo/`.
There's likely a library that will automate handling of non-absolute URLs for
you, perhaps as part of the web-scraping process. I'm afraid I don't know much
about web scraping first hand, but perhaps somebody else can suggest one in a
comment.
|
Reinforcement learning methodes that map continuous to continuous
Question: I am building a model where firms have to set prices and make production
decisions. Prices are continuous and so are the decision variables.
(inventory, last sales, prices...).
What reinforcement learning method can I use that maps continuous to
continuous ? Which python packages are there? If there are no python packages,
I could write a wrapper.
Answer: [PyBrain](http://pybrain.org/) machine learnign library is what you're looking
for. It is quite complex implementation of neural networks, but when you
understand it you will get a really powerful tool.
PyBrain is a python library for neural network modelling. [Overview of the
PyBrain](http://pybrain.org/) should get you a basic idea: at each timestep
you provides neural network with a set of continuous values and take out
another set of continuous values. But more important is that you can evaluate
the output and train your neural network.
All these steps - including network training - are already implemented in
PyBrain.
|
Two Python modules require each other's contents - can that work?
Question: I have a Bottle webserver module with the following line:
from foobar.formtools import auto_process_form_insert
And the `foobar.formtools` module contains this line:
from foobar.webserver import redirect, redirect_back
Of course, both result in the following errors (respectively):
> ImportError: cannot import name auto_process_form_insert
> ImportError: cannot import name redirect
Is it simply a fact that in Python two modules can't import each other and all
module imports must be hierarchical in nature, or am I doing something wrong?
Alternatively, is there a workaround short of placing all these nice functions
in new modules?
Answer: Modules _can_ import each other cyclically, but there's a catch. In the simple
case, it should work by moving the `import` statements to the bottom of the
file or not using the `from` syntax.
Here's why that works:
When you import a module, Python first checks `sys.modules`. If it's in there,
it just imports from there. If it's not there, it tries to import it in the
normal way; basically, it finds the file and runs the stuff in it.
Running a module populates the module's contents. For example, say we have
this module, creatively named `example_opener`:
import webbrowser
def open_example():
webbrowser.open('http://www.example.com/')
At the start, the module is empty. Then Python executes:
import webbrowser
After that, the module only contains `webbrowser`. Then Python executes this:
def open_example():
webbrowser.open('http://www.example.com/')
Python creates `open_example`. Now the module contains `webbrowser` and
`open_example`.
Say `webbrowser` contained this code:
from example_opener import open_example
def open(url):
print url
Say `example_opener` is imported first. This code is executed:
import webbrowser
`webbrowser` has not yet been imported, so Python executes the contents of
`webbrowser`:
from example_opener import open_example
`example_opener` _has_ been imported, but not yet fully executed. Python
doesn't care. Python pulls the module out of `sys.modules`. At this point,
`example_opener` is still empty. It hasn't defined `open_example` yet, nor
even completed importing `webbrowser`. Python can't find `open_example` in
`example_opener`, so it fails.
What if we imported `open_example` from the end of `webbrowser` and
`webbrowser` from the end of `example_opener`? Python would start by executing
this code:
def open_example():
webbrowser.open('http://www.example.com/')
`webbrowser` does not exist yet, but it doesn't matter until `open_example` is
called. Now `example_opener` contains only `open_example`. It then executes:
import webbrowser
It has not been imported yet, so Python executes `webbrowser`. It starts:
def open(url):
print url
It defines `open`. Then it executes:
from example_opener import open_example
`example_opener` is in `sys.modules`, so it uses that. `example_opener`
contains `open_example`, so it succeeds. Python finishes importing
`webbrowser`. That concludes importing `webbrowser` from `example_opener`.
That's the last thing in `example_opener`, so the import of `example_opener`
finishes, successful, as well.
|
import django models classes into utility module
Question: I have two model classes in my models.py module in the default location.
PythonFinal
|_ manage.py
|_ template
|_ PythonFinal
| |_ __init__.py
| |_ settings.py
| |_ urls.py
| |_ swgi.py
|
|
|___ fertility
|_ __init__.py
|_ models.py
|_ tests.py
|_ views.py
|_ dateUtils.py
I simply want to import the classes into dateUtils.py
from fertility.models import Cycle, Period
if __name__ == '__main__':
p1 = Period(periodFirstDay='2012-7-26' , periodNumber=4)
If I run this module I get
ImportError: no module named fertility
If I try to import models from the python commandline I get
import models
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "models.py", line 1, in <module>
from django.db import models
File "/usr/local/lib/python2.6/dist-packages/django/db/__init__.py", line 11, in <module>
if DEFAULT_DB_ALIAS not in settings.DATABASES:
File "/usr/local/lib/python2.6/dist-packages/django/utils/functional.py", line 184, in inner
self._setup()
File "/usr/local/lib/python2.6/dist-packages/django/conf/__init__.py", line 40, in _setup
raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE)
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
I added my projects root folder to the PYTHONPATH in ~/.bashrc. My wsgi.py
reads
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "PythonFinal.settings")
I do not think it is not a circular import because I get the ImportError
instead of a NamingError, and I simply don't have many imports yet. For
obvious reasons I need to be able to import my model to other modules I can
unit test or I need another simple workflow that accomplishes the same.
Answer: If `PythonFinal` is in `/home/users/jeremy/django/PythonFinal`, then
`/home/users/jeremy/django` should be in your `PYTHONPATH` environment
variable, and `DJANGO_SETTINGS_MODULE` should be set to
`"PythonFinal.PythonFinal.settings"`. Then you can use
from PythonFinal.fertility.models import Cycle, Period
from the Python command line.
It is, however, more common to have the `settings.py` file in the same folder
as `manage.py`, and a number of tools and tutorials expect this setup...
|
Requests Module Python
Question: I have an application running with PHP and CURL. My idea is to move the
application to Python-Django-Requests. I have been unable to work, I hope you
can give me a hand please. The application works as follows: Collect: a
number, a message and through an API sends an SMS.
PHP code. <http://pastebin.com/PqpBgstD>
import requests
import cookielib
posdata = "p_num_text=00513015924048&smstemplate=&message=message_sending&txtcount=8
+char+%3A+1+Sms&hiddcount=152"
jar = cookielib.CookieJar()
user = 'xxx'
pass = 'xxx'
values = {'app': 'page', 'inc': 'login', 'op': 'auth_login',
'username': user, 'password': pass} # data login
r = requests.post(url, data=values, cookies=jar) # Login
values = {'app': 'menu', 'inc': 'send_sms',
'op': 'sendsmstopv_yes'}# values to enter to send the sms
r = requests.post(url, data=values, params=posdata, cookies=jar)# enter the area sms
print r.content
How I can pass the code in CURL to Requests?
Does the above code is fine?
Answer: Your code will not work, I've attached the corrected code below, note that you
don't need to use `cookielib` as `Requests`'s `cookie` will generate a
`CookieJar` object.
import requests
url = "http://dominio.com/subdominio/index.php"
username = 'xxx'
password = 'xxx'
payload = {
'app': 'page',
'inc': 'login',
'op': 'auth_login',
'username': username,
'password': password}
r = requests.post(url, data=payload) # Login
cSMS = "Sms"
payload = {
'p_num_text': '00513015924048',
'smstemplate': '',
'message': 'message_sending',
'txtcount': '8',
'char': cSMS, # your php code seems to be off for this one, double check it
'hiddcount': '153'}
url = "http://dominio.com/subdominio/index.php?app=menu&inc=send_sms&op=sendsmstopv_yes"
r = requests.post(url, data=payload, cookies=r.cookies) # enter the area sms
print r.text
|
Error in trying to open dialog box from a widget button in python
Question: I'm new to python. I'm trying to open a dialog box to get a value from within
a widget that does a list of other staff allready.
But getting errors and can't figure out what to do.
Here's my code:
import Tkinter,Tkconstants,tkFileDialog
from Tkinter import *
import csv
import numpy
import math
import numpy.random as nrnd
import matplotlib.pyplot as plt
import shutil
import tkMessageBox
global filesavepath
class App:
def __init__(self,master):
self.mymaster=master
frame=Frame(master)
frame.pack()
self.importbutton=Button(frame,text='Import Data',command=self.importdata)
self.importbutton.pack()
self.executebutton=Button(frame,text='Execute',command=self.popup)
self.executebutton.pack()
self.distribution_rep=Button(frame,text='Repeat Purchase Score Distribution',command=self.distrepbutton)
self.distribution_rep.pack()
self.distribution_churn=Button(frame,text='Churn Probability Distribution',command=self.distchurnbutton)
self.distribution_churn.pack()
self.exitbutton=Button(frame,text='Exit',command=self.exitapp)
self.exitbutton.pack()
self.file_opt=options={}
options['defaultextension']=''
options['filetypes']=[('allfiles','.*'),('textfiles','.txt')]
options['initialdir']='C:\\'
options['initialfile']='myfile.txt'
options['parent']=root
options['title']='Thisisatitle'
def importdata(self):
filename=tkFileDialog.askopenfilename(**self.file_opt)
filesavepath="C:/input_full.csv"
shutil.copy2(filename,filesavepath)
if filename:
return open(filename,'r')
def popup(self):
top = self.top = Tkinter.Toplevel(self)
myLabel = Tkinter.Label(top, text='Enter your username below')
myLabel.pack()
self.myEntryBox = Tkinter.Entry(top)
self.myEntryBox.pack()
mySubmitButton = Tkinter.Button(top, text='Done', command=self.execbutton)
mySubmitButton.pack()
def execbutton(self):
if self.myEntryBox.get() != "":
self.timevalue = self.myEntryBox.get()
self.top.destroy()
execfile("Repeat Purchase Algo in python v6")
tkMessageBox.showinfo("Job Done", "Probability Computation completed")
def send(self):
global timevalue
timevalue=self.myEntryBox.get()
self.top.destroy()
def distrepbutton(self):
plt.hist(prob,bins=10,normed=TRUE)
plt.xlabel('Probability')
plt.title('Histogram of Repeat Purchase Probability')
plt.show()
def distchurnbutton(self):
plt.hist(churn_prob,bins=10,normed=TRUE)
plt.ylabel('Probability')
plt.title('Histogram of Churn Probability')
plt.show()
def exitapp(self):
self.mymaster.destroy()
root=Tk()
root.title('Repeat Puchase Widget')
app=App(root)
root.mainloop()
So as may be apparent to you, I'm importing dataset with an Import button,
executing some analysis in another code through a button called Execute, and
then showing some graphs.
What I wanted was to open a pop up kind of window on click of "Execute" button
that will input a value. But I'm getting the following error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
File "C:/Python27/widget_repeat_purchase_v4", line 42, in popup
top = self.top = Tkinter.Toplevel(self)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 2017, in __init__
BaseWidget.__init__(self, master, 'toplevel', cnf, {}, extra)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1965, in __init__
BaseWidget._setup(self, master, cnf)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1943, in _setup
self.tk = master.tk
AttributeError: App instance has no attribute 'tk'
I've no idea what to do. Please help.
Answer: When you create the toplevel widget, you are passing `self` as the first
argument. Tkinter requires that this be a parent widget. However, in your code
`self` does not represent a widget.
In your specific case you want to pass in `self.mymaster` rather than `self`:
top = self.top = Tkinter.Toplevel(self.mymaster)
|
Python: BeautifulSoup extract text from anchor tag
Question: I want to extract text from following src of the image tag and text of the
anchor tag which is inside the div class data.
I successfully manage to extract the img src but I am having trouble on
extracting the text from the anchor tag.
<a class="title" href="http://rads.stackoverflow.com/amzn/click/B0073HSK0K">Nikon COOLPIX L26 16.1 MP Digital Camera with 5x Zoom NIKKOR Glass Lens and 3-inch LCD (Red)</a>
Here is the link for the entire [HTML
page](http://www.amazon.com/s/ref=sr_pg_1?rh=n:172282,k%3adigital%20camera&keywords=digital%20camera&ie=UTF8&qid=1343600585)
Here is my code
for div in soup.findAll('div', attrs={'class':'image'}):
print "\n"
for data in div.findNextSibling('div', attrs={'class':'data'}):
for a in data.findAll('a', attrs={'class':'title'}):
print a.text
for img in div.findAll('img'):
print img['src']
What I am trying to do is extract the image src (link) and the title in side
the div class=data.
so for example
<a class="title" href="http://rads.stackoverflow.com/amzn/click/B0073HSK0K">Nikon COOLPIX L26 16.1 MP Digital Camera with 5x Zoom NIKKOR Glass Lens and 3-inch LCD (Red)</a>
I want to extract : `Nikon COOLPIX L26 16.1 MP Digital Camera with 5x Zoom
NIKKOR Glass Lens and 3-inch LCD (Red)`
Answer: This will help:
from BeautifulSoup import BeautifulSoup
data = '''<div class="image">
<a href="http://www.example.com/eg1">Content1<img
src="http://image.example.com/img1.jpg" /></a>
</div>
<div class="image">
<a href="http://www.example.com/eg2">Content2<img
src="http://image.example.com/img2.jpg" /> </a>
</div>'''
soup = BeautifulSoup(data)
for div in soup.findAll('div', attrs={'class':'image'}):
print div.find('a')['href']
print div.find('a').contents[0]
print div.find('img')['src']
If you are looking into Amazon products then you should be using the official
API. There is at least [one Python
package](http://pypi.python.org/pypi/python-amazon-product-api/) that will
ease your scraping issues and keep your activity within the terms of use.
|
Installing IPython for Sublime Text 2's embedded Python interpreter
Question: I am trying to install the IpythonIntegration package in sublime,
I installed in a bash shell:
1. the latest ipython
2. pyzmq
3. pyside
However, the sublime console still gives me an error of
Reloading plugin /home/areal/.config/sublime-text-2/Packages/User/ipython_repl.py
Traceback (most recent call last):
File "./sublime_plugin.py", line 62, in reload_plugin
File "./ipython_repl.py", line 13, in <module>
from IPython.zmq.blockingkernelmanager import BlockingKernelManager
ImportError: No module named IPython.zmq.blockingkernelmanager
**EDIT:**
Even a `import IPython` won't work.
When in python console, `import IPython` and `import zmq` work, however:
from IPython.zmq.blockingkernelmanager import BlockingKernelManager
Fails with:
ImportError: No module named zmq.blockingkernelmanager
I have `0MQ 3.2` (also tried with 2.x), and latest `PyZMQ`. I am working with
`Python 2.7.2` on `Ubuntu 11.10`.
So in general I have 2 problems:
1. No IPython in Sublime (I assume it is because sublime works with an embedded interpreter)
2. No zmq module in IPython
Answer: I am not using Ubuntu, but I meet similar issue in Mac OS X.
The reason why it success in standalone python and fail in sublime text 2 is :
sublime text 2 is using python 2.6 defaultly, while you standalone python is
2.7.
To solve this, in my OS X, I create a soft link from 2.7 to 2.6, something
like below:
cd /Library/Frameworks/Python.framework/Versions/
sudo mv 2.6 2.6-backup
ln -s 2.7 2.6
I think you can do same thing in Ubuntu.
|
Emacs24 + Pymacs -f switch with pymacs-load-path redundant?
Question: I've upgraded to Emacs24 and, when launching Pymacs it would break because of
timeout.
Below is the backtrace:
Debugger entered--Lisp error: (error "Pymacs helper did not start within 30 seconds")
signal(error ("Pymacs helper did not start within 30 seconds"))
pymacs-report-error("Pymacs helper did not start within %d seconds" 30)
(if (accept-process-output process pymacs-timeout-at-start) nil (pymacs-report-error "Pymacs helper did not start within %d seconds" pymacs-timeout-at-start))
(unless (accept-process-output process pymacs-timeout-at-start) (pymacs-report-error "Pymacs helper did not start within %d seconds" pymacs-timeout-at-start))
(while (progn (goto-char (point-min)) (not (re-search-forward "<\\([0-9]+\\) " nil t))) (unless (accept-process-output process pymacs-timeout-at-start) (pymacs-report-error "Pymacs helper did not start within %d seconds" pymacs-timeout-at-start)))
(let ((process (apply (quote start-process) "pymacs" buffer (let ((python (getenv "PYMACS_PYTHON"))) (if (or (null python) (equal python "")) "python" python)) "-c" (concat "import sys;" " from Pymacs.pymacs import main;" " main(*sys.argv[1:])") (append (and (>= emacs-major-version 24) (quote ("-f"))) (mapcar (quote expand-file-name) pymacs-load-path))))) (pymacs-kill-without-query process) (while (progn (goto-char (point-min)) (not (re-search-forward "<\\([0-9]+\\) " nil t))) (unless (accept-process-output process pymacs-timeout-at-start) (pymacs-report-error "Pymacs helper did not start within %d seconds" pymacs-timeout-at-start))) (let ((marker (process-mark process)) (limit-position (+ (match-end 0) (string-to-number (match-string 1))))) (while (< (marker-position marker) limit-position) (unless (accept-process-output process pymacs-timeout-at-start) (pymacs-report-error "Pymacs helper probably was interrupted at start")))))
(progn (let ((process (apply (quote start-process) "pymacs" buffer (let ((python ...)) (if (or ... ...) "python" python)) "-c" (concat "import sys;" " from Pymacs.pymacs import main;" " main(*sys.argv[1:])") (append (and (>= emacs-major-version 24) (quote ...)) (mapcar (quote expand-file-name) pymacs-load-path))))) (pymacs-kill-without-query process) (while (progn (goto-char (point-min)) (not (re-search-forward "<\\([0-9]+\\) " nil t))) (unless (accept-process-output process pymacs-timeout-at-start) (pymacs-report-error "Pymacs helper did not start within %d seconds" pymacs-timeout-at-start))) (let ((marker (process-mark process)) (limit-position (+ (match-end 0) (string-to-number (match-string 1))))) (while (< (marker-position marker) limit-position) (unless (accept-process-output process pymacs-timeout-at-start) (pymacs-report-error "Pymacs helper probably was interrupted at start"))))) (goto-char (match-end 0)) (let ((reply (read (current-buffer)))) (if (and (pymacs-proper-list-p reply) (= (length reply) 2) (eq (car reply) (quote version))) (unless (string-equal (cadr reply) "0.24-beta2") (pymacs-report-error "Pymacs Lisp version is 0.24-beta2, Python is %s" (cadr reply))) (pymacs-report-error "Pymacs got an invalid initial reply"))))
(unwind-protect (progn (let ((process (apply (quote start-process) "pymacs" buffer (let (...) (if ... "python" python)) "-c" (concat "import sys;" " from Pymacs.pymacs import main;" " main(*sys.argv[1:])") (append (and ... ...) (mapcar ... pymacs-load-path))))) (pymacs-kill-without-query process) (while (progn (goto-char (point-min)) (not (re-search-forward "<\\([0-9]+\\) " nil t))) (unless (accept-process-output process pymacs-timeout-at-start) (pymacs-report-error "Pymacs helper did not start within %d seconds" pymacs-timeout-at-start))) (let ((marker (process-mark process)) (limit-position (+ (match-end 0) (string-to-number ...)))) (while (< (marker-position marker) limit-position) (unless (accept-process-output process pymacs-timeout-at-start) (pymacs-report-error "Pymacs helper probably was interrupted at start"))))) (goto-char (match-end 0)) (let ((reply (read (current-buffer)))) (if (and (pymacs-proper-list-p reply) (= (length reply) 2) (eq (car reply) (quote version))) (unless (string-equal (cadr reply) "0.24-beta2") (pymacs-report-error "Pymacs Lisp version is 0.24-beta2, Python is %s" (cadr reply))) (pymacs-report-error "Pymacs got an invalid initial reply")))) (set-match-data save-match-data-internal (quote evaporate)))
(let ((save-match-data-internal (match-data))) (unwind-protect (progn (let ((process (apply (quote start-process) "pymacs" buffer (let ... ...) "-c" (concat "import sys;" " from Pymacs.pymacs import main;" " main(*sys.argv[1:])") (append ... ...)))) (pymacs-kill-without-query process) (while (progn (goto-char (point-min)) (not (re-search-forward "<\\([0-9]+\\) " nil t))) (unless (accept-process-output process pymacs-timeout-at-start) (pymacs-report-error "Pymacs helper did not start within %d seconds" pymacs-timeout-at-start))) (let ((marker (process-mark process)) (limit-position (+ ... ...))) (while (< (marker-position marker) limit-position) (unless (accept-process-output process pymacs-timeout-at-start) (pymacs-report-error "Pymacs helper probably was interrupted at start"))))) (goto-char (match-end 0)) (let ((reply (read (current-buffer)))) (if (and (pymacs-proper-list-p reply) (= (length reply) 2) (eq (car reply) (quote version))) (unless (string-equal (cadr reply) "0.24-beta2") (pymacs-report-error "Pymacs Lisp version is 0.24-beta2, Python is %s" (cadr reply))) (pymacs-report-error "Pymacs got an invalid initial reply")))) (set-match-data save-match-data-internal (quote evaporate))))
(save-match-data (let ((process (apply (quote start-process) "pymacs" buffer (let ((python ...)) (if (or ... ...) "python" python)) "-c" (concat "import sys;" " from Pymacs.pymacs import main;" " main(*sys.argv[1:])") (append (and (>= emacs-major-version 24) (quote ...)) (mapcar (quote expand-file-name) pymacs-load-path))))) (pymacs-kill-without-query process) (while (progn (goto-char (point-min)) (not (re-search-forward "<\\([0-9]+\\) " nil t))) (unless (accept-process-output process pymacs-timeout-at-start) (pymacs-report-error "Pymacs helper did not start within %d seconds" pymacs-timeout-at-start))) (let ((marker (process-mark process)) (limit-position (+ (match-end 0) (string-to-number (match-string 1))))) (while (< (marker-position marker) limit-position) (unless (accept-process-output process pymacs-timeout-at-start) (pymacs-report-error "Pymacs helper probably was interrupted at start"))))) (goto-char (match-end 0)) (let ((reply (read (current-buffer)))) (if (and (pymacs-proper-list-p reply) (= (length reply) 2) (eq (car reply) (quote version))) (unless (string-equal (cadr reply) "0.24-beta2") (pymacs-report-error "Pymacs Lisp version is 0.24-beta2, Python is %s" (cadr reply))) (pymacs-report-error "Pymacs got an invalid initial reply"))))
(save-current-buffer (set-buffer buffer) (erase-buffer) (buffer-disable-undo) (pymacs-set-buffer-multibyte nil) (set-buffer-file-coding-system (quote raw-text)) (save-match-data (let ((process (apply (quote start-process) "pymacs" buffer (let (...) (if ... "python" python)) "-c" (concat "import sys;" " from Pymacs.pymacs import main;" " main(*sys.argv[1:])") (append (and ... ...) (mapcar ... pymacs-load-path))))) (pymacs-kill-without-query process) (while (progn (goto-char (point-min)) (not (re-search-forward "<\\([0-9]+\\) " nil t))) (unless (accept-process-output process pymacs-timeout-at-start) (pymacs-report-error "Pymacs helper did not start within %d seconds" pymacs-timeout-at-start))) (let ((marker (process-mark process)) (limit-position (+ (match-end 0) (string-to-number ...)))) (while (< (marker-position marker) limit-position) (unless (accept-process-output process pymacs-timeout-at-start) (pymacs-report-error "Pymacs helper probably was interrupted at start"))))) (goto-char (match-end 0)) (let ((reply (read (current-buffer)))) (if (and (pymacs-proper-list-p reply) (= (length reply) 2) (eq (car reply) (quote version))) (unless (string-equal (cadr reply) "0.24-beta2") (pymacs-report-error "Pymacs Lisp version is 0.24-beta2, Python is %s" (cadr reply))) (pymacs-report-error "Pymacs got an invalid initial reply")))))
(with-current-buffer buffer (erase-buffer) (buffer-disable-undo) (pymacs-set-buffer-multibyte nil) (set-buffer-file-coding-system (quote raw-text)) (save-match-data (let ((process (apply (quote start-process) "pymacs" buffer (let (...) (if ... "python" python)) "-c" (concat "import sys;" " from Pymacs.pymacs import main;" " main(*sys.argv[1:])") (append (and ... ...) (mapcar ... pymacs-load-path))))) (pymacs-kill-without-query process) (while (progn (goto-char (point-min)) (not (re-search-forward "<\\([0-9]+\\) " nil t))) (unless (accept-process-output process pymacs-timeout-at-start) (pymacs-report-error "Pymacs helper did not start within %d seconds" pymacs-timeout-at-start))) (let ((marker (process-mark process)) (limit-position (+ (match-end 0) (string-to-number ...)))) (while (< (marker-position marker) limit-position) (unless (accept-process-output process pymacs-timeout-at-start) (pymacs-report-error "Pymacs helper probably was interrupted at start"))))) (goto-char (match-end 0)) (let ((reply (read (current-buffer)))) (if (and (pymacs-proper-list-p reply) (= (length reply) 2) (eq (car reply) (quote version))) (unless (string-equal (cadr reply) "0.24-beta2") (pymacs-report-error "Pymacs Lisp version is 0.24-beta2, Python is %s" (cadr reply))) (pymacs-report-error "Pymacs got an invalid initial reply")))))
(let ((buffer (get-buffer-create "*Pymacs*"))) (with-current-buffer buffer (erase-buffer) (buffer-disable-undo) (pymacs-set-buffer-multibyte nil) (set-buffer-file-coding-system (quote raw-text)) (save-match-data (let ((process (apply (quote start-process) "pymacs" buffer (let ... ...) "-c" (concat "import sys;" " from Pymacs.pymacs import main;" " main(*sys.argv[1:])") (append ... ...)))) (pymacs-kill-without-query process) (while (progn (goto-char (point-min)) (not (re-search-forward "<\\([0-9]+\\) " nil t))) (unless (accept-process-output process pymacs-timeout-at-start) (pymacs-report-error "Pymacs helper did not start within %d seconds" pymacs-timeout-at-start))) (let ((marker (process-mark process)) (limit-position (+ ... ...))) (while (< (marker-position marker) limit-position) (unless (accept-process-output process pymacs-timeout-at-start) (pymacs-report-error "Pymacs helper probably was interrupted at start"))))) (goto-char (match-end 0)) (let ((reply (read (current-buffer)))) (if (and (pymacs-proper-list-p reply) (= (length reply) 2) (eq (car reply) (quote version))) (unless (string-equal (cadr reply) "0.24-beta2") (pymacs-report-error "Pymacs Lisp version is 0.24-beta2, Python is %s" (cadr reply))) (pymacs-report-error "Pymacs got an invalid initial reply"))))) (if (not pymacs-use-hash-tables) (setq pymacs-weak-hash t) (when pymacs-used-ids (let ((pymacs-transit-buffer buffer) (pymacs-forget-mutability t) (pymacs-gc-inhibit t)) (pymacs-apply "zombie_python" pymacs-used-ids)) (setq pymacs-used-ids nil)) (setq pymacs-weak-hash (make-hash-table :weakness (quote value))) (if (boundp (quote post-gc-hook)) (add-hook (quote post-gc-hook) (quote pymacs-schedule-gc)) (setq pymacs-gc-timer (run-at-time 20 20 (quote pymacs-schedule-gc))))) (setq pymacs-transit-buffer buffer))
pymacs-start-services()
(if (and pymacs-transit-buffer (buffer-name pymacs-transit-buffer) (get-buffer-process pymacs-transit-buffer)) nil (when pymacs-weak-hash (unless (or (eq pymacs-auto-restart t) (and (eq pymacs-auto-restart (quote ask)) (yes-or-no-p "The Pymacs helper died. Restart it? "))) (pymacs-report-error "There is no Pymacs helper!"))) (pymacs-start-services))
(unless (and pymacs-transit-buffer (buffer-name pymacs-transit-buffer) (get-buffer-process pymacs-transit-buffer)) (when pymacs-weak-hash (unless (or (eq pymacs-auto-restart t) (and (eq pymacs-auto-restart (quote ask)) (yes-or-no-p "The Pymacs helper died. Restart it? "))) (pymacs-report-error "There is no Pymacs helper!"))) (pymacs-start-services))
pymacs-serve-until-reply("eval" (pymacs-print-for-apply (quote "pymacs_load_helper") (quote ("ropemacs" "rope-"))))
pymacs-call("pymacs_load_helper" "ropemacs" "rope-")
(let ((lisp-code (pymacs-call "pymacs_load_helper" module prefix))) (cond (lisp-code (let ((result (eval lisp-code))) (message "Pymacs loading %s...done" module) result)) (noerror (message "Pymacs loading %s...failed" module) nil) (t (pymacs-report-error "Pymacs loading %s...failed" module))))
pymacs-load("ropemacs" "rope-")
eval-buffer(#<buffer *load*> nil "/home/wvxvw/.emacs" nil t) ; Reading at buffer position 11007
load-with-code-conversion("/home/wvxvw/.emacs" "/home/wvxvw/.emacs" t t)
load("~/.emacs" t t)
#[0 "\205\262
I then looked into:
(defun pymacs-start-services ()
;; This function gets called automatically, as needed.
(let ((buffer (get-buffer-create "*Pymacs*")))
(with-current-buffer buffer
;; Erase the buffer in case some previous incarnation of the
;; Pymacs helper died. Otherwise, the "(goto-char (point-min))"
;; below might not find the proper synchronising reply and later
;; trigger a spurious "Protocol error" diagnostic.
(erase-buffer)
(buffer-disable-undo)
(pymacs-set-buffer-multibyte nil)
(set-buffer-file-coding-system 'raw-text)
(save-match-data
;; Launch the Pymacs helper.
(let ((process
(apply 'start-process "pymacs" buffer
(let ((python (getenv "PYMACS_PYTHON")))
(if (or (null python) (equal python ""))
"python"
python))
"-c" (concat "import sys;"
" from Pymacs.pymacs import main;"
" main(*sys.argv[1:])")
(append
(and (>= emacs-major-version 24) '("-f"))
(mapcar 'expand-file-name pymacs-load-path)))))
(pymacs-kill-without-query process)
;; Receive the synchronising reply.
(while (progn
(goto-char (point-min))
(not (re-search-forward "<\\([0-9]+\\)\t" nil t)))
(unless (accept-process-output process pymacs-timeout-at-start)
(pymacs-report-error
"Pymacs helper did not start within %d seconds"
pymacs-timeout-at-start)))
(let ((marker (process-mark process))
(limit-position (+ (match-end 0)
(string-to-number (match-string 1)))))
(while (< (marker-position marker) limit-position)
(unless (accept-process-output process pymacs-timeout-at-start)
(pymacs-report-error
"Pymacs helper probably was interrupted at start")))))
;; Check that synchronisation occurred.
(goto-char (match-end 0))
(let ((reply (read (current-buffer))))
(if (and (pymacs-proper-list-p reply)
(= (length reply) 2)
(eq (car reply) 'version))
(unless (string-equal (cadr reply) "0.24-beta2")
(pymacs-report-error
"Pymacs Lisp version is 0.24-beta2, Python is %s"
(cadr reply)))
(pymacs-report-error "Pymacs got an invalid initial reply")))))
(if (not pymacs-use-hash-tables)
(setq pymacs-weak-hash t)
(when pymacs-used-ids
;; A previous Pymacs session occurred in this Emacs session,
;; some IDs hang around which do not correspond to anything on
;; the Python side. Python should not recycle such IDs for
;; new objects.
(let ((pymacs-transit-buffer buffer)
(pymacs-forget-mutability t)
(pymacs-gc-inhibit t))
(pymacs-apply "zombie_python" pymacs-used-ids))
(setq pymacs-used-ids nil))
(setq pymacs-weak-hash (make-hash-table :weakness 'value))
(if (boundp 'post-gc-hook)
(add-hook 'post-gc-hook 'pymacs-schedule-gc)
(setq pymacs-gc-timer (run-at-time 20 20 'pymacs-schedule-gc))))
;; If nothing failed, only then declare that Pymacs has started!
(setq pymacs-transit-buffer buffer)))
The part below `;; Launch the Pymacs helper.` I then tried to reproduce it by
simply running the same command in console:
wvxvw@wvxvw-desktop:~$ python -c 'import sys;
from Pymacs.pymacs import main;
main(*sys.argv[1:])' -f "/home/wvxvw/programs/pymacs/" "/home/wvxvw/programs/rope-0.9.3/" "/home/wvxvw/programs/ropemacs/" "/home/wvxvw/programs/ropemode/"
> > Traceback (most recent call last):
File "<string>", line 3, in <module>
File "/usr/lib/python2.7/dist-packages/Pymacs/pymacs.py", line 57, in main
options, arguments = getopt.getopt(arguments, 'd:s:')
File "/usr/lib/python2.7/getopt.py", line 90, in getopt
opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])
File "/usr/lib/python2.7/getopt.py", line 190, in do_shorts
if short_has_arg(opt, shortopts):
File "/usr/lib/python2.7/getopt.py", line 206, in short_has_arg
raise GetoptError('option -%s not recognized' % opt, opt)
getopt.GetoptError: option -f not recognized
If I remove `-f` switch, it seems to work fine (as it used to!). My question
is thus: why was this switch needed? I might have done something else wrong,
if this switch was needed, but it doesn't work for me?
If I then comment out the `-f` switch, it fails on version check:
~~`Debugger entered--Lisp error: (error "Pymacs Lisp version is 0.24-beta2,
Python is 0.23")` Now, how do I get the 0.24-beta2 version of Pymacs?~~ Sorry,
that was me forgetting to remove the reference to the old epy-setup, however,
after removing it, Pymacs starts fine, with the proper version (but it doesn't
need -f switch). What am I doing wrong?
Answer: Answer is here:
<http://docs.python.org/library/sys.html#module-sys>
The list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. If no script name was passed to the Python interpreter, argv[0] is the empty string.
To loop over the standard input, or the list of files given on the command line, see the fileinput module.
IMO with sys.argv[1:] you get all remaining arguments; "-f" from some shell-
script, not appropriate here
|
HTTPResponse instance has no attribute 'status_code' in python/django
Question: I have used python httplib to implement REST api to connect with Django
tastypie. But whenever i try to get the status code it is showing following
error
AttributeError at /actions/login
HTTPResponse instance has no attribute 'status_code'
My code goes below
import hashlib
import hmac
from django.shortcuts import render_to_response
from django.template import RequestContext
def loginAction(request):
username=request.POST['email']
password=request.POST['password']
import httplib, urllib
params = urllib.urlencode({'username': username})
#hash username here to authenticate
digest=hmac.new("qnscAdgRlkIhAUPY44oiexBKtQbGY0orf7OV1I50", str(request.POST['password']),hashlib.sha1).hexdigest()
auth=username+":"+digest
headers = {"Content-type": "application/json","Accept": "text/plain","Authorization":auth}
conn = httplib.HTTPConnection("localhost",8000)
conn.request("POST", "/api/ecp/profile/", params, headers)
conn.set_debuglevel(1)
response = conn.getresponse()
return response
Answer: You must return a django.http.HttpResponse, not a httplib.HttpResponse
See: (httplib)
<http://docs.python.org/library/httplib.html#httplib.HTTPResponse>
and: (django) <https://docs.djangoproject.com/en/dev/ref/request-response/>
|
strict match anywhere in line regex python
Question: I need to strictly find line
`createNode transform -n "bar1_1" -p "bar1";` in a file that has many such
lines
...
createNode transform -n "pTorus1";
setAttr ".t" -type "double3" -0.47688973199150198 0 -10.843417358550912 ;
createNode transform -n "bar1_1" -p "bar1"; < ----------- this one
setAttr ".t" -type "double3" -20.4535357685646444 0 -10.843414345343878 ;
createNode mesh -n "pTorusShape1" -p "pTorus1";
setAttr -k off ".v";
setAttr ".vir" yes;
setAttr ".vif" yes;
setAttr ".uvst[0].uvsn" -type "string" "map1";
setAttr ".cuvs" -type "string" "map1";
setAttr ".dcc" -type "string" "Ambient+Diffuse";
setAttr ".covm[0]" 0 1 1;
setAttr ".cdvm[0]" 0 1 1;
createNode transform -n "bar1_1" -p "bar11"; < ------- not this
setAttr ".t" -type "double3" -20.47342345353453535358 0 -10.843417342423342233 ;
createNode lightLinker -s -n "lightLinker1";
setAttr -s 2 ".lnk";
setAttr -s 2 ".slnk";
...
tried this regex but it does not work,
import re
reg = re.compile("bar1")
aa = "createNode transform -n "bar1_1" -p "bar11";"
bb = reg.match(aa)
What regex should I use to strictly find line that contains -p "bar1" ( not
bar11, see marked line above ) ?
Answer: I'm not 100% clear on the question, but I think it's one of these two...:
re.match(r'bar1.+', string) # make sure there's any remaining chars
re.match(r'bar1\d+',string) # make sure there's digits after
Or, if your createNode wotsit is meant to be a string, you could mean:
>>> s = 'aa = createNode transform -n "bar1_1" -p "bar11" and "bar1";'
>>> re.findall(r'"(bar1.+?)"', s)
['bar1_1', 'bar11'] # note, that the added "bar1" is not returned
|
Avoiding TypeError when using timedelta to compare times
Question: I have a nested list containing times and some corresponding information, and
am trying to extract one line from the start of a block of times that follow
on from each other by a second (e.g. 10:04:23,10:04:24,10:04:25..). There
should be a lot of these little blocks. I'm not sure if what I have is on the
right lines, and if it is, it raises a TypeError and I'm not sure how to get
around it.
This is data relating to visits of animals to an area, and recordings are
taken every second. My aim is to have only one recording per visit, hence the
first line from a block of following-on times.
previous_and_next is stolen from
[here](http://stackoverflow.com/questions/1011938/python-previous-and-next-
values-inside-a-loop)
data=[['07/11/2012', '09:53:36', 'U', '#0F', '0006E7895B', 'T', 'U\n', '09:53:36'],
['05/13/2012', '09:54:27', 'U', '#0F', '0006E3DADA', 'T', 'U\n', '5031', '09:54:27'] etc]
#define a function to get previous and following values
from itertools import tee, islice, chain
def previous_and_next(some_iterable):
prevs, items, nexts = tee(some_iterable, 3)
prevs = chain([None], prevs)
nexts = chain(islice(nexts, 1, None), [None])
return zip(prevs, items, nexts)
#convert times to datetime objects
for d in data:
try:
f=datetime.datetime.strptime(d[1],'%H:%M:%S')
g=f.strftime('%H:%M:%S')
d.append(g)
except:
pass
new_list=[]
for prev,item,next in previous_and_next(data):
aftersecond=item[1]+datetime.timedelta(seconds=1)
if next[1]==aftersecond: #if next time is this time plus a second
this=True
else:
this==False
while this==True:
continue
else:
new_list.append(data)
aftersecond is raising `TypeError: Can't convert 'datetime.timedelta' object
to str implicitly`, which I understand, but don't understand how to avoid. I'm
not even certain this code does what I want it to do.
Thank you for your help!
Answer: I am suggesting this solution which seems simpler but may be too simple:
import datetime
from pprint import pprint
data=[['07/11/2012', '09:53:36', 'U', '#0F', '0006E7895B', 'T', 'U\n', '09:53:36'],
['07/11/2012', '09:53:37', 'U', '#0F', '0006E7895B', 'T', 'U\n', '09:53:37'],
['07/11/2012', '09:53:38', 'U', '#0F', '0006E7895B', 'T', 'U\n', '09:53:38'],
['05/13/2012', '09:54:27', 'U', '#0F', '0006E3DADA', 'T', 'U\n', '5031', '09:54:27'],
['05/13/2012', '09:54:28', 'U', '#0F', '0006E3DADA', 'T', 'U\n', '5031', '09:54:28'],
['05/13/2012', '09:54:29', 'U', '#0F', '0006E3DADA', 'T', 'U\n', '5031', '09:54:29']]
#convert times to datetime objects
for d in data:
dt = ' '.join( d[0:2] )
dt = datetime.datetime.strptime(dt,'%m/%d/%Y %H:%M:%S')
d.append( dt )
newdata = [ data[0] ]
latest_time = newdata[-1][-1]
for d in data[1:]:
delta = d[-1] - latest_time
latest_time = d[-1]
if delta != datetime.timedelta(0, 1):
newdata.append( d )
pprint(newdata)
With this dummy data, assuming that there are two animal visits with three
observations each, the result will be:
[['07/11/2012',
'09:53:36',
'U',
'#0F',
'0006E7895B',
'T',
'U\n',
'09:53:36',
datetime.datetime(2012, 7, 11, 9, 53, 36)],
['05/13/2012',
'09:54:27',
'U',
'#0F',
'0006E3DADA',
'T',
'U\n',
'5031',
'09:54:27',
datetime.datetime(2012, 5, 13, 9, 54, 27)]]
|
Concatenating Multiple .fasta Files
Question: I'm trying to concatenate hundreds of .fasta files into a single, large fasta
file containing all of the sequences. I haven't found a specific method to
accomplish this in the forums. I did come across this code from
<http://zientzilaria.heroku.com/blog/2007/10/29/merging-single-or-multiple-
sequence-fasta-files>, which I have adapted a bit.
Fasta.py contains the following code:
class fasta:
def __init__(self, name, sequence):
self.name = name
self.sequence = sequence
def read_fasta(file):
items = []
index = 0
for line in file:
if line.startswith(">"):
if index >= 1:
items.append(aninstance)
index+=1
name = line[:-1]
seq = ''
aninstance = fasta(name, seq)
else:
seq += line[:-1]
aninstance = fasta(name, seq)
items.append(aninstance)
return items
And here is the adapted script to concatenate .fasta files:
import sys
import glob
import fasta
#obtain directory containing single fasta files for query
filepattern = input('Filename pattern to match: ')
#obtain output directory
outfile = input('Filename of output file: ')
#create new output file
output = open(outfile, 'w')
#initialize lists
names = []
seqs = []
#glob.glob returns a list of files that match the pattern
for file in glob.glob(filepattern):
print ("file: " + file)
#we read the contents and an instance of the class is returned
contents = fasta.read_fasta(open(file).readlines())
#a file can contain more than one sequence so we read them in a loop
for item in contents:
names.append(item.name)
seqs.append(item.sequence)
#we print the output
for i in range(len(names)):
output.write(names[i] + '\n' + seqs[i] + '\n\n')
output.close()
print("done")
It is able to read the fasta files but the newly created output file contains
no sequences. The error I receive is due to the fasta.py, which is beyond my
capability to mess with:
Traceback (most recent call last):
File "C:\Python32\myfiles\test\3\Fasta_Concatenate.py", line 28, in <module>
contents = fasta.read_fasta(open(file).readlines())
File "C:\Python32\lib\fasta.py", line 18, in read_fasta
seq += line[:-1]
UnboundLocalError: local variable 'seq' referenced before assignment
Any suggestions? Thanks!
Answer: I think using `python` for this job is overkill. On the command line, a quick
way to concatenate single/multiple fasta files with the `.fasta` or `.fa`
extensions is to simply:
cat *.fa* > newfile.txt
|
django CLI script and database router: cannot import name connections
Question: I made a database ruter for `myapp` application in file
`/myproject/myapp/routers.py`
class ShardingRouter(object):
def db_for_read(self, model, **hints):
return 'default'
def db_for_write(self, model, **hints):
return 'default'
def allow_relation(self, obj1, obj2, **hints):
return None
def allow_syncdb(self, db, model):
return None
In `settings.py` I have:
from django.db import connections
DATABASE_ROUTERS = ['myproject.myapp.routers.ShardingRouter',]
This works well for normal application running through wsgi, but I have one
CLI script `/myproject/parser_jobs.py` it is starting with cron or manually
from CLI:
import os, sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
...
...
if __name__ == "__main__":
do_some_long_boring_work()
now, when i run this script, I'm getting import error:
Traceback (most recent call last):
File "/hosting/myproject/myproject/parser_jobs.py", line 20, in <module>
import settings
File "/hosting/myproject/myproject/settings.py", line 46, in <module>
from django.db import connections
File "/usr/local/lib/python2.7/dist-packages/django/db/__init__.py", line 11, in <module>
if DEFAULT_DB_ALIAS not in settings.DATABASES:
File "/usr/local/lib/python2.7/dist-packages/django/utils/functional.py", line 184, in inner
self._setup()
File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 42, in _setup
self._wrapped = Settings(settings_module)
File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 95, in __init__
raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
ImportError: Could not import settings 'myproject.myproject' (Is it on sys.path?): cannot import name connections
Looks like it found settings.py, but while importing it fails on `from
django.db import connections`. If i comment this string, it works, but without
my db router:( I can add `using()` everywhere, but it's not cool.
So, website works good, but cli script fails. Please, help!
* * *
update: `/hosting/myproject/myproject/parser_jobs.py` worked good from cli,
before I added DB router
`pprint` of `sys.path` in this script:
['/hosting/myproject/myproject',
'/hosting/myproject',
'/usr/lib/python2.7',
'/usr/lib/python2.7/plat-linux2',
'/usr/lib/python2.7/lib-tk',
'/usr/lib/python2.7/lib-old',
'/usr/lib/python2.7/lib-dynload',
'/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages/PIL',
'/usr/lib/python2.7/dist-packages/gst-0.10',
'/usr/lib/python2.7/dist-packages/gtk-2.0',
'/usr/lib/python2.7/dist-packages/ubuntu-sso-client',
'/usr/lib/pymodules/python2.7']
* * *
update: wsgi script, website works good with it:
import os
import sys
path = '/hosting/myproject'
if path not in sys.path:
sys.path.insert(0, path)
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
Answer: my script was in the same folder with `settings.py` when I moved it from
`/hosting/myproject/myproject/parser_jobs.py` to
`/hosting/myproject/parser_jobs.py` (where in django1.4 manage.py should be)
it become working correct.
Also I changed `os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")`
to `os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")`
And now it works!
In previous location `parser_jobs.py` works only without db router
|
Having trouble setting java.library.path for Jython
Question: I'm working with some legacy code at work. Trying to run on of the python
scripts in our code via Jython, I'm getting an UnsatisfiedLinkError. I've
tried to use the "-D" option to set the java.class.path option, but it doesn't
seem to resolve things. For the following example, `Durandal.jar` is available
under `C:\scm\main\core\isidurandal\durandal\build`
"C:\Program Files\Java\jdk1.6.0_31\bin\java.exe" -Xint "-Dpython.path=c:\scm\main\core\isidurandal\durandal\scripts\lib" "-Dpython.home=c:\bin\jython2.5.2" "-Djava.library.path=c:\scm\main\core\isidurandal\durandal\build" -classpath "c:\bin\jython2.5.2\jython.jar;c:\scm\main\core\isidurandal\durandal\build\durandal.jar;c:\scm\main\core\isidurandal\japanese\build\durandalJapanese.jar;c:\scm\main\core\isidurandal\biometrics\build\MtiBiometrics.jar" org.python.util.jython tools\alignSequences.py
=========================================================
Monolithic library init failed with UnsatisfiedLinkError:
java.lang.UnsatisfiedLinkError: no durandal in java.library.path
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1738)
at java.lang.Runtime.loadLibrary0(Runtime.java:823)
at java.lang.System.loadLibrary(System.java:1028)
at com.interactivesys.durandal.base.Library.<clinit>(Unknown Source)
at com.interactivesys.durandal.recognition.Library.<clinit>(Unknown Sour
ce)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:247)
at org.python.core.Py.loadAndInitClass(Py.java:895)
at org.python.core.Py.findClassInternal(Py.java:830)
at org.python.core.Py.findClassEx(Py.java:881)
at org.python.core.packagecache.SysPackageManager.findClass(SysPackageMa
nager.java:133)
at org.python.core.packagecache.PackageManager.findClass(PackageManager.
java:28)
at org.python.core.packagecache.SysPackageManager.findClass(SysPackageMa
nager.java:122)
at org.python.core.PyJavaPackage.__findattr_ex__(PyJavaPackage.java:137)
at org.python.core.PyObject.__findattr__(PyObject.java:863)
at org.python.core.imp.import_name(imp.java:849)
at org.python.core.imp.importName(imp.java:884)
at org.python.core.ImportFunction.__call__(__builtin__.java:1220)
at org.python.core.PyObject.__call__(PyObject.java:357)
at org.python.core.__builtin__.__import__(__builtin__.java:1173)
at org.python.core.imp.importFromAs(imp.java:978)
at org.python.core.imp.importFrom(imp.java:954)
at org.python.pycode._pyx0.f$0(tools\alignSequences.py:18)
at org.python.pycode._pyx0.call_function(tools\alignSequences.py)
at org.python.core.PyTableCode.call(PyTableCode.java:165)
at org.python.core.PyCode.call(PyCode.java:18)
at org.python.core.Py.runCode(Py.java:1261)
at org.python.util.PythonInterpreter.execfile(PythonInterpreter.java:235
)
at org.python.util.jython.run(jython.java:247)
at org.python.util.jython.main(jython.java:129)
Traceback (most recent call last):
File "tools\alignSequences.py", line 1, in <module>
from com.interactivesys.durandal.recognition import Library
java.lang.UnsatisfiedLinkError: com.interactivesys.durandal.base.ResourceLocator
.resolvePath(Ljava/lang/String;)Ljava/lang/String;
at com.interactivesys.durandal.base.ResourceLocator.resolvePath(Native M
ethod)
at com.interactivesys.durandal.base.Library.<clinit>(Unknown Source)
at com.interactivesys.durandal.recognition.Library.<clinit>(Unknown Sour
ce)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:247)
at org.python.core.Py.loadAndInitClass(Py.java:895)
at org.python.core.Py.findClassInternal(Py.java:830)
at org.python.core.Py.findClassEx(Py.java:881)
at org.python.core.packagecache.SysPackageManager.findClass(SysPackageMa
nager.java:133)
at org.python.core.packagecache.PackageManager.findClass(PackageManager.
java:28)
at org.python.core.packagecache.SysPackageManager.findClass(SysPackageMa
nager.java:122)
at org.python.core.PyJavaPackage.__findattr_ex__(PyJavaPackage.java:137)
at org.python.core.PyObject.__findattr__(PyObject.java:863)
at org.python.core.imp.import_name(imp.java:849)
at org.python.core.imp.importName(imp.java:884)
at org.python.core.ImportFunction.__call__(__builtin__.java:1220)
at org.python.core.PyObject.__call__(PyObject.java:357)
at org.python.core.__builtin__.__import__(__builtin__.java:1173)
at org.python.core.imp.importFromAs(imp.java:978)
at org.python.core.imp.importFrom(imp.java:954)
at org.python.pycode._pyx0.f$0(tools\alignSequences.py:18)
at org.python.pycode._pyx0.call_function(tools\alignSequences.py)
at org.python.core.PyTableCode.call(PyTableCode.java:165)
at org.python.core.PyCode.call(PyCode.java:18)
at org.python.core.Py.runCode(Py.java:1261)
at org.python.util.PythonInterpreter.execfile(PythonInterpreter.java:235
)
at org.python.util.jython.run(jython.java:247)
at org.python.util.jython.main(jython.java:129)
java.lang.UnsatisfiedLinkError: java.lang.UnsatisfiedLinkError: com.interactives
ys.durandal.base.ResourceLocator.resolvePath(Ljava/lang/String;)Ljava/lang/Strin
g;
My understanding is that this error generally happens when one tries to access
a library which is not in the class path, but I think I've set it correctly on
the command line. Then again, I'm also not yet very familiar with Jython (not
horribly familiar with Java or Python), so I'm somewhat at sea.
_Edit:_ It looks like this might be an issue with trying to run a 32-bit DLL
under 64-bit Java. I will revise my question if that turns out to be the case.
Answer: Indeed, the answer, as it turns out, is that it was a 32-bit DLL and I was
trying to run it with the 64-bit Java. Not very intuitive error messages...
|
Get output when username is asked on msysgit in Python (on windows)
Question: I'm trying to get the output when doing a git fetch, but it's halting asking
for the user name and I'm unable to detect that.
I.e.: In a Python script I'm doing:
cmd = 'git fetch origin master'.split()
import subprocess
p = subprocess.Popen(cmd, cwd='.',stderr=subprocess.PIPE)
while p.poll() is None:
r = p.stderr.read(1)
print(r)
And it just halts without printing anything. If I ran it without piping
stderr, the message asking for the username appears (so, it's writing but
stderr.read does not detect anything).
[16:41:45 X:\]python test.py
Username for 'my.domain.com.br':
I've tried dealing with stderr.fileno() directly, changing the Popen bufsize,
writing to the process.stdin, closing stdin and many different things to no
avail. Anyone knows of a way to get that to work? (my feeling is that msysgit
is just writing asking for the username without flushing or writing a new line
and Python cannot deal with that properly, in which case it might only be
fixed at msysgit? -- although it does appear in the shell if I don't pipe it,
which is odd).
Context: I'm doing a program to help in dealing with multiple repositories at
once (https://github.com/fabioz/mu-repo), so, as it can execute that for lots
of repositories at once, not piping it is not really an option as too many
things appear garbled (things do work if ssh access is specified or the
password is already set through other means, but I'd like to have a way to say
to users that the process is stuck waiting for input instead of just hanging
there -- if there's a way to execute it making sure that git will fail if the
password is asked, that'd suffice too).
Answer: Set up your global config for user name and email. Then git will not prompt
for these.
git config --global user.name "Your Name"
git config --global user.email "[email protected]"
|
How to open and search a file in a telnet session with Python
Question: I'm using the following code to log into a server and go to a particular
directory (where the logfile I want to search for a string resides). I have
accomplished this with the Paramiko module (ssh), fairly straightforward. But
the telnetlib module does not have many functions that I see to accomplish
this. Does anyone know how I would open the file and search through it for a
particular string (The server in question only allows Telnet logins - no ssh)
... Thanks:
import sys
import telnetlib
HOST = "10.28.46.14"
user = raw_input("Enter your username: ")
password = ""
tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "\n")
if password == "":
tn.read_until("Password: ")
tn.write(password + "\n")
#print "Login successful!"
else:
print "Your password is incorrect."
tn.write("cd /var/opt/mylog/log\n")
tn.write("ls\n")
tn.read_until("\n")
#tn.write("exit\n")
my_ls = tn.read_until("my.log")
print my_ls
Answer: Did you check with the owner of the machine about ssh vs telnet? There aren't
many operating systems that ship with telnet out of the box anymore, because
telnet is subject to replay attacks.
What if you tell tn to do a grep? You might append an "echo $?" after the
grep, to get an exit code - 0 means there was one or more matches, anything
else means there weren't any.
|
Python- bottle - cookies keep changing
Question: Below is my code for setting and reading cookies in bottle.
if request.get_cookie('mycookiename'):
cookie_id = request.get_cookie('mycookiename')
else:
cookie_id=str(uuid4())
response.set_cookie('mycookiename', cookie_id , max_age=31556952*2, domain='%s' % (cookie_domain))
When I go to firefox and firebug, I can see that the cookie is set. But, when
I refresh the page, I get a new cookie. Every request is a new cookie id.
So, how do I resolve?
Answer: This code works. You set a new value cookie with uuid4 if you have not a
cookie already define.
In your code, i guess your "else" condition is bad.
# -*- coding: utf-8 -*-
#!/usr/bin/env python
from uuid import uuid4
import bottle
@bottle.route('/cookie')
def cookie():
cookie_id = bottle.request.get_cookie('mycookiename', str(uuid4()))
bottle.response.set_cookie('mycookiename', cookie_id)
return 'hello cookie'
if __name__ == '__main__':
bottle.run(host='localhost', port=8080)
|
ElementTree: What is the syntax for the 'match' argument to the 'find' method?
Question: The official documentation
[here](http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.find)
just says, "match may be a tag name or path", but I don't see a definition of
"path" anywhere. From looking at examples on the web I gather it's some
stripped-down XPath-like notation, but it's unclear exactly what is allowed --
for example, should the path start with a `/`, a `//`, or no delimiter at all?
Can I specify attributes with `[@att = "value"]`?
Answer: Well, looking at the source code at
<http://hg.python.org/cpython/file/2.7/Lib/xml/etree/ElementTree.py> we find
that `Element.find` is implemented as
def find(self, path, namespaces=None):
return ElementPath.find(self, path, namespaces)
`ElementPath` is implemented as
try:
from . import ElementPath
except ImportError:
ElementPath = _SimpleElementPath()
`_SimpleElementPath` only checks tag name:
# emulate pre-1.2 find/findtext/findall behaviour
def find(self, element, tag, namespaces=None):
for elem in element:
if elem.tag == tag:
return elem
return None
So let's look at ElementPath.py:
<http://hg.python.org/cpython/file/f98e2944cb40/Lib/xml/etree/ElementPath.py>
It states,
# limited xpath support for element trees
So I would assume valid XPath is likely a valid argument for `find`. I'm not
familiar enough with XPath to determine exactly what it supports, but
<http://effbot.org/zone/element-xpath.htm> describes how much it supported
five years ago and includes a table of syntax.
> ElementTree provides limited support for XPath expressions. The goal is to
> support a small subset of the abbreviated syntax; a full XPath engine is
> outside the scope of the core library.
<http://docs.python.org/dev/library/xml.etree.elementtree.html#xpath-support>
has a more updated table. It doesn't look too different.
|
Problems with deploying flask WSGI application on apache2
Question: I created a one file Flask app so I can test how to deploy it on apache2
server. I followed the steps on the
[Flask](http://flask.pocoo.org/docs/deploying/mod_wsgi/#installing-mod-wsgi)
as far as the server and WSGI configuration goes. When I point to the resource
in the browser it says I have no permissions. WSGI daemon is given the same
permissions as the Flask app. Below is the VirtualHost configuration.
<VirtualHost *:80>
ServerName localhost
WSGIDaemonProcess flask_test user=someuser group=someuser threads=5
WSGIScriptAlias /flask_test/ /var/www/flask_test/flask_test.wsgi
DocumentRoot /var/www/flask_test/
ErrorLog /var/www/flask_test/logs/error.log
<Directory /var/www/flask_test/>
WSGIProcessGroup flask_test
WSGIApplicationGroup %{GLOBAL}
WSGIScriptReloading On
Order deny,allow
Deny from all
</Directory>
</VirtualHost>
Here's the WSGI file
import sys
activate_this = '/home/someuser/pyProjects/general/venv/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))
sys.path.append('/home/someuser/pyProjects')
from general import test as application
And finally the output from error.log
[Tue Jul 31 01:51:18 2012] [error] Exception KeyError: KeyError(140345719740224,) in <module 'threading' from '/usr/lib/python2.6/threading.pyc'> ignored
[Tue Jul 31 01:51:21 2012] [error] [client 108.207.222.48] client denied by server configuration: /var/www/flask_test/flask_test.wsgi
[Tue Jul 31 01:51:21 2012] [error] [client 108.207.222.48] client denied by server configuration: /var/www/flask_test/favicon.ico
EDIT: After implementing Graham Dumpleton suggestions server now returns code
500 with following error `TypeError: 'module' object is not callable `
Answer: Generally want:
WSGIScriptAlias /flask_test/ /var/www/flask_test/flask_test.wsgi
No trailing slash on the mount point for a sub URL.
Worse is that you have:
Deny from all
So you are explicitly telling Apache to return forbidden.
You should have:
Allow from all
in that context.
|
"TypeError: 'module' object is not callable" when running with py.test under /test folder
Question: I have a class `Foo` which lives in `Src/Projects/SomeProject/Foo.py`
I have a class `FooTest(unittest.TestCase)` which lives in:
Src/Projects/SomeProject/tests/FooTest.py
When I run it with pytest (I just type 'py.test' in Src to run all tests), I
get:
def setUp(self):
self.foo = Foo()
TypeError: 'module' object is not callable
(I have `from Foo import Foo` in `FooTest.py` and `Foo.py` is in `sys.path`.
But when I run it with python: `python
Src/Projects/SomeProject/tests/FooTest.py` everything works.)
Also, if I just move FooTest.py to `Src/Projects/SomeProject` then running
with py.test suddenly works.
Any ideas?
Answer: You need to check your python path; some other `Foo.Foo` is being found before
your module `Foo`.
Alternatively, in a `try`/`except TypeError` suite, print out the path of the
offending module:
def setUp(self):
try:
self.foo = Foo()
except TypeError:
# What module Foo is this?
print Foo.__file__
raise
|
Fetch data in IE8 using pywin32
Question: * * *
I've been trying to fetch data using pywin32(Internet Explorer) but can't find
anything good, Basically I want to fetch the data from the current source of
IE PAGE for example : if <http://whoer.net> is opened then I would like to
fetch the country or if the country is this then do this the "If" statement
work, but my main concept for this post is to get the data using
pywin32(Python2.5) or either print the data on the python console window or
so. Currently using:
import pythoncom
from win32com.client import *
pythoncom.CoInitialize()
ie = Dispatch("InternetExplorer.Application")
ie.Navigate2("http://whoer.net")
ie.Visible = True
Please Let me know how to search or find any data in that or print it.Thanks
EDIT : Note that I don't want to use any other modules/library(like
urllib/mechanize) I want it on IE.
Answer: I realize you don't want to use any external modules, however, you might have
a better time of it using something like [Selenium](http://seleniumhq.org/) to
deal with the content of the web page, or if you wanted to go lower level you
could even use the built-in
[urllib2](http://docs.python.org/library/urllib2.html).
If you insist on using just win32com, the topic is far too complex to give in
an answer. My recommendation is to look at the source code for
[PAMIE](http://pamie.sourceforge.net/). It's bit old, but it's a pure Python
module that does IE browser automation using (for the most part) just
win32com, and as far as I know the only other dependenciese are on built-in
modules. It should work just fine on Python 2.5, as well.
|
Python reading files in a directory
Question: I have a .csv with 3000 rows of data in 2 columns like this:
uc007ayl.1 ENSMUSG00000041439
uc009mkn.1 ENSMUSG00000031708
uc009mkn.1 ENSMUSG00000035491
In another folder I have a graphs with name like this:
uc007csg.1_nt_counts.txt
uc007gjg.1_nt_counts.txt
You should notice those graphs have a name in the same format of my 1st column
I am trying to use python to identify those rows that have a graph and print
the name of 2nd column in a new .txt file
These are the codes I have
import csv
with open("C:/*my dir*/UCSC to Ensembl.csv", "r") as f:
reader = csv.reader(f, delimiter = ',')
for row in reader:
print row[0]
But this as far as I can get and I am stuck.
Answer: You're almost there:
import csv
import os.path
with open("C:/*my dir*/UCSC to Ensembl.csv", "rb") as f:
reader = csv.reader(f, delimiter = ',')
for row in reader:
graph_filename = os.path.join("C:/folder", row[0] + "_nt_counts.txt")
if os.path.exists(graph_filename):
print (row[1])
Note that the repeated calls to
[`os.path.exists`](http://docs.python.org/library/os.path.html#os.path.exists)
may slow down the process, especially if the directory lies on a remote
filesystem and does not significantly more files than the number of lines in
the CSV file. You may want to use
[`os.listdir`](http://stackoverflow.com/a/11738276/4279) instead:
import csv
import os
graphs = set(os.listdir("C:/graph folder"))
with open("C:/*my dir*/UCSC to Ensembl.csv", "rb") as f:
reader = csv.reader(f, delimiter = ',')
for row in reader:
if row[0] + "_nt_counts.txt" in graphs:
print (row[1])
|
Writing variables to a hex file in Python
Question: So, I have got a float value: -1.0f, or something. And how could I write it
into a file in hexadecimal format in Python? I mean that we open the file in
notepad, we won't see the hexadecimal values, just the ASCII code.
Answer: In Python 3:
>>> import struct
>>> "".join("{0:02X}".format(b) for b in struct.pack(">f", -1.0))
'BF800000'
In Python 2:
>>> import struct
>>> "".join("{0:02X}".format(ord(b)) for b in struct.pack(">f", -1.0))
'BF800000'
|
Sorting Python dictionary based on nested dictionary values
Question: How do you sort a Python dictionary based on the inner value of a nested
dictionary?
For example, sort `mydict` below based on the value of `context`:
mydict = {
'age': {'context': 2},
'address': {'context': 4},
'name': {'context': 1}
}
The result should be like this:
{
'name': {'context': 1},
'age': {'context': 2},
'address': {'context': 4}
}
Answer:
>>> from collections import OrderedDict
>>> mydict = {
'age': {'context': 2},
'address': {'context': 4},
'name': {'context': 1}
}
>>> OrderedDict(sorted(mydict.iteritems(), key=lambda x: x[1]['context']))
OrderedDict([('name', {'context': 1}), ('age', {'context': 2}), ('address', {'context': 4})])
|
Transform URL string into normal string in python (%20 to space etc)
Question: Is there any way in python to transfrom this-> %CE%B1%CE%BB%20 into this: "αλ
" which is its real representation?
Thanks in advance!
Answer:
>>> import urllib2
>>> print urllib2.unquote("%CE%B1%CE%BB%20")
αλ
|
Why does multiprocess.Process not write the file while threading.Thread does?
Question: The dotestsrl and the dotestmt functions work, and they create and write to
the files. The dotestmp function runs fast, but does not create nor write to
the files. What can I do to make it so that dotestmp performs the same task as
dotestmt but using multiprocessing.Process? (This is on a dual-core,
hyperthreaded machine, running Windows 7 and Python 3.2.3; if that matters)
import sys, os, datetime, threading, multiprocessing
def dowrk(fp):
with open(fp, mode="w") as f:
for i in range(1000000):
f.write(str(i))
def dotestsrl():
fp = "C:\\Users\\user1\\Desktop\\"
fn = "tst.txt"
start = datetime.datetime.now()
for fni in range(1, 5):
dowrk(fp+str(fni)+fn)
end = datetime.datetime.now()
print("***DONE at: ", end - start)
def dotestmt():
fp = "C:\\Users\\user1\\Desktop\\"
fn = "tst.txt"
lst = []
start = datetime.datetime.now()
for fni in range(1, 5):
t = threading.Thread(target=dowrk, args=(fp+str(fni)+fn,))
lst.append(t)
t.start()
for te in lst:
te.join()
end = datetime.datetime.now()
print("***DONE at: ", end - start)
def dotestmp():
fp = "C:\\Users\\user1\\Desktop\\"
fn = "tst.txt"
lsp = []
start = datetime.datetime.now()
for fni in range(1, 5):
p = multiprocessing.Process(target=dowrk, args=(fp+str(fni)+fn,))
lsp.append(p)
p.start()
for pe in lsp:
pe.join()
end = datetime.datetime.now()
print("***DONE at: ", end - start)
dotestsrl() # ***DONE at: 0:00:08.029000
dotestmt() # ***DONE at: 0:00:07.697000
dotestmp() # ***DONE at: 0:00:00.257000, but doesn't actually write files.
Answer: You could try:
def dowrk_safe(*args, **kwargs):
try:
return dowrk(*args, **kwargs)
except Exception:
import sys
import traceback
traceback.print_exc(file=sys.stderr)
instead of `dowrk()` function and see if there are any errors.
|
Use a DLL with python (using ctypes), not working
Question: I'm trying to write a DLL that I can import in Python (2.7), and I'm having
difficulties "making it work". When I load the library in Python using
`WinDLL()` or `windll.LoadLibrary()`, and test the exported function the
output i get is empty. If I add an argument to `TestFunction()` it raises a
`ValueError` which states that there is probably to many arguments (it's
really not).
**python-file:**
from ctypes import *
x = windll.LoadLibrary('./pymod.dll')
print x.TestFunction(123) #Should return 123.
**main.h:**
#ifndef __MAIN_H__
#define __MAIN_H__
#include <windows.h>
#define DLL_EXPORT __declspec(dllexport)
#ifdef __cplusplus
extern "C"
{
#endif
int DLL_EXPORT TestFunction(int data);
#ifdef __cplusplus
}
#endif
#endif
and **main.cpp:**
#include "main.h"
int DLL_EXPORT TestFunction(int x = 0) {
return x;
}
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) {
switch (fdwReason){
case DLL_PROCESS_ATTACH:
break;
case DLL_PROCESS_DETACH:
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
}
return TRUE;
}
**Solved** : Issue was wrong calling convention.
Answer: My first guess would be that you are using a different calling convention than
your Python assumes.
int DLL_EXPORT TestFunction(int data);
That declaration probably means that `cdecl` calling convention will be used;
while use of `windll` makes Python believe that the `stdcall` convention
should be used. That effectively changes the way that arguments are passed,
and thus makes Python believe that you have passed the wrong number of
arguments. This is noted in the [ctypes
documentation](http://docs.python.org/library/ctypes.html#calling-functions).
If that's the case, you can do either of the following:
1. Change the calling convention in the C code to `stdcall` (which is used in Windows system DLLs). If you are using MSVC, they have [a doc on developing DLLs](http://msdn.microsoft.com/en-us/library/office/bb687850.aspx);
2. Change the calling convention expected by the Python code to `cdecl`. This is done by using `cdll` instead of `windll`.
|
Lexical cast from string to type
Question: Recently, I was trying to store and read information from files in Python, and
came across a slight problem: I wanted to read type information from text
files. Type casting from string to int or to float is quite efficient, but
type casting from string to type seems to be another problem. Naturally, I
tried something like this:
var_type = type('int')
However, `type` isn't used as a cast but as a mechanism to find the type of
the variable, which is actually `str` here.
I found a way to do it with:
var_type = eval('int')
But I generally try to avoid functions/statements like `eval` or `exec` where
I can. So my question is the following: Is there another pythonic (and more
specific) way to cast a string to a type?
Answer: I like using `locate`, which works on built-in types:
>>> from pydoc import locate
>>> locate('int')
<type 'int'>
>>> t = locate('int')
>>> t('1')
1
...as well as anything it can find in the path:
>>> locate('datetime.date')
<type 'datetime.date'>
>>> d = locate('datetime.date')
>>> d(2015, 4, 23)
datetime.date(2015, 4, 23)
...including your custom types:
>>> locate('mypackage.model.base.BaseModel')
<class 'mypackage.model.base.BaseModel'>
>>> m = locate('mypackage.model.base.BaseModel')
>>> m()
<mypackage.model.base.BaseModel object at 0x1099f6c10>
|
Reliance Broadband Auto Login Script - Syntax Error When Running on Windows
Question: I am using Reliance Broadband which has web based login for accessing
internet. It gets log-off every 24hrs, so I have to sign in again.
I came across a [PYTHON script](https://github.com/zyxware/reliance-auto-
login-script), which keeps checking connection and keeps the connection alive.
Somehow When I run it on windows after installing the latest Python version, I
get following syntax error.
C:\Documents and Settings\CS\Desktop>reliance-login.py
File "C:\Documents and Settings\CS\Desktop\reliance-login.py", line 48
if debug: print "Testing"
^
SyntaxError: invalid syntax
Can anyone please check and let me know what exactly is the issue?
=====
Thanks sr2222, I tried 2to3, after removing all + n - ... I am still getting
some error.
Following is the script afer 2to3.. can you please run it on your machine n
help in fixing the error.
#!/usr/bin/env python
# encoding: utf-8
"""
# Reliance Login Script for Python 2.x v1.0
#
# Copyright (c) 2009 Kunal Dua, http://www.kunaldua.com/blog/?p=330
# Copyright (c) 2012 Anoop John, http://www.zyxware.com
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
"""
import urllib.request, urllib.error, urllib.parse, urllib, http.cookiejar, time, re, sys
username = 'username'
password = 'password'
req_headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; U; ru; rv:5.0.1.6) Gecko/20110501 Firefox/5.0.1 Firefox/5.0.1'
}
request = urllib.request.Request(url, headers=req_headers)
if not opener:
jar = http.cookiejar.FileCookieJar("cookies")
opener = urllib.request.build_opener(urllib2.HTTPCookieProcessor(jar))
response = opener.open(request, data)
code = response.code
headers = response.headers
def is_internet_on():
'''test if the machine is connected to the internet'''
if debug: print("Testing")
try:
code, headers, html, opener = get_url('http://74.125.113.99', timeout=10)
if debug: print(html)
if re.search('google.com', html):
return True
else:
return False
except:
if debug: print("Error")
return False
return False
def internet_connect():
'''try to connect to the internet'''
code, headers, html, cur_opener = get_url("http://10.239.89.15/reliance/startportal_isg.do", timeout=10)
if debug: print(html)
login_data = urllib.parse.urlencode({'userId' : username, 'password' : password, 'action' : 'doLoginSubmit'})
code, headers, html, cur_opener = get_url('http://10.239.89.15/reliance/login.do', data=login_data, opener=cur_opener)
if debug: print(html)
def internet_disconnect():
'''try to disconnect from the internet'''
code, headers, html, cur_opener = get_url('http://10.239.89.15/reliance/login.do', timeout=10)
if debug: print(html)
code, headers, html, cur_opener = get_url('http://10.239.89.15/reliance/logout.do', opener=cur_opener)
if debug: print(html)
def internet_keep_alive():
'''login and keep the connection live'''
while True:
if not is_internet_on():
internet_connect()
if debug: print("Not connected")
else:
if debug: print("Connected")
pass
time.sleep(check_interval)
def print_usage():
print("Reliance Netconnect AutoLogin")
print("-----------------------------")
print("usage:" + sys.argv[0] + " [login|logout]\n")
print("If there are no arguments it runs in an infinite loop and will try to remain connected to the internet.")
keep_alive = True
if (len(sys.argv) > 1):
Answer: Did you download Python 2 or Python 3? That's Python 2.X print syntax, if you
have a Python 3 interpreter, you will see that error. That script is probably
written in Python 2.X. You can either download a different interpreter or run
the 2to3.py script on the source of your stay-alive script to get it working
under Python 3.
Also, wow, there are ISPs that still do that? Sorry you are stuck with that.
|
Python OpenCV Box2D
Question: I am trying to call OpenCV function MinAreaRect2 from within python. I use
OpenCV 2.4.2 with python 2.7 and numpy 1.6. I went this far :
import cv
def nda2ipl(arr, dtype=None):
return cv.fromarray(np.ascontiguousarray(arr, dtype=dtype))
def min_area_rect2(points):
storage = cv.CreateMemStorage()
cv_points = nda2ipl(points.reshape((-1, 1, 2)))
out = cv.MinAreaRect2(cv_points, storage)
return out
I can call this function with a ndarray of shape (N x 2). I get this kind of
results :
((476.5, 604.5), (951.0, 1207.0), -0.0)
I assume that the first tuple is the center of the box, the second gives the
width and the height and the last is the angle.
The problem is I could not get a clear reference stating this. Actually, the
opencv documentation tells me what the functions returns in Python.
I found the [official documentation about this
function](http://docs.opencv.org/modules/imgproc/doc/structural_analysis_and_shape_descriptors.html?highlight=minarearect#cv.MinAreaRect2)
but this is not very helpful.
What are exactly the output of MinAreaRect2 in python ? More generally, where
do you get precise documentation about the OpenCV python wrapper ?
Answer: OpenCV Python wrapper documentation is kept along with the normal
documentation in same site, www.docs.opencv.org
Earlier Python module used was `cv` interface, which used native data types
from original C++ interface like cvMat, cvSeq etc.
Later it was shifted to more better, advanced and simpler module `cv2`
interface. In it, everything is returned as either Numpy arrays or native
python data types.
Here, tuple returned has the same arguments as that of
**[cvBox2D](http://docs.opencv.org/modules/core/doc/old_basic_structures.html?highlight=box2d#cvbox2d)**.
You can find more details the differences between different python wrappers
here : [What is different between all these OpenCV Python
interfaces?](http://stackoverflow.com/questions/10417108/what-is-different-
between-all-these-opencv-python-interfaces/10425504#10425504)
Here, your assumption is correct. Those values specified exactly what you
mentioned.
If you want to draw rotated rect, you need 4 vertices of the rectangle. For
that, you need a function which is never seen in documentation, ie
**cv2.cv.BoxPoints()** (but don't worry, it will be there in documentation
when OpenCV 2.4.3 is released. )
You can find an example on how to draw rotated rectangle in this article :
[**Rotated
Rectangle**](http://opencvpython.blogspot.in/2012/06/contours-2-brotherhood.html)

|
Tkinter GUI Python background color
Question: I'm writing a Tkinter application with buttons, graphs, sliders, etc, but I
can't get their background uniform.
import Tkinter
from Tkinter import *
root =Tk()
root.title('Button')
root.configure(bg='gray')
Button(text='Button',bg='gray').pack(side=BOTTOM)
root.mainloop()
If you run this code, the background of the main window is indeed gray, but
the image of the button has a white area around it. Is there any way to fix
this?
Answer: If the issue is that you don't like the default button effect on your system,
you don't have to change the border width; instead you can set `relief='flat'`
in the button declaration. That way, you'll still get the "sunken" look when
you click the button, which you won't get if you just set `borderwidth` to 0
or a value close to it. Another issue with lessening `borderwidth` is that it
may make the button smaller than expected.
|
How to wait for 20 secs for user to press any key?
Question: How can I wait for user to press any key for 20 secs? I.e. I show the message
and it counts 20 secs, the code continues execution either if 20 secs are
passed OR if user pressed any key. How can I do it with python?
Answer: If you're on Windows:
def wait_for_user(secs):
import msvcrt
import time
start = time.time()
while True:
if msvcrt.kbhit():
msvcrt.getch()
break
if time.time() - start > secs:
break
|
Why does this python dictionary get created out of order using setdefault()?
Question: I'm just starting to play around with Python (VBA background). Why does this
dictionary get created out of order? Shouldn't it be a:1, b:2...etc.?
class Card:
def county(self):
c = 0
l = 0
groupL = {} # groupL for Loop
for n in range(0,13):
c += 1
l = chr(n+97)
groupL.setdefault(l,c)
return groupL
pick_card = Card()
group = pick_card.county()
print group
here's the output:
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6, 'i': 9, 'h': 8, 'k': 11, 'j': 10, 'm': 13, 'l': 12}
or, does it just get printed out of order?
Answer: Dictionaries have no order in python. In other words, when you iterate over a
dictionary, the order that the keys/items are "yielded" is not the order that
you put them into the dictionary. (Try your code on a different version of
python and you're likely to get differently ordered output). If you want a
dictionary that is ordered, you need a `collections.OrderedDict` which wasn't
introduced until python 2.7. You can find equivalent recipes on `ActiveState`
if you're using an older version of python. However, often it's good enough to
just sort the items (e.g. `sorted(mydict.items())`.
**EDIT** as requested, an OrderedDict example:
from collections import OrderedDict
groupL = OrderedDict() # groupL for Loop
c = 0
for n in range(0,13):
c += 1
l = chr(n+97)
groupL.setdefault(l,c)
print (groupL)
|
Python2.7 - Sqlite3 - 2 inputs
Question: I am writing a small python script like this:
#!/usr/bin/env python
from sqlite3 import dbapi2 as sqlite
from sys import argv,exit
db_name = "hashez.db"
def define_db():
try:
conn = sqlite.connect(db_name)
except IOError as e:
print "problem while creating/connecting the db:",e.args[0]
exit(1)
return conn
def write_db(conn,cursor,na,ha):
conn.execute("CREATE TABLE IF NOT EXISTS user (name TEXT UNIQUE, hash TEXT UNIQUE)")
query = "INSERT OR REPLACE INTO user VALUES($name,$hash)"
cursor.execute(query,[na],[ha])
cursor.close()
conn.commit()
conn.close()
exit(0)
if __name__ == "__main__":
if len(argv) == 2:
na,ha = argv[1]
#ha = argv[2]
else:
print "no argument given - stopping now"
exit(1)
conn = define_db()
cursor = conn.cursor()
write_db(conn,cursor,na,ha)
I have no problem when I try to take in one input
`python user.py blah`
but When I try to do with more than one,It goes into the else loop.
where am I doing the errors? Please guide me thru...
Answer: You get this error because the first argument is actually the file name.
A simple test file shows how this works:
[~]$ cat test.py
from sys import argv
if __name__ == '__main__':
print argv
print len(argv)
[~]$ python test.py one two
['test.py', 'one', 'two']
3
[~]$ python test.py one
['test.py', 'one']
2
You should also fix your SQL/query
query = "INSERT OR REPLACE INTO user VALUES(?,?)"
cursor.execute(query,[na,ha])
conn.commit()
See the [sqlite api docs](http://docs.python.org/library/sqlite3.html).
|
Can python threads access variables in the namespace?
Question: I have a script that creates a bunch of threads, runs a program to use the
threads to run tasks from a queue, and returns something from each thread. I
want to count how many of these returned successfully, so I set a variable
"successful=0" and increment it every time the queue reports a task completed
successfully.
However, I'm getting "UnboundLocalError: local variable 'successful'
referenced before assignment"
What's going on?
Here's some example code:
successful = 0
q = Queue(200)
for i in range(100):
t=Thread(target=foo)
t.daemon=True
t.start()
def foo():
while True:
task=q.get()
#do some work
print task
successful+=1 # triggers an error
q.task_done()
for i in range(100):
q.put("Foo")
q.join()
print successful
Answer:
successful+=1
is not a thread-safe operation. With multiple threads trying to increment a
shared global variable, collisions may happen and `successful` will not be
incremented properly.
To avoid this error, use a lock:
lock = threading.Lock()
def foo():
global successful
while True:
...
with lock:
successful+=1
* * *
Here is some code to demonstrate that x += 1 is not threadsafe:
import threading
lock = threading.Lock()
x = 0
def foo():
global x
for i in xrange(1000000):
# with lock: # Uncomment this to get the right answer
x += 1
threads = [threading.Thread(target=foo), threading.Thread(target=foo)]
for t in threads:
t.daemon = True
t.start()
for t in threads:
t.join()
print(x)
yields:
% test.py
1539065
% test.py
1436487
These results do not agree and are less than the expected 2000000.
Uncommenting the lock yields the correct result.
|
Python 3, Scrypt module, Hashes Not Matching
Question: Using: Python 3.2.3, scrypt 0.5.5 module, Ubuntu 12.04
I installed the scrypt module fine. I ran the sample code on the page fine. I
also found an [expanded version of the sample
code](http://aleccolocco.blogspot.com/2011/09/how-to-protect-passwords-with-
python.html), which did fine too. But I wanted to test if it would hash the
same word twice, so I added a section call to Encrypt(), to simulate the
concept of hashing it once for the DB and then hashing again when a user logs
in, so my full code looks like this:
import random,scrypt
class Encrypt(object):
def __init__(self):
pass
def randSTR(self,length):
return ''.join(chr(random.randint(0,255)) for i in range(length))
def hashPWD(self,pwd, maxtime=0.5, datalength=64):
return scrypt.encrypt(self.randSTR(datalength), pwd, maxtime=maxtime)
def verifyPWD(self,hashed_password, guessed_password, maxtime=0.5):
try:
scrypt.decrypt(hashed_password, guessed_password, maxtime)
return True
except scrypt.error:
return False
if __name__ == '__main__':
e = Encrypt()
user_pw = 'theansweris42'
user_salt = 't9'
pw_salt = user_pw + user_salt
hashed_pw = e.hashPWD(pw_salt) # To be stored len()==192
y = e.verifyPWD(hashed_pw, pw_salt) # True
n = e.verifyPWD(hashed_pw, 'guessing'+ pw_salt) # False
print(y)
print(n)
#print("Hash: %s" % (hashed_pw))
x = Encrypt()
user_pw2 = 'theansweris42'
user_salt2 = 't9'
pw_salt2 = user_pw2 + user_salt2
hashed_pw2 = x.hashPWD(pw_salt2) # To be stored len()==192
y2 = x.verifyPWD(hashed_pw, hashed_pw2) # True
print(y2)
print(pw_salt)
print(pw_salt2)
print(hashed_pw)
print(hashed_pw2)
...as you can see, I also hard coded the salt (for testing). Strangely,
everytime I run this, the hashed_pw & hashed_pw2 are always different. Why is
this hashing the same password differently each time? Shouldn't it be
outputting the same hash each time I give it the exact same input? I've been
trying to figure this out for an hour, so I figure I better ask.
Answer: You encrypt two different random strings with the same password (plus a salt).
This will result in two different outputs.
The trick used here is that the password + salt can be used to decrypt that
random string, while the incorrect password will raise an error. Hence, you
don't need to store the original random string to make sure that the password
was correct, and since the string used was random (within the limits of the
random number generator) it's going to be extremely hard to crack the
password.
|
How to use pip to install lxml in different version of python?
Question: In my os, `/usr/bin/python` is python2.6, and `/usr/local/bin/python` is
python2.7. I have installed pip, however, when I use the command:
pip install lxml
I found I can use lxml in python2.7, but I can't use it in python2.6
>>> import lxml
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named lxml
How can I install lxml in python2.6 with pip?
Answer: Each `pip` executable is for one Python version/install, and it can tell you
which. On my system:
$ pip --version
pip 1.1 from /usr/lib/python2.7/site-packages (python 2.7)
You may also have symlinks such as `pip-2.7` for a particular version.
In your case, if you don’t have it already, you need first to install pip in
Python 2.6. Depending on you OS it might be better to install it with the
distribution’s packages, or to install it through
[distribute](http://packages.python.org/distribute/) (aka. `easy_install`)
|
ImportError: No module named statsmodels
Question: Hi I downloaded the StatsModels source from
<http://pypi.python.org/pypi/statsmodels#downloads> I then untarred to
/usr/local/lib/python2.7/dist-packages
and per the documentation at
<http://statsmodels.sourceforge.net/devel/install.html> did this
sudo python setup.py install
It installed, but when I try to import
import statsmodels.api as sm
I get the following error
Traceback (most recent call last):
File "/home/Astrophysics/Histogram_Fast.py", line 6, in <module>
import statsmodels.api as sm
ImportError: No module named statsmodels.api
I read a few post that have had a similar problem and checked that setuptools
was installed and it was also in
/usr/local/lib/python2.7/dist-packages
I'm kinda at a loss on this and would appriceate any help
I am also running
numpy 1.6
so thats not the problem
Answer: * you shouldn't untar it to /usr/local/lib/python2.7/dist-packages (you could use any temporary directory)
* you might have used by mistake a different python executable e.g., /usr/bin/python instead of the one corresponding to /usr/local/lib/python2.7
You should use `pip` corresponding to a desired python version to install it:
$ python -mpip install statsmodels
It would allow you to upgrade/uninstall it easily.
Don't install as a root to avoid the risk of messing with system python
installation by accident. You could use `--user` option or virtualenv instead.
|
Python folder structure for larger projects
Question: I'm new to using python for larger projects. I figured out following folder
structure for my python project:
project
--> doc
--> src
--> hardware
--> devices
--> device1
--> device2
--> measurement
--> ui
--> util
--> tests
--> hardware
--> devices
--> device1
--> device2
--> measurement
--> ui
--> util
The tests folder contains unittests for modules in the soure folder. Is this
the right approach for such a program?
How should I do the importing? I thought to add the root folder to the python
path and import every module absolute from the root path. Should I do this so?
This program is used on several coimputers. How should I deploy it? Currently
I use `SVN` and every computer gets the whole project and starts it from
there. There is one disadvantage, I have to add the prject path to the
`PYTHONPATH` on every computer.
Answer: The global structure looks good to me. You need a module to write a setup.py
script to install your package such as
[setuptools](http://packages.python.org/an_example_pypi_project/setuptools.html).
This will allow installation and distribution of the package. See also
[Pypi](http://pypi.python.org/pypi) for distribution of the package.
Typically, you can :
sudo setup.py install
to install your package at the system level. Or you can :
sudo setup.py install --prefix=~/local
to install at the user level. But then you have to add
~/local/lib/python/site-packages to your PYTHONPATH. But it has to be done
only once for all packages installed by this user.
If your package is stored on PyPI, you can on any machine do :
easy_install mypackage
to auto-magically install the package.
Even better you can make your packages only visible in isolated python
"virtual environment" using
[virtualenv](http://pypi.python.org/pypi/virtualenv/). This allow for testing
of various packages and versions on the same computer a breeze.
You can also add README files and such at the package root level.
|
Get function callers' information in python
Question: I want to get information about the callers of a specific function in python.
For example:
class SomeClass():
def __init__(self, x):
self.x = x
def caller(self):
return special_func(self.x)
def special_func(x):
print "My caller is the 'caller' function in an 'SomeClass' class."
Is it possible with python?
Answer: Yes, the
[`sys._getframe()`](http://docs.python.org/library/sys.html#sys._getframe)
function let's you retrieve frames from the current execution stack, which you
can then inspect with the methods and documentation found in the [`inspect`
module](http://docs.python.org/library/inspect.html); you'll be looking for
specific locals in the `f_locals` attribute, as well as for the `f_code`
information:
import sys
def special_func(x):
callingframe = sys._getframe(1)
print 'My caller is the %r function in a %r class' % (
callingframe.f_code.co_name,
callingframe.f_locals['self'].__class__.__name__)
Note that you'll need to take some care to detect what kind of information you
find in each frame.
|
How do I replace a specific part of a string in Python
Question: As of now I am trying to scrape Good.is.The code as of now gives me the
regular image(turn the if statement to True) but I want to higher res picture.
I was wondering how I would replace a certain text so that I could download
the high res picture. I want to change the html:
<http://awesome.good.is/transparency/web/1207/invasion-of-the-
drones/flash.html> to <http://awesome.good.is/transparency/web/1207/invasion-
of-the-drones/flat.html> (The end is different). My code is:
import os, urllib, urllib2
from BeautifulSoup import BeautifulSoup
import HTMLParser
parser = HTMLParser.HTMLParser()
# make folder.
folderName = 'Good.is'
if not os.path.exists(folderName):
os.makedirs(folderName)
list = []
# Python ranges start from the first argument and iterate up to one
# less than the second argument, so we need 36 + 1 = 37
for i in range(1, 37):
list.append("http://www.good.is/infographics/page:" + str(i) + "/sort:recent/range:all")
listIterator1 = []
listIterator1[:] = range(0,37)
counter = 0
for x in listIterator1:
soup = BeautifulSoup(urllib2.urlopen(list[x]).read())
body = soup.findAll("ul", attrs = {'id': 'gallery_list_elements'})
number = len(body[0].findAll("p"))
listIterator = []
listIterator[:] = range(0,number)
for i in listIterator:
paragraphs = body[0].findAll("p")
nextArticle = body[0].findAll("a")[2]
text = body[0].findAll("p")[i]
if len(paragraphs) > 0:
#print image['src']
counter += 1
print counter
print parser.unescape(text.getText())
print "http://www.good.is" + nextArticle['href']
originalArticle = "http://www.good.is" + nextArticle['href']
article = BeautifulSoup(urllib2.urlopen(originalArticle).read())
title = article.findAll("div", attrs = {'class': 'title_and_image'})
getTitle = title[0].findAll("h1")
article1 = article.findAll("div", attrs = {'class': 'body'})
articleImage = article1[0].find("p")
betterImage = articleImage.find("a")
articleImage1 = articleImage.find("img")
paragraphsWithinSection = article1[0].findAll("p")
print betterImage['href']
if len(paragraphsWithinSection) > 1:
articleText = article1[0].findAll("p")[1]
else:
articleText = article1[0].findAll("p")[0]
print articleImage1['src']
print parser.unescape(getTitle)
if not articleText is None:
print parser.unescape(articleText.getText())
print '\n'
link = articleImage1['src']
x += 1
actually_download = False
if actually_download:
filename = link.split('/')[-1]
urllib.urlretrieve(link, filename)
Answer: Have a look at
[str.replace](http://docs.python.org/library/string.html#string.replace). If
that isn't general enough to get the job done, you'll need to use a regular
expression ( [re](http://docs.python.org/library/re.html) \-- probably
`re.sub` ).
>>> str1="http://awesome.good.is/transparency/web/1207/invasion-of-the-drones/flash.html"
>>> str1.replace("flash","flat")
'http://awesome.good.is/transparency/web/1207/invasion-of-the-drones/flat.html'
|
How do you find the similarity of tuples, as a fraction, in python?
Question: For instance, if I had the tuples (1,2) and (3,2) in python, is there any way
to have a program return 0.5 or 1/2? I've searched but haven't been able to
find anything.
Answer:
>>> a = (1, 2)
>>> b = (3, 2)
>>> sum(x == y for x, y in zip(a, b)) / float(len(a))
0.5
The `float()` call is only necessary on Python 2.x, to avoid the integer
division. Alternatively you could use `from __future__ import division` at the
top of your file.
|
Custom Tags in Django 1.2 with Google App Engine Python 2.7
Question: Creating a custom tag in Google App Engine Python2.5 with Webapp used to be a
joyful experience. Here: [Django Templates and variable
attributes](http://stackoverflow.com/questions/35948/django-templates-and-
variable-attributes)
But now, in Python 2.7 with Webapp2 and Django 1.2, it is a pain in the ass. I
can only find bits of information here and there, and some of the methods
contradict with each other.
The method described in <http://www.john-smith.me/Tag/webapp2> ranks high in
Google, but some people claim it is "what a waste of time" [Webapp2 custom
tags](http://stackoverflow.com/questions/10618551/webapp2-custom-tags)
This one method seems to work
from django.template.loader import add_to_builtins
add_to_builtins('xxxxx')
But I dont know the details. Who can provide a step by step example?
I dont know why there are no official documents about these stuff. I mean,
this is not science experiments in which we explore the unknown. There
supposed to be some documentation so the developers can save their time.
Answer: I had same problem.
The fix:
1. Create templatetags folder. Add there module with custom tags as explained in Django docs [Custom template tags and filters](https://docs.djangoproject.com/en/1.4/howto/custom-template-tags/). Example folder structure:
app.yaml
myapp/
__init__.py
templatetags/
__init__.py
myTags.py
2. In settings.py set INSTALLED_APPS to myapp (name of folder which contains templatetags sub-folder):
INSTALLED_APPS = ( 'myapp' )
3. Now when you call {% load myTags %} in template Django should also seek the mytags module in myapp/*/templatetags/ folder.
|
Python, Sqlite not saving results on the file
Question: I have this code in Python:
conn = sqlite3.connect("people.db")
cursor = conn.cursor()
sql = 'create table if not exists people (id integer, name VARCHAR(255))'
cursor.execute(sql)
conn.commit()
sql = 'insert into people VALUES (3, "test")'
cursor.execute(sql)
conn.commit()
sql = 'insert into people VALUES (5, "test")'
cursor.execute(sql)
conn.commit()
print 'Printing all inserted'
cursor.execute("select * from people")
for row in cursor.fetchall():
print row
cursor.close()
conn.close()
But seems is never saving to the database, there is always the same elements
on the db as if it was not saving anything.
On the other side If I try to access the db file via sqlite it I got this
error:
Unable to open database "people.db": file is encrypted or is not a database
I found on some other answers to use `conn.commit` instead of `conn.commit()`
but is not changing the results.
Any idea?
Answer: This seems to work alright for me ("In database" increases on each run):
import random, sqlite3
conn = sqlite3.connect("people.db")
cursor = conn.cursor()
sql = 'create table if not exists people (id integer, name VARCHAR(255))'
cursor.execute(sql)
for x in xrange(5):
cursor.execute('insert into people VALUES (?, "test")', (random.randint(1, 10000),))
conn.commit()
cursor.execute("select count(*) from people")
print "In database:", cursor.fetchone()[0]
|
PyDev PYTHONPATH does not work for separate test und src directories
Question: This is probably a noob problem. For that I apologize, but I couldn't find a
solution so far. I short, for some reason that I don't understand, I can't
access modules from my `src` directory in my tests. My project setup looks
like this:
src/package/module.py
tests/package/module_test.py
and my test roughly looks like this:
import package
import unittest
class module_test(TestCase):
def testSomeMethod(self):
m = package.SomeClass() #there is class of that name in module.py
I checked the run configuration setup in PyDev and it says that both `src` and
`tests` are on the PYTHONPATH when I execute the tests. But when I try to run
this test, I get the error `'module' object has no attribute 'SomeClass'`.
What am I doing wrong?
Answer: When you do `import package`, you import the package, not the module inside
it. If you want to import the module, you need to do `from package import
module` (and then refer to the class as `module.SomeClass`, not
`package.SomeClass`).
Packages are containers for groups of modules. They don't magically allow you
to access everything inside any of the modules (although you can have them
automatically import their modules). You still have to import the individual
modules in the package.
|
Try to revisit the URL in javascript
Question: I want to visit certain REST URI.
$.ajax({
type: "POST",
url: url + "result/" + ticket_id,
success: function(data) {
setTimeout(function(){pollResponse(url,data.id);}, 3000);
}
});
This works. It visits the URI, and the views function does its job. So on
`success` it moves on to the new URI.
function pollResponse(url, id)
{
$.getJSON(url + "status/" + id, {},
function(data) {
if (data.report == null)
{
console.log(data.status_response);
setTimeout(function(){pollResponse(url, id);}, 3000);
}
else
console.alert('DONE!');
}
);
};
If the URI does not return `report` as part of the data (or being empty), then
we will ask again in 3 seconds.
But after it prints the log in the console, the response stops with `[200]
OK`. It doesn't ask the server any more.
All I did with my Python's views function is
from cornice import Service
status = Service(name='status',
path=root+'/status/{some_id}',
description=status_desc)
@status.get()
def get_status(request):
// do something
if (...):
return {'report': ''}
else:
return {'report': 'NOT EMPTY')
Answer: You may have a parsing issue in the result or a cross domain issue. Try
changing your code to use the `ajax` function directly:
$.ajax({
url: url + "status/" + id,
dataType: 'json',
data: {},
success: function(data) {
if (data.report == null)
{
console.log(data.status_response);
setTimeout(function(){pollResponse(url, id);}, 3000);
}
else
console.alert('DONE!');
},
error: function(jqXHR, textStatus, errorThrown) {
console.error(textStatus);
console.error(errorThrown);
console.log(jqXHR.responseText);
}
);
This way you can see if the response is causing an error. If there is a
parsing error, you can get the data through jqXHR.responseText on the error
function and see what is wrong.
The shortcut functions for AJAX in jQuery error silently on many cases. This
is why i rarely use them.
|
Parallel running of several jobs in a python script
Question: I am not a programmer and hence simple answers will be appreciated. I am a MD
and am involved in a bioinformatics project.
Let's say I have a Python script, `abc.py` and I have a text file,
`commandline.txt` with 113 command lines, 1 in each line, for this script to
be run in parallel. I want each of these jobs to be run in its own directory
called scatter.001, scatter.002, ... , scatter.113, (just a unique number for
each), to be created in the directory where I am executing the script from.
I am running, Windows 7 with Python 2.7.
What is the command line for doing this? (python xyz\abc.py ....... )
PS:
-p 100 -m 10000000 -e 10 -k I:\Exome\Invex\analyses\PatientSet.load_maf.pkl ,UBE2Q1,RNF17,RNF10,REM1,PMM2,ZNF709,ZNF708,ZNF879,DISC1,RPL37,ZNF700,ZNF707,CAMK4,ZC3H10,ZC3H13,RNF115,ZC3H14,SPN,HMGCLL1,CEACAM5,GRIN1,DHX8,NUP98,XPC,SP4,SP5,CAMKV,SPPL3,RAB40C,RAB40A,COL7A1,GTSE1,OVCH1,FAM183B,KIAA0831,SPPL2B,ITGA8,ITGA9,MYO3B,ATP2A2,ITGA1,ITGA2,ITGA3,ITGA5,RIT1,ITGA7,TRHR,LOC100132288,DENND4A,DENND4B,TAP2,GAP43,PAMR1,HRH2,HRH3,HRH1,FBXL18,FAM169B,GHDC,SDK1,SDK2,THSD4,THSD1,ZFP161,CHST8,COL4A5,COL4A4,COL4A3,COL4A2,COL4A1,CHST1,CHST5,CHST4,ITGAX I:\Exome\Invex\analyses\First7.final_analysis_set.maf I:\Exome\Invex\temp\unzipped_power_files First7 I:\Exome\Invex\analyses\First7.individual_set.txt I:\Exome\Invex\hg19.fasta I:\Exome\Invex\hg19_encoded_by_trinucleotide.fasta I:\Exome\Invex\TCGA.hg19.June2011.gaf I:\Exome\Invex\hg19 I:\Exome\Invex\pph2_whpss_reduced I:\Exome\Invex\cosmic_num_times_each_chr_pos_mutated.tab
That is an example of one line in commandline.txt. I have 113 such lines, in
the file..
Answer: If you go this way, you're getting into windows shell programming, which
nobody does. (I mean somebody does it, but they're an extremely small group.)
It would be simplest if you wrote a second python script that loops through
the arguments that you want to pass to the second script, and calls a functoin
with those arguments.
from subprocess import Popen
from os import mkdir
argfile = open('commandline.txt')
for number, line in enumerate(argfile):
newpath = 'scatter.%03i' % number
mkdir(newpath)
cmd = '../abc.py ' + line.strip()
print 'Running %r in %r' % (cmd, newpath)
Popen(cmd, shell=True, cwd=newpath)
This creates a directory, and runs your command as a separate process in that
directory. Since it doesn't wait for the subprocess to finish before starting
another, this gives the paralellism you want.
* * *
The in-series version just
[waits](http://docs.python.org/library/subprocess#subprocess.Popen.wait)
before it starts another subprocess. Add one line at the end of the loop:
p = Popen(cmd, shell=True, cwd=newpath)
p.wait()
|
Installing and Running CGI Proxy Python on Tomcat 7
Question: I want to set up a proxy running on tomcat for openlayers, so I followed these
steps:
1. Downloaded the proxy.cgi file from the OpenLayers web site:
<http://trac.osgeo.org/openlayers/browser/trunk/openlayers/examples/proxy.cgi>
Here is the code:
#!c:/Python27/python.exe
"""This is a blind proxy that we use to get around browser
restrictions that prevent the Javascript from loading pages not on the
same server as the Javascript. This has several problems: it's less
efficient, it might break some sites, and it's a security risk because
people can use this proxy to browse the web and possibly do bad stuff
with it. It only loads pages via http and https, but it can load any
content type. It supports GET and POST requests."""
import urllib2
import cgi
import sys, os
# Designed to prevent Open Proxy type stuff.
allowedHosts = ['www.openlayers.org', 'openlayers.org',
'labs.metacarta.com', 'world.freemap.in',
'prototype.openmnnd.org', 'geo.openplans.org',
'sigma.openplans.org', 'demo.opengeo.org',
'www.openstreetmap.org', 'sample.azavea.com',
'v2.suite.opengeo.org', 'v-swe.uni-muenster.de:8080',
'vmap0.tiles.osgeo.org', 'www.openrouteservice.org','localhost:6901']
method = os.environ["REQUEST_METHOD"]
if method == "POST":
qs = os.environ["QUERY_STRING"]
d = cgi.parse_qs(qs)
if d.has_key("url"):
url = d["url"][0]
else:
url = "http://www.openlayers.org"
else:
fs = cgi.FieldStorage()
url = fs.getvalue('url', "http://www.openlayers.org")
try:
host = url.split("/")[2]
if allowedHosts and not host in allowedHosts:
print "Status: 502 Bad Gateway"
print "Content-Type: text/plain"
print
print "This proxy does not allow you to access that location (%s)." % (host,)
print
print os.environ
elif url.startswith("http://") or url.startswith("https://"):
if method == "POST":
length = int(os.environ["CONTENT_LENGTH"])
headers = {"Content-Type": os.environ["CONTENT_TYPE"]}
body = sys.stdin.read(length)
r = urllib2.Request(url, body, headers)
y = urllib2.urlopen(r)
else:
y = urllib2.urlopen(url)
# print content type header
i = y.info()
if i.has_key("Content-Type"):
print "Content-Type: %s" % (i["Content-Type"])
else:
print "Content-Type: text/plain"
print
print y.read()
y.close()
else:
print "Content-Type: text/plain"
print
print "Illegal request."
except Exception, E:
print "Status: 500 Unexpected Error"
print "Content-Type: text/plain"
print
print "Some unexpected error occurred. Error text was:", E
1. I have my tomcat at port 6901, so I modified the proxy.cgi file to include my domain in the allowedHosts list:
allowedHosts = ['localhost:6901']
2. I copied the proxy.cgi file to the following folder:
$TOMCAT_PATH$/webapps/myApp/WEB-INF/cgi/
3. Modified the file web.xml of the web app by adding the sections below the file at
$TOMCAT_PATH$/webapps/myApp/WEB-INF/web.xml
<servlet>
<servlet-name>cgi</servlet-name>
<servlet-class>org.apache.catalina.servlets.CGIServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>cgiPathPrefix</param-name>
<param-value>WEB-INF/cgi</param-value>
</init-param>
<init-param>
<param-name>executable</param-name>
<param-value>c:\python25\python.exe</param-value>
</init-param>
<init-param>
<param-name>passShellEnvironment</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>5</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>cgi</servlet-name>
<url-pattern>/cgi-bin/*</url-pattern>
</servlet-mapping>
Comment: the “param-value” for the “executable” parameter has to contain the
path to your Pyhton installation. (it does!)
1. Modified the file context.xml of my web app by adding the element below, file at `$TOMCAT_PATH$/webapps/myApp/META-INF/context.xml`
2. Restarted Tomcat
3. To use the proxy with OpenLayers, included this single line into the code:
OpenLayers.ProxyHost = "/yourWebApp/cgi-bin/proxy.cgi?url=";
But the proxy isn't working! When I try to use it like:
/myApp/cgi-bin/proxy.cgi?url=labs.metacarta.com
I get this error:
Some unexpected error occurred. Error text was: list index out of range
I think it's related to os.environ["REQUEST_METHOD"], but I don't know how
it's related.
Answer: The problem appears to be in your `allowedHosts` line. It should include the
hosts that you want to connect to over the proxy (e.g. `allowedHosts =
['labs.metacarta.com']`)
|
Why type('string') seems to return null string in python cgi
Question: I'm reading Mark Lutz's _Programming Python 3rd editon_ , and I'm puzzled with
a question: `type('something')` always result in an empty string.
Could someone kindly explain this?
Context info:
I add one line to the script `$CODEROOT\pp3e\Internet\Web\cgi-bin\tutor0.py`
#!/usr/bin/python
#######################################################
# runs on the server, prints html to create a new page;
# url=http://localhost/cgi-bin/tutor0.py
#######################################################
print "Content-type: text/html\n"
print "<TITLE>CGI 101</TITLE>"
print "<H1>A First CGI script</H1>"
print '<p>[%s]'%type('apple') # ★ I add this line
print "<P>Hello, CGI World!</P>"
**For the added line, I hope to see in browser`[<type 'str'>]` , but I
actually see `[]` .**

The python to start a HTTP server is at
`$CODEROOT\pp3e\Internet\Web\webserver.py`
#########################################################################
# implement HTTP web server in Python which knows how to serve HTML
# pages and run server side CGI scripts; serves files/scripts from
# the current working dir and port 80, unless command-line args;
# python scripts must be stored in webdir\cgi-bin or webdir\htbin;
# more than one of these may be running on the same machine to serve
# from different directories, as long as they listen on different ports;
#########################################################################
webdir = '.' # where your html files and cgi-bin script directory live
port = 80 # http://servername/ if 80, else use http://servername:xxxx/
import os, sys
from BaseHTTPServer import HTTPServer
from CGIHTTPServer import CGIHTTPRequestHandler
if len(sys.argv) > 1: webdir = sys.argv[1] # command-line args
if len(sys.argv) > 2: port = int(sys.argv[2]) # else dafault ., 80
print 'webdir "%s", port %s' % (webdir, port)
# hack for Windows: os.environ not propogated
# to subprocess by os.popen2, force in-process
if sys.platform[:3] == 'win':
CGIHTTPRequestHandler.have_popen2 = False
CGIHTTPRequestHandler.have_popen3 = False # emulate path after fork
sys.path.append('cgi-bin') # else only adds my dir
os.chdir(webdir) # run in html root dir
srvraddr = ("", port) # my hostname, portnumber
srvrobj = HTTPServer(srvraddr, CGIHTTPRequestHandler)
srvrobj.serve_forever() # serve clients till exit
My environment:
* Python 2.7
* Windows 7 x64
Answer: Probably because the angle brackets in `<type 'str'>` are causing the output
to be treated as HTML.
Try changing:
print '<p>[%s]'%type('apple') # ★ I add this line
into:
hstr = "%s"%type('apple')
hstr = hstr.replace('<','<').replace('>','>')
print '<p>[%s]'%hstr
|
How to arrange and set up unit testing in Python
Question: I am working on a project in Python, using Git for version control, and I've
decided it's time to add a couple of unit tests. However, I'm not sure about
the best way to go about this.
I have two main questions: which framework should I use and how should I
arrange my tests? For the first, I'm planning to use unittest since it is
built in to Python, but if there is a compelling reason to prefer something
else I'm open to suggestions. The second is a tougher question, because my
code is already somewhat disorganized, with lots of submodules and relative
imports. I'm not sure where to fit the testing code. Also, I'd prefer to keep
the testing code seperate from everything else if possible. Lastly, I want the
tests to be easy to run, preferably with a single commandline command and
minimal path setup.
How do large Python projects handle testing? I understand that there is
typically an automated system to run tests on all new checkins. How do they do
it? What are the best practices for setting up a testing system?
Answer: Test framework choosing is mostly about personal preferences, there are some
of widespread:
* unittest — it's a clone of java's junit framework, so its syntax not so python-frendly
* unittest2 — a featured unittest
* pytest — comprehensive and complicated framework, but its source code is a little scary, so it's sometimes difficult to find solution if you have any issues
* nose — it grown from pytest but simpler, maybe its a good idea for you to use nose
Usual directory structure, for example, is:
- project
| - module_name
| - submodule.py
| - tests
| requirements.txt
| test_submodule.py
| - requirements.txt
One of best practices is using virtualenv:
$ virtualenv env # create virtualenv
$ env/bin/activate # activate virtualenv
$ pip install -r requirements.txt # install project requirements
$ pip install -r tests/requirements.txt # install testing requirements
$ py.test # if you use pytest
|
Changing package install order in Python
Question: Does anyone know if package install order matters in Python? More specifically
my pip `requirements.txt` for a Django website I am building was:
Django==1.4
MySQL-python==1.2.3
django-evolution==0.6.7
django-pagination==1.0.7
boto==2.5.2
numpy==1.6.2
requests==0.13.1
simplejson==2.5.2
gunicorn==0.14.6
When deploying to Heroku the application would crash with the following error:
2012-08-05T09:26:56+00:00 app[web.1]: 2012-08-05 09:26:56 [12] [INFO] Worker exiting (pid: 12)
2012-08-05T09:26:56+00:00 app[web.1]: 2012-08-05 09:26:56 [8] [INFO] Worker exiting (pid: 8)
2012-08-05T09:26:56+00:00 app[web.1]: 2012-08-05 09:26:56 [4] [INFO] Handling signal: term
2012-08-05T09:26:56+00:00 app[web.1]: 2012-08-05 09:26:56 [7] [INFO] Worker exiting (pid: 7)
2012-08-05T09:26:56+00:00 app[web.1]: 2012-08-05 09:26:56 [4] [INFO] Starting gunicorn 0.14.6
2012-08-05T09:26:56+00:00 app[web.1]: 2012-08-05 09:26:56 [4] [INFO] Listening at: http://0.0.0.0:20132 (4)
2012-08-05T09:26:56+00:00 app[web.1]: 2012-08-05 09:26:56 [4] [INFO] Using worker: sync
2012-08-05T09:26:56+00:00 app[web.1]: 2012-08-05 09:26:56 [7] [INFO] Booting worker with pid: 7
2012-08-05T09:26:56+00:00 app[web.1]: 2012-08-05 09:26:56 [8] [INFO] Booting worker with pid: 8
2012-08-05T09:26:56+00:00 app[web.1]: 2012-08-05 09:26:56 [9] [INFO] Booting worker with pid: 9
2012-08-05T09:26:56+00:00 app[web.1]: 2012-08-05 09:26:56 [10] [INFO] Booting worker with pid: 10
2012-08-05T09:26:57+00:00 heroku[web.1]: State changed from starting to up
2012-08-05T09:26:57+00:00 heroku[web.1]: Process exited with status 143
2012-08-05T09:27:17+00:00 app[web.1]: Usage: gunicorn [options]
2012-08-05T09:27:17+00:00 app[web.1]: gunicorn: error: no such option: --workers
2012-08-05T09:27:17+00:00 app[web.1]:
2012-08-05T09:27:17+00:00 app[web.1]: 2012-08-05 09:27:17 [9] [INFO] Worker exiting (pid: 9)
Where my `Procfile` is as follows:
web: python manage.py collectstatic --noinput; gunicorn commerical_production.wsgi:application --workers=4 --bind=0.0.0.0:$PORT
The problem was fixed by simply changing the order of requirements to:
Django==1.4
gunicorn==0.14.6
MySQL-python==1.2.3
django-evolution==0.6.7
django-pagination==1.0.7
boto==2.5.2
numpy==1.6.2
requests==0.13.1
simplejson==2.5.2
(note that `gunicorn` is now moved to the top)
I found this out by luckily guessing to try and change the order of the
imports but my question is has anyone else run into this problem or know why
the order of the packages makes a difference when installed from the
`requirements.txt`? Could this problem indicative of some larger dependency
issue that is in my app?
Answer: Pip is not very good at handling package dependencies as easy_install. We had
the same problem in our project. Even though the order in req.txt was correct,
we had dependency problems that is related to order.
My solution is to feed the req.txt to easy_install, but than you should be
careful with the packages that is editable or those from github etc.
You may want to check below links:
<http://metak4ml.blogspot.com/2009/08/easyinstall-read-pip-
requirementstxt.html> http://community.webfaction.com/questions/1220/using-
easy_install-to-get-all-dependencies-listed-in-requirementstxt (while read
line answer is close to what we do)
|
Cannot use HTMLUnit Webdriver from Python
Question: I'm trying to use the HTMLUnit WebDriver from Python with the following code:
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.remote.webdriver import WebDriver
if __name__ == '__main__':
webdriver = WebDriver('http://127.0.0.1:4444/wd/hub', DesiredCapabilities.HTMLUNIT)
webdriver.get('http://www.google.com')
... and get the following error:
Traceback (most recent call last):
File "bcc_mon_webdriver.py", line 8, in <module>
webdriver = WebDriver('http://127.0.0.1:4444/wd/hub', DesiredCapabilities.HTMLUNIT)
File "c:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 63, in __init__
self.start_session(desired_capabilities, browser_profile)
File "c:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 105, in start_session
'desiredCapabilities': desired_capabilities,
File "c:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 156, in execute
self.error_handler.check_response(response)
File "c:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 147, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: u'Error forwarding the new session cannot find : {platform=ANY, browserName=htmlunit, version=}' ; Stacktrace: Method process threw an error in RequestHandler.java
I use `selenium-server-standalone-2.25.0.jar` with the Python `selenium`
module also in version 2.25. The Selenium server is running on localhost and
it works fine with e.g. `DesiredCapabilities.FIREFOX`.
Do I have to install htmlunit manually? The selenium websites says that the
standalone-jar contains all dependencies.
Answer: The problem is you don't have a node that matches the `{platform=ANY,
browserName=htmlunit, version=}` pattern. To fix it you need to start a
selenium node with those browser settings, like this:
java -jar selenium-server-standalone-2.25.0.jar -role node -hub http://localhost:4444/grid/register -browser browserName=htmlunit
On the Selenium wiki ( <http://code.google.com/p/selenium/wiki/Grid2> ) it
says:
> "By default, this starts 11 browsers : 5 Firefox, 5 Chrome, 1 Internet
> Explorer."
So to be able to use different browsers - like `htmlunit` \- you'll have to
start nodes with -browser parameter, check `desired_capabilities.py` file
(located in your selenium egg under selenium/webdriver/common/) for a
reference of which parameters are required for each browser.
|
Can Python's selenium library play a test case saved as HTML
Question: I'd like to be able to write a Django
[LiveServerTestCase](https://docs.djangoproject.com/en/dev/topics/testing/?from=olddocs#django.test.LiveServerTestCase)
which runs a Selenium test that has been saved as HTML using the Selenium IDE.
The code might look something like this:
from django.test import LiveServerTestCase
from selenium.webdriver.firefox.webdriver import WebDriver
class TestUserStories(LiveServerTestCase):
@classmethod
def setUpClass(cls):
cls.selenium = WebDriver()
super(MySeleniumTests, cls).setUpClass()
def test_registration(self):
# Note - 'run_html_test' doesn't exist
self.selenium.run_html_test('selenium/registration.html')
This would allow our QA team (who don't speak python) to write tests using the
Firefox Selenium IDE and save them as HTML. Is this possible?
As far as I can tell, HTML is the best format to save the tests in as it
allows them to be edited in the IDE later on - exporting to python doesn't
allow this and also generates python that needs converting to work with the
Django LiveServerTestCase.
Answer: I started a project myself to build this sort of shim: to wrap existing HTML-
based Selenium tests with Python, without having to convert the existing
tests. It was for the same reason you state: a (client) testing team wanted to
write HTML Selenium tests, but we wanted to run them using Selenium RC. Here's
the link:
<https://github.com/jpstacey/PySelenese>
However, we mothballed the specific sub-project it was built for, so it hasn't
had any attention for a long time.
With regards to your specific request, writing a standalone LiveServerTestCase
isn't optimal, because you then lose Selenium's idea of having many test cases
within a suite, and a suite index.html to define it. PySelenese instead wraps
the whole test suite and runs all test cases within it, in the order that the
Selenium IDE would run it; but I admit that the code to do that isn't
currently very pretty and could be more Pythonic.
But this in theory could do what you want, so feel free to try it out, fork
the github project, make your own changes etc. The PySelenese layer currently
has limited support for many Selenium commands, but that's fairly extensible.
(Explicit disclaimer: PySelenese started as my own personal Github project.)
|
Differences between functools.partial and a similar lambda?
Question: In Python, suppose I have a function `f` that I want to pass around with some
secondary arguments (assume for simplicity that it's just the first argument
that remains variable).
What are the differences between doing it these two ways (if any)?
# Assume secondary_args and secondary_kwargs have been defined
import functools
g1 = functools.partial(f, *secondary_args, **secondary_kwargs)
g2 = lambda x: f(x, *secondary_args, **secondary_kwargs)
In the [doc page for
`partial`](http://docs.python.org/library/functools.html), for example, there
is this quote:
> `partial` objects defined in classes behave like static methods and do not
> transform into bound methods during instance attribute look-up.
Will the lambda-method suffer from this if used to make a class method from
arguments supplied to the class (either in the constructor or through a
function later on)?
Answer: 1. A lambda function has the same type as a standard function, so it will behave like an instance method.
2. The `partial` object in your example can be called like this:
g1(x, y, z)
leading to this call (not valid Python syntax, but you get the idea):
f(*secondary_args, x, y, z, **secondary_kwargs)
The lambda only accepts a single argument and uses a different argument order.
(Of course both of these differences can be overcome – I'm just answering what
the differences between the two versions you gave are.)
3. Execution of the `partial` object is slightly faster than execution of the equivalent `lambda`.
|
Using StringIO for ConfigObj and Unicode
Question: I am trying to use StringIO to feed ConfigObj. I would like to do this in my
unit tests, so that I can mock config "files", on the fly, depending on what I
want to test in the configuration objects.
I have a whole bunch of things that I am taking care of in the configuration
module (I am reading several conf file, aggregating and "formatting"
information for the rest of the apps). However, in the tests, I am facing a
unicode error from **hell**. I think I have pinned down my problem to the
minimal functionning code, that I have extracted and over-simplified for the
purpose of this question.
I am doing the following:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import configobj
import io
def main():
"""Main stuff"""
input_config = """
[Header]
author = PloucPlouc
description = Test config
[Study]
name_of_study = Testing
version = 9999
"""
# Just not to trust my default encoding
input_config = unicode(input_config, "utf-8")
test_config_fileio = io.StringIO(input_config)
print configobj.ConfigObj(infile=test_config_fileio, encoding="UTF8")
if __name__ == "__main__":
main()
It produces the following traceback:
Traceback (most recent call last):
File "test_configobj.py", line 101, in <module>
main()
File "test_configobj.py", line 98, in main
print configobj.ConfigObj(infile=test_config_fileio, encoding='UTF8')
File "/work/irlin168_1/USER/Apps/python272/lib/python2.7/site-packages/configobj-4.7.2-py2.7.egg/configobj.py", line 1242, in __init__
self._load(infile, configspec)
File "/work/irlin168_1/USER/Apps/python272/lib/python2.7/site-packages/configobj-4.7.2-py2.7.egg/configobj.py", line 1302, in _load
infile = self._handle_bom(infile)
File "/work/irlin168_1/USER/Apps/python272/lib/python2.7/site-packages/configobj-4.7.2-py2.7.egg/configobj.py", line 1442, in _handle_bom
if not line.startswith(BOM):
UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 0: ordinal not in range(128)
I am using Python-2.7.2 (32 bits) on linux. My locale for the console and for
the editor (Kile) are set to fr_FR.utf8.
I thought I could do this.
From the [io.StringIO
documentation](http://docs.python.org/library/stringio.html#module-StringIO),
I got this:
> The StringIO object can accept either Unicode or 8-bit strings, but mixing
> the two may take some care.
And from [ConfigObj
documentation](http://www.voidspace.org.uk/python/articles/configobj.shtml#unicode-
support), I can do this:
>
> >>> config = ConfigObj('config.ini', encoding='UTF8')
> >>> config['name']
> u'Michael Foord'
>
and [this](http://www.voidspace.org.uk/python/configobj.html#configobj-
specifications):
> infile: None
>
> You don't need to specify an infile. If you omit it, an empty ConfigObj will
> be created. infile can be :
>
>
> [...]
> A StringIO instance or file object, or any object with a read method.
> The filename attribute of your ConfigObj will be None [5].
>
>
> 'encoding': None
>
> By default ConfigObj does not decode the file/strings you pass it into
> Unicode [8]. If you want your config file as Unicode (keys and members) you
> need to provide an encoding to decode the file with. This encoding will also
> be used to encode the config file when writing.
My question is why does it produce this? What else did I not understand from
(simple) Unicode handling?...
By looking at this [answer](http://stackoverflow.com/a/10864570/493211), I
changed:
input_config = unicode(input_config, "utf8")
to (importing codecs module breforehand):
input_config = unicode(input_config, "utf8").strip(codecs.BOM_UTF8.decode("utf8", "strict"))
in order to get rid of possible included byte order mark, but it did not help.
Thanks a lot
NB: I have the same traceback if I use StringIO.StringIO instead of
io.StringIO.
Answer: This line:
input_config = unicode(input_config, "utf8")
is converting your input to Unicode, but this line:
print configobj.ConfigObj(infile=test_config_fileio, encoding="UTF8")
is declaring the input to be a UTF-8-encoded byte string. The error indicates
a Unicode string was passed when a byte string was expected, so commenting out
the first line above should resolve the issue. I don't have `configobj` at the
moment so can't test it.
|
Is yield-based coroutine is REAL coroutine?
Question: I was implementing greenlet API just for practicing.
from greenlet import greenlet
def test1():
print 12
gr2.switch()
print 34
def test2():
print 56
gr1.switch()
print 78
gr1 = greenlet(test1)
gr2 = greenlet(test2)
gr1.switch()
here's my messy code
def test1():
tmp1=yield
print 12
try:
gv2.send(1)
except StopIteration:
pass
tmp1=yield
print 34
def test2():
tmp2=yield
print 56
try:
gv2.send(1)
except StopIteration:
pass
tmp1=yield
print 78
gv1=test1()
gv1.next()
gv2=test2()
gv2.next()
gv1.send(1)
Shows,
12
56
Traceback (most recent call last):
File "prog.py", line 26, in <module>
gv1.send(1)
File "prog.py", line 5, in test1
gv2.send(1)
File "prog.py", line 15, in test2
gv2.send(1)
ValueError: generator already executing
So, I don't know I guess correctly,
but It looks that after test1 send '1' to test2, it still has something,
no control-flow switching happens unlike gevent. test1 still have the flow.
if not, I don't understand what greenlet can do but python "coroutine" can't
exists.
My question is
1. is python coroutine(yield-based) is the real thing(comparing it of others...lisp,ruby,&c)
2. if right, would you please give some tips for that spagetti code?
Answer: The generator instance of `test2()` is sending a value to itself.
def test2():
tmp2=yield
print 56
try:
gv2.send(1) # this is the offending line
except StopIteration:
pass
tmp1=yield
print 78
`send()` will _resume_ the generator, but whenever code is executed inside
`test2()`, it is already running. That is why it throws up.
Did you want to do: `gv1.send(1)`? That would not work either.
Here is why:
* Current situation: before `gv1.send(1)` at the very end of your example
* gv1 is dormant
* gv2 is dormant
* `gv1.send(1)` is invoked, this resumes `gv1`
* `gv1` proceeds to `gv2.send(1)`
* this resumes `gv2`
* `gv2` proceeds to `gv1.send(1)`
* `gv1` is being resumed, **however** , `gv1` has not reached a `yield` statement since it was last resumed. Ergo, it is still running, which is why it would also throw.
Essentially, the difference could be summarized like this:
* greenlets **share** an inherent connection with each other: `.switch()` pauses the currently executing greenlet and will resume however.
* generators, on the other hand, are completely **independent** from each other. There is no shared context in which generators are executed.
* `yield` will "pause" a generator
* `next()`/ `send()` will resume a paused generator, invoking them on running generators will result in an exception.
Why are you accessing `gv2` (which represents one _particular_ instance of
`test2`) at all? The generator `test2()` should be self-contained and not make
any assumptions about how it is being used. What if you decide, that you want
to invoke the generator from some other scope? It doesn't make any sense to
send values to yourself anyway: You already have them.
|
ImportError: No module named observers after installed watchdog
Question: Im trying to run [official watchdog simple
example](http://packages.python.org/watchdog/quickstart.html#a-simple-example)
after installing the `watchdog` module using pip: `pip install watchdog`, and
i get an error:
from watchdog.observers import Observer
ImportError: No module named observers
Can someone please help me?
Answer: I figured the cause for the ImportError issue. My module name was the same as
the module I was trying to import. Renaming my module to something else other
than watchdog or observers resolved this issue. Thanks all for your help!
damn "Answer you question" button works only in firefox, not in chrome.
|
python subprocess set shell var. and then run command - how?
Question: I need to do this:
$ export PYRO_HMAC_KEY=123
$ python -m Pyro4.naming
So, i found that the second one is possible to do with
subprocess.Popen(['python','-m','Pyro4.naming'])
but how export shell variable before that?
Answer: To update the existing environment...
import os, subprocess
d = dict(os.environ) # Make a copy of the current environment
d['PYRO_HMAC_KEY'] = '123'
subprocess.Popen(['python', '-m', 'Pyro4.naming'], env=d)
|
Select all text in a textbox Selenium RC using Ctrl + A
Question: I am trying to select all the text in a textbox in order to clear the textbox.
I am using Ctrl+A to do this using the following Python 2.7 code on Selenium
RC standalone 2.20.0.jar Server on Windows 7 firefox:
from selenium import selenium
s = selenium('remote-machine-ip', 4444, '*chrome', 'http://my-website-with-textbox')
locator = 'mylocator-of-textbox'
s.open()
s.type(locator, 'mytext')
s.focus(locator)
s.control_key_down()
s.key_down(locator, "A")
s.key_press(locator, "A")
s.key_up(locator, "A")
s.control_key_up()
# Nothing happens here... I cannot see the text getting selected...
# Nothing gets cleared here except the last char
s.key_down(locator, chr(8)) # Pressing backspace
s.key_press(locator, chr(8))
s.key_up(locator, chr(8))
Any help? Thanks, Amit
Answer: I'm using clear() in WebDriver without any hassle...
el = self.selenium.find_element_by_name(name)
el.clear()
|
undefined symbol: PyExc_ImportError when embedding Python in C
Question: I'm developing a C shared library that makes a call to a python script. When I
run the application I get this error:
Traceback (most recent call last):
File "/home/ubuntu/galaxy-es/lib/galaxy/earthsystem/gridftp_security/gridftp_acl_plugin.py", line 2, in <module>
import galaxy.eggs
File "/home/ubuntu/galaxy-es/lib/galaxy/eggs/__init__.py", line 5, in <module>
import os, sys, shutil, glob, urllib, urllib2, ConfigParser, HTMLParser, zipimport, zipfile
File "/usr/lib/python2.7/zipfile.py", line 6, in <module>
import io
File "/usr/lib/python2.7/io.py", line 60, in <module>
import _io
ImportError: /usr/lib/python2.7/lib-dynload/_io.so: undefined symbol: PyExc_ImportError
If I try to import the module io from console works fine instead:
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import galaxy.eggs
>>>
During the compilation of library I've used this compiler option as suggest
here : [Embedding python in C, undefined symbol:
PyExc_ImportError](http://stackoverflow.com/questions/4767057/embedding-
python-in-c-undefined-symbol-pyexc-importerror) In addition I've added also
the compiler options obtained from python-config
--includes|--libs|--cflags|--ldflags
Here you can find the log of makefile of library
<http://pastebin.com/348rhBjM>
Thanks a lot, any help will be apreciated.
Answer: I've found the solution. Maybe can be useful for someone else. It's a bug of
python as written here <http://mail.python.org/pipermail/new-bugs-
announce/2008-November/003322.html> I've used the solution posted here
<http://www.cilogon.org/gsi-c-authz>
|
How include static files to setuptools - python package
Question: It's impossible to include static files! I tried everything that I've found in
tutorials and the documentation, but all in vain...
I want to include the ./static/data.txt, there is my code:
# setup.py
import os,glob
from setuptools import setup,find_packages
setup(
name = "PotatoProject",
version = "0.1.1",
author = "Master Splinter",
author_email = "[email protected]",
description = ("The potatoproject!"),
url = 'http://www.google.com',
license = "BSD",
# adding packages
packages=find_packages('src'),
package_dir = {'':'src'},
# trying to add files...
include_package_data = True,
package_data = {
'': ['*.txt'],
'': ['static/*.txt'],
'static': ['*.txt'],
},
scripts=['src/startPotato'],
classifiers=[
"Development Status :: 3 - Alpha",
"Topic :: Utilities",
"License :: OSI Approved :: BSD License",
],
)
the file system:
.
├── setup.py
└── src
├── distutils_setup.py
├── Potato
│ ├── __init__.py
│ ├── potatoData.txt
│ └── printer.py
├── startPotato
├── static
│ └── data.txt
└── Tomato
├── big.py
└── __init__.py
the output when running: **$ python setup.py sdist**
running sdist
running egg_info
creating src/PotatoProject.egg-info
writing src/PotatoProject.egg-info/PKG-INFO
writing top-level names to src/PotatoProject.egg-info/top_level.txt
writing dependency_links to src/PotatoProject.egg-info/dependency_links.txt
writing manifest file 'src/PotatoProject.egg-info/SOURCES.txt'
reading manifest file 'src/PotatoProject.egg-info/SOURCES.txt'
writing manifest file 'src/PotatoProject.egg-info/SOURCES.txt'
warning: sdist: standard file not found: should have one of README, README.txt
creating PotatoProject-0.1.1
creating PotatoProject-0.1.1/src
creating PotatoProject-0.1.1/src/Potato
creating PotatoProject-0.1.1/src/PotatoProject.egg-info
creating PotatoProject-0.1.1/src/Tomato
making hard links in PotatoProject-0.1.1...
hard linking setup.py -> PotatoProject-0.1.1
hard linking src/startPotato -> PotatoProject-0.1.1/src
hard linking src/Potato/__init__.py -> PotatoProject-0.1.1/src/Potato
hard linking src/Potato/printer.py -> PotatoProject-0.1.1/src/Potato
hard linking src/PotatoProject.egg-info/PKG-INFO -> PotatoProject-0.1.1/src/PotatoProject.egg-info
hard linking src/PotatoProject.egg-info/SOURCES.txt -> PotatoProject-0.1.1/src/PotatoProject.egg-info
hard linking src/PotatoProject.egg-info/dependency_links.txt -> PotatoProject-0.1.1/src/PotatoProject.egg-info
hard linking src/PotatoProject.egg-info/top_level.txt -> PotatoProject-0.1.1/src/PotatoProject.egg-info
hard linking src/Tomato/__init__.py -> PotatoProject-0.1.1/src/Tomato
hard linking src/Tomato/big.py -> PotatoProject-0.1.1/src/Tomato
Writing PotatoProject-0.1.1/setup.cfg
creating dist
Creating tar archive
removing 'PotatoProject-0.1.1' (and everything under it)
and no txt added! No static/data.txt nor Potato/potatoData.txt...
What am I missing?! Thanks!
Answer: Just added a `MANIFEST.in` in the same directory of `setup.py`, that looks
like this:
include src/static/*
include src/Potato/*.txt
and It worked (:
I do not know if this is the best way out, looks like that the `setup.py`
should do this by itself, but worked anyway...
|
Spline Interpolation with Python
Question: I wrote the following code to perform a spline interpolation:
import numpy as np
import scipy as sp
x1 = [1., 0.88, 0.67, 0.50, 0.35, 0.27, 0.18, 0.11, 0.08, 0.04, 0.04, 0.02]
y1 = [0., 13.99, 27.99, 41.98, 55.98, 69.97, 83.97, 97.97, 111.96, 125.96, 139.95, 153.95]
x = np.array(x1)
y = np.array(y1)
new_length = 25
new_x = np.linspace(x.min(), x.max(), new_length)
new_y = sp.interpolate.interp1d(x, y, kind='cubic')(new_x)
but I am getting:
ValueError: A value in x_new is below the interpolation range.
in `interpolate.py`
Any help would be appreciated.
Answer: From the [scipy documentation on
scipy.interpolate.interp1d](http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interp1d.html):
> scipy.interpolate.interp1d(x, y, kind='linear', axis=-1, copy=True,
> bounds_error=True, fill_value=np.nan)
>
> x : array_like. A 1-D array of monotonically increasing real values.
>
> ...
The problem is that the x values are not [monotonically
increasing](http://planetmath.org/MonotonicallyIncreasing.html). In fact they
are monotonically decreasing. Let me know if this works and if its still the
computation you are looking for.:
import numpy as np
import scipy as sp
from scipy.interpolate import interp1d
x1 = sorted([1., 0.88, 0.67, 0.50, 0.35, 0.27, 0.18, 0.11, 0.08, 0.04, 0.04, 0.02])
y1 = [0., 13.99, 27.99, 41.98, 55.98, 69.97, 83.97, 97.97, 111.96, 125.96, 139.95, 153.95]
new_length = 25
new_x = np.linspace(x.min(), x.max(), new_length)
new_y = sp.interpolate.interp1d(x, y, kind='cubic')(new_x)
|
python cross platform apps
Question: I'm trying to make an app in CPython that should work on both linux and
windows. I'm using the webkit library, witch works fine on linux (Ubuntu
12.04), but I can't get it to work on Windows.
I know that I can compile my app into a Windows executable _(.exe)_ with
`py2exe`, but to do that it must work on my Windows machine.
The question is: Is there any way I can package my app under linux, so it will
have it's dependencies (webkit) bundled with it, so it will work under
Windows? Or is there any way to make a windows executable that doesn't need
any dependencies from a python file, under linux?
Thank you!
EDIT: Here is my code for the test app:
import gtk
import webkit
class Base:
def __init__(self):
self.builder = gtk.Builder()
self.builder.add_from_file("youtubeWindow.ui")
self.main_window = self.builder.get_object("main_window")
self.scrl_window = self.builder.get_object("scrl_window")
self.webview = webkit.WebView()
self.scrl_window.add(self.webview)
self.webview.show()
self.webview.open("http://youtu.be/o-akcEzQ6Y8")
self.main_window.show()
def main(self):
gtk.main()
print __name__
if __name__ == "__main__":
base = Base()
base.main()
Answer: Ok, so i couldn't get webkit to work on windows with GTK, but i found out that
Qt provides an integrated WebKit module, so I donwloaded PySide (the Qt
wrapper for python) and I tested it with this script:
import sys
from PySide import QtCore
from PySide import QtGui
from PySide import QtWebKit
class MainWindow (QtGui.QWidget):
def __init__(self):
super(MainWindow, self).__init__()
self.setGeometry(300,300,800,600)
self.setWindowTitle('QtPlayer')
web = QtWebKit.QWebView(self)
web.settings().setAttribute(QtWebKit.QWebSettings.PluginsEnabled, True)
web.load(QtCore.QUrl("http://youtu.be/Dys1_TuUmI4"))
web.show()
self.show()
def main():
app = QtGui.QApplication(sys.argv)
win = MainWindow()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Also i used _GUI2EXE_ and *cx_Freeze* to package it into an .exe windows app.
(Don't forget to include the modules _atexit,PySide.QtNetwork_ , more details
[here](http://qt-project.org/wiki/Packaging_PySide_applications_on_Windows))
A cool guide on Qt-Webkit can be found
[here](http://www.rkblog.rk.edu.pl/w/p/webkit-pyqt-rendering-web-pages/) (It
usese PyQt, but it's compatible with Pyside)
Also a Pyside tutorial [here](http://zetcode.com/gui/pysidetutorial/)
|
Use opencv stitcher from python
Question: OpenCV can be used with the pythonbindings and it works quite well. However I
was wondering (hoping really) whether it is possible to use [OpenCv's
stitcher](http://docs.opencv.org/modules/stitching/doc/stitching.html) in
python as well. I've tried several things but wasn't able to get it to work.
If it is at all possible I probably need to do an extra import but I can't
figure it out and google doesn't give me the answer either. Hope there's a
opencv-python guru among you who can help me out.
Answer: Okay, so, I figured it out finally. So far I've only ported the stitch method
with two arguments, ask me if you have trouble exposing whatever else you
might need.
The easiest way to build it is by compiling everything in a position-
independent way (-fPIC option for gcc) into a dynamic library, whilst linking
opencv_core and opencv_stitching libraries. You'll have to also add the
include directory for whatever version of python you're building against, so
it can find the correct Python.h header.
If you build correctly, you'll be able to use the compiled library the same
way as you would use a python module.
Unfortunately, since they don't provide access to the constructor, I've had to
settle for making a global instance of the thing. If there's another elegant
way, I'm all ears (eyes). This means whenever you call the .Stitcher()
constructor it will return the same instance (there's a separate one that
tries to use GPU during construction, use .Stitcher(True) for that).
Here's my pythonPort.h file:
/*
* File: pythonPort.h
* Author: algomorph
*
* Created on December 5, 2012, 10:18 AM
*/
#ifndef PYTHONPORT_H
#define PYTHONPORT_H
#define MODULESTR "mycv"
#include "Python.h"
#include "numpy/ndarrayobject.h"
#include <opencv2/core/core.hpp>
#include <opencv2/stitching/stitcher.hpp>
/*
//include your own custom extensions here
#include "savgol.h"
#include "filters.hpp"
*/
#include "pythonPortAux.h"
#endif
MODULESTR should be whatever you want to name your module. I've kept it the
same as the name of the library it compiles.
You'll have to copy whatever opencv_to and opencv_from routines you need from
the cv2.cpp file and put into something like my pythonPortAux.h. Mine has lots
of routines from there, you can find it [at this
link](http://algomorph.com/storage/pythonPortAux.h). MKTYPE2 macro is also
there.
The rest is here in the pythonPort.cpp file below (I have other things there,
this is just the Stitcher-relevant portion):
#include "pythonPort.h"
struct pycvex_Stitcher_t
{
PyObject_HEAD
Ptr<cv::Stitcher> v;
};
static PyTypeObject pycvex_Stitcher_Type =
{
PyObject_HEAD_INIT(&PyType_Type)
0,
MODULESTR".Stitcher",
sizeof(pycvex_Stitcher_t),
};
static void pycvex_Stitcher_dealloc(PyObject* self)
{
//((pycvex_Stitcher_t*)self)->v.release();
PyObject_Del(self);
}
static PyObject* pyopencv_from(const Ptr<cv::Stitcher>& r)
{
pycvex_Stitcher_t *m = PyObject_NEW(pycvex_Stitcher_t, &pycvex_Stitcher_Type);
new (&(m->v)) Ptr<cv::Stitcher>(); // init Ptr with placement new
m->v = r;
return (PyObject*)m;
}
static bool pyopencv_to(PyObject* src, Ptr<cv::Stitcher>& dst, const char* name="<unknown>")
{
if( src == NULL || src == Py_None )
return true;
if(!PyObject_TypeCheck(src, &pycvex_Stitcher_Type))
{
failmsg("Expected cv::Stitcher for argument '%s'", name);
return false;
}
dst = ((pycvex_Stitcher_t*)src)->v;
return true;
}
static PyObject* pycvex_Stitcher_repr(PyObject* self)
{
char str[1000];
sprintf(str, "<Stitcher %p>", self);
return PyString_FromString(str);
}
Stitcher gStitcher = cv::Stitcher::createDefault(false);
Stitcher gStitcherGPU = cv::Stitcher::createDefault(true);
static PyObject* pycvex_Stitcher_Stitcher(PyObject* , PyObject* args, PyObject* kw)
{
PyErr_Clear();
{
pycvex_Stitcher_t* self = 0;
bool try_use_gpu = false;
const char* keywords[] = { "img", "pt1", "pt2","connectivity","leftToRight", NULL };
if (PyArg_ParseTupleAndKeywords(args, kw, "|b:Stitcher",
(char**) keywords, &try_use_gpu)){
self = PyObject_NEW(pycvex_Stitcher_t, &pycvex_Stitcher_Type);
if (self)
ERRWRAP2(
if(try_use_gpu)
self->v = &gStitcherGPU;
else
self->v = &gStitcher;
);
return (PyObject*) self;
}
}
return NULL;
}
static PyGetSetDef pycvex_Stitcher_getseters[] =
{
{NULL} /* Sentinel */
};
static PyObject* pycvex_Stitcher_stitch(PyObject* self, PyObject* args, PyObject* kw){
if(!PyObject_TypeCheck(self, &pycvex_Stitcher_Type))
return failmsgp("Incorrect type of self (must be 'Stitcher' or its derivative)");
Stitcher* _self_ = ((pycvex_Stitcher_t*)self)->v;
//Stitcher::Status status;
int status;
PyObject* pyobj_images = NULL;
vector<Mat> images = vector<Mat>();
Mat pano;
const char* keywords[] = { "images", NULL };
if( PyArg_ParseTupleAndKeywords(args, kw, "O:Stitcher.stitch", (char**)keywords, &pyobj_images) &&
pyopencv_to(pyobj_images, images, ArgInfo("images", false)))
{
ERRWRAP2( status = (int)_self_->stitch(images, pano));
return Py_BuildValue("(NN)", pyopencv_from(status), pyopencv_from(pano));
}
return NULL;
}
static PyMethodDef pycvex_Stitcher_methods[] =
{
{"stitch", (PyCFunction)pycvex_Stitcher_stitch, METH_KEYWORDS, "stitch(image) -> status, pano"},
{NULL, NULL}
};
static void pycvex_Stitcher_specials(void)
{
pycvex_Stitcher_Type.tp_base = NULL;
pycvex_Stitcher_Type.tp_dealloc = pycvex_Stitcher_dealloc;
pycvex_Stitcher_Type.tp_repr = pycvex_Stitcher_repr;
pycvex_Stitcher_Type.tp_getset = pycvex_Stitcher_getseters;
pycvex_Stitcher_Type.tp_methods = pycvex_Stitcher_methods;
}
static PyMethodDef methods[] = {
{"Stitcher",(PyCFunction)pycvex_Stitcher_Stitcher, METH_KEYWORDS, "Stitcher([tryUseGpu=False]) -> <Stitcher object>"},
{NULL, NULL}
};
extern "C"{
#if defined WIN32 || defined _WIN32
__declspec(dllexport)
#endif
void initcvex()
{
MKTYPE2(Stitcher);
import_array();
PyObject* m = Py_InitModule(MODULESTR, methods);
PyObject* d = PyModule_GetDict(m);
//PyDict_SetItemString(d, "__version__", PyString_FromString(CV_VERSION))
opencv_error = PyErr_NewException((char*)MODULESTR".error", NULL, NULL);
PyDict_SetItemString(d, "error", opencv_error);
}
}
|
How do I render jinja2 output to a file in Python instead of a Browser
Question: I have a jinja2 template (.html file) that I want to render (replace the
tokens with values from my py file). Instead of sending the rendered result to
a browser, however, I want to write it to a new .html file. I would imagine
the solution would also be similar for a django template.
How can I do this?
Answer: How about something like this?
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader('templates'))
template = env.get_template('test.html')
output_from_parsed_template = template.render(foo='Hello World!')
print output_from_parsed_template
# to save the results
with open("my_new_file.html", "wb") as fh:
fh.write(output_from_parsed_template)
**test.html**
<h1>{{ foo }}</h1>
**output**
<h1>Hello World!</h1>
If you are using a framework, such as Flask, then you could do this at the
bottom of your view, before you return.
output_from_parsed_template = render_template('test.html', foo="Hello World!")
with open("some_new_file.html", "wb") as f:
f.write(output_from_parsed_template)
return output_from_parsed_template
|
Reverse AND inverse python3.x OrderedDict efficiently
Question: After many attempts to create one-liners that will invert key-value pairs, and
reverse an OrderedDict, I have this:
from collections import OrderedDict as OD
attributes=OD((('brand','asus'), ('os','linux'), ('processor','i5'), ('memory','4G')))
print(attributes)
reversed_attributes=OD(reversed(list(attributes.items())))
print(reversed_attributes)
inverted_attributes=OD([reversed(item) for item in attributes.items()])
print(inverted_attributes)
''' Prints
OrderedDict([('brand', 'asus'), ('os', 'linux'), ('processor', 'i5'), ('memory', '4G')])
OrderedDict([('memory', '4G'), ('processor', 'i5'), ('os', 'linux'), ('brand', 'asus')])
OrderedDict([('asus', 'brand'), ('linux', 'os'), ('i5', 'processor'), ('4G', 'memory')])
'''
This works, but is it inefficient? By using reversed(list(a.items())) is this
creating a lot of overhead, and so is not pythonic? Same for the
inverted_attributes.
The point was to avoid for loops and so on, but will this decrease performance
as we scale up?
Answer: interesting I also came up with other ways.
>>> from collections import OrderedDict as OD
>>> attributes = OD((('brand','asus'), ('os','linux'), ('processor','i5'), ('memory','4G')))
if you want to reverse you can do this
>>> reverse = OD(attributes.items()[::-1])
or a more pythonic approach:
>>> reverse = OD(reversed(attributes.items()))
note you don't need to create `list` items is already a list, and while
`reversed` is a generator `OrderedDict` will simply iterate through to it
generate the new dict.
both generating similar timings.
$ python -m timeit "from collections import OrderedDict as OD; attributes = OD((('brand','asus'), ('os','linux'), ('processor','i5'), ('memory','4G')))" "reverse = OD(attributes.items()[::-1])"
10000 loops, best of 3: 54.8 usec per loop
$ python -m timeit "from collections import OrderedDict as OD; attributes = OD((('brand','asus'), ('os','linux'), ('processor','i5'), ('memory','4G')))" "reverse = OD(reversed(attributes.items()))"
10000 loops, best of 3: 54.4 usec per loop
$ python -m timeit "from collections import OrderedDict as OD; attributes = OD((('brand','asus'), ('os','linux'), ('processor','i5'), ('memory','4G')))" "reversed_attributes=OD(reversed(list(attributes.items())))"
10000 loops, best of 3: 54.4 usec per loop
if you want to invert:
>>> invert = OD(zip(*zip(*attributes.items())[::-1]))
or more pythonic:
>>> invert = OD(map(reversed, attributes.items()))
again both generating similar timings.
$ python -m timeit "from collections import OrderedDict as OD; attributes = OD((('brand','asus'), ('os','linux'), ('processor','i5'), ('memory','4G')));" "invert = OD(zip(*zip(*attributes.items())[::-1]))"
10000 loops, best of 3: 57 usec per loop
$ python -m timeit "from collections import OrderedDict as OD; attributes = OD((('brand','asus'), ('os','linux'), ('processor','i5'), ('memory','4G')));" "invert = OD(map(reversed, attributes.items()))"
10000 loops, best of 3: 56.8 usec per loop
$ python -m timeit "from collections import OrderedDict as OD; attributes = OD((('brand','asus'), ('os','linux'), ('processor','i5'), ('memory','4G')));" "inverted_attributes=OD([reversed(item) for item in attributes.items()])"
10000 loops, best of 3: 55.8 usec per loop
you can use the two methods in conjunction to both reverse and invert.
> This works, but is it inefficient? By using reversed(list(a.items())) is
> this creating a lot of overhead, and so is not pythonic? Same for the
> inverted_attributes.
something can generate a lot of overhead and be pythonic on the other hand
something can very very efficient and not be very pythonic, the term has being
a bit abused, but thats just my opinion
exert from wikipedia:
> A common neologism in the Python community is pythonic, which can have a
> wide range of meanings related to program style. To say that code is
> pythonic is to say that it uses Python idioms well, that it is natural or
> shows fluency in the language. Likewise, to say of an interface or language
> feature that it is pythonic is to say that it works well with Python idioms,
> that its use meshes well with the rest of the language.
>
> In contrast, a mark of unpythonic code is that it attempts to write C++ (or
> Lisp, Perl, or Java) code in Python—that is, provides a rough transcription
> rather than an idiomatic translation of forms from another language. The
> concept of pythonicity is tightly bound to Python's minimalist philosophy of
> readability and avoiding the "there's more than one way to do it" approach.
> Unreadable code or incomprehensible idioms are unpythonic.
as for:
> but will this decrease performance as we scale up?
This hard to say, without knowing why you are making such transforms, or
whether or not their an integral part of your system, fundamentally at a bare
minimun they are adding linear time/space overhead which may or may not be
good, if the number of entries remains small, then no problem but if at every
request, assuming this happening at a web server, your are doing this on a
large dicts, this can be quite harsh, and may require a redesign to avoid
this.
|
traceroute multiple hosts in python
Question: I'm writing a script to do traceroute for a list of hostnames. what I'm trying
to do is reading hostname from a text file, line by line, performing tracert
for each host using subprocess and writing the result in another file. here is
my code
# import subprocess
import subprocess
# Prepare host and results file
Open_host = open('c:/OSN/host.txt','r')
Write_results = open('c:/OSN/TracerouteResults.txt','a')
host = Open_host.readline()
# while loop: excuse trace route for each host
while host:
print host
# execute Traceroute process and pipe the result to a string
Traceroute = subprocess.Popen(["tracert", '-w', '100', host],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while True:
hop = Traceroute.stdout.readline()
if not hop: break
print '-->',hop
Write_results.write( hop )
Traceroute.wait()
# Reading a new host
host = Open_host.readline()
# close files
Open_host.close()
Write_results.close()
My problem is that this script works only for a host file with 1 hostname (or
1 line). when host file contain multiple line, for example: hostname1.com
hostname2.com hostname3.com It will give me this notice for the 1st two line
"Unable to resolve target system name hostname1.com"
"Unable to resolve target system name hostname2.com"
And only give tracert result for the last line.
I'm not sure what's wrong with my script, please help me to fix it. Thanks a
lot.
Steven
Answer: Try `host = host.strip()` before making the call; tracert seems to be choking
on the newlines.
|
Node frequency using networkx
Question: I’m just learning python, so I appreciate the help. I have a two-column data
set, the first is a unique id, and the second is a string of items. I’m using
networkX to make a tree from the data (see below). I need to know the item
frequency per level. For example, for the path in A (1,2,3,4), the counts for
each node should be 1:4, 2:2, 3:2, and 4:2. How do I get the node count?
My data looks like this:
A 1, 2, 3, 4
B 1, 2, 1, 4
C 1, 3, 4, 3
D 1, 4, 3, 2
The code I have so far is the following:
#create graph
G = nx.MultiGraph()
#read in strings from csv
testfile = 'C:…file.txt'
with open(testfile, "r") as f:
line = f.readline
f = (i for i in f if '\t' in i.rstrip())
for line in f:
customerID, path = line.rstrip().split("\t")
path2 = path.rstrip("\\").rstrip("}").split(",")
pathInt = list()
for x in path2:
if x is not None:
newx = int(x)
pathInt.append(newx)
print(pathInt)
varlength = len(pathInt)
pathTuple = tuple(pathInt)
G.add_path([pathTuple[:i+1] for i in range(0, varlength)])
nx.draw(G)
plt.show() # display
Answer: Firstly you can make the conversion from you string list to a int tuple a
little bit more concise:
pathTuple = tuple(int(x) for x in path2 )
G.add_path([path[:i+1] for i in range(0, len(path))])
For storing the count data I would use a defaultdict in a defaultdict,
basically a data structure that allows double indexing and then defaults to 0.
import collections
counts = collections.defaultdict(lambda:collections.defaultdict(lambda:0))
This can be used for this kind of access: `counts[level][node]` which we then
can use to count how often each node appears on each level by looking at its
position in the path.
After this your code would look like this:
#create graph
G = nx.MultiGraph()
#read in strings from csv
testfile = 'C:…file.txt'
with open(testfile, "r") as f:
line = f.readline
f = (i for i in f if '\t' in i.rstrip())
for line in f:
customerID, path = line.rstrip().split("\t")
path2 = path.rstrip("\\").rstrip("}").split(",")
pathTuple = tuple(int(x) for x in path2 )
G.add_path([pathTuple[:i+1] for i in range(0, len(pathTuple))])
for level, node in enumerate(path):
counts[level][node]+=1
And you can then do this:
level = 0
node = 1
print 'Node', node, 'appears', counts[level][node], 'times on level', level
>>> Node 1 appears 4 times on level 0
|
Python object extension which gets a list in constructor never passes the creation step (SIGSEV), why?
Question: I've been fighting for a lot of time with an error and I've run short of ideas
on what's happening and why it doesn't work.
First of all, I'm trying to create a new object type for Python through a C
extension. This object is created using a list, numpy array etc... But I
cannot even make this part work.
The actual minimal code that fails is:
#include <python2.7/Python.h>
#include <python2.7/structmember.h>
#include <numpy/arrayobject.h>
#include "../python/NumpyHelperFuncs.h"
#include <cmath>
#include <algorithm>
#include <iostream>
using namespace std;
typedef struct {
PyObject_HEAD
} CondensedMatrix;
static void condensedMatrix_dealloc(CondensedMatrix* self){
self->ob_type->tp_free((PyObject*)self);
}
static PyObject* condensedMatrix_new(PyTypeObject *type, PyObject *args, PyObject *kwds){
CondensedMatrix *self;
self = (CondensedMatrix*) type->tp_alloc(type, 0);
return (PyObject *) self;
}
static int condensedMatrix_init(CondensedMatrix *self, PyObject *args, PyObject *kwds){
PyObject* input;
PyArrayObject* rmsd_numpy_array;
cout<<"Minimum class creation"<<flush<<endl;
if (! PyArg_ParseTuple(args, "O",&input)){
PyErr_SetString(PyExc_RuntimeError, "Error parsing parameters.");
return -1;
}
rmsd_numpy_array = (PyArrayObject *) PyArray_ContiguousFromObject(input, PyArray_FLOAT, 1, 1);
Py_DECREF(rmsd_numpy_array);
return 0;
}
static PyMemberDef condensedMatrix_members[] = {
{NULL} /* Sentinel */
};
static PyMethodDef condensedMatrix_methods[] = {
{NULL} /* Sentinel */
};
static PyTypeObject CondensedMatrixType = {
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"condensedMatrix.CondensedMatrixType", /*tp_name*/
sizeof(CondensedMatrix), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)condensedMatrix_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT| Py_TPFLAGS_BASETYPE , /*tp_flags*/
"Condensed matrix as in pdist", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
condensedMatrix_methods, /* tp_methods */
condensedMatrix_members, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)condensedMatrix_init, /* tp_init */
0, /* tp_alloc */
condensedMatrix_new, /* tp_new */
};
#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */
#define PyMODINIT_FUNC void
#endif
PyMODINIT_FUNC initcondensedMatrix(void){
PyObject* module;
if (PyType_Ready(&CondensedMatrixType) < 0)
return;
module = Py_InitModule3("condensedMatrix", NULL,"Fast Access Condensed Matrix");
if (module == NULL)
return;
Py_INCREF(&CondensedMatrixType);
PyModule_AddObject(module, "CondensedMatrix", (PyObject*) &CondensedMatrixType);
}
This code has been written following the tips (and copy/pasting):
[http://docs.python.org/extending/newtypes.html](http://docs.python.org/extending/newtypes.html#id2)
I've tested the Noddy code and it works, but if I add a fourth parameter to
get a list, it also exits with a sigsev.
I compile the code above with:
gcc -pthread -fno-strict-aliasing -fmessage-length=0 -O2 -Wall -D_FORTIFY_SOURCE=2 -fstack-protector -funwind-tables -fasynchronous-unwind-tables -fPIC -c matrix.cpp
g++ -pthread -shared matrix/matrix.o -lpython2.7 -o condensedMatrix.so -fopenmp
And I use it with: if **name** == '**main** ': data_con = [3,4,5,6] matrix =
CondensedMatrix(data_con)
I've also read [PyArg_ParseTuple SegFaults in
CApi](http://stackoverflow.com/questions/7760658/pyarg-parsetuple-segfaults-
in-capi)
Does anyone know why it does a segfault after pyarg_parsetuple?
Ubuntu 12.04 , gcc 4.6.3 , Python 2.7.3
Thanks!
Answer: So, it looks like the error was indeed very easy to solve as the only needed
thing was a missing 'import_array();' sentence in the init function:
PyMODINIT_FUNC initcondensedMatrix(void){
PyObject* module;
if (PyType_Ready(&CondensedMatrixType) < 0)
return;
module = Py_InitModule3("condensedMatrix", NULL,"Fast Access Condensed Matrix");
if (module == NULL)
return;
Py_INCREF(&CondensedMatrixType);
PyModule_AddObject(module, "CondensedMatrix", (PyObject*) &CondensedMatrixType);
import_array();
}
And that was all ...
|
Filter xml data in Python
Question: Please help, Python beginner,
after getting all the data from xml, **data_list =
xmlTree.findall('.//data')** e.g here I get 10 rows Now, I need to keep only a
few rows for which attribute 'name' values match with elements of another list
(inputID) with three IDs inside. e.g. remains only 3 rows whose name attribute
match with the list elements
Thank you.
Answer: You can use a for loop to iterate over each element, then decide if each
element should be removed. I used the Python doc [ElementTree XML
API](http://docs.python.org/library/xml.etree.elementtree.html) for reference.
from xml.etree.ElementTree import ElementTree
tree = ElementTree()
# Test input
tree.parse("sample.xml")
# List containing names you want to keep
inputID = ['name1', 'name2', 'name3']
for node in tree.findall('.//data'):
# Remove node if the name attribute value is not in inputID
if not node.attrib.get('name') in inputID:
tree.getroot().remove(node)
# Do what you want with the modified xml
tree.write('sample_out.xml')
|
Importing module from package
Question: I am trying to import a module from a package set up as per instructions from
[Modules Python Tutorial](http://docs.python.org/tutorial/modules.html). My
directory tree is:
$ pwd
/home/me/lib/python/pygplib
$ ls *
__init__.py
atcf:
atcf.py __init__.py
I am able to import `pygplib` but `pygplib.atcf` does not seem to exist:
In [1]: import pygplib
In [2]: dir(pygplib)
Out[2]: ['__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']
What am I doing wrong? All my `__init__.py` files are blank. Thank you.
Answer: Submodules don't get imported when you import the top package, and thus don't
appear in `dir`. Instead, do
from pygplib import atcf
Or
from pygplib.atcf import atcf
|
Python OOP --action() function
Question: I'm new to Python OOP and trying to create a OOP program to manage a library.
This code is from a book.
This code is working as expected but I need to understand how the `action()`
calls the corresponding function when I select a particular option, e.g.: when
I select `1` the `show_notes` function is called even though we don't call it.
`Menu.py`
import sys
from notebook import Notebook, Note
class Menu:
'''Display a menu and respond to choices when run.'''
def __init__(self):
self.notebook = Notebook()
self.choices = {
"1": self.show_notes,
"2": self.search_notes,
"3": self.add_note,
"4": self.modify_note,
"5": self.quit
}
def display_menu(self):
print("""
Notebook Menu
1. Show all Notes
2. Search Notes
3. Add Note
4. Modify Note
5. Quit
""")
def run(self):
'''Display the menu and respond to choices.'''
while True:
self.display_menu()
choice = input("Enter an option: ")
action = self.choices.get(choice)
if action:
action()
else:
print("{0} is not a valid choice".format(choice))
def show_notes(self, notes=None):
if not notes:
notes = self.notebook.notes
for note in notes:
print("{0}: {1}\n{2}".format(
note.id, note.tags, note.memo))
def search_notes(self):
filter = input("Search for: ")
notes = self.notebook.search(filter)
self.show_notes(notes)
def add_note(self):
memo = input("Enter a memo: ")
self.notebook.new_note(memo)
print("Your note has been added.")
def modify_note(self):
id = input("Enter a note id: ")
memo = input("Enter a memo: ")
tags = input("Enter tags: ")
if memo:
self.notebook.modify_memo(id, memo)
if tags:
self.notebook.modify_tags(id, tags)
def quit(self):
print("Thank you for using your notebook today.")
sys.exit(0)
if __name__ == "__main__":
Menu().run()
`notebook.py`
import datetime
# Store the next available id for all new notes
last_id = 0
class Note:
'''Represent a note in the notebook. Match against a
string in searches and store tags for each note.'''
def __init__(self, memo, tags=''):
'''initialize a note with memo and optional
space-separated tags. Automatically set the note's
creation date and a unique id'''
self.memo = memo
self.tags = tags
self.creation_date = datetime.date.today()
global last_id
last_id += 1
self.id = last_id
def match(self, filter):
'''Determine if this note matches the filter
text. Return True if it matches, False otherwise.
Search is case sensitive and matches both text and
tags.'''
return filter in self.memo or filter in self.tags
class Notebook:
'''Represent a collection of notes that can be tagged,
modified, and searched.'''
def __init__(self):
'''Initialize a notebook with an empty list.'''
self.notes = []
def new_note(self, memo, tags=''):
'''Create a new note and add it to the list.'''
self.notes.append(Note(memo, tags))
def _find_note(self, note_id):
'''Locate the note with the given id.'''
for note in self.notes:
if str(note.id) == str(note_id):
return note
return None
def modify_memo(self, note_id, memo):
'''Find the note with the given id and change its
memo to the given value.'''
note = self._find_note(note_id)
if note:
note.memo = memo
return True
return False
def modify_tags(self, note_id, tags):
'''Find the note with the given id and change its
tags to the given value.'''
note = self._find_note(note_id)
if note:
note.tags = tags
return True
return False
def search(self, filter):
'''Find all notes that match the given filter
string.'''
return [note for note in self.notes if
note.match(filter)]
Answer: Functions and methods are themselves objects. So the dict contains objects
which we then call.
So self.choices is a dictionary with "1", "2", etc as keys. The values are
method objects. When you get the value from the dictionary, you get that
object (called a "callable") and assign it to `action`. Then you call that
object with `action()`.
The key bit of code is this:
self.choices = {
"1": self.show_notes,
"2": self.search_notes,
"3": self.add_note,
"4": self.modify_note,
"5": self.quit
}
`self.choices["1"]` evaluates to the value of `self.show_notes`, which is then
assigned to `action`, which you then call with `action()`.
(As an aside: The menu in the example code is hardcoded, but in fact could be
autogenerated, if the methods had docstrings. `"\n".join("%s: %s" % (key,
action.__doc__) for key, action in sorted(self.choices.iteritems()))` To
properly handle a menu with >=10 items, you'd want to make the keys into
integers, or expand the one-liner.)
|
How Can I Make This Python Script Work With Python 3?
Question: I downloaded this script to help me convert some PNGs. It is however, from
2003 and the first time I tried to run it, it gave me errors for exception
syntax. I managed to fix that and ran it again. Then it gave me errors for the
print syntax. I fixed those as well. Now I have absolutely no idea whats going
on besides the script not working.
The script is:
from struct import *
from zlib import *
import stat
import sys
import os
def getNormalizedPNG(filename):
pngheader = "\x89PNG\r\n\x1a\n"
file = open(filename, "rb")
oldPNG = file.read()
file.close()
if oldPNG[:8] != pngheader:
return None
newPNG = oldPNG[:8]
chunkPos = len(newPNG)
# For each chunk in the PNG file
while chunkPos < len(oldPNG):
# Reading chunk
chunkLength = oldPNG[chunkPos:chunkPos+4]
chunkLength = unpack(">L", chunkLength)[0]
chunkType = oldPNG[chunkPos+4 : chunkPos+8]
chunkData = oldPNG[chunkPos+8:chunkPos+8+chunkLength]
chunkCRC = oldPNG[chunkPos+chunkLength+8:chunkPos+chunkLength+12]
chunkCRC = unpack(">L", chunkCRC)[0]
chunkPos += chunkLength + 12
# Parsing the header chunk
if chunkType == "IHDR":
width = unpack(">L", chunkData[0:4])[0]
height = unpack(">L", chunkData[4:8])[0]
# Parsing the image chunk
if chunkType == "IDAT":
try:
# Uncompressing the image chunk
bufSize = width * height * 4 + height
chunkData = decompress( chunkData, -8, bufSize)
except Exception as e:
# The PNG image is normalized
return None
# Swapping red & blue bytes for each pixel
newdata = ""
for y in xrange(height):
i = len(newdata)
newdata += chunkData[i]
for x in xrange(width):
i = len(newdata)
newdata += chunkData[i+2]
newdata += chunkData[i+1]
newdata += chunkData[i+0]
newdata += chunkData[i+3]
# Compressing the image chunk
chunkData = newdata
chunkData = compress( chunkData )
chunkLength = len( chunkData )
chunkCRC = crc32(chunkType)
chunkCRC = crc32(chunkData, chunkCRC)
chunkCRC = (chunkCRC + 0x100000000) % 0x100000000
# Removing CgBI chunk
if chunkType != "CgBI":
newPNG += pack(">L", chunkLength)
newPNG += chunkType
if chunkLength > 0:
newPNG += chunkData
newPNG += pack(">L", chunkCRC)
# Stopping the PNG file parsing
if chunkType == "IEND":
break
return newPNG
def updatePNG(filename):
data = getNormalizedPNG(filename)
if data != None:
file = open(filename, "wb")
file.write(data)
file.close()
return True
return data
def getFiles(base):
global _dirs
global _pngs
if base == ".":
_dirs = []
_pngs = []
if base in _dirs:
return
files = os.listdir(base)
for file in files:
filepath = os.path.join(base, file)
try:
st = os.lstat(filepath)
except os.error:
continue
if stat.S_ISDIR(st.st_mode):
if not filepath in _dirs:
getFiles(filepath)
_dirs.append( filepath )
elif file[-4:].lower() == ".png":
if not filepath in _pngs:
_pngs.append( filepath )
if base == ".":
return _dirs, _pngs
print ("iPhone PNG Images Normalizer v1.0")
print (" ")
print ("[+] Searching PNG files..."),
dirs, pngs = getFiles(".")
print ("ok")
if len(pngs) == 0:
print (" ")
print ("[!] Alert: There are no PNG files found. Move this python file to the folder that contains the PNG files to normalize.")
exit()
print (" ")
print (" - %d PNG files were found at this folder (and subfolders).") % len(pngs)
print (" ")
while True:
normalize = raw_input("[?] Do you want to normalize all images (Y/N)? ").lower()
if len(normalize) > 0 and (normalize[0] == "y" or normalize[0] == "n"):
break
normalized = 0
if normalize[0] == "y":
for ipng in xrange(len(pngs)):
perc = (float(ipng) / len(pngs)) * 100.0
print ("%.2f%% %s") % (perc, pngs[ipng])
if updatePNG(pngs[ipng]):
normalized += 1
print (" ")
print ("[+] %d PNG files were normalized.") % normalized
Now when I run it in the DOS window, I get this error:
C:\wamp\www\py>ipin.py
iPhone PNG Images Normalizer v1.0
[+] Searching PNG files...
ok
- %d PNG files were found at this folder (and subfolders).
Traceback (most recent call last):
File "C:\wamp\www\py\ipin.py", line 158, in <module>
print (" - %d PNG files were found at this folder (and subfolders).") % len(pngs)
TypeError: unsupported operand type(s) for %: 'NoneType' and 'int'
What do I do?
Answer: You might want to move the `%` operator inside the parenthesis.
print (" - %d PNG files were found at this folder (and subfolders)." % len(pngs))
|
How to overcome "datetime.datetime not JSON serializable" in python?
Question: I have a basic dict as follows:
sample = {}
sample['title'] = "String"
sample['somedate'] = somedatetimehere
When I try to do `jsonify(sample)` I get:
> TypeError: datetime.datetime(2012, 8, 8, 21, 46, 24, 862000) is not JSON
> serializable
What can I do such that my dictionary sample can overcome the error above?
Note: Though it may not be relevant, the dictionaries are generated from the
retrieval of records out of mongodb where when I print out
`str(sample['somedate'])`, the output is `2012-08-08 21:46:24.862000`.
Answer: Building on other answers, a simple solution based on a specific serializer
that just converts datetime.datetime objects to strings.
from datetime import datetime
def json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, datetime):
serial = obj.isoformat()
return serial
raise TypeError ("Type not serializable")
As seen, the code just checks to find out if object is of class
datetime.datetime, and then uses .isoformat() to produce a serialized version
of it, according to ISO 8601 format, YYYY-MM-DDTHH:MM:SS (which is easily
decoded by JavaScript). If more complex serialized representations are sought,
other code could be used instead of str() (see other answers to this question
for examples). The code ends by raising an exception, to deal with the case it
is called with a non-serializable type which is not datetime.
This json_serial function can be used as follows:
from datetime import datetime
from json import dumps
print dumps(datetime.now(), default=json_serial)
The details about how the default parameter to json.dumps works can be found
in [Section Basic Usage of the json module
documentation](http://docs.python.org/2/library/json.html#basic-usage).
|
PSSE/Python import excel values and export bus voltages from PSSE
Question: Could someone please help me with Python. I am trying to run 168 newton
raphson load flow studies for different values for loads and gens. I have
these values set out in an excel spreadsheet and would like to automatically
upload these values into PSSE, run the simulation then export the bus voltage
results to another spreadsheet for all 168 sims in separate columns.
I have the following code but it is showing an error with line 47: def
runstudy(hour, values) SyntaxError: invalid syntax
I am not sure how to rectify this.
Any help would be greatly appreciated
from __future__ import with_statement
from collections import defaultdict
import csv
import psspy
CSV_PQ_FILENAME = 'c:/Users\14088757\Desktop\EP401_Simulation Values_1.1.csv'
OUTPUT_CSV_FILENAME = 'c:/Users\14088757\Desktop\EP401_Simulation Values_1.1.csv'
STUDY_BASECASE = 'c:/Users\14088757\Desktop\EP401_PSSE_URA_20120716_6626.01.sav'
with open(CSV_PQ_FILENAME) as csvfile:
reader = csv.reader(csvfile)
headers = reader.next()
data = list(reader)
# now all the data from that sheet is in 'data'
# the columns are:
# load?, bus num, id, p or q, 6625, 6626, ....
hourly_data = defaultdict(list)
hour_headings = headers[4:]
for row in data:
isload, busnum, _id, porq = row[:4]
hour_values = row[4:]
# group all of the hourly data together in one list.
for hour, value in zip(hour_headings, hour_values):
hourly_data[hour].append(
(int(isload), int(busnum), _id, porq, float(value))
# hourly_data now looks like this:
# { '6626': [
# (1, 104, '1', 'P', 0.33243)
# ...
# ],
# '6627': [ ... ]
# '6628': [ ... ]
#}
# lets run some simulations.
def runstudy(hour, values)
# reload the base case.
psspy.case(STUDY_BASECASE)
# assume CSV has columns as described in the doc string
for isload, bus, _id, porq, value in values:
if isload:
if porq.lower() == 'p':
psspy.load_data_3(bus, _id, realar1=value)
elif porq.lower() == 'q':
psspy.load_data_3(bus, _id, realar2=value)
else:
psspy.machine_data_2(bus, _id, realar1=value)
# solve case after adding all loads / machines.
psspy.fnsl()
# return the bus voltages.
# now to write the new bus voltages to a file.
ierr, (voltages,) = psspy.abusreal(sid=-1, string=["PU"])
ierr, (buses,) = psspy.abusint(sid=-1, string=["NUMBER"])
return buses, voltages
# here we assume the buses will always be the same, no need
# keep storing them. I'll only store the voltages.
all_results = {}
for hour, values in hourly_data.items():
buses, voltages = runstudy(hour, values)
all_results[hour] = voltages
# now write all the results to a csv file
# CSV will have these columns:
# bus number, voltage (pu) 2265, 2267, ...
spreadsheet_results = [['buses'] + buses]
for hour, voltages in all_results.items():
spreadsheet_results.append([hour + ' pu'] + voltages)
# spreadsheet_results now looks like the one we want to write to the CSV.
with open(OUTPUT_CSV_FILENAME, 'wb') as output:
output.writerows(spreadsheet_results)
Answer: Jim,
There is a simple syntax error. I am sure you have noticed it by now. Do this
-
def runstudy(hours, values):
I cannot say much about the rest of the code unless your share your .sav and
.csv files. I would be like to know how it went especially because I am
interested in PSSE. Mail me the files if you need further help.
|
serializing and deserializing lambdas
Question: I would like to serialize on machine A and deserialize on machine B a python
lambda. There are a couple of obvious problems with that:
* the pickle module does not serialize or deserialize code. It only serializes the names of classes/methods/functions
* some of the answers I found with google suggest the use of the low-level marshal module to serialize the func_code attribute of the lambda but they fail to describe how one could reconstruct a function object from the deserialized code object
* marhshal(l.func_code) will not serialize the closure associated with the lambda which leads to the problem of detecting when a given lambda really needs a closure and warning the user that he is trying to serialize a lambda that uses a closure
Hence, my question(s):
* how would one reconstruct a function from the deserialized (demarshaled) code object ?
* how would one detect that a given lambda will not work properly without the associated closure ?
Answer: Surprisingly, checking whether a lambda will work without its associated
closure is actually fairly easy. According to the [data model
documentation](http://docs.python.org/release/2.6.2/reference/datamodel.html),
you can just check the `func_closure` attribute:
>>> def get_lambdas():
... bar = 42
... return (lambda: 1, lambda: bar)
...
>>> no_vars, vars = get_lambdas()
>>> print no_vars.func_closure
None
>>> print vars.func_closure
(<cell at 0x1020d3d70: int object at 0x7fc150413708>,)
>>> print vars.func_closure[0].cell_contents
42
>>>
Then serializing + loading the lambda is fairly straight forward:
>>> import marshal, types
>>> old = lambda: 42
>>> old_code_serialized = marshal.dumps(old.func_code)
>>> new_code = marshal.loads(old_code_serialized)
>>> new = types.FunctionType(new_code, globals())
>>> new()
42
It's worth taking a look at the documentation for the `FunctionType`:
function(code, globals[, name[, argdefs[, closure]]])
Create a function object from a code object and a dictionary.
The optional name string overrides the name from the code object.
The optional argdefs tuple specifies the default argument values.
The optional closure tuple supplies the bindings for free variables.
Notice that you can also supply a closure… Which means you might even be able
to serialize the old function's closure then load it at the other end :)
|
python csv unicode 'ascii' codec can't encode character u'\xf6' in position 1: ordinal not in range(128)
Question: I have copied this script from [python web site][1] This is another question
but now problem with encoding:
import sqlite3
import csv
import codecs
import cStringIO
import sys
class UTF8Recoder:
"""
Iterator that reads an encoded stream and reencodes the input to UTF-8
"""
def __init__(self, f, encoding):
self.reader = codecs.getreader(encoding)(f)
def __iter__(self):
return self
def next(self):
return self.reader.next().encode("utf-8")
class UnicodeReader:
"""
A CSV reader which will iterate over lines in the CSV file "f",
which is encoded in the given encoding.
"""
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
f = UTF8Recoder(f, encoding)
self.reader = csv.reader(f, dialect=dialect, **kwds)
def next(self):
row = self.reader.next()
return [unicode(s, "utf-8") for s in row]
def __iter__(self):
return self
class UnicodeWriter:
"""
A CSV writer which will write rows to CSV file "f",
which is encoded in the given encoding.
"""
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
# Redirect output to a queue
self.queue = cStringIO.StringIO()
self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
self.stream = f
self.encoder = codecs.getincrementalencoder(encoding)()
def writerow(self, row):
self.writer.writerow([s.encode("utf-8") for s in row])
# Fetch UTF-8 output from the queue ...
data = self.queue.getvalue()
data = data.decode("utf-8")
# ... and reencode it into the target encoding
data = self.encoder.encode(data)
# write to the target stream
self.stream.write(data)
# empty queue
self.queue.truncate(0)
def writerows(self, rows):
for row in rows:
self.writerow(row)
This time problem with encoding, when I ran this it gave me this error:
Traceback (most recent call last):
File "makeCSV.py", line 87, in <module>
uW.writerow(d)
File "makeCSV.py", line 54, in writerow
self.writer.writerow([s.encode("utf-8") for s in row])
AttributeError: 'int' object has no attribute 'encode'
Then I converted all integers to string, but this time I got this error:
Traceback (most recent call last):
File "makeCSV.py", line 87, in <module>
uW.writerow(d)
File "makeCSV.py", line 54, in writerow
self.writer.writerow([str(s).encode("utf-8") for s in row])
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 1: ordinal not in range(128)
I have implemented above to deal with unicode characters, but it gives me such
error. What is the problem and how to fix it?
Answer: > Then I converted all integers to string,
You converted both integers _and_ strings to _byte strings_. For strings this
will use the default character encoding which happens to be ASCII, and this
fails when you have non-ASCII characters. You want `unicode` instead of `str`.
self.writer.writerow([unicode(s).encode("utf-8") for s in row])
It might be better to convert everything to unicode before calling that
method. The class is designed specifically for parsing Unicode strings. It was
not designed to support other data types.
|
Uploading command-line utilities to PyPI
Question: I made a program that should be run from the shell with only one command (like
`$ program_name`, that's it). I'm confused if I should upload this program to
the PyPI list because when I browse through the list I have only encountered
packages/modules that are designed to be imported into other python programs.
The program is also specifically designed for python users, so only
programmers who work with python would use it. It would be nice if I could
upload it there mainly because it is easier to package and distribute and only
python users would use it anyway.
Answer: Of course you can upload it.
There are plenty of command-line utilities listed on PyPI, including, for
example, [`pip`](https://pypi.python.org/pypi/pip).
In fact, there are over [2700 packages marked as running in the Console
environment](https://pypi.python.org/pypi?%3aaction=browse&show=all&c=8).
|
Why must "exec" (and not "eval") be used for Python import statements?
Question: I'm trying to run a snippet of Python from within Java, using Jython. If I use
an exec statement to import, everything works.
PythonInterpreter pi = new PythonInterpreter();
pi.exec("import re");
PythonObject o = pi.eval("re.match('abc', 'abc123')"); // returns a MatchObject
o = pi.eval("re.match('abc', 'def123')"); // returns Py.None
If, however, I try to combine the two lines, all hell breaks loose. This:
PythonInterpreter pi = new PythonInterpreter();
pi.eval("import re"); // exception!
PythonObject o = pi.eval("re.match('abc', 'abc123')"); // never gets here
o = pi.eval("re.match('abc', 'def123')"); // ....
...throws an exception `"no viable alternative at input 'import'",
('<string>',1,0,'import re\n')`.
This matters, because ideally I'd like to be able to eval a whole script as a
single string, without having to break the imports out into a separate part.
Am I doing something wrong? Is there another way to tell Jython "take this
whole blob of script, including imports, and run it, then give me back a
result"? This needs to be at runtime -- pre-compiling the Python into `.class`
files is not an option.
Answer: The problem is that **eval** _evaluates expressions_ and _returns some result_
, while **exec** _executes statements_ in some context. import is a statement,
while re.match() is an expression.
|
Write a file in Python 2.7 without getting blocked by Windows?
Question: I'm writing a simple fuzzer for use on Windows applications based on the
Charlie Miller code from the babysitting an army of monkeys talk. However I
keep receiving the error
Traceback (most recent call last):
File "D:/Python27/fuzzer.py", line 29, in <module>
process=subprocess.Popen([app_choice,fuzz_output])
File "D:\Python27\lib\subprocess.py", line 679, in __init__
errread, errwrite)
File "D:\Python27\lib\subprocess.py", line 896, in _execute_child
startupinfo)
WindowsError: [Error 5] Access is denied
Does anyone know how to bypass this? I'm really stumped because I'm not all
too familiar with Windows 7 permissions or Python 2.7 to be honest. Full code
below
#List of file names (all located in the python folder)
fuzz_files=[ "slides_algo-guiding.pdf", "slides_algo-intro-annotated- final.pdf","slides_algo-merge1.pdf"]
apps=["C:\Program Files (x86)\Adobe\Reader 9.0\Reader"
]
#Creates an output file in the Python folder
fuzz_output="fuzz.pdf"
FuzzFactor=50
num_tests=1000
import math
import string
import random
import subprocess
import time
for i in range(num_tests):
file_choice=random.choice(fuzz_files)
app_choice=random.choice(apps)
buf=bytearray(open(file_choice,'rb').read())
#Charlie Miller code
numwrites=random.randrange(math.ceil((float(len(buf))/FuzzFactor)))+1
for j in range(numwrites):
rbyte=random.randrange(256)
rn=random.randrange(len(buf))
buf[rn]="%c"%(rbyte)
#End Charlie miller code
#Write code
open(fuzz_output,'wb').write(buf)
process=subprocess.Popen([app_choice,fuzz_output])
time.sleep(1)
crashed=process.poll()
if not crashed:
process.terminate()
Answer: I believe that `C:\Program Files (x86)\Adobe\Reader 9.0\Reader` is the path of
a _folder_ , not an executable. Therefore trying to run it with `Popen` makes
no sense.
Also, you should be using raw strings when writing Windows paths `r"C:\Program
Files (x86)\Adobe\Reader 9.0\Reader\AcroRd32.exe"` or using slashes instead
`"C:/Program Files (x86)/Adobe/Reader 9.0/Reader/AcroRd32.exe"`. You were just
lucky that there weren't any valid escape sequences in the paths.
|
Python: How can I group this list of items by category?
Question: Working with a Django app. I have a List of `ads` and I want to be able to
filter on these in templates (eg, grab all ads of `spot_id = 1`, then pick a
random one.
I'm using raw SQL via the cursor instead of Django's mysterious querying, so I
already have my list (converted into a dict). Here's what I have so far:
# list/dict of ads
[
{'filename': u'rc_ad_06_02_11.gif', 'spot_id': 1L },
{'filename': u'k_banner.jpg', 'spot_id': 1L},
{'filename': u'dwarves-banner.gif', 'spot_id': 1L},
{'filename': u'k_skyscraper.jpg', 'spot_id': 2L }
]
# attempt to group them somehow
final_ads = []
last_spot_id = 0
for a in ads:
if a['spot_id'] != last_spot_id:
final_ads[a['spot_id']][] = a # syntax error here
last_spot_id = a['spot_id']
logger.info(final_ads)
This doesn't work. What I'm essentially trying to get to is a list of this
kind of structure:
[
1: [
{'filename': u'rc_ad_06_02_11.gif', 'spot_id': 1L },
{'filename': u'k_banner.jpg', 'spot_id': 1L},
{'filename': u'dwarves-banner.gif', 'spot_id': 1L}
],
2: [
{'filename': u'k_skyscraper.jpg', 'spot_id': 2L }
]
]
(couldn't think of a proper way of representing this, sorry if it doesn't look
right).
If anyone can show me a smarter way of doing this I'd be very appreciative.
Thanks.
Answer: defaultdict should handle this nice it will return a dict rather than a list
final_ads will be something like {1:[a1,a3,a4],2:[a2,a5]...}
from collections import defaultdict
final_ads = defaultdict(list)
for a in ads:
final_ads[a['spot_id']].append(a)
print final_ads
for spot_id in sorted(final_ads.keys()):
print "Spot %s=%s"%(spot_id,final_ads[spot_id])
above code with your list of dicts ~~returns~~ prints
defaultdict(<type 'list'>, {1L: [{'spot_id': 1L, 'filename': u'rc_ad_06_02_11.gif'}, {'spot_id': 1L, 'filename': u'k_banner.jpg'}, {'spot_id': 1L, 'filename': u'dwarves-banner.gif'}], 2L: [{'spot_id': 2L, 'filename': u'k_skyscraper.jpg'}]})
Spot 1=[{'spot_id': 1L, 'filename': u'rc_ad_06_02_11.gif'}, {'spot_id': 1L, 'filename': u'k_banner.jpg'}, {'spot_id': 1L, 'filename': u'dwarves-banner.gif'}]
Spot 2=[{'spot_id': 2L, 'filename': u'k_skyscraper.jpg'}]
|
No plotting in matplotlib after version upgrade
Question: I just updated matplotlib to 1.1.0 on a server running ubuntu 10.04 LTS in
order to play better with pandas. Pandas was converting my index according the
functionality of a different version of matplotlib. I installed on one server
using "easyinstall -U matplotlib" and "pip install -U matplotlib" on the
other.
I cannot plot in any of my previous working scripts or in ipython. show() has
stopped working in pylab. Could someone point me in the direction of what may
be broken?
I took the following test script "simple_plot.py" from matplotlib's site and
tested it on various servers after first deleting my config directory.
from pylab import *
plot([1,2,3])
show()
simple_plot produces a plot on all servers that are running on versions <=
0.99 but has no output on version 1.1.
here is the debug output on one server that does not work:
$HOME=/home/michael
CONFIGDIR=/home/michael/.matplotlib
matplotlib data path /usr/local/lib/python2.6/dist-packages/matplotlib-1.1.0-py2.6-linux-x86_64.egg/matplotlib/mpl-data
loaded rc file /usr/local/lib/python2.6/dist-packages/matplotlib-1.1.0-py2.6-linux-x86_64.egg/matplotlib/mpl-data/matplotlibrc
matplotlib version 1.1.0
verbose.level debug
interactive is False
platform is linux2
Using fontManager instance from /home/michael/.matplotlib/fontList.cache
backend agg version v2.2
python version:2.6.5
findfont: Matching :family=sans-serif:style=normal:variant=normal:weight=normal:stretch=normal:size=medium to Bitstream Vera Sans (/usr/local/lib/python2.6/dist-packages/matplotlib-1.1.0-py2.6-linux- x86_64.egg/matplotlib/mpl-data/fonts/ttf/Vera.ttf) with score of 0.000000
Answer: You are using the Agg backend, which does not show the figure on the display.
This is the default for matplotlib. You need to change your backend in your
matplotlib configuration file (usually ~/.matplotlib/matplotlibrc). Look for
the part:
backend : Agg
And replace 'Agg' with one of: GTKAgg, Qt4Agg, TkAgg, WXAgg. You may not have
all of these (or any!) installed in your system, so try one that works.
If you don't have the file ~/.matplotlib/matplotlibrc, then copy it from your
main configuration:
cp /usr/local/lib/python2.6/dist-packages/matplotlib-1.1.0-py2.6-linux-x86_64.egg/matplotlib/mpl-data/matplotlibrc ~/.matplotlib/matplotlibrc
|
How to emit an gtk.gdk event with a string as a data package in Python
Question: I have a problem in that I need to emit data based on data I receive from a
hardware thread. Ideally, I'd like to emit a signal with a data package.
I don't know what to fill in for the ???? below.
Do I need to make my own event class?
Something like this:
import gtk.gdk as gdk
import gtk.glade as glade
class ApplicationFrame(object):
def __init__(self, *args, **kwargs):
...
self.glade = glade.XML(ui_filepath)
self.window = self.glade.get_widget(self.widget_name)
# for keystrokes:
self.window.add_events(gtk.gdk.KEY_PRESS_MASK)
self.window.connect("key-press-event", self.default_handler)
# for my special event ????
self.window.add_events(gtk.gdk.????)
self.window.connect("????", self.default_handler)
...
def emit_signal(self, name, data):
event = gdk.Event(gdk.????)
event.name = name
event.data = data
self.window.emit(event)
def default_handler(self, widget, event):
name, data = self.extract_data_from(event)
# do something special with the information...
Thanks in advance!
Edit: Final implementation (only showing new functions/additions)...
class ApplicationFrame(Ui_ApplicationFrame):
"""Standard Application Frame for Application"""
__gsignals__ = {
'data-received': (gobject.SIGNAL_RUN_FIRST,
gobject.TYPE_NONE,
(gobject.TYPE_PYOBJECT,)),
}
...
def handle_new_data(self, data):
"""Callback routine when data arrives on bus"""
self.window.emit('data-received', data)
def do_data_received(self, data):
"""Callback routine for emitted 'data-received' signal"""
...
...
gobject.type_register(ApplicationFrame)
Answer: Don't define another `gdk.Event`. Those are only used to represent X11 events
or their equivalents on other platforms. Instead, you need to have your class
inherit from `gobject.GObject`, and then define a dictionary member with the
magic name `__gsignals__`.
How to do it is described [here](http://www.pygtk.org/articles/subclassing-
gobject/sub-classing-gobject-in-python.htm).
Like this:
class ApplicationFrame(gobject.GObject):
__gsignals__ = {
'data-received': (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, (gobject.TYPE_PYOBJECT,))
}
def do_data_recieved(self, data):
# default handler
|
Can't rm -r directory using python subprocess.call
Question: Welp, I need to remove some huge temporary directories from python and I can't
seem to use rm -r. I'm working thought a big dataset (on s3) I don't have the
disc space to leave them around.
The usual way I would call a command from python is
import subprocess
subprocess.call('rm','-r','/home/nathan/emptytest')
That gives me
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/subprocess.py", line 493, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 629, in __init__
raise TypeError("bufsize must be an integer")
TypeError: bufsize must be an integer
What's this all about?
Answer: You're calling it the wrong way. The first argument should be a list:
import subprocess
subprocess.call(['rm','-r','/home/nathan/emptytest'])
You might also just want to try and use
[shutitl.rmtree](http://docs.python.org/library/shutil.html#shutil.rmtree)
|
How do I use FCGI with Python (and Django) on Fedora 17?
Question: I'm having trouble accessing my "index.fcgi"; I keep getting a 500 Internal
Server Error. Here's my error_log:
[Thu Aug 09 19:40:17 2012] [warn] [client 127.0.0.1] (104)Connection reset by peer: mod_fcgid: error reading data from FastCGI server
[Thu Aug 09 19:40:17 2012] [error] [client 127.0.0.1] Premature end of script headers: index.fcgi
Here's what I have in my .htaccess file:
Options +ExecCGI
Options +Indexes
AddHandler fcgid-script .fcgi
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.fcgi/ [QSA,L]
and here's my index.fcgi:
#!/usr/bin/python2.7
from django.core.servers.fastcgi import runfastcgi
runfastcgi(method="threaded", daemonize="false")
print "Content-type: text/html\n\n"
print
print "<html>"
print "<body>"
print "<b>test</b>"
print "</body>"
print "</html>"
I have even removed the django import and runfastcgi component, and I'm still
inable to see my page.
Why is this happening to me? I have definitely installed mod_python, mod_wsgi,
mod_fcgid, mod_fcgi, but nothing seems to be making it run...
Answer: There is a way to solve this problem: cd to the directory where index.fcgi is
there and run `./index.fcgi`
\- This will give you the exact error.
|
How can I consistently convert strings like "3.71B" and "4M" to numbers in Python?
Question: I have some rather mangled code that almost produces the **tangible
price/book** from Yahoo Finance for companies (a nice module called
`ystockquote` gets the **intangible price/book** value already).
My problem is this:
For one of the variables in the calculation, **shares outstanding** I'm
getting strings like **10.89B** and **4.9M** , where **B** and **M** stand
respectively for **billion** and **million**. I'm having trouble converting
them to numbers, here's where I'm at:
shares=''.join(node.findAll(text=True)).strip().replace('M','000000').replace('B','000000000').replace('.','') for node in soup2.findAll('td')[110:112]
Which is pretty messy, but I think it would work if instead of
.replace('M','000000').replace('B','000000000').replace('.','')
I was using a regular expression with variables. I guess the question is
simply which regular expression and variables. Other suggestions are also
good.
### EDIT:
To be specific I'm hoping to have something that works for numbers with zero,
one, or two decimals but these answers all look helpful.
Answer:
>>> from decimal import Decimal
>>> d = {
'M': 6,
'B': 9
}
>>> def text_to_num(text):
if text[-1] in d:
num, magnitude = text[:-1], text[-1]
return Decimal(num) * 10 ** d[magnitude]
else:
return Decimal(text)
>>> text_to_num('3.17B')
Decimal('3170000000.00')
>>> text_to_num('4M')
Decimal('4000000')
>>> text_to_num('4.1234567891234B')
Decimal('4123456789.1234000000000')
You can `int()` the result if you want too
|
Debian Python 2.5 including module from AlchemyAPI
Question: Trying to install **AlchemyAPI.py-2.5**
Can't get example running.
Debian 6.0
### python example/sentiment.py:
Traceback (most recent call last):
File "example/sentiment.py", line 4, in <module>
import AlchemyAPI
ImportError: No module named AlchemyAPI
How do I install that module? in README it says:
> To install this module, copy the desired AlchemyAPI.py file into your
> desired Python import directory.
What is my desired directory if I'm running on debian ?
Very confusing, any help appreciated.
Answer: You need to rename `AlchemyAPI.py-2.5` to `AlchemyAPI.py` for it to be
importable, and add it to the PYTHONPATH (which includes the Python package
directories and the working dir).
In your example you can copy the file to: `example/AlchemyAPI.py`.
|
Reverse DNS lookup in Python
Question: If I have an IP address like 2001:4860:4860::8888
How can I get the fully qualified domain in the format foo.ip6.arpa ?
EDIT: Both the solutions so far give me google-public-dns-a.google.com - maybe
Reverse DNS was the wrong name. For this I'd expect the output to be something
like 8.8.8.8.0...etc.ip6.arpa
Answer: using dnspython.
from dns import resolver,reversename
addr=reversename.from_address("2001:4860:4860::8888")
str(resolver.query(addr,"PTR")[0])
|
Getting the top length of a key in Python
Question: > **Possible Duplicate:**
> [Find longest (string) key in
> dictionary](http://stackoverflow.com/questions/10895567/find-longest-string-
> key-in-dictionary)
Without folding. Example:
from functools import reduce
dict = {'t1': 'test1', 'test2': 't2'}
print(len(reduce(lambda x, y: x if len(x) >= len(y) else y, dict.keys())))
Is there any way to get the longest key's length in a a dictionary (preferably
in one line)? There's nothing wrong with folding but I'm just interested if
there's another way to do it in Python 3.
Answer: You can simply do
max(map(len, my_dict))
This will take the lengths of all keys and extract the maximum of these
lengths.
To get the longest key itself, use
max(my_dict, key=len)
|
How to get the module from which the currently executing function was called?
Question: This is my best solution so far to the problem of accessing the calling module
from within a function:
import inspect
import sys
def calling_module(level=0):
filename = inspect.stack()[level+2][1]
modulename = inspect.getmodulename(filename)
try:
return sys.modules[modulename]
except KeyError:
return sys.modules['__main__']
...but implicit in the handling of the `KeyError` is the (largely unfounded)
assumption that it can happen only if `filename` is being run as `__main__`.
Does the Python standard library provide a more robust way to do this?
Answer: I find that the following works well:
import inspect
def printfunc()
stk = inspect.stack()[1]
mod = inspect.getmodule(stk[0])
print "Currently in " + mod + "." + stk[3]
which I have inside a utility function called something like `printfunc()`
|
Simple Python Import
Question: I have a simple Python import question. I have a module _(let's call it**A**)_
that is importing a module **B**. Module B imports a lot of other modules C,
D, E, F, etc. I want module A to be able to use the modules C, D, E, F, etc.
Is there an easy way to do this? I don't want to directly import C, D, E, F,
etc from A.
What I'm trying to accomplish is to provide an API to script developers, who
write module A. So, I wanted module A only to have to include module B which
is the main entry point to the API and imports all the modules in the API.
Answer: You could do...
from B import *
...inside module A (although you need to make sure that there's nothing else
inside module B that has the same name with anything inside module A,
otherwise you'll have a namespace collision).
Once you do that, you could do...
C.blah()
D.testing.meh()
...inside module A, as usual.
Alternatively, a better solution would be to do something like the below in
module A:
import B
B.C.blah()
B.D.testing.meh()
|
How to import custom json module instead of the default in python 2.7?
Question: Assuming my directory structure is:
C:\Scripts\myscript.py
C:\Scripts\customjson\json.py
The myscript.py python script has at the top:
sys.path.append(os.path.join(os.path.dirname(sys.argv[0]), 'customjson'))
import json
The thing is, I have a "customjson" folder that contains a json.py that I want
to use instead of the default json package that Python 2.7 comes with. How do
I make it so that the script uses "customjson" instead of the standard json?
Answer: Try to insert your customjson directory first in `sys.path`:
sys.path.insert(0, os.path.join(os.path.dirname(sys.argv[0]), 'customjson'))
import json
|
Newbie. Django Tutorial (from django website) stuck at part 2 - admin
Question: I have read many answers here but none did answer my exact question.
I did the part one, the polls. I started part 2, the admin, however, after
runserve, when i try to acces the page, here is the error i get (my project
name is john):
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/
Using the URLconf defined in john.urls, Django tried these URL patterns, in this order:
^admin/
The current URL, , didn't match any of these.
You're seeing this error because you have DEBUG = True in your Django settings file. ``
My code - urls.py:
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'newgrid.views.home', name='home'),
# url(r'^newgrid/', include('newgrid.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
Models.py:
from django.db import models
import datetime
from django.utils import timezone
# Create your models here.
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __unicode__(self):
return self.question
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
def __unicode__(self):
return self.choice
settings.py:
# Django settings for newgrid project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', '[email protected]'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'C:/john/john/johny.db', # Or path to database file if using sqlite3.
'USER': '', # Not used with sqlite3.
'PASSWORD': '', # Not used with sqlite3.
'HOST': '', # Set to empty string for localhost. Not used with sqlite3.
'PORT': '', # Set to empty string for default. Not used with sqlite3.
}
}
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/home/media/media.lawrence.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://media.lawrence.com/static/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'cl8%_lzxbct-^ebmpje25%r&5*0=$qmv9gw6i$^arox*kr4$_e'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'newgrid.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'newgrid.wsgi.application'
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
#'django.contrib.admindocs',
'polls'
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
Thats about it. Oh yea, im in WinXP.
Answer: You're navigating to the wrong URL. As [the tutorial
says](https://docs.djangoproject.com/en/1.4/intro/tutorial02/#start-the-
development-server),
> Now, open a Web browser and go to `/admin/` on your local domain — _e.g._ ,
> `http://127.0.0.1:8000/admin/`. You should see the admin's login screen:
|
Pygame: key.get_pressed() does not coincide with the event queue
Question: I'm attempting to work out simple controls for an application using pygame in
Python. I have got the basics working, but I'm hitting a weird wall: I am
using the arrow keys to control my character. If I hold down one arrow key,
then hold down another arrow key (to move diagonally), the character moves as
expected. However, if I release the _second_ key that I pressed (while still
holding down the _first_ key), the character stops moving, even though I am
still holding down that first key. Here is my simple movement code:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if pygame.key.get_pressed()[K_LEFT]:
player.pos = (player.pos[0] - 2, player.pos[1])
if pygame.key.get_pressed()[K_RIGHT]:
player.pos = (player.pos[0] + 2, player.pos[1])
if pygame.key.get_pressed()[K_UP]:
player.pos = (player.pos[0], player.pos[1] - 2)
if pygame.key.get_pressed()[K_DOWN]:
player.pos = (player.pos[0], player.pos[1] + 2)
Now, I was naturally very confused by this. So I tried to print some lines to
debug. In the top of the main control loop, I wrote:
print (pygame.key.get_pressed()[K_DOWN], pygame.key.get_pressed()[K_RIGHT])
print pygame.event.get()
...to output a tuple displaying the state of the down and right arrow keys,
and then display the pygame event queue. My results baffled me even more. If I
move the character diagonally down and right, pressing the down key first and
then the right key, _then_ release the right key to make it move simply
downward, the character stops moving as before... but this is printed to the
shell:
(1, 0)
[]
That is, when I _release_ the right arrow key and still hold down the down
arrow key, pygame.key.get_pressed() understands that the down arrow key is
still being held down, but there is nothing in the event queue.
Also, earlier in the code (before the control loop) I am invoking
pygame.key.set_repeat(1, 2)
to make the character continue to move while the key is held down.
Any help will be appreciated! Thanks :)
Answer: For things like movement, you should not check for events (like `KEYDOWN` or
`KEYUP`), but check every iteration of your mainloop if your movement keys are
pressed (using
[`get_pressed`](http://www.pygame.org/docs/ref/key.html#pygame.key.get_pressed)).
In your code, you check the pressed keys only if there's also a `KEYDOWN`
event.
* * *
There are also some other things to consider:
* You should seperate the key-mapping and the speed of your player, so it will be easier later on to change either of this.
* You should determine a movement vector and normalize it first, since otherwise, if your vertical and horizontal movement speed is `10`, your diagonal movement speed would be ~`14`.
**Working example:**
import pygame
import math
pygame.init()
screen = pygame.display.set_mode((200, 200))
run = True
pos = (100, 100)
clock = pygame.time.Clock()
# speed of your player
speed = 2
# key bindings
move_map = {pygame.K_LEFT: (-1, 0),
pygame.K_RIGHT: (1, 0),
pygame.K_UP: (0, -1),
pygame.K_DOWN: (0, 1)}
while run:
screen.fill((0, 255, 0))
# draw player, but convert position to integers first
pygame.draw.circle(screen, (255, 0, 0), map(int, pos), 10)
pygame.display.flip()
# determine movement vector
pressed = pygame.key.get_pressed()
move_vector = (0, 0)
for m in (move_map[key] for key in move_map if pressed[key]):
move_vector = map(sum, zip(move_vector, m))
# normalize movement vector if necessary
if sum(map(abs, move_vector)) == 2:
move_vector = [p/1.4142 for p in move_vector]
# apply speed to movement vector
move_vector = [speed*p for p in move_vector]
# update position of player
pos = map(sum, zip(pos, move_vector))
for e in pygame.event.get():
if e.type == pygame.QUIT: run = False
clock.tick(60)
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.