text
stringlengths 226
34.5k
|
---|
Python with Mysql - pdf file insertion during runtime
Question: I have a script that stores results in pdf format in a particular folder. I
want to create a mysql database ( which is successful with the below code ),
and populate the pdf results to it. what would be the best way , storing the
file as such , or as reference to the location. The file size would be around
2MB. Could someone help in explaining the same with some working examples. I
am new to both python and mysql.Thanks in advance. To clarify more : I tried
using LOAD DATA INFILE and the BLOB type for the result file column , but it
dosent seem to work .I am using pymysql api module to connect to the
database.Below code is to connect to the database and is successful.
import pymsql
conn = pymysql.connect(host='hostname', port=3306, user='root', passwd='abcdef', db='mydb')
cur = conn.cursor()
cur.execute("SELECT * FROM userlogin")
for r in cur.fetchall():
print(r)
cur.close()
conn.close()
Answer: Since you seem to be close to getting mysql to store strings for you (user
names), your best bet is to just stick with what you did there and store the
file path just as you stored the strings in your `userlogin` table (but in a
different table with a foreign key to `userlogin`). It will probably be the
most efficient approach in the long run anyway, especially if you store
important metadata along with the file path (like keywords or even complete
n-gram sets)... now you're talking about a file indexing system like Google
Desktop or Xapian... just so you know what you're up against if you want to do
this the "best" way.
|
Python search data within all XML elements
Question: Newbie - I am trying to use lxml to find "error" in any element (sample XML
file below, but it should work regardless to how nested the tags are):
<test>
<test1>
error
</test1>
<test2>
<test3>
error
</test3>
</test2>
</test>
So far it seems that lxml is only capable of searching for tags and not the
data within the tags - is this correct?
Answer: Are you asking if there's a built-in function to search the text in an
element? It's pretty simple to write your own search routine using `lxml`'s
`etree` parser. For example:
**test.xml**
<test>
<test1>
error
</test1>
<test2>
<test3>
error
</test3>
</test2>
</test>
And from the command line:
>>> import lxml.etree as etree
>>> for event, element in etree.iterparse("test.xml"):
... # Print the tag of a matching element
... if element.text.strip() == "error":
... print element.tag
...
test1
test3
EDIT: If you end up going this route and don't need to muck about with XML
namespaces I recommend you check out `xml.etree.cElementTree` instead of
`lxml.etree`. It's included in the Python standard modules and is on par or
slightly faster than `lxml.etree`.
|
pydev multithread debugging
Question: I'm trying to debug an application which makes use of the pynetdicom library.
I'm not sure how relevant that specific detail is, however what IS relevant is
that it makes heavy use of multithreading to run background socket listener
tasks without blocking the main thread. The storescp.py example can be used to
reproduce this.
Whenever I place a breakpoint that gets encountered (regardless of what
thread, main or child, it gets encountered in), I get the following traceback:
Traceback (most recent call last):
File "/Applications/Aptana Studio 3/plugins/org.python.pydev_2.7.0.2013012902/pysrc/pydevd.py", line 1397, in <module>
debugger.run(setup['file'], None, None)
File "/Applications/Aptana Studio 3/plugins/org.python.pydev_2.7.0.2013012902/pysrc/pydevd.py", line 1090, in run
pydev_imports.execfile(file, globals, locals) #execute the script
File "/Users/alexw/Development/Python/kreport2/KReport2/dicomdatascraper.py", line 183, in <module>
oldDicomList = copy.copy(newData)
File "/Users/alexw/Development/Python/kreport2/KReport2/dicomdatascraper.py", line 183, in <module>
oldDicomList = copy.copy(newData)
File "/Applications/Aptana Studio 3/plugins/org.python.pydev_2.7.0.2013012902/pysrc/pydevd_frame.py", line 135, in trace_dispatch
self.doWaitSuspend(thread, frame, event, arg)
File "/Applications/Aptana Studio 3/plugins/org.python.pydev_2.7.0.2013012902/pysrc/pydevd_frame.py", line 25, in doWaitSuspend
self._args[0].doWaitSuspend(*args, **kwargs)
File "/Applications/Aptana Studio 3/plugins/org.python.pydev_2.7.0.2013012902/pysrc/pydevd.py", line 832, in doWaitSuspend
self.processInternalCommands()
File "/Applications/Aptana Studio 3/plugins/org.python.pydev_2.7.0.2013012902/pysrc/pydevd.py", line 360, in processInternalCommands
thread_id = GetThreadId(t)
File "/Applications/Aptana Studio 3/plugins/org.python.pydev_2.7.0.2013012902/pysrc/pydevd_constants.py", line 140, in GetThreadId
return thread.__pydevd_id__
File "/Users/alexw/.virtualenvs/kreport2dev/devlibs/pynetdicom/source/netdicom/applicationentity.py", line 73, in __getattr__
obj = eval(attr)()
File "<string>", line 1, in <module>
NameError: name '__pydevd_id__' is not defined
My thought is that, perhaps, in order to make things work, PyDev monkey-
patches a `__pydevd_id__` into spawned threads, however fails to patch those
into _these_ threads because they are, in fact, subclasses and not direct
instances of `threading.Thread` (in this case, the worker is an instance of
`class Association(threading.Thread):`).
Of course, I don't know PyDev well enough to confirm this theory, or else fix
it. And it seems neither does the internet.
Is subclassing `Thread` so rarely used a pattern that it's simply not
considered in the PyDev architecture? Without re-architecting the library, how
could this issue be remedied?
Answer: I simply needed to look harder at that traceback.
The pynetdicom library, in its subclassing of `threading.Thread`, overrode
`__getattr__` and somewhat broke it. The problem was:
def __getattr__(self, attr):
#while not self.AssociationEstablished:
# time.sleep(0.001)
obj = eval(attr)
# do some stuff
return obj
when a nonexistent attribute is passed, a NameError is raised. This isn't
caught by pydev's monkeypatching routine (`if thread.__pydevd_id__ raises
AttributeError, thread.__pydevd_id__ = stuff`)
The solution was to update that section thusly:
def __getattr__(self, attr):
#while not self.AssociationEstablished:
# time.sleep(0.001)
try:
obj = eval(attr)
except NameError:
raise AttributeError
# do some stuff
return obj
This intercepts the NameError and raises an AttributeError instead, as
`__getattr__` should if the queried attribute doesn't exist.
|
python one more stupid debug
Question: sorry, i am a bit of a pain but i damaged my code, i cannot understand what is
wrong. I just removed a if statement but now it appears the timedelta is not
recognized anymore and it breaks the code. I am pretty sure i havent removed
any of the reference though. I am scratching my head but cannot find what is
the problem..
Would you know what went wrong?
import random
import datetime
import csv
from itertools import groupby
def generator():
i=0
while 1:
yield random.randint(-1, 1), datetime.datetime.now()
i=i+1
def keyfunc(timestamp,interval):
xt = datetime.datetime(2013, 4,4)
dt=timestamp
delta_second =(dt - xt).seconds
normalize_second = (delta_second / (interval*60)) * (interval*60)
newtime = xt + timedelta(seconds=normalize_second)
return newtime
mynumber = 100
for random_number, current_time in generator():
mynumber += random_number
reftime5min = keyfunc(current_time,5)
print mynumber,",", current_time, reftime5min
the error i get now is:
Traceback (most recent call last):
File "", line 35, in
File "", line 28, in keyfunc
NameError: global name 'timedelta' is not defined
Answer: Change `timedelta` to `datetime.timedelta`. You're not importing the
`timedelta` class directly, so you need to use the qualified name.
|
sh: Syntax error: Bad fd number
Question: I need some help in running this code. I took this code from
(<http://easybioinfo.free.fr/?q=content/amber-trajectory-gromacs-xtc-
conversion>). I am trying to convert amber trajectory to gromacs trajectory.
When I execute this code, I get some errors. I paste the errors below this
code:
#!/usr/bin/python
#Workflow based on Trajectory Converter - v1.5 by: Justin Lemkul
#completely reimplemented and improved by Peter Schmidtke & Jesus Seco
import sys,os,re,fnmatch
if len(sys.argv)>4 :
f=sys.argv[1]
if not os.path.exists(f):
sys.exit(" ERROR : Something you provided does not exist. Breaking up.\n\nUSAGE : python trajconv_peter.py amberCrd amberTop trajDir trajPattern outPutPrefix\n\n \
Example : python amber2xtc.py mdcrd.crd mdcrd.top md *.x.gz md_gromacs\n")
else :
sys.exit(" \n USAGE : python amber2xtc.py AMBERCRD AMBERTOP TRAJDIR TRAJPATTERN OUTPUTPREFIX\n\
Example : python amber2xtc.py mdcrd.crd mdcrd.top md *.x.gz md_gromacs\n\
Note that the AmberCrd can also be a PDB file.\n")
crd=sys.argv[1]
top=sys.argv[2]
trajdir=sys.argv[3]
pattern=sys.argv[4]
outputPref=sys.argv[5]
traj_files=fnmatch.filter(os.listdir(trajdir),pattern) #get the fpocket output folders
RE_DIGIT = re.compile(r'(\d+)') #set a pattern to find digits
ALPHANUM_KEY = lambda s: [int(g) if g.isdigit() else g for g in RE_DIGIT.split(s)] #create on the fly function (lambda) to return numbers in filename strings
traj_files.sort(key=ALPHANUM_KEY) #sort by these numbers in filenames
print "Will convert the following files : "
print traj_files
csn=1
for file in traj_files :
ptrajtmp=open("ptraj_tmp.ptr","w")
print "currently converting "+file
ptrajtmp.write("trajin "+trajdir+os.sep+file+"\n")
ptrajtmp.write("reference "+crd+"\n")
ptrajtmp.write("center ~:WAT,CIO mass origin\n")
ptrajtmp.write("image origin center :* byres familiar\n")
ptrajtmp.write("trajout pdb_tmp/mdcrd.pdb pdb")
ptrajtmp.close()
if not os.path.exists("pdb_tmp"):
os.mkdir("pdb_tmp")
os.system("ptraj "+top +" ptraj_tmp.ptr >/dev/null 2>&1")
if not os.path.exists("xtc_tmp"):
os.mkdir("xtc_tmp")
#move to *.pdb
os.system("cd pdb_tmp; ls *.pdb.* | cut -f3 -d\".\" | awk '{print \"mv mdcrd.pdb.\"$0\" mdcrd_\"$0\".pdb\" }' | sh ; cd ../")
pdb_files=fnmatch.filter(os.listdir("pdb_tmp"),"*.pdb")
pdb_files.sort(key=ALPHANUM_KEY) #sort by these numbers in filenames
if csn==1:
os.system("editconf -f pdb_tmp/mdcrd_1.pdb -o "+outputPref+"_t1_top.gro >/dev/null 2>&1")
for pdb in pdb_files:
os.system("echo \"0\" | trjconv -s pdb_tmp/"+pdb+" -f pdb_tmp/"+pdb+" -o xtc_tmp/traj_"+str(csn)+".pdb.xtc -t0 "+str(csn)+" >/dev/null 2>&1")
csn+=1
if os.path.exists(outputPref+"_traj.xtc"):
os.system("trjcat -f "+outputPref+"_traj.xtc xtc_tmp/*.pdb.xtc -o "+outputPref+"_traj.xtc >& trajcat.log")
else :
os.system("trjcat -f xtc_tmp/*.pdb.xtc -o "+outputPref+"_traj.xtc >& trajcat.log")
os.system("rm -rf pdb_tmp/*.pdb")
os.system("rm -rf xtc_tmp/*.xtc")
os.remove("ptraj_tmp.ptr")
os.system("rmdir pdb_tmp")
os.system("rmdir xtc_tmp")
The error is as below:
vijay@glycosim:~/Simulation-Folder-Feb2013/chapter5-thermo-paper2-Vj/analysis-malto-/28-difusion-coeff-malto-thermo/convert-gromacs-format$ python2.7 amber2xtc.py malto-THERMO.crd malto-THERMO.top TRAJDIR malto*.traj md_gromacss
Will convert the following files :
['malto-thermo.set11.traj', 'malto-thermo.set12.traj', 'malto-thermo.set13.traj', 'malto-thermo.set14.traj', 'malto-thermo.set15.traj']
currently converting malto-thermo.set11.traj
ls: cannot access *.pdb.*: No such file or directory
sh: Syntax error: Bad fd number
currently converting malto-thermo.set12.traj
ls: cannot access *.pdb.*: No such file or directory
sh: Syntax error: Bad fd number
currently converting malto-thermo.set13.traj
ls: cannot access *.pdb.*: No such file or directory
sh: Syntax error: Bad fd number
currently converting malto-thermo.set14.traj
ls: cannot access *.pdb.*: No such file or directory
sh: Syntax error: Bad fd number
currently converting malto-thermo.set15.traj
ls: cannot access *.pdb.*: No such file or directory
sh: Syntax error: Bad fd number
vijay@glycosim:~/Simulation-Folder-Feb2013/chapter5-thermo-paper2-Vj/analysis-malto-/28-difusion-coeff-malto-thermo/convert-gromacs-format$
For information, I am using Ubuntu 11.10 (64 bit).
How this error can be corrected? Appreciate any help. Thank you.
Answer: The problem could be, that in Ubuntu 11.x /bin/sh is linked to /bin/dash and
not to bin bash.
check the link:
ls -l /bin/sh
If /bin/sh is a link to /bin/dash, change it to /bin/bash.
sudo mv /bin/sh /bin/sh.orig
sudo ln -s /bin/bash /bin/sh
|
Python function scoping with import
Question: I have the following modules:
main.py
import my_import
my_import.a_func()
my_import.py
FOO = "foo"
BAR = []
def a_func():
BAR.append("bar") #ok
FOO = FOO + "foo" #UnboundLocalError:
#local variable 'FOO' referenced before assignment
This is probably due to the importing, but how?
[EDIT]
From the answers I get it is not the importing that is the crulpit, but the
follwing is still weird:
FOO = "foo"
BAR = []
def a_func():
BAR.append("bar")
print(FOO)
a_func()
\--> prints "foo"
FOO = "foo"
BAR = []
def a_func():
BAR.append("bar")
print(FOO)
FOO = FOO + "foo"
a_func()
\--> fails with "UnboundLocalError: local variable 'FOO' referenced before
assignment" AND DOES NOT PRINT "foo"
Looks like the interpreter is looking for assignments in the current scope
before it actually runs the code.
Answer: When Python parses a function definition, it notes all variable names that are
on the left-hand side of assignment statements, such as
FOO = FOO + "foo"
It registers all such variable names as **local variables**.
Let me emphasize that the assignment statement causes Python to register `FOO`
as a local variable at the time the _function definition is parsed_ , not when
the function is called. So later, when the function is called, even references
to `FOO` that occur **before the assignment** still refer to the local
variable and can raise an `UnboundLocalError`.
def a_func():
BAR.append("bar")
print(FOO) #<--- "Freaky" UnboundLocalError occurs here!
FOO = FOO + "foo"
So inside `a_func`, FOO is a local variable. In the case where there is no
`print(FOO)` statement, Python reaches the assignment and it evaluates the
right-hand side first. It encounters the variable name, `FOO`, recognizes it
as a **local variable** and asks what's its value? It has no value! So it
raises an `UnboundLocalError`.
To fix, use `global FOO` to declare that the `FOO` inside `a_func` refers to a
global variable:
FOO = "foo"
BAR = []
def a_func():
global FOO
BAR.append("bar") #ok
FOO = FOO + "foo" assignment
In contrast, `BAR.append('bar')` works because Python first looks up the
variable `BAR` \-- it does not consider it a local variable since there was no
assignment of the form `BAR = ...`. It finds `BAR` in the global scope, then
looks up its append method, and then mutates `BAR`. Thus you can mutate `BAR`
but can't assign to `FOO` (without the `global FOO` statement.)
|
Handling unhandled exception in GUI
Question: I am mostly writing a small tools for tech savvy people, e.g. programmers,
engineers etc. As those tools are usually quick hacks improved over time I
know that there are going to be unhandled exceptions and the users are not
going to mind. I would like the user to be able to send me the traceback so I
can examine what happened and possibly improve the application.
I usually do wxPython programming but I have done some Java recently. I have
hooked up the [`TaskDialog`](http://code.google.com/p/oxbow/) class to the
`Thread.UncaughtExceptionHandler()` and I am quite happy with the result.
Especially that it can catch and handle exceptions from any thread:


I was doing something similar in wxPython for a long time. However:
1. I had to write a decorator-hack to be able to print exceptions from another thread well.
2. Even when functional, the result is quite ugly.

Here is the code for both Java and wxPython so you can see what I have done:
Java:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.JButton;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import com.ezware.dialog.task.TaskDialogs;
public class SwingExceptionTest {
private JFrame frame;
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (ClassNotFoundException e) {
}
catch (InstantiationException e) {
}
catch (IllegalAccessException e) {
}
catch (UnsupportedLookAndFeelException e) {
}
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
public void uncaughtException(Thread t, Throwable e) {
TaskDialogs.showException(e);
}
});
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SwingExceptionTest window = new SwingExceptionTest();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public SwingExceptionTest() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 600, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0};
gridBagLayout.rowHeights = new int[]{0, 0};
gridBagLayout.columnWeights = new double[]{0.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, Double.MIN_VALUE};
frame.getContentPane().setLayout(gridBagLayout);
JButton btnNewButton = new JButton("Throw!");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
onButton();
}
});
GridBagConstraints gbc_btnNewButton = new GridBagConstraints();
gbc_btnNewButton.gridx = 0;
gbc_btnNewButton.gridy = 0;
frame.getContentPane().add(btnNewButton, gbc_btnNewButton);
}
protected void onButton(){
Thread worker = new Thread() {
public void run() {
throw new RuntimeException("Exception!");
}
};
worker.start();
}
}
wxPython:
import StringIO
import sys
import traceback
import wx
from wx.lib.delayedresult import startWorker
def thread_guard(f):
def thread_guard_wrapper(*args, **kwargs) :
try:
r = f(*args, **kwargs)
return r
except Exception:
exc = sys.exc_info()
output = StringIO.StringIO()
traceback.print_exception(exc[0], exc[1], exc[2], file=output)
raise Exception("<THREAD GUARD>\n\n" + output.getvalue())
return thread_guard_wrapper
@thread_guard
def thread_func():
return 1 / 0
def thread_done(result):
r = result.get()
print r
class MainWindow(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs)
self.panel = wx.Panel(self)
self.button = wx.Button(self.panel, label="Throw!")
self.button.Bind(wx.EVT_BUTTON, self.OnButton)
self.sizer = wx.BoxSizer()
self.sizer.Add(self.button)
self.panel.SetSizerAndFit(self.sizer)
self.Show()
def OnButton(self, e):
startWorker(thread_done, thread_func)
app = wx.App(True)
win = MainWindow(None, size=(600, 400))
app.MainLoop()
Now the question:
**Can I do easily something similar to Java solution in wxPython? Or maybe, is
there a better way in either Java or wxPython?**
Answer: In Python you can set `sys.execpthook` to a function that you want to be
called for uncaught exceptions. Then you won't need the decorators, you can
just deal with the exceptions centrally in your hook function instead.
And rather than just printing the exception traceback text and letting it be
displayed in the stock stdout window you can do something more intelligent
with it, like using a dialog to display the text and have controls that allow
the user to send the error information back to the developer, to ignore future
errors, to restart the application, or whatever you want.
|
subprocess and Type Str doesnt support the buffer API
Question: I have
cmd = subprocess.Popen('dir',shell=True,stdout=subprocess.PIPE)
for line in cmd.stdout:
columns = line.split(' ')
print (columns[3])
have error in line 3 Type Str doesnt support the buffer API.
What am i doing wrong i am on Python 3.3
Answer: You are reading binary data, not `str`, so you need to decode the output
first:
import locale
encoding = locale.getdefaultlocale()[1]
cmd = subprocess.Popen('dir',shell=True,stdout=subprocess.PIPE)
for line in cmd.stdout:
columns = line.decode(encoding).split()
if columns:
print(columns[-1])
You were trying to split a `bytes` value using a `str` argument:
>>> b'one two'.split(' ')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Type str doesn't support the buffer API
By decoding you avoid that problem, and your `print()` call will not have to
prepend the output with `b'..'` either.
However, you probably just want to use the `os` module instead to get
filesystem information:
import os
for filename in os.listdir('.'):
print(filename)
|
Appending a subprocess to a list seems to just append the subprocess object location in python?
Question: Using the following command at the console prints the local MAC address of
wlan0's NIC. I want to integrate this into a script where the 0th sublist of a
list will be filled with the local MAC in exer
ifconfig wlan0 | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'
The list in use, localisation, gets it's 1st and 2nd sublists from a dict
called scanned.
So I want to have the local MAC in the 0th sublist and an entry for every
entry in the 1st and 2nd sublists. I have tried the code:
for s in scanned:
localisation[0].append(subprocess.Popen("ifconfig wlan0 | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'", shell=True))
but I just get
<subprocess.Popen object at 0x2bf0f50>
For every entry into the list. Although there are the correct amount of
entries.
I also have the problem that for some reason the program prints the output of
the code to the screen which I don't want to happen.
What am I doing wrong?
Answer: the popen object is a file object in a sense.
from subprocess import *
handle = Popen(c, stdin=PIPE, stderr=PIPE, stdout=PIPE)
handle.stdin.write('echo "Heeey there"')
print handle.stdout.read()
handle.flush()
The reason why not ALL output is redirected for you is stderr=PIPE, it must be
otherwise that will be echoed into the console no matter what. Redirecting it
to PIPE is a good idea.
Also, using `shell=True` is generally a bad idea unless you know why you need
it.. in this case (i don't think) you don't need it.
Aaaand finally, you need to devide your command that you would like to execute
into a list, at least a 2 item list or more. example:
c = ['ssh', '-t', 'user@host', "service --status-all"]
which would be `ssh -t user@root "service --status-all"` normally, notice the
NOT splitted part of `"service --status-all"` because that's a parameter sent
as a whole to the SSH client in my example.
Without trying, try:
c = ["ifconfig", "wlan0 | grep -o -E '([[:xdigit:]]{1,2}:){5}[[:xdigit:]]{1,2}'"]
* * *
Or even:
from uuid import getnode as get_mac
mac = get_mac()
|
(Python Newb) Writing to file what is printed?
Question: Thanks to the kindness on this website i've installed
2.7/setuptools/feedparser all without issue.. I've figured out feedparser and
it works without issue.
I've been reading tutorials on how to write to file (text) via python, i've
had moderate success doing this with text.. However when I try to write a list
of data it goes all screwy on me and does nothing at all.
ORIGINAL:
import feedparser
result = feedparser.parse('https://gdata.youtube.com/feeds/api/videos/Ej4_G-E1cAM/comments')
for entry in result.entries:
print entry.author
MY ATTEMPT:
import feedparser
result = feedparser.parse('https://gdata.youtube.com/feeds/api/videos/Ej4_G-E1cAM/comments')
for entry in result.entries:
with open("write.txt", "w") as text_file:
text_file.write entry.author
I'm attempting to harvest comments for an upcoming giveaway on my YouTube
channel.. If anyone is wondering what i'm using this seemingly useless data
for.
Best Regards, -Mitch Powell
Answer:
import feedparser
f = open('filename','w')
result = feedparser.parse('https://gdata.youtube.com/feeds/api/videos/Ej4_G-E1cAM/comments')
for entry in result.entries:
f.write(entry.author)
|
Sort list of tuples by value Python
Question: I've got a list of tuples as the example:
result = [(1, 6.06), (2, 6.23), (3, 7.03), (4, 6.88), (5, 6.43), (6, 6.57)]
How can I sort the list by value in descending order?
Answer: Probably something like:
result.sort(key=lambda x:x[1],reverse=True)
Or some prefer
from operator import itemgetter
result.sort(key=itemgetter(1),reverse=True)
...
or perhaps just:
result.sort(reverse=True)
depending on what you mean by `value`.
If you don't want to sort the list in place, you can always use `sorted` in
much the same way. Of course, the canonical guide to how to sort in python is
found at the following link: ["Sorting Mini-HOW
TO"](http://wiki.python.org/moin/HowTo/Sorting/)
|
Python 3.3 - urllib.request - import error
Question: When I try to run the following Python 3.3 code on OS X 10.8 in PyCharm 2.7
(or run the .py file with the Python 3.3/2.7.3 launcher):
import urllib.request
f = urllib.request.urlopen('http://www.python.org/')
print(f.read(300))
I get the following error message:
/System/Library/Frameworks/Python.framework/Versions/3.3/bin/python3 /Users/username/PycharmProjects/urllib/urllib.py
Traceback (most recent call last):
File "<frozen importlib._bootstrap>", line 1512, in _find_and_load_unlocked
AttributeError: 'module' object has no attribute '__path__'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/username/PycharmProjects/urllib/urllib.py", line 3, in <module>
import urllib.request
File "/Users/username/PycharmProjects/urllib/urllib.py", line 3, in <module>
import urllib.request
ImportError: No module named 'urllib.request'; urllib is not a package
Process finished with exit code 1
The only way I can succesfully run the code is via the Python shell.
Any ideas on how to solve this?
Thanks.
* * *
I changed the filename to url.py, now it succesfully executes in PyCharm.
But when executing the file via Python Launcher 3.3 it gives me the following
error:
File "/Users/username/PycharmProjects/urllib/url.py", line 3, in <module>
import urllib.request
ImportError: No module named request
Why is the code running fine in PyCharm (3.3) but giving me an error when
launched with Python Launcher (3.3)?
Answer: You named your file `urllib`, it is shadowing the standard library package.
Rename your file.
|
Creating an OSX PyQt app using Pyinstaller 2, PyQt4 and Qt5
Question: I am trying to package a PyQt program for OSX using PyInstaller 2, where PyQt4
(4.10) has been built against Qt 5.0.2 (from Git). The following simple
example doesn't work.
import sys
from PyQt4.QtGui import QApplication, QMessageBox
def main():
print "Hello"
a = QApplication(sys.argv)
m = QMessageBox(QMessageBox.Information, "Title", "Hello")
m.exec_()
if __name__=="__main__":
main()
Spec file generated using pyinstaller-2.0/utils/MakeSpec.py and modified to
add the BUNDLE class.
a = Analysis(['hello.py'],
pathex=['/Users/glenn/rp/src/demo'],
hiddenimports=[],
hookspath=None)
pyz = PYZ(a.pure)
exe = EXE(pyz,
a.scripts,
exclude_binaries=1,
name=os.path.join('build/pyi.darwin/hello', 'hello'),
debug=False,
strip=None,
upx=True,
console=False )
coll = COLLECT(exe,
a.binaries,
a.zipfiles,
a.datas,
strip=None,
upx=True,
name=os.path.join('dist', 'hello'))
app = BUNDLE(coll,
name=os.path.join('dist', 'hello.app'),
appname="Hello",
version = '0.1'
)
Packaging command
> python pyinstaller.py --windowed hello.spec
Running the binary directly from the terminal gives this output before it
crashes:
$ ./dist/hello.app/Contents/MacOS/hello
Hello
Failed to load platform plugin "cocoa". Available platforms are:
Abort trap: 6
and this is the stack trace:
Exception Type: EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Application Specific Information:
abort() called
Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0 libsystem_kernel.dylib 0x9a671a6a __pthread_kill + 10
1 libsystem_c.dylib 0x93163b2f pthread_kill + 101
2 libsystem_c.dylib 0x9319a4ec abort + 168
3 QtCore 0x03db156b qt_message_fatal(QtMsgType, QMessageLogContext const&, QString const&) + 11
4 QtCore 0x03db19df QMessageLogger::fatal(char const*, ...) const + 63
5 QtGui 0x068abceb QGuiApplicationPrivate::createPlatformIntegration() + 3547
6 QtGui 0x068abd16 QGuiApplicationPrivate::createEventDispatcher() + 38
7 QtCore 0x03f4f2c4 QCoreApplication::init() + 100
8 QtCore 0x03f4f23b QCoreApplication::QCoreApplication(QCoreApplicationPrivate&) + 59
9 QtGui 0x068aa0d0 QGuiApplication::QGuiApplication(QGuiApplicationPrivate&) + 32
10 QtWidgets 0x06c695de QApplication::QApplication(int&, char**, int) + 238
11 PyQt4.QtGui.so 0x06394454 init_QApplication + 196
12 sip.so 0x007bc7d5 sipSimpleWrapper_init + 266
13 Python 0x0385c174 type_call + 340
14 Python 0x0380d401 PyObject_Call + 97
15 Python 0x0389c093 PyEval_EvalFrameEx + 10131
16 Python 0x038a0490 fast_function + 192
17 Python 0x0389beae PyEval_EvalFrameEx + 9646
18 Python 0x038998b2 PyEval_EvalCodeEx + 1922
19 Python 0x03899127 PyEval_EvalCode + 87
20 Python 0x038be06e PyRun_StringFlags + 126
21 Python 0x038bdfb1 PyRun_SimpleStringFlags + 81
22 Python 0x038bf619 PyRun_SimpleString + 25
23 hello 0x00003240 runScripts + 240
24 hello 0x0000280a main + 442
25 hello 0x00001eb9 _start + 224
26 hello 0x00001dd8 start + 40
The issue appears to be that it can't find the libqcocoa.dylib plugin. This is
not surprising as it is not packaged. Is that the actual issue here and do I
need to include this plugin? If so where does it need to go? I have tried
putting it in demo.app/Contents/plugins but that doesn't help.
Answer: The right place to put libqcocoa.dylib is in
`Contents/MacOS/qt4_plugins/platforms`:
extralibs = [("qt4_plugins/platforms/libqcocoa.dylib", "/path/to/libqcocoa.dylib", "BINARY")
]
coll = COLLECT(exe,
a.binaries + extralibs,
a.zipfiles,
a.datas,
strip=None,
upx=False,
name=os.path.join('dist', 'hello'))
The app now starts but the dialog window never appears. Edit: This is because
PyInstaller (v 2.0) adds LSBackgroundOnly=true to the apps Info.plist.
Removing this allows the window to show.
|
Python: Appending a to a list from a dictionary
Question: This is going to be long but I don't know how else to effectively explain
this.
So I have 2 files that I am reading in. The first one has a list of
characters.The second file is a list of 3 characters and then it's matching
identifier character(separated by a tab).
With the second file I made a dictionary with the 3 characters as the items
and the one character as the corresponding key. What I need to do is take 3
characters at a time from the first list and compare it with the dictionary.
If there is a match I need to take the corresponding key and append it to a
new list that I will print out. If the match is a '*' character I need to stop
not continue comparing the list to the dictionary.
I'm having trouble with the comparing and then making the new list by using
the append function.
Here is part of the first input file:
Seq0
ATGGAAGCGAGGATGtGa
Here is part the second:
AUU I
AUC I
AUA I
CUU L
GUU V
UGA *
Here is my code so far:
input = open("input.fasta", "r")
codons = open("codons.txt", "r")
counts = 1
amino_acids = {}
for lines in codons:
lines = lines.strip()
codon, acid = lines.split("\t")
amino_acids[codon] = acid
counts += 1
count = 1
for line in input:
if count%2 == 0:
line = line.upper()
line = line.strip()
line = line.replace(" ", "")
line = line.replace("T", "U")
import re
if not re.match("^[AUCG]*$", line):
print "Error!"
if re.match("^[AUCG]*$", line):
mrna = len(line)/3
first = 0
last = 3
while mrna != 0:
codon = line[first:last]
first += 3
last += 3
mrna -= 1
list = []
if codon == amino_acids[codon]:
list.append(acid)
if acid == "*":
mrna = 0
for acid in list:
print acid
So I want my output to look something like this:
M L I V *
But I'm not getting even close to this. Please help!
Answer: The following is purely untested code. Check indentation, syntax and logic,
but should be closer to what you want.
import re
codons = open("codons.txt", "r")
amino_acids = {}
for lines in codons:
lines = lines.strip()
codon, acid = lines.split("\t")
amino_acids[codon] = acid
input = open("input.fasta", "r")
count = 0
list = []
for line in input:
count += 1
if count%2 == 0: #i.e. only care about even lines
line = line.upper()
line = line.strip()
line = line.replace(" ", "")
line = line.replace("T", "U")
if not re.match("^[AUCG]*$", line):
print "Error!"
else:
mrna = len(line)/3
first = 0
while mrna != 0:
codon = line[first:first+3]
first += 3
mrna -= 1
if codon in amino_acids:
list.append(amino_acids[codon])
if acid == "*":
mrna = 0
for acid in list:
print acid
|
Python islice is reading the same lines
Question: I have a big log-file (> 1GB) which should be analysed, so I wrote a python-
program. I have used `islice` so I could read the file in chunks (10,000
lines) so my server won't run out of memory.
I've looked up some `islice` solutions on stackoverflow and implemented one,
but the program doesn't work as expected because isclice is reading the same
lines every time (but stops correctly after reading the whole file...). I
can't use `with open` because it comes with python 2.5, I have python 2.4...
My code looks like:
n = 100000; # n lines
inf = open(fn, "r")
while True:
next_n_lines = list(islice(inf, n))
if not next_n_lines:
break
out_fn = produce_clean_logfile(next_n_lines)
a, t = main(out_fn)
send_log(a,t)
Do you know what's wrong?
Thanks in advance. Regards, John.
Answer:
from itertools import islice
n = 2; # n lines
fn = "myfile"
inf = open(fn, "r")
while True:
next_n_lines = list(islice(inf, n))
if not next_n_lines:
break
print next_n_lines
works for me on python 2.5, 2.6, 2.7 => I can see the lines displayed in
order.
The error certainly comes from your other functions, could you update your
question?
|
Raspberry Pi - Rainforest EMU-2 - Python - Read time from SCE smart meter
Question: I am now to programming in Python and this is my first project. Any help would
be appreciated.
I recently obtained a device from Rainforest that reads my electric meter. The
unit has a USB port accessible via USB. I managed to hook the device up to my
Raspberry Pi and extract a hex string from the serial port. Currently the
string is reading 0x18f0cb39. I need to take this number and convert it into
proper format and output it as time and date. The manual for device I am
programming is at
<http://www.rainforestautomation.com/sites/default/files/download/rfa-z106/raven_xml_api_r127.pdf>
I am quite confused when it comes to converting epoch to time and date. I put
#'s in front of lines having difficulties.
The code that I have written is:
#!/usr/bin/env python
import serial
import time
serial.port = serial.Serial("/dev/ttyUSB0", 115200, timeout=0.5)
serial.port.write("<Command><Name>get_time</Name><Refresh>N</Refresh></Command>")
response=serialport.readline(none)
response=serialport.readline(none)
response=serialport.readline(none)
response=serialport.readline(none)
response=serialport.readline(none)
myString=response[13:23]
#struct_time = int(raw_input(((myString >> 40) +1970, (ts >> 32 & 0xFF) +1, ts >> 24 & 0xFF, ts>> 16)))
#thetime=time.strftime("%7-%m-%d-%H-%M-%s)
print myString
Thanks in advance for the help
Scott
Answer: Looking at the documentation, I don't understand exactly how you are using the
slice 13:23 to get your time (in hex) out of the TimeCluster response, but the
gist of your question and your commented out code seems to be how do I convert
0x18f0cb39 to a local date and time?
>>> import time
>>> help(time)
(output snipped, but this is so handy....)
>>> t = 0x18f0cb39
>>> time.ctime(t)
'Tue Apr 5 15:37:29 1983'
>>> time.localtime(t)
time.struct_time(tm_year=1983, tm_mon=4, tm_mday=5, tm_hour=15, tm_min=37, tm_sec=29, tm_wday=1, tm_yday=95, tm_isdst=0)
Since you posted your question 6 days ago and today is the 11th, the date in
that answer seems to be off by exactly 30 years, so I must be doing something
wrong, but maybe this will take you a step in the right direction or prompt
someone else to write a better answer for you.
|
Segmentation fault (core dumped). Using C module in python
Question: I am newbie in python and I am trying to launch python script with a module
writen on C. I am getting Segmentation fault (core dumped) error when I am
trying to launch python script. Here is a C code:
// input_device.c
#include "Python.h"
#include "input.h"
static PyObject* input_device_open(PyObject* self, PyObject* id)
{
int fd, nr;
PyObject* pyfd;
if (!PyInt_Check(id))
return NULL;
nr = (int)PyInt_AsLong(id);
fd = device_open(nr, 0);
if (fd == -1)
return NULL;
pyfd = PyInt_FromLong(fd);
Py_INCREF(pyfd);
return pyfd;
}
static PyMethodDef module_methods[] =
{
{ "device_open", (PyCFunction)input_device_open, METH_VARARGS, "..." },
{ NULL, NULL, 0, NULL }
};
PyMODINIT_FUNC initinput_device(void)
{
Py_InitModule4("input_device", module_methods, "wrapper methods", 0, PYTHON_API_VERSION);
}
and the python script:
from input_device import device_open
device_open(1)
Could someone take a look and point me in the right direction, what I am doing
wrong. Thanks in advance.
Answer: Is it legitimate to return `NULL` without setting an exception, or making sure
that one has been set by a function you have called? I thought that `NULL` was
a signal that Python could go look for an exception to raise for the user.
I am not sure that the `Py_INCREF(pyfd);` is necessary; doesn't the object
already have a refcount of 1 upon creation?
|
prevent the closure of command Prompt with Python when an "exception" occurs
Question: I have a script in Python 2.7 converted in executable with py2exe. The INPUT
data is a text file where the delimiter need to be valid following this
function:
# Check if delimeter is valid
def get_parse(filename, delimiters=['\t', ',', ' ', ':', ';', '-']):
with open(filename) as f:
f.next()
secondline = f.next()
for delimiter in delimiters:
if len(secondline.rstrip().split(delimiter)) >= 3:
return delimiter
raise Exception("couldn't find a delimiter that worked!")
When the delimiter is not valid (ex: a dot) i am looking for two solution in a
Python elegant way:
* Until the right INPUT data is not load you can not pass to OUTFILE
or
* The script break the code, show the error, but the windows (when is a *.exe) doesn't close immediately leaving the user without an explanation
* * *
INPUT = raw_input("Input (*.txt): ")
while not os.path.exists(INPUT):
print IOError("No such file or directory: %s" % INPUT)
INPUT = raw_input("Input (*.txt): ")
try:
parse = get_parse(INPUT)
except Exception:
print ValueError("Delimiter type not valid")
break
OUTPUT = raw_input("Output (*.txt): ")
with this solution (break) the Window of my *.exe file close leaving the user
without an explanation
Answer: You can hook the exception handler for uncaught exceptions using
[`sys.excepthook`](http://docs.python.org/library/sys.html#sys.excepthook),
and have it call
[`raw_input()`](http://docs.python.org/2/library/functions.html#raw_input) (or
[`input()`](http://docs.python.org/3/library/functions.html#input) in 3.x) as
per [this answer](http://stackoverflow.com/a/1000968/786020).
For a quick example:
import sys
def wait_on_uncaught_exception(type, value, traceback):
print 'My Error Information'
print 'Type:', type
print 'Value:', value
print 'Traceback:', traceback
raw_input("Press any key to exit...")
sys.excepthook=wait_on_uncaught_exception
Just modify that to have whatever output or whatever you want (I suggest
looking into the
[`traceback`](http://docs.python.org/2/library/traceback.html) module).
But if you want it more specific to your code, then just put `raw_input("Press
any key to exit...")` in the solution you already have, and it should be fine.
The above should provide a more general solution.
|
Create hierarchical python object where arguments to methods are from hierarchy
Question: There is an existing module I use containing a class that has methods with
string arguments that take the form:
existing_object.existing_method("arg1")
or
existing_object.existing_method("arg1:arg2")
The arguments are in a hierarchical structure. I would like to create a module
that objectifies the arguments and makes them methods of the class of the
imported module such that use would look like this:
my_object.arg1.my_method()
or
my_object.arg1.arg2.my_method()
my_method() would call existing_method() while passing it the "arg1:arg2" as
an argument.
If someone could point me in the right direction to get started I'd appreciate
it.
Answer: You can do this with a custom `__getattr__` that returns special method caller
instances:
class MethodCaller(object):
def __init__(self, args, parent):
self.args = args
self.parent = parent
def __getattr__(self, name):
return MethodCaller(self.args + (name,), self.parent)
def my_method(self):
return self.parent.existing_method(':'.join(self.args))
class MyClass(object):
def __getattr__(self, name):
return MethodCaller((name,), self)
def existing_method(self, arg):
print arg
Example:
>>> MyClass().arg1.my_method()
arg1
>>> MyClass().arg1.arg2.my_method()
arg1:arg2
>>> MyClass().foo.bar.my_method()
foo:bar
|
What option do I need in setup.py to create the package in the right directory?
Question: I am using `setup.py` to create a python package, which I want to install via
`pip`. To correctly install the files under
lib/python2.7/site-packages/<package-name>
I used the following option in `setup.py`:
'package_dir': {'':'lib'}
as [described here](http://docs.python.org/2/distutils/setupscript.html) but
get an error
error: package directory 'lib' does not exist
Well, there is no such directory as I want the _current_ directory to be
installed as package `lib` or whatever. I also tried to use
'package_dir': {'mycode':''}
which installes the code directly in
lib/python2.7/site-packages/
and not under
lib/python2.7/site-packages/<package-name>
What am I doing wrong, and where is this documented? I might overlooked the
documentation of this basic feature as the documentation for `setup.py` is
'suboptimal'.
Answer: The description to how to do this an be found in the [distribute
documentation](https://the-hitchhikers-guide-to-
packaging.readthedocs.io/en/latest/quickstart.html)... Within a directory
containing all of the project (`TowelStuff/` in the given example) you specify
the name of the actual module (`towelstuff/`). To include this as _your_
module you need to add the following line in `setup.py`:
'packages': ['towelstuff']
After having created the sdist (from within `TowelStuff/`), the installation
of this package will install it under `site-packages/towelstuff`, which can be
imported as usual (`from towelstuff import ...`).
|
running script multiple times simultaniously in python 2.7
Question: Hello I am trying to run a script multiple times but would like this to take
place at the same time from what I understood i was to use subprocess and
threading together however when i run it it still looks like it is being
executed sequentially can someone help me so that i can get it to run the same
script over and over but at the same time? is it in fact working and just
really slow?
edit forgot the last piece of code now at the bottom
here is what i have so far
import os
import datetime
import threading
from subprocess import Popen
today = datetime.date.today()
os.makedirs("C:/newscript_image/" + str(today))
class myThread(threading.Thread):
def run(self):
for filename in os.listdir('./newscript/'):
if '.htm' in filename:
name = filename.strip('.htm')
dbfolder = "C:/newscript/db/" + name
os.makedirs(dbfolder)
Popen("python.exe C:/execution.py" + ' ' + filename + ' ' + name + ' ' + str(today) + ' ' + dbfolder)
myThread().start()
Answer: Personally, I'd use `multiprocessing`. I'd write a function that takes a
filename and does whatever the main guts of `execution` does (probably by
importing `execution` and running some function within it):
import multiprocessing
import execution
import datetime
#assume we have a function:
#exection.run_main_with_args(filename,name,today_str,dbfolder)
today = datetime.datetime.today()
def my_execute(filename):
if '.htm' in filename:
name = filename.strip('.htm')
dbfolder = "C:/newscript/db/" + name
os.makedirs(dbfolder)
execution.run_main_with_args(filename,name,str(today),dbfolder)
p = multiprocessing.Pool()
p.map(my_execute,list_of_files_to_process)
|
python threading in a loop
Question: I have a project that requires a bunch of large matrices, which are stored in
~200 MB files, to be cross-correlated (i.e. FFT * conj(FFT)) with each other.
The number of files is such that I can't just load them all up and then do my
processing. On the other hand, reading in each file as I need it is slower
than I'd like.
what I have so far is something like:
result=0
for i in xrange(N_files):
f1 = file_reader(file_list[i])
############################################################################
# here I want to have file_reader go start reading the next file I'll need #
############################################################################
in_place_processing(f1)
for j in xrange(i+1,N_files):
f2 = file_reader(file_list[j])
##################################################################
# here I want to have file_reader go start reading the next file #
##################################################################
in_place_processing(f2)
result += processing_function(f1,f2)
So basically, I just want to have two threads that will each read a file, give
it to me when I ask for it (or as soon as it's done after I ask for it), and
then go start reading the next file for when I ask for it. The object the
file_reader returns is rather large and complicated, so I'm not sure if
multiprocessing is the way to go here...
I've read about threading and queues but can't seem to figure out the part
where I ask the thread to go read the file and can proceed with the program
while it does. I don't want the threads to simply go about their business in
the background -- am I missing a detail here, or is threading not the way to
go?
Answer: Below is an example of using the `multiprocessing` module that will spawn off
child processes to call your `file_reader` method and queue up their results.
The queue should block when full, so you can control the number of read
ahead's you'd like to perform with the `QUEUE_SIZE` constant.
This utilizes a standard Producer/Consumer model of multiprocess
communication, with the child processes act as Producers, with the main thread
being the Consumer. The `join` method call in the class destructor ensures the
child process resources are cleaned up properly. There are some print
statements interspersed for demonstration purposes.
Additionally, I added the ability for the QueuedFileReader class to offload
work to a worker thread or run in the main thread, rather than using a child
process, for comparison. This is done by specifying the mode parameter at
class initialization to `MODE_THREADS` or `MODE_SYNCHRONOUS`, respectively.
import multiprocessing as mp
import Queue
import threading
import time
QUEUE_SIZE = 2 #buffer size of queue
## Placeholder for your functions and variables
N_files = 10
file_list = ['file %d' % i for i in range(N_files)]
def file_reader(filename):
time.sleep(.1)
result = (filename,'processed')
return result
def in_place_processing(f):
time.sleep(.2)
def processing_function(f1,f2):
print f1, f2
return id(f1) & id(f2)
MODE_SYNCHRONOUS = 0 #file_reader called in main thread synchronously
MODE_THREADS = 1 #file_reader executed in worker thread
MODE_PROCESS = 2 #file_reader executed in child_process
##################################################
## Class to encapsulate multiprocessing objects.
class QueuedFileReader():
def __init__(self, idlist, mode=MODE_PROCESS):
self.mode = mode
self.idlist = idlist
if mode == MODE_PROCESS:
self.queue = mp.Queue(QUEUE_SIZE)
self.process = mp.Process(target=QueuedFileReader.worker,
args=(self.queue,idlist))
self.process.start()
elif mode == MODE_THREADS:
self.queue = Queue.Queue(QUEUE_SIZE)
self.thread = threading.Thread(target=QueuedFileReader.worker,
args=(self.queue,idlist))
self.thread.start()
@staticmethod
def worker(queue, idlist):
for i in idlist:
queue.put((i, file_reader(file_list[i])))
print id(queue), 'queued', file_list[i]
queue.put('done')
def __iter__(self):
if self.mode == MODE_SYNCHRONOUS:
self.index = 0
return self
def next(self):
if self.mode == MODE_SYNCHRONOUS:
if self.index == len(self.idlist): raise StopIteration
q = (self.idlist[self.index],
file_reader(file_list[self.idlist[self.index]]))
self.index += 1
else:
q = self.queue.get()
if q == 'done': raise StopIteration
return q
def __del__(self):
if self.mode == MODE_PROCESS:
self.process.join()
elif self.mode == MODE_THREADS:
self.thread.join()
#mode = MODE_PROCESS
mode = MODE_THREADS
#mode = MODE_SYNCHRONOUS
result = 0
for i, f1 in QueuedFileReader(range(N_files),mode):
in_place_processing(f1)
for j, f2 in QueuedFileReader(range(i+1,N_files),mode):
in_place_processing(f2)
result += processing_function(f1,f2)
If your intermediate values are too large to pass through the Queue, you can
execute each iteration of the outer loop in its own process. A handy way to do
that would be using the `Pool` class in `multiprocessing` as in the example
below.
import multiprocessing as mp
import time
## Placeholder for your functions and variables
N_files = 10
file_list = ['file %d' % i for i in range(N_files)]
def file_reader(filename):
time.sleep(.1)
result = (filename,'processed')
return result
def in_place_processing(f):
time.sleep(.2)
def processing_function(f1,f2):
print f1, f2
return id(f1) & id(f2)
def file_task(file_index):
print file_index
f1 = file_reader(file_list[file_index])
in_place_processing(f1)
task_result = 0
for j in range(file_index+1, N_files):
f2 = file_reader(file_list[j])
in_place_processing(f2)
task_result += processing_function(f1,f2)
return task_result
pool = mp.Pool(processes=None) #processes default to mp.cpu_count()
result = 0
for file_result in pool.map(file_task, range(N_files)):
result += file_result
print 'result', result
#or simply
#result = sum(pool.map(file_task, range(N_files)))
|
Principal Component Analysis (PCA) - accessing shape
Question: I am a beginner in python and I am trying to apply Principal Component
Analysis (PCA) to a set of images. I want to put the images in a matrix to be
able to perform PCA. I am still at the beginning but I am having errors.
import numpy as np
import Image
import os
#insert images to matrix
dirname = 'C:\Users\Karim\Downloads\shp_marcel_train\Marcel-Train\A'
X = [np.asarray(Image.open(os.path.join(dirname, fn))) for fn in os.listdir(dirname)]
#get dimensions
num_data,dim = X.shape
It gives `AttributeError: 'list' object has no attribute 'shape'`
anyone can help?
a link to a detailed tutorial would be appreciated
Answer: As you've defined it, `X` is a list:
X = [... for fn in ...]
Python lists do not have a shape attribute. Inside this list are NumPy arrays
which _do_ have a shape attribute. So you could say
num_data = len(X)
shape_of_first_array = X[0].shape
(You didn't explain what `dim` is supposed to represent...)
* * *
Here is an [example of face recognition](http://scipy-
lectures.github.io/advanced/scikit-learn/index.html#id9) done with PCA and a
State Vector Machine. Here is [another related example](http://scikit-
learn.org/dev/auto_examples/applications/face_recognition.html).
|
python: writing HTML in python function. syntaxError: expected an intended block
Question: i am trying to generate a html checkbox within a python function. this is my
code
import HTML
def CreateEvent(str):
"This prints a passed string into this function"
print str;
return;
CreateEvent ('''
content-type: text/html
<html>
<head>
<title> the list of all possible events that can be notified by our system </title>
</head>
<body>
<form>
<input type="checkbox" name="tsunami" value="tsunami">tsunami<br>
<input type="checkbox" name="earthquake" value="earthquake">earthquake<br>
<input type="checkbox" name="volcano" value="volcano">volcano<br>
<input type="checkbox" name="hurricane" value="hurricane">hurricane<br>
<input type="checkbox" name="sinkholes" value="sinkholes">sinkholes<br>
<input type="checkbox" name="tornado" value="tornado">tornado<br>
<input type="checkbox" name="landslide" value="landslide">landslide<br>
<input type="checkbox" name="downburst" value="downburst">downburst<br>
</form>
<input type="submit" value="Submit">
</body>
</html>
''')
but when i try to compile it , it is giving the syntax error: expected an
intended block. please let me know how to solve this problem.
Answer: You have no indentation in the comments.
Note: The comment is `"""` and not `"`
import HTML
def CreateEvent(str):
"""This prints a passed string into this function"""
#^ Indentation space needed here - Also docstrings are represented with """ and not "
print str
#Good practice to have 4 spaces as indentation.
return
# ^ No need of ;
A good idea would be to install the `pep8` python library and do a
pep8 <filename>.py
and fix the issues, if any
|
Gtk/python and portability
Question: How do programmers write portable UI code that works on multiple
distributions? I am considering desktop distributions and not
specialized/embedded distributions. For writing UI applications, you have to
assume certain things will be available on the platform either as standard or
by means of added dependencies. Is there a "minimum" UI/widget standard that
Linux distributions own?
How does Gnome vs KDE distributions come into picture when you are writing the
code?
I have a python script that uses Gtk and Webkit. Following are imports that my
script uses.
import os
import threading
from gi.repository import WebKit
from gi.repository import Gtk
from gi.repository import GLib, GObject
What will be the best source to find out on which distributions my code will
work?
Answer: There is not much stuff you have to consider for writing a cross-distribution
UI.
Actually the only incompatibility issue that I can remember is:
Tray Icon or Notification Area or App Indicator (so called in Ubuntu)
For example standard tray icon (created by `gtk.StatusIcon` does not work in
Ubuntu's Unity by default
You better use `appindicator.Indicator` if appindicator module was found,
otherwise just use classic `StatusIcon`
And if you care too much about the style/theme of your program, you may have
issues on other environments like KDE
Unless you use suitable Theme Engines to act like a bridge, take a look at:
<https://wiki.archlinux.org/index.php/Uniform_Look_for_Qt_and_GTK_Applications>
For finding out about the distribution / OS, I have written such a function:
def getOsFullDesc():
name = ''
if os.path.isfile('/etc/lsb-release'):
lines = open('/etc/lsb-release').read().split('\n')
for line in lines:
if line.startswith('DISTRIB_DESCRIPTION='):
name = line.split('=')[1]
if name[0]=='"' and name[-1]=='"':
return name[1:-1]
if os.path.isfile('/suse/etc/SuSE-release'):
return open('/suse/etc/SuSE-release').read().split('\n')[0]
try:
import platform
return ' '.join(platform.dist()).strip().title()
#return platform.platform().replace('-', ' ')
except ImportError:
pass
if os.name=='posix':
osType = os.getenv('OSTYPE')
if osType!='':
return osType
## sys.platform == 'linux2'
return os.name
|
"StackHash_0a9e error" when exit from python
Question: I'm a beginner of python,I wrote a small program, when I exit the program,
sometimes (more than 50% probability) it show an error.This occurred only
after I **exit** the program.Could you please help me to find is there
something wrong with my code.
Really thanks.
ps:I'm using python3.3 and pyqt4 on win7 sp1 x64
**error:**
问题签名:
问题事件名称: BEX
应用程序名: python.exe
应用程序版本: 0.0.0.0
应用程序时间戳: 5150c40a
故障模块名称: StackHash_0a9e
故障模块版本: 0.0.0.0
故障模块时间戳: 00000000
异常偏移: 00388100
异常代码: c0000005
异常数据: 00000008
OS 版本: 6.1.7601.2.1.0.256.1
区域设置 ID: 2052
其他信息 1: 0a9e
其他信息 2: 0a9e372d3b4ad19135b953a78882e789
其他信息 3: 0a9e
其他信息 4: 0a9e372d3b4ad19135b953a78882e789
**console return this:**
Process finished with exit code -1073741819
**main code:**
import urllib
import http.cookiejar
import time
import sys
from bs4 import BeautifulSoup
from PyQt4 import QtGui
from PyQt4 import QtCore
class BaiduMainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(BaiduMainWindow, self).__init__(parent)
self.initUI()
def initUI(self):
self.centralwidget = BaiduWidget(self)
self.setCentralWidget(self.centralwidget)
self.resize(600, 400)
self.move(QtGui.QApplication.desktop().screen().rect().center() - self.rect().center())
self.statusBar().showMessage('Ready')
class BaiduWidget(QtGui.QWidget):
def __init__(self, parent):
super(BaiduWidget, self).__init__(parent)
self.initUI()
def initUI(self):
lb = QtGui.QLabel('Search Word')
self.keyWordEdit = QtGui.QLineEdit()
self.OKButton = QtGui.QPushButton('Search')
self.containFilter = QtGui.QLineEdit()
self.exceptFilter = QtGui.QLineEdit()
self.result = QtGui.QTextBrowser()
spacerItem = QtGui.QSpacerItem(30, 50)
grid = QtGui.QGridLayout()
grid.setSpacing(10)
grid.addItem(spacerItem, 0, 0)
grid.addWidget(lb, 1, 0)
grid.addWidget(self.keyWordEdit, 2, 0)
grid.addWidget(self.OKButton, 5, 0)
grid.addItem(spacerItem, 7, 0)
grid.addWidget(self.result, 0, 1, 8, 1)
grid.setColumnStretch(1, 4)
self.setLayout(grid)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
form = BaiduMainWindow()
form.show()
sys.exit(app.exec_())
Answer: The problem is: `spacerItem` has beed added to `grid` twice. This object would
probably be freed twice by Qt when you exited the program.
def initUI(self):
lb = QtGui.QLabel('Search Word')
self.keyWordEdit = QtGui.QLineEdit()
self.OKButton = QtGui.QPushButton('Search')
self.containFilter = QtGui.QLineEdit()
self.exceptFilter = QtGui.QLineEdit()
self.result = QtGui.QTextBrowser()
spacerItem = QtGui.QSpacerItem(30, 50)
grid = QtGui.QGridLayout()
grid.setSpacing(10)
grid.addItem(**spacerItem** , 0, 0)
grid.addWidget(lb, 1, 0)
grid.addWidget(self.keyWordEdit, 2, 0)
grid.addWidget(self.OKButton, 5, 0)
grid.addItem(**spacerItem** , 7, 0)
grid.addWidget(self.result, 0, 1, 8, 1)
grid.setColumnStretch(1, 4)
self.setLayout(grid)
You should use two `QSpacerItem`s.
def initUI(self):
lb = QtGui.QLabel('Search Word')
self.keyWordEdit = QtGui.QLineEdit()
self.OKButton = QtGui.QPushButton('Search')
self.containFilter = QtGui.QLineEdit()
self.exceptFilter = QtGui.QLineEdit()
self.result = QtGui.QTextBrowser()
spacerItem = QtGui.QSpacerItem(30, 50)
**spacerItem2 = QtGui.QSpacerItem(30, 50)**
grid = QtGui.QGridLayout()
grid.setSpacing(10)
grid.addItem(spacerItem, 0, 0)
grid.addWidget(lb, 1, 0)
grid.addWidget(self.keyWordEdit, 2, 0)
grid.addWidget(self.OKButton, 5, 0)
grid.addItem(**spacerItem2** , 7, 0)
grid.addWidget(self.result, 0, 1, 8, 1)
grid.setColumnStretch(1, 4)
self.setLayout(grid)
|
How to package a python program with pyqt4 module by cxfreeze
Question: I wrote a program using PyQt4.QtGui and QtCore,I packaged it into exe,and it
works good on my computer,but it can't run on others' computer
**The error is this:**
cx_Freeze: Python error in main script
---------------------------
Traceback (most recent call last):
File "C:\Python33\lib\site-packages\cx_Freeze\initscripts\Console3.py", line 27, in <module>
File "baidu.py", line 6, in <module>
File "C:\Python\32-bit\3.3\lib\importlib\_bootstrap.py", line 1607, in _handle_fromlist
File "C:\Python\32-bit\3.3\lib\importlib\_bootstrap.py", line 313, in _call_with_frames_removed
File "C:\Python\32-bit\3.3\lib\importlib\_bootstrap.py", line 1558, in _find_and_load
File "C:\Python\32-bit\3.3\lib\importlib\_bootstrap.py", line 1525, in _find_and_load_unlocked
File "ExtensionLoader_PyQt4_QtGui.py", line 11, in <module>
ImportError: DLL load failed: 找不到指定的模块。
**The packaged files are:**
├─_bz2.pyd
├─_hashlib.pyd
├─_socket.pyd
├─_ssl.pyd
├─baidu.exe
├─icudt49.dll
├─icuin49.dll
├─icuuc49.dll
├─LIBEAY32.dll
├─libGLESv2.dll
├─lxml.etree.pyd
├─PyQt4.QtCore.pyd
├─PyQt4.QtGui.pyd
├─PyQt4.QtNetwork.pyd
├─python33.dll
├─Qt5Core.dll
├─Qt5Gui.dll
├─Qt5Network.dll
├─Qt5PrintSupport.dll
├─Qt5Widgets.dll
├─sip.pyd
├─SSLEAY32.dll
└─unicodedata.pyd
I just used "cxfreeze baidu.py --base-name=Win32GUI --target-dir d:\123" to
package it. I wonder if I missed some arguments when using cxfreeze result in
this problem,and how to package it to exe.Thank you
Answer: `d3dcompiler_43.dll` is needed to run pyqt
|
python how to access input params in MagicMock?
Question: I want to add a unit test for the function 'method_a':
def method_a(some_thing):
#some logic here
return update({'a':1}, request=some_thing)
def update(value, request):
if request:
return value.update({'b':2})
return value.update({'c':3})
Actually I don't care the logic of update method. All I want to do is to use
MagicMock or whatever tools to mock update method, and let it return the first
paramater of it received (In this case, should return {'a': 1}). How can I do
that?
Answer: You can use `patch` function. Here's an example:
from unittest import TestCase
from mock import patch
def method_a(some_thing):
#some logic here
return update({'a': 1}, request=some_thing)
def update(value, request):
if request:
return value.update({'b': 2})
return value.update({'c': 3})
class TestMethodA(TestCase):
def test_mocked_update(self):
with patch('%s.update' % __name__, lambda value, request: value):
self.assertEqual(method_a('test'), {'a': 1})
Hope that helps.
|
Memcached doesnt allow to cache item larger that 1mb limit even if it was overrided
Question: Using `python-memcached==1.48`
Terminal:
memcached -I 10m
Python:
Python 2.7.3 (default, Sep 26 2012, 21:51:14)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import memcache
>>> mc = memcache.Client(['127.0.0.1:11211'], debug=0)
>>> print(mc.set('test', ''.join(['a' for x in xrange(1*1024*1024+1)])))
0
>>> print(mc.set('test', ''.join(['a' for x in xrange(1*1024*1024)])))
True
Can anybody reproduce this actually?
Answer: You have to tell `python-memcache` what the maximum value size is before it
will accept values larger than 1MB:
import memcache
mc = memcache.Client(['127.0.0.1:11211'],
debug = 0,
server_max_value_length = 1024*1024*10
)
|
Why does my parallel performance top out?
Question: I've been playing around with Python a lot lately, and in comparing numerous
parallelization packages, I noticed that the performance increase from serial
to parallel seems to top out at 6 processes instead of 8--the number of cores
my MacBook Pro (OS X 10.8.2) has.
The attached plot compares the timing of different tasks as a function of
number of processes (parallel or sequential). This example is using the python
built-int
'[multiprocessing](http://docs.python.org/2/library/multiprocessing.html)'
package 'Memory' vs. 'Processor' refers to memory-intensive (just allocating
large arrays) vs. computationally intensive (many operations) functions.
What is the cause of the top-out below 8-processes?

(The 'Time's are averaged over 100 function calls for each number of
processes)
import multiprocessing as mp
import time
import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt
iters = 100
mem_num = 1000
pro_num = 20000
max_procs = 10
line_width = 2.0
legend_size = 10
fig_name = 'timing.pdf'
def UseMemory(num):
test1 = np.zeros([num,num])
test2 = np.arange(num*num)
test3 = np.array(test2).reshape([num, num])
test4 = np.empty(num, dtype=object)
return
def UseProcessor(num):
test1 = np.arange(num)
test1 = np.cos(test1)
test1 = np.sqrt(np.fabs(test1))
test2 = np.zeros(num)
for i in range(num): test2[i] = test1[i]
return np.std(test2)
def MemJob(its):
for ii in range(its): UseMemory(mem_num)
def ProJob(its):
for ii in range(iters): UseProcessor(pro_num)
if __name__ == "__main__":
print '\nParTest\n'
proc_range = np.arange(1,max_procs+1,step=1)
test_times = np.zeros([len(proc_range),2,2]) # test_times[num_procs][0-ser,1-par][0-mem,1-pro]
tot_times = np.zeros([len(proc_range),2 ]) # tot_times[num_procs][0-ser,1-par]
print ' Testing %2d numbers of processors between [%d,%d]' % (len(proc_range), 1, max_procs)
print ' Iterations %d, Memory Length %d, Processor Length %d' % (iters, mem_num, pro_num)
for it in range(len(proc_range)):
procs = proc_range[it]
job_arg = procs*[iters]
print '\n - %2d, Processes = %3d' % (it, procs)
# --- Test Serial ---
print ' - - Serial'
# Test Memory
all_start = time.time()
start = time.time()
map(MemJob, [procs*iters])
ser_mem_time = time.time() - start
# Test Processor
start = time.time()
map(ProJob, job_arg)
ser_pro_time = time.time() - start
ser_time = time.time() - all_start
# --- Test Parallel : multiprocessing ---
print ' - - Parallel: multiprocessing'
pool = mp.Pool(processes=procs)
# Test Memory
all_start = time.time()
start = time.time()
pool.map(MemJob, job_arg)
par_mem_time = time.time() - start
# Test Processor
start = time.time()
pool.map(ProJob, job_arg)
par_pro_time = time.time() - start
par_time = time.time() - all_start
print ' - - Collecting'
ser_mem_time /= procs
ser_pro_time /= procs
par_mem_time /= procs
par_pro_time /= procs
ser_time /= procs
par_time /= procs
test_times[it][0] = [ ser_mem_time, ser_pro_time ]
test_times[it][1] = [ par_mem_time, par_pro_time ]
tot_times[it] = [ ser_time , par_time ]
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlabel('Number of Processes')
ax.set_ylabel('Time [s]')
ax.xaxis.grid(True)
ax.yaxis.grid(True)
lines = []
names = []
l1, = ax.plot(proc_range, test_times[:,0,0], linewidth=line_width)
lines.append(l1)
names.append('Serial Memory')
l1, = ax.plot(proc_range, test_times[:,0,1], linewidth=line_width)
lines.append(l1)
names.append('Serial Processor')
l1, = ax.plot(proc_range, tot_times[:,0], linewidth=line_width)
lines.append(l1)
names.append('Serial')
l1, = ax.plot(proc_range, test_times[:,1,0], linewidth=line_width)
lines.append(l1)
names.append('Parallel Memory')
l1, = ax.plot(proc_range, test_times[:,1,1], linewidth=line_width)
lines.append(l1)
names.append('Parallel Processor')
l1, = ax.plot(proc_range, tot_times[:,1], linewidth=line_width)
lines.append(l1)
names.append('Parallel')
plt.legend(lines, names, ncol=2, prop={'size':legend_size}, fancybox=True, shadow=True, bbox_to_anchor=(1.10, 1.10))
fig.savefig(fig_name,dpi=fig.get_dpi())
print ' - Saved to ', fig_name
plt.show(block=True)
Answer: From the discussion above I think you have the information you need, but I'm
adding an answer to collect facts in case it benefits others (plus I wanted to
work it through myself). (Due credit to @bamboon who mentioned some of this
first.)
First, your MacBook has a CPU with four physical cores, but the design of the
chip is such that each core's hardware has the ability to run two threads.
This is called "simultaneous multithreading" (SMT) and in this case is
embodied by Intel's [hyperthreading](https://en.wikipedia.org/wiki/Hyper-
threading) feature. So taken all together you have 8 "virtual cores" (4 + 4 =
8).
Note that the OS treats all the virtual cores the same, i.e. it does not
distinguish between the two SMT threads offered by a physical core, and that's
why `sysctl` returns 8 when you query it. Python will do the same thing:
>>> import multiprocessing
>>> multiprocessing.cpu_count()
8
Second, the speedup limit you're encountering is a well-known phenomenon in
which parallel performance saturates and does not improve with the addition of
more processors working on the problem. This effect is described by [Amdahl's
Law](http://en.wikipedia.org/wiki/Amdahl%27s_law), a quantitative statement
about how much speedup to expect from multiple processors depending on how
much code can be parallelized and how much runs serially.
Typically a number of factors limit relative speedup, including details of the
OS and even the computer's architecture (e.g. how SMT works in a hardware
core), so that even if you parallelize as much of your code as you can, your
performance will not scale indefinitely. Understanding where the serial
bottleneck is can require very detailed analysis of your program and its
running environment.
You can find a good example with discussion in [this
question](http://superuser.com/questions/279629/how-much-speedup-does-a-hyper-
thread-give-in-theory/).
I hope this helps.
|
Opening multiple python files from folder
Question: I am trying to take a folder which contains 9 files, each containing FASTA
records of separate genes, and remove duplicate records. I want to set it up
so that the script is called with the folder that contains the genes as the
first parameter, and a new folder name to rewrite the new files without
duplicates to. However, if the files are stored in a folder called results
within the current directory it is not letting me open any of the gene files
within that folder to process them for duplicates. I have searched around and
it seems that I should be able to call python's open() function with a string
of the file name like this:
`input_handle = open(f, "r")`
This line is not allowng me to open the file to read its contents, and I think
it may have something to do with the type of f, which shows to be type 'str'
when I call type(f)
Also, if I use the full path:
`input_handle = open('~/Documents/Research/Scala/hiv-biojava-
scala/results/rev.fa', "r")`
It says that no such file exists. I have checked my spelling and I am sure
that the file does exist. I also get that file does not exist if I try to call
its name as a raw string:
`input_handle = open(r'~/Documents/Research/Scala/hiv-biojava-
scala/results/rev.fa', "r")`
Or if I try to call it as the following it says that no global results exists:
`input_handle = open(os.path.join(os.curdir,results/f), "r")`
Here is the full code. If anybody knows what the problem is I would really
appreciate any help that you could offer.
#!/usr/bin/python
import os
import os.path
import sys
import re
from Bio import SeqIO
def processFiles(files) :
for f in files:
process(f)
def process(f):
input_handle = open(f, "r")
records = list(SeqIO.parse(input_handle, "fasta"))
print records
i = 0
while i < len(records)-1:
temp = records[i]
next = records[i+1]
if (next.id == temp.id) :
print "duplicate found at " + next.id
if (len(next.seq) < len(temp.seq)) :
records.pop(i+1)
else :
records.pop(i)
i = i + 1
output_handle = open("out.fa", "w")
for record in records:
SeqIO.write(records, output_handle, "fasta")
input_handle.close()
def main():
input_folder = sys.argv[1]
out_folder = sys.argv[2]
if os.path.exists(out_folder):
print("Folder %s exists; please specify empty folder or new one" % out_folder)
sys.exit(1)
os.makedirs(out_folder)
files = os.listdir(input_folder)
print files
processFiles(files)
main()
Answer: Try `input_handle = open(os.path.join(os.getcwd,results/f), "r")`. `os.curdir`
returns `.` See mail.python.org/pipermail/python-
list/2012-September/631864.html.
|
Creating a regular expression in django
Question: New to Django so I'm unsure how to achieve the following...
I have this regular expression
"@£$¥èéùìòÇ\fØø\nÅåΔ_ΦΓΛΩΠΨΣΘΞÆæßÉ !\"#¤%&'()*+,-./[0-9]:;<=>\?¡[A-Z]ÄÖÑܧ¿[a-z]äöñüà\^\{\}\[~\]\|€"
I have this function:
def validate_GSM_characters(value):
""" Raise a ValidationError if the value contains any values not within
the GSM character set.
"""
msg = u"Invalid characters."
raise ValidationError(msg)
At the moment it does nothing, but I need to know how in Django/Python a regex
function that allows me to check value. I did a Google search and can only
seem to find articles relating to model validation.
Answer: Just use the expression with the `re` module:
import re
yourrule = re.compile(r"@£$¥èéùìòÇ\fØø\nÅåΔ_ΦΓΛΩΠΨΣΘΞÆæßÉ !\"#¤%&'()*+,-./[0-9]:;<=>\?¡[A-Z]ÄÖÑܧ¿[a-z]äöñüà\^\{\}\[~\]\|€")
def validate_GSM_characters(value):
""" Raise a ValidationError if the value contains any values not within
the GSM character set.
"""
if not yourrule.search(value):
msg = u"Invalid characters."
raise ValidationError(msg)
You could also just use a
[`RegexValidator`](https://docs.djangoproject.com/en/dev/ref/validators/#regexvalidator);
simply pass it your expression and your message, then use that instead of the
above function.
|
Neo4J - Simple "follower" graph
Question: I'm attempting to create a simple Twitter-esque "follower / friend" graph
using Neo4J and Python. The graph would look something like
user_1 FOLLOWS user_2
user_1 FOLLOWS user_3
user_2 FOLLOWS user_1
After a day of reading I thought it best to dive straight in using the REST
interface and, since I'm using Python, py2neo. Here is my code:
from py2neo import neo4j
def main():
g = neo4j.GraphDatabaseService()
# Create an index for our user nodes
index = g.get_or_create_index(neo4j.Node, "user")
# Create a single node, User 1
node = index.get_or_create("user", "User_1", {"id": "User_1"})
# Populate the graph with some more users just for testing
nodes = []
for user in ["User_2", "User_3", "User_4", "User_5"]:
nodes.append( index.get_or_create("user", user, {"id":user}) )
# Create a relationship between User_1 and User_2
g.get_or_create_relationships( (node, "FOLLOWS", nodes[0]) )
if __name__ == '__main__':
main()
As you can see, I'm using get_or_create_relationships to prevent duplicate
relationships and when adding thousands of nodes I'm assuming this is going to
incur some kind of overhead.
Using straight up "node.create_relationship_to(nodes[0], "FOLLOWERS")" seems
to create duplicate relationships each time the script is run which for a
graph db newbie confuses me slightly since the relationship is exactly the
same.
The likelihood of creating duplicate relationships is very low but in the
event it were to happen, would this cause issues with graph traversal? Should
I be indexing my FOLLOWS index with some kind of unique function?
Answer: I would use cypher `CREATE UNIQUE` to only create a FOLLOWs releationship if
there is none existing, see <http://docs.neo4j.org/chunked/milestone/query-
create-unique.html>
Would that work?
|
How to get file names from Web directory - Python code
Question: I would like to know how to get a list of filenames (.jpg image files) that
are stored on a server.
I am looking for code which stores all the filenames (with their extension) in
an Excel table or in the CSV format.
Any tips will be very helpful.
Answer: It's pretty easy to get the filenames of all files stored in a certain folder,
and you can easily write it in a file (in whatever format you want) :
import os
filenames = os.listdir('path to directory')
logFile = open('filenames.txt')
for name in filenames:
logFile.write(filename)
logFile.close()
You must execute this code on your server, so make sure you can execute Python
code on it.
Once that's done, you can retrieve it from your server using the `urllib2`
module : [How do I download a file over HTTP using
Python?](http://stackoverflow.com/questions/22676/how-do-i-download-a-file-
over-http-using-python)
|
Python: custom logging across all modules
Question: **Task**
I have a collection of scripts and I'd like them to produce unified logging
messages with minimum alterations to modules doing logging the actual
messages.
I've written a small module 'custom_logger' which I plan to call from the main
application once, have it return a logger, which I'd then continue using.
The submodules I'd be importing into the app should only (or rather I wish
them to)
* should only "import logging as log" - so that nothing specific to my site is required to make them just run if someone else finds them useful.
* should just log messages with log.info/error('message') without adding anything site-specific to them
* should use the already configured 'root' logger with all its formatting and handers and not affect the root logger's configuration
*custom_logger.py*
import logging
import logging.handlers
import os
import sys
def getLogger(name='root', loglevel='INFO'):
logger = logging.getLogger(name)
# if logger 'name' already exists, return it to avoid logging duplicate
# messages by attaching multiple handlers of the same type
if logger.handlers:
return logger
# if logger 'name' does not already exist, create it and attach handlers
else:
# set logLevel to loglevel or to INFO if requested level is incorrect
loglevel = getattr(logging, loglevel.upper(), logging.INFO)
logger.setLevel(loglevel)
fmt = '%(asctime)s %(filename)-18s %(levelname)-8s: %(message)s'
fmt_date = '%Y-%m-%dT%T%Z'
formatter = logging.Formatter(fmt, fmt_date)
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger.addHandler(handler)
if logger.name == 'root':
logger.warning('Running: %s %s',
os.path.basename(sys.argv[0]),
' '.join(sys.argv[1:]))
return logger
Then comes the submodule which has a few test messages with examples of what
works and what doesn't.
_submodule.py_
import sys
import custom_logger
import logging
class SubClass(object):
def __init__(self):
# NOK (no idea why since by default (no name parameter), it should return the root logger)
#log = logging.getLogger()
#log.info('message from SubClass / __init__')
# OK (works as expected)
#log = logging.getLogger('root')
#log.info('message from SubClass / __init__')
# OK (works as expected)
log = custom_logger.getLogger('root')
log.info('message from SubClass / __init__')
def SomeMethod(self):
# OK but I'd have to define `log` for every method, which is unacceptable
# Please see question below all code snippets
log = custom_logger.getLogger('root')
log.info('message from SubClass / SomeMethod')
And the main app: _app.py_ Nothing special here:
#!/usr/bin/python
import custom_logger
import submodule
log = custom_logger.getLogger('root', loglevel='DEBUG')
log.debug('debug message')
log.info('info message')
log.warning('warning message')
log.error('error message')
a = submodule.SubClass() # this should produce a log message
a.SomeMethod() # so should this
Output that I'm after and that I'm getting, just in an exteremely ugly way:
% ./app.py
2013-04-08T03:07:46BST custom_logger.py WARNING : Running: app.py
2013-04-08T03:07:46BST app.py DEBUG : debug message
2013-04-08T03:07:46BST app.py INFO : info message
2013-04-08T03:07:46BST app.py WARNING : warning message
2013-04-08T03:07:46BST app.py ERROR : error message
2013-04-08T03:07:46BST submodule.py INFO : message from SubClass / __init__
2013-04-08T03:07:46BST submodule.py INFO : message from SubClass / SomeMethod
I want to be able to define a logger in the app.py and then in the submodules
only use the standard Python logging library to make use of an already
configured logger in the app.py.
Also, an ugly workaround: if I place the below code after the imports in
submodule.py:
log = custom_logger.getLogger('root')
it will be executed before my logger is configured in app.py, effectively
making the submodule, not my app configure logging.
Another workaround I considered: within the constuctor of the SubClass class,
I could define
`self.log = custom_logger.getLogger('root')`
and then use self.log.error('some error'). There must be a nicer way - if you
can suggest something useful or point out where I misunderstood the
documentation, I'd be very grateful!
PS. I've spent quite a bit reading the Python logging howto (basic and
advanced) and the cookbook so if I've missed something useful there, please
point it out.
Thank you!
Answer: If you want to change root logger you could just use `getLogger()` everywhere,
with no arguments.
Regarding the instance setup only in the main module, you can instantiate your
logger, add your own Handler, and use it in all the other submodules (as I did
bellow).
I created a class that inherits the StreamHandler in `custom_logger.py`:
class MyHandler(logging.StreamHandler):
def __init__(self):
logging.StreamHandler.__init__(self)
fmt = '%(asctime)s %(filename)-18s %(levelname)-8s: %(message)s'
fmt_date = '%Y-%m-%dT%T%Z'
formatter = logging.Formatter(fmt, fmt_date)
self.setFormatter(formatter)
Then, in `submodule.py`, I put the getLogger after the imports and commented
it in the methods:
import sys
import logging
log = logging.getLogger('root')
class SubClass(object):
def __init__(self):
log.info('message from SubClass / __init__')
def SomeMethod(self):
log.info('message from SubClass / SomeMethod')
Then, in app.py I created a Logger instance (that will be the same in all
modules) and added my handler, which formats the output:
#!/usr/bin/python
import logging
import custom_logger
import submodule
log = logging.getLogger('root')
log.setLevel('DEBUG')
log.addHandler(custom_logger.MyHandler())
log.debug('debug message')
log.info('info message')
log.warning('warning message')
log.error('error message')
a = submodule.SubClass() # this should produce a log message
a.SomeMethod() # so should this
Output:
./app.py
2013-04-08T15:20:05EEST app.py DEBUG : debug message
2013-04-08T15:20:05EEST app.py INFO : info message
2013-04-08T15:20:05EEST app.py WARNING : warning message
2013-04-08T15:20:05EEST app.py ERROR : error message
2013-04-08T15:20:05EEST submodule.py INFO : message from SubClass / __init__
2013-04-08T15:20:05EEST submodule.py INFO : message from SubClass / SomeMethod
|
run python script as cgi apache server
Question: I am trying to make a python script run as cgi, using an Apache server. My
script looks something like this:
#!/usr/bin/python
import cgi
if __name__ == "__main__":
print("Content-type: text/html")
print("<HTML>")
print("<HEAD>")
I have done the necessary configurations in httpd.conf(in my opinion):
<Directory "/opt/lampp/htdocs/xampp/python">
Options +ExecCGI
AddHandler cgi-script .cgi .py
Order allow,deny
Allow from all
</Directory>
I have set the execution permission for the script with chmod
However, when I try to access the script via localhost i get an Error 500:End
of script output before headers:script.py What could be the problem? The
script is created in an Unix like environment so I think the problem of clrf
vs lf doesn't stand. Thanks a lot.
Answer: I think you are missing a print statement after
print("Content-type: text/html")
The output of a CGI script should consist of two sections, separated by a
blank line. The first section contains a number of headers, telling the client
what kind of data is following.
The second section is usually HTML, which allows the client software to
display nicely formatted text with header, in-line images, etc.
It may look like
#!/usr/bin/env python
print "Content-Type: text/html"
print
print """
<TITLE>CGI script ! Python</TITLE>
<H1>This is my first CGI script</H1>
Hello, world!
"""
For more details visit [python-cgi](http://docs.python.org/2/library/cgi.html)
For python3
#!/usr/bin/env python3
print("Content-Type: text/html")
print()
print ("""
<TITLE>CGI script ! Python</TITLE>
<H1>This is my first CGI script</H1>
Hello, world!
"""
)
|
Special characters in audio devices name : Pyaudio
Question: I'm currently facing a hard problem. I need to use Pyaudio on a french windows
environnement and the name of the audio devices contains `é` or `è` by
default.
This is the error I get when a special character is present:
u=self.p.get_device_info_by_index(e)
File "C:\Python27\lib\site-packages\pyaudio.py", line 977, in get_device_info_
by_index
pa.get_device_info(device_index)
File "C:\Python27\lib\site-packages\pyaudio.py", line 987, in _make_device_inf
o_dictionary
print device_info.name
UnicodeDecodeError: 'utf8' codec can't decode byte 0xe9 in position 13: invalid
continuation byte
This wouldn't be a problem if I could access the code (I would need to add a
u"..." in front of the string chain I guess).
The problem is that I looked inside the Pyaudio code and the method causing
the bug is defined in an pyd file (_portaudio.pyd), therefor, I can't modify
it!
I tried to download _portaudio to compile it myself, but the distribution I
found is coded in C and quite heavy (I don't know the first thing about C).
Maybe I could do something there but I don't know exactly where and how.
I could also handle the problem by just commenting the line getting the name
of the audio devices, but it's much harder to identify a specific audio input
without its name to show to the user.
EDIT :
Here is the overall process : I call the function from pyaudio :
import pyaudio
self.p= pyaudio.PyAudio()
i=self.p.get_device_count()
for e in range(i):
u=self.p.get_device_info_by_index(e)
This will lead me into the pyaudio module which calls the method :
device_info.name
device_info being an object defined in _portaudio.pyd. Since the name of
particular audio devices contain "é" or "è" (Thank you windows), and the
_portaudio.pyd is not encoded to handle those characters. It returns the error
:
UnicodeDecodeError: 'utf8' codec can't decode byte 0xe9 in position 13: invalid
continuation byte
Answer: I'm facing exactly the same problem. In my case, there are Chinese charactors
in the name of audio device, and UnicodeDecodeError occured when I `print
device_info.name`
Here is my solution.
Use [pymedia](http://pymedia.org/docs/pymedia.audio.sound.html) instead of
pyaudio. Try this:
>>> import pymedia
>>> dict_list = pymedia.audio.sound.getIDevices()
>>> print dict_list
({'name': '\xc2\xf3\xbf\xcb\xb7\xe7 (Realtek High Definition', 'channels': 2, 'manufId': '1', 'formats': 1048575, 'id': 0, 'productId': '65'},)
>>> dict_list = pymedia.audio.sound.getODevices()
>>> print dict_list
({'name': '\xd1\xef\xc9\xf9\xc6\xf7 (MV USB AUDIO)', 'channels': 2, 'manufId': 'ffff', 'formats': 1048575, 'id': 0, 'productId': 'ffff'}, {'name': '\xd1\xef\xc9\xf9\xc6\xf7 (Realtek High Definition', 'channels': 2, 'manufId': '1', 'formats': 1048575, 'id': 1, 'productId': '64'})
I'm using python 2.7 .
|
Python: splitting a complex string including parentheses and |
Question: In a test file, I have records in the form
DATA(VALUE1|VALUE2||VALUE4)
and so on.
I'd like to split this string in two passes, the first yielding "DATA", and
the second giving me what's inside the parentheses, split at the "|". The
second part looks trivial, but so far my attempts at the first were ugly.
I'm more inclined towards regex than parsing as lines are quite simple in the
end.
Answer: Another suggestion:
>>> s = "DATA(VALUE1|VALUE2||VALUE4)"
>>> import re
>>> matches = re.findall("[^()]+", s)
>>> matches
['DATA', 'VALUE1|VALUE2||VALUE4']
>>> result = {matches[0]: matches[1].split("|")}
>>> result
{'DATA': ['VALUE1', 'VALUE2', '', 'VALUE4']}
|
Python extract values from JSON
Question: I'm looking to extract sets of values from a JSON and write them to a file.
The format of the JSON is as follows:
"interactions": [
{
"type": "free",
"input": [
[ 1, 4594, 119218, 0, [71, 46], [2295, 1492], [71, 46], [2295, 1492], 16017, 520790446, [71, 46, 71, 46], [71, 46, 71, 46] ],
[ 1, 4594, 119219, 0, [72, 46], [2323, 1492], [72, 46], [2323, 1492], 26016, 520790456, [72, 46, 72, 46], [72, 46, 72, 46] ],
[ 1, 4594, 119220, 0, [72, 45], [2323, 1464], [72, 45], [2323, 1464], 26016, 520790466, [72, 45, 72, 45], [72, 45, 72, 45] ],
[ 1, 4594, 119221, 0, [72, 45], [2323, 1464], [72, 45], [2323, 1464], 26016, 520790476, [72, 45, 72, 45], [72, 45, 72, 45] ],
[ 1, 4594, 119222, 0, [73, 45], [2350, 1464], [73, 45], [2350, 1464], 26016, 520790486, [73, 45, 73, 45], [73, 45, 73, 45] ],
[ 1, 4594, 119223, 0, [73, 45], [2350, 1464], [73, 45], [2350, 1464], 26016, 520790496, [73, 45, 73, 45], [73, 45, 73, 45] ],
[ 1, 4594, 119224, 0, [73, 45], [2350, 1464], [73, 45], [2350, 1464], 46000, 520790506, [73, 45, 73, 45], [73, 45, 73, 45] ]
]
What I need to extract, is the [71, 46] column, and then the column which
starts with 520790446, and write it to an output file.
Below is the code I've got at the minute:
import json
json_data = open("test_json.json")
data = json.load(json_data)
json_data.close()
# Need some sort of nested loop here to iterate through each line of the block, and each block also.
print data["interactions"][0]["input"][0][4], '\t', data["interactions"][0]["input"][0][9]
There are several of these blocks of variable length, and I need to extract
all the values until the end of the file. I'm stuck at the loop structure
though.
Could anyone be of assistance?
Answer: You can get at the data like so:
[x[4] for x in data["interactions"][0]["input"]]
[x[9] for x in data["interactions"][0]["input"]]
or in one go, something like
[[x[4], x[9]] for x in data["interactions"][0]["input"]]
To answer the first part of the comment:
[[x[4], x[9]] for x in interaction["input"] for interaction in data["interactions"]]
|
installing my first WSGI
Question: I am installing a flask app with apache modewsgi.
I have solved multiple troubles already: \- environment variables \-
virtualenv \- file permissions
But now I am really stuck with application name. I have no idea what to write
in the "from" directive of WSGI file.
here is my ~user/appname.com/appname.com.wsgi
activate_this = '/home/user/appname.com/venv/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))
import sys
sys.path.insert(0, '/home/user/appname.com')
from appname.com import app as application
which causes the following log.
[Mon Apr 08 15:50:26 2013] [error] [client 64.120.6.170] mod_wsgi (pid=6392): Exception occurred processing WSGI script '/home/user/appname.com/appname.com.wsgi'.
[Mon Apr 08 15:50:26 2013] [error] [client 64.120.6.170] Traceback (most recent call last):
[Mon Apr 08 15:50:26 2013] [error] [client 64.120.6.170] File "/home/user/appname.com/appname.com.wsgi", line 5, in <module>
[Mon Apr 08 15:50:26 2013] [error] [client 64.120.6.170] from appname.com import app as application
[Mon Apr 08 15:50:26 2013] [error] [client 64.120.6.170] ImportError: No module named appname.com
However if I remove the the from `appname.com` I can run the .wsgi from python
commandline without error but within apache, it throws the error below...
[Mon Apr 08 15:27:31 2013] [error] [client 64.120.6.170] mod_wsgi (pid=6274): Exception occurred processing WSGI script '/home/user/appname.com/appname.com.wsgi'.
[Mon Apr 08 15:27:31 2013] [error] [client 64.120.6.170] TypeError: 'module' object is not callable
_UPDATE:_
Here is a structure of ~user/appname.com/
app/
controller.py
__init__.py
models.py
...
static/
...
templates/
config.py
Procfile
README
requirements.txt
run.py
appname.com.wsgi
Answer: Because of how you have structured your directories, you would need to add:
* /home/user
to sys.path.
To explain what the second error is, would need to see what is in 'com.py'.
I would suggest though that it is a very bad idea to name your directory
'appname.com'. The presence of the '.' in the directory name will confuse
Python.
|
segmentation fault in python
Question: How can I run the following program in python 2.7.3
import sys
sys.setrecursionlimit(2 ** 20)
def f(x):
if (x==0): return 0
else: return f(x-1)+1
print f(200000)
This code receives segmentation fault in Ubuntu.
Answer: The Python interpreter runs out of stack space. Like any other process in the
same situation, it is getting killed by the operating system.
You could try increasing the OS stack size limit (`ulimit -c`).
A better approach might be to rewrite your code so that it does not require
recursion this deep (your particular example can be trivially converted into
iteration).
|
Accessing python parent folder
Question: I've looked through previous answers which seem to suggest I should be able to
use:
from .. import code
though it produces this: ValueError: Attempted relative import beyond toplevel
package
though this doesn't seem to be working. My file structure is as follows:
scraper/
__init__.py
bot/
scraper.py
__init__.py
wigan/
council.py
__init__.py
I'm able to from scraper load council using:
from wigan import council
though from council, none of the following work when trying to load
scraper.py:
from .. import scraper
from scraper.bot import scraper
from scraper.bot.scraper import scraper
Any help would be great. Thanks :-)
Answer: I suspect the problem you're having is that you're running a script that is
located in package. This is one of the most awkwardly supported features in
Python. When you run a script directly, it puts your current path at the start
of the Python search path. If you're inside of a package though, this will be
wrong.
To properly run `scrapper.py` (if that's your script), you should change to
the top level folder (whatever is above `scrapper/`), then run `python -m
scrapper.bot.scrapper`.
Or, if you add that top level folder to the Python search path, either by
using the `PYTHONPATH` environment variable, or by installing it (or an
appropriate `.pth` file) into the `site-packages` folder, then the current
directory restriction will be relaxed and you can run the script from
anywhere.
There are other issues with running modules as scripts if you're also going to
import them by name from other modules. The script will be imported as
`__main__`, not as its actual name. If you import it by name too, you'll get a
second copy of the script, which may mean it doesn't work as intended (if
there is any global state in the module, it may be inconsistent between the
copies). This is one reason it is often suggested that scripts do as little
work as possible (just import something from another module, and then run it).
You may want to refactor your code to do this too.
|
Getting a lists of times in Python from 0:0:0 to 23:59:59 and then comparing with datetime values
Question: I was working on code to generate the time for an entire day with 30 second
intervals. I tried using DT.datetime and DT.time but I always end up with
either a datetime value or a timedelta value like (0,2970). Can someone please
tell me how to do this.
So I need a list that has data like:
[00:00:00] [00:00:01] [00:00:02]
till [23:59:59] and needed to compare it against a datetime value like
6/23/2011 6:38:00 AM.
Thanks!
Answer: There's a great [answer](http://stackoverflow.com/a/9736260/196068) on how to
get a list of incremental values for seconds for a 24-hour day. I reused a
part of it.
* **Note 1**. I'm not sure how you're thinking of comparing `time` with `datetime`. Assuming that you're just going to compare the time part and extracting that.
* **Note 2**. The `time.strptime` call expects a 12-hour AM/PM-based time, as in your example. Its result is then passed to `time.strftime` that returns a 24-hour-based time.
Here's what I think you're looking for:
my_time = '6/23/2011 6:38:00 AM' # time you defined
from datetime import datetime, timedelta
from time import strftime, strptime
now = datetime(2013, 1, 1, 0, 0, 0)
last = datetime(2013, 1, 1, 23, 59, 59)
delta = timedelta(seconds=1)
times = []
while now <= last:
times.append(now.strftime('%H:%M:%S'))
now += delta
twenty_four_hour_based_time = strftime('%H:%M:%S', strptime(my_time, '%m/%d/%Y %I:%M:%S %p'))
twenty_four_hour_based_time in times # returns True
|
Game Development in Python, ruby or LUA?
Question: I have experience in game development in some game engines in Action Script 3
and C++. However, I would like to improve the productivity and so I want to
develop a new project in Python, ruby or LUA. Would it be a good idea? If yes,
which one would you suggest? and what is the killer game development tool set
or engine?
Answer: If you're any good, go with [Pyglet](http://www.pyglet.org/).
It's a cross-platform Python version independent hook against OpenGL with
outstanding performance. It's a bit tricky but it does the job better than
anything else out there in the Python world.
If you're a beginner, i'd go with [Pygame](http://www.pygame.org/).
It's a bit taxing on the system but with a modern computer that isn't a
issue.. also, it got pre-packaged API's for game development (hence the name)
:)
A "official" list of Python gaming/graphic engines:
<http://wiki.python.org/moin/PythonGames>
Some good ones:
* Panda3D
* Pyglet
* PyGame
* Blender3D
# Example Pyglet code:
#!/usr/bin/python
import pyglet
from time import time, sleep
class Window(pyglet.window.Window):
def __init__(self, refreshrate):
super(Window, self).__init__(vsync = False)
self.frames = 0
self.framerate = pyglet.text.Label(text='Unknown', font_name='Verdana', font_size=8, x=10, y=10, color=(255,255,255,255))
self.last = time()
self.alive = 1
self.refreshrate = refreshrate
self.click = None
self.drag = False
def on_draw(self):
self.render()
def on_mouse_press(self, x, y, button, modifiers):
self.click = x,y
def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
if self.click:
self.drag = True
print 'Drag offset:',(dx,dy)
def on_mouse_release(self, x, y, button, modifiers):
if not self.drag and self.click:
print 'You clicked here', self.click, 'Relese point:',(x,y)
else:
print 'You draged from', self.click, 'to:',(x,y)
self.click = None
self.drag = False
def render(self):
self.clear()
if time() - self.last >= 1:
self.framerate.text = str(self.frames)
self.frames = 0
self.last = time()
else:
self.frames += 1
self.framerate.draw()
self.flip()
def on_close(self):
self.alive = 0
def run(self):
while self.alive:
self.render()
# ----> Note: <----
# Without self.dispatc_events() the screen will freeze
# due to the fact that i don't call pyglet.app.run(),
# because i like to have the control when and what locks
# the application, since pyglet.app.run() is a locking call.
event = self.dispatch_events()
sleep(1.0/self.refreshrate)
win = Window(23) # set the fps
win.run()
* * *
# Note on Pyglet with Python 3.X:
You'll have to download the **1.2alpha1** otherwise it will complain about you
not having Python3.X installed :)
|
Using C datatypes with ctypes in python
Question: I tried to use C char pointer datatype in python 3.3. I used following code:
from ctypes import *
firstname = c_char_p("I am a noob programmer".encode("utf-8"))
print(firstname.value)
My desired output was
I am a noob programmer
but what I got was
b'I am a noob programmer'
I am following a tutorial made for python 2.6. I used "ascii" as the parameter
for encode function. And also tried the "bytes()" instead of encode. But no
difference at either time.Why don't I get my desired output? and How can I get
the output as desired.
Please anybody help me to understand..
Answer: In Python 3 you need to decode it back to `str` if you want it to behave like
`str`.
print(firstname.value.decode("utf-8"))
|
Graphs in xlsx File overwrite by openpyxl
Question: We need to update xlsx sheet using python script which do some calcualtion and
update one worksheet. I choose openpyxl as it supoort writing/updating xlsx
File. In the Excel sheet contain some graphs also but When I update excel
sheet than graph does not work into excel and data update respectively. I
think we had some issue for updating graph with openpyxl.Can anyone provide me
some input to fix this issue
or In other word,In the Excel sheet I have 10 worksheet.In worksheet 1, it
contain graphs. I have updated worksheet number 5. Worksheet is updated
successfully. But I have loose the graphs of worksheet 1.
#!/usr/bin/env python
from openpyxl import load_workbook
import openpyxl
print "pylx"
ddr_sam45_flop = "Flip_Flop.xlsx"
flop_workbook = load_workbook(ddr_sam45_flop)
raw_flop_workbook = flop_workbook.get_sheet_by_name(name ='RAW')
raw_flop_workbook.cell(row = 1 , column = 1).value = 889999
flop_workbook.save(ddr_sam45_flop)
print "End"
(Please consider me new to openpyxl)
Answer: Openpyxl does not support graphs or chart as of now
|
Basic Python programming, calculating probabilities of random locations falling within regions using arrays of random locations
Question: Consider a 100X100 array.
* Generate an array of several thousand random locations within such an array, e.g. (3,75) and (56, 34).
* Calculate how often one of your random locations falls within 15 pixels of any of the (straight) edges
(I have done these two parts above) But I need help doing:
1. Calculate how often one of your random locations falls within (either side) 15 pixels of a circle with a radius of 50 pixels, and write the result to the screen e.g. On average N% of the locations in the array fall in this region [N being a number between 0 and 100] Note that coordinates in the corners are within 15 pixels of the circle, then they should be included in this (if they are are more than 15 pixels away, then they shouldn’t be).
2. Add code that requests a location within your array from the user and then alerts them if that location falls that region, e.g. Warning: your chosen location falls near the edge of the circle.
How do I go about doing this? I already have my array of random locations from
using this code:
from pylab import *
import math as m
from numpy import *
from random import randrange
N = 3000
coords_array = array([randrange(100) for _ in range(2 * N)]).reshape(N, 2)
So how do I go about doing parts (1) and (2)? I was thinking of using a
boolean expression (if, or) to do it, but i am not sure at all if it would
even work, and if it would how to do it.
Answer: This isn't a homework question, is it?
To deal with the circle business, I would begin with a check to see that the
point does not fall within the off-limits area. If your circle is centered at
(0,0), then the off-limits area is `35 <= x**2 + y**2 <= 65`
|
displaying files from a directory using Bootstrap Carousel
Question: I am new to JavaScript and started experimenting with Bootstrap Carousel. I
wrote test code that works and displays images when I manually create the
Carousel items, e.g
<div id="myCarousel" class="carousel slide" data-interval="false">
<div class="carousel-inner">
<div class="item active">
<img src="img/1.jpg"/>
</div>
<div class="item">
<img src="img/2.jpg"/>
</div>
<div class="item">
<img src="img/3.jpg"/>
</div>
</div><!-- .carousel-inner -->
</div><!-- .carousel -->
However, what I would like to do is to specify a local directory and be able
to automatically load and view the images there, that is create the list of
Carousel items automatically.
My questions are:
* How can I do this with scripting, e.g. using perl or python to get the list of files in the directory? How do I pass this list to Carousel in JS?
* Googling, I found that HTML5 has a File API that enables JS to access the local file system. How can I do the above using this approach?
Thanks!
Answer: Just make a loop in your choice of language that reads the contents of a
directory and outputs the HTML.
e.g. in python
import os
dirname = 'img'
html = '<div id="myCarousel" class="carousel slide" data-interval="false">\n\t<div class="carousel-inner">'
active = "active"
for filename in os.listdir(dirname):
if ".jpg" in filename:
html = html + '\n\t\t<div class="item %s"><img src="%s"/></div>' % (active, dirname + "/" + filename)
active = ""
html = html + '</div><!-- .carousel-inner -->\n</div><!-- .carousel -->'
then obviously you need to do something with the html variable like write it
to a file
|
how to run my own external command in python script
Question: I wanna to run my own non-system external commands in python.
Such as "sudo insteon on 23". Subprocess and os.system are designed for system
calls.
Does anybody know how to do it?
Thanks
Answer: You can use
[subprocess.Popen](http://docs.python.org/2/library/subprocess.html#using-the-
subprocess-module) for this:
import shlex
import subprocess
proc = subprocess.Popen(shlex.split('sudo insteon on 23'))
proc.communicate()
|
python pexpect: SSHing then updating the date
Question: I have finally have my python pexpect script working except for the most
important part updating the date! I am able to SSH in the box but my second
command does not execute properly. I have been banging my head on the wall
trying to figure out why. I have checked the output of the sting and it should
be working based on whats coded. I am not a expert when it comes to python or
pexpect so I am in need of a bit of help figuring out why my time is not
updating.
**my original code** :
list = ["089"]
sn = 0
ssh_new_conn = 'Are you sure you want to continue connecting'
class ThreadClass(threading.Thread):
def __init__(self, index):
super(ThreadClass, self).__init__()
self.index = index
def run(self):
sn = storelist[self.index]
#easterndate = (currenttime + datetime.timedelta(0, 3600))
#easterndate = easterndate
est = timezone('US/Eastern')
cst = timezone('US/Central')
#currenttime = (datetime.now())
currenttime = cst.localize(datetime.now())
#easterndate = (currenttime + timedelta(0, 3600))
#easterndate = easterndate.strftime("%a %b %d %H:%M:%S %Z %Y")
easterndate = currenttime.astimezone(est).strftime("%a %b %d %H:%M:%S %Z %Y")
command1 = "/usr/bin/ssh %(username)s@%(hostname)s" % locals()
command2 = " sudo date -s\"%(easterndate)s\"" % locals()
command3 = " sudo date -s\"%(currenttime)s\"" % locals()
now = datetime.now()
#central
if sn == "073" or sn == "066" or sn == "016": #or sn == "022":
p = pexpect.spawn((command1 + command3), timeout=360)
#eastern
else:
print(command1 + command2)
p = pexpect.spawn((command1 + command2), timeout=360)
# Handles the 3 possible connection outcomes:
# a) Ssh to the remote host for the first time, triggering 'Are you sure you want to continue connecting'
# b) ask you for password
# c) No password is needed at all, because you already have the key.
i = p.expect([ssh_new_conn,'[pP]assword:',pexpect.EOF])
print ' Initial pexpect command output: ', i
if i == 0:
# send 'yes'
p.sendline('yes')
i = p.expect(['[pP]assword:',pexpect.EOF])
print 'sent yes. pexpect command output', i
if i == 0:
# send the password
print "logging into box %(sn)s" % locals()
p.sendline(password)
print "login successful"
print "Setting the time..."
elif i == 1:
# send the password
print "logging into box %(sn)s" % locals()
p.sendline(password)
print "login successful"
print "Setting the time..."
p.close()
elif i == 2:
print "pexpect faced key or connection timeout"
pass
print p.before
for i in range(len(list)):
t = ThreadClass(i)
t.start()
**New Code** :
class ThreadClass(threading.Thread):
def __init__(self, index):
super(ThreadClass, self).__init__()
self.index = index
def run(self):
try:
sn = storelist[self.index]
username = raw_input('username: ')
password = raw_input('password: ')
hostname = "[hostname]"
est = timezone('US/Eastern')
cst = timezone('US/Central')
#currenttime = (datetime.now())
currenttime = cst.localize(datetime.now())
#easterndate = (currenttime + timedelta(0, 3600))
#easterndate = easterndate.strftime("%a %b %d %H:%M:%S %Z %Y")
easterndate = currenttime.astimezone(est).strftime("%a %b %d %H:%M:%S %Z %Y")
ssh = pxssh.pxssh()
print(hostname + " " + username + " " + password)
ssh.login(hostname, username, password)
if sn == "073" or sn == "066" or sn == "016": #or sn == "022":
ssh.sendline ('date') # run a command
ssh.prompt() # match the prompt
print(s.before) # print everything before the prompt.
ssh.sendline ('sudo date -s\"%(currenttime)s\"' % locals()) # run a command
ssh.expect('(?i)password.*:') # match password prompt for sudo
ssh.sendline(password)
ssh.prompt()
print(s.before)
ssh.logout()
else:
ssh.sendline ('date') # run a command
ssh.prompt() # match the prompt
print(s.before) # print everything before the prompt.
ssh.sendline ('sudo date -s\"%(easterndate)s\"' % locals()) # run a command
ssh.expect('(?i)password.*:') # match password prompt for sudo
ssh.sendline(password)
ssh.prompt()
print(s.before)
ssh.logout()
except pxssh.ExceptionPxssh as e:
print(e)
for i in range(len(storelist)):
t = ThreadClass(i)
t.start()
**New Error I am getting** :
Traceback (most recent call last):
File "./sshtest.py", line 8, in <module>
s.login (hostname, username, password)
File "/usr/lib/python2.6/dist-packages/pxssh.py", line 243, in login
if not self.synch_original_prompt():
File "/usr/lib/python2.6/dist-packages/pxssh.py", line 134, in synch_original_prompt
self.read_nonblocking(size=10000,timeout=1) # GAS: Clear out the cache before getting the prompt
File "/usr/lib/python2.6/dist-packages/pexpect.py", line 824, in read_nonblocking
raise TIMEOUT ('Timeout exceeded in read_nonblocking().')
pexpect.TIMEOUT: Timeout exceeded in read_nonblocking().
**SOLUTION TO ERROR**
I figured out the solution to the error I was getting. Due to a known bug I
had to add the following lines to usr/lib/python.2.6/dist-packages/pxssh.py:
self.sendline() #line 134
time.sleep(0.5) #line 135
self.read_nonblocking(size=10000,timeout=1) # GAS: Clear out the cache before getting the prompt
Answer: You should probably handle the sudo password prompt (+ `-t` ssh option to get
a tty) and use `p.expect(EOF)` before `p.close()` to avoid killing the child
process prematurely.
Here's an example based on [pexpect
docs](http://pexpect.sourceforge.net/pxssh.html):
import pxssh
try:
s = pxssh.pxssh()
s.login (hostname, username, password)
s.sendline ('date') # run a command
s.prompt() # match the prompt
print(s.before) # print everything before the prompt.
s.sendline ('sudo date') # run a command
s.expect('(?i)password.*:') # match password prompt for sudo
s.sendline(password)
s.prompt()
print(s.before)
s.logout()
except pxssh.ExceptionPxssh as e:
print(e)
You could also try [`fabric`](http://fabfile.org):
# fabfile.py
from fabric.api import run, sudo
def date():
run('date')
sudo('date')
Usage:
$ fab -H localhost,user@host date
|
Unexpected Syntax Error using '<' and '>'
Question: I have been set a simple task:
Write a program for a game where the computer generates a random starting
number between 20 and 30. The player and the computer can remove 1,2 or 3 from
the number in turns. Something like this... Starting number : 25 How many do
you want to remove? 3 22 left Computer removes 2 20 left The player who has to
remove the last value to bring the number down to 0 is the loser. 1 left
Computer removes 1 You win!
I am trying to create it so that the player can only enter numbers 1, 2 or 3
to remove.
I get the syntax error of invalid syntax where the if statement is:
import random
import time
start=random.randint(20,30)
print('Starting number is',start)
personremove=int(input('How many do you want to remove? '))
if personremove=<3 or >1:
print('Enter a number between 1 and 3')
personremove=int(input('How many do you want to remove? '))
current=start-personremove
print(current,'left')
compremove=random.randint(1,3)
current=start-personremove-compremove
print('Computer removes',compremove)
print(current,'left')
Any help would be greatly appreciated, I am only a beginner to python as you
can probably tell.
Answer: `if personremove=<3 or >1:` should be
if personremove <= 3 or personremove > 1:
|
How to add a filter function in couchdb with python?
Question: I know i can use couchdb.ViewDefinition to create a view for a database.Is
there something similar to create a changes filter function or I can just
create a design document with the filters field?
Answer: Currently there is no such what unless you'll operate with design documents as
regular onces e.g. dumping python function to source code and assigning it to
ddoc filters field.
You may try to apply patch from [issue 186](http://code.google.com/p/couchdb-
python/issues/detail?id=186): it provides support of definition
show/list/update/filter/validate_doc_update functions in manner like views
currently does.
For instance:
from couchdb import design, mapping
class Post(mapping.Document):
by_author = design.FilterFunction('posts', 'by_name', '''
function(doc, req){
if (req.query.author){
return doc.author === req.query.author;
}
throw({'invalid_query': 'author name was not specified'});
}
''')
if __name__ == '__main__:
design.sync_docs(db, [Post])
Feedback and bugs are welcomed (:
|
RabbitMQ - pika - rabbit.js - node.js
Question: I'm using Python, rabbitmq, pika, rabbit.js and node.js.
The idea is to send messages to clients and act accordingly. There are
multiple types of messages being sent.
So, on the server side I have a method which will receive the message and the
exchange to send the message to:
import pika
def send(exchange, message):
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange=exchange, type='fanout',)
channel.basic_publish(exchange=exchange,
routing_key='',
body=message)
Still on the server side, using node.js, I have the multiple contexts, which,
I believe, the exchanges will call according to the name: (Note: "clients"
refers to the list of clients connected to the server.)
var context = require('rabbit.js').createContext();
context.on('ready', function() {
var consumer_1 = context.socket('SUB');
var consumer_2 = context.socket('SUB');
consumer_1.setEncoding('utf8');
consumer_1.connect('consumer_1', function (){
consumer_1.on('data', function(data){
try {
io.sockets.emit("client_method_1", data);
}catch(err){
console.log("[CONSUMER 1 ERROR] " + err);
}
});
consumer_2.setEncoding('utf8');
consumer_2.connect('client_method_2', function (){
consumer_2.on('data', function(data){
try {
clients[data.client].emit('client_method_2', data.action );
}
catch(err) {
console.log("[CONSUMER 2 ERROR]: " + err);
}
});
});
What's happening here is that consumer_1 is emitting messages to all clients
and consumer_2 is emitting to a specific client and that part is working well.
What's wrong is that all consumers are receiving messages from all exchanges.
If I try to send a message to consumer_1, the consumer_2 also receives the
message.
On the practical side, if I call:
send('consumer_1', data)
The result would be:
* node will emit to 'client_method_1';
* and also will try to emit to 'client_method_2'.
How do I call a specific consumer without calling every other?
Or, should I declare only one consumer and filter the data to call different
methods?
**EDIT:**
Following TokenMacGuy advice, I've tried to change the exchange type to
"_topic_ " or "_direct_ ". That should do exactly what I want.
But there's always a but, somehow I can't redeclare the exchange. When I
restart node I keep getting this error:
[(406, "PRECONDITION_FAILED - cannot redeclare exchange 'consumer_1' in vhost '/' with different type, durable, internal or autodelete value")]
Ok, so I've checked the list_exchanged on rabbitmq and the consumer is still
with "_fanout_ ".
direct
amq.direct direct
amq.fanout fanout
amq.headers headers
amq.match headers
amq.rabbitmq.log topic
amq.rabbitmq.trace topic
amq.topic topic
celery direct
celery.pidbox fanout
consumer_1 fanout
consumer_2 fanout
consumer_3 fanout
Next move was to reset the rabbitmq by stoping, reseting (and later force
reseting) and starting it.
I've send a message to consumer_1
Now the consumer_1 is listed as "_direct_ ":
direct
amq.direct direct
amq.fanout fanout
amq.headers headers
amq.match headers
amq.rabbitmq.log topic
amq.rabbitmq.trace topic
amq.topic topic
celery direct
celery.pidbox fanout
consumer_1 direct
consumer_2 fanout
consumer_3 fanout
Ok, since I've only called consumer_1 and all other appear on the list there
must be a file with that information. Where? I have no idea!!
Anyway, same PRECONDITION_FAILED error occurs on consumer_1.
Any ideas?
Answer: The `fanout` exchange type has only one behavior, delivering messages to every
queue bound to it. The other exchange types can deliver messages with more
narrow criteria. The most convenient is probably the `topic` exchange type,
which takes a binding key consisting of wild cards, and causes all messages
which match that wild card to be delivered to those specific queues. (here's a
link that goes into some detail: <http://www.rabbitmq.com/tutorials/tutorial-
five-python.html>)
|
qsub python import
Question: I'm running a job on the cluster for the first time. I run it with the
following command:
qsub -cwd -S /usr/bin/python myScript.py
I have a python script that starts with:
import time
import anotherScript
The error I get:
Traceback (most recent call last):
File "/opt/sge62/default/spool/hpc01/job_scripts/487174", line 11, in <module>
import anotherScript
ImportError: No module named anotherScript
the `anotherScript.py` is in the same directory as `myScript.py`.
What can I do to solve the problem? would appreciate any help
Answer: well, problem was solved by `sys.path.append(currentWorkingDirectory)`.
However, it's definitely not a nice way.
|
Unable to redirect python script result to a text file in windows
Question: Here is my python code.I'm trying to do elastic search in python.
from pyes import *
from pyes.mappings import *
conn = ES('http://search.twitter.com/search.json?q=poplio')
conn.indices.create_index("test-index")
I'm trying this tutorial
[pyes](http://pyes.readthedocs.org/en/latest/manual/usage.html)
The issue is when i try to run this python script in windows i get a detailed
message on msdos prompt which i don't know if its an error or any thing else.
So i tried to redirect that message to a text file but i don't see any thing
in that file.
Here is how i redirect the output of script
python script.py > log.txt
But log.txt is empty.
What is going wrong.
Answer: It might be printing those messages to STDERR. Try doing the following:
> python script.py > log.txt 2>&1
This will redirect the STDERR to STDOUT as well. You should see those messages
then.
|
numerical ODE solving in python
Question: I am new to Python so at this moment in time, I can only very basic problems.
How do I numerically solve an ODE in Python?
Consider

\ddot{u}(\phi) = -u + \sqrt{u}
with the following conditions
u(0) = 1.49907
and
\dot{u}(0) = 0
with the constraint
0 <= \phi <= 7\pi.
Then finally I want to produce a parametric plot where the x and y coordinates
are generated as a function of u.
The problem is I need to run odeint twice since this is a second order
differential equation. I tried having it run again after the first time but it
comes back with a Jacobian error. There must be away to run the twice all at
once.
Here is the error:
odepack.error: The function and its Jacobian must be callable functions
which the code below generates. The line in question is the sol = odeint.
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
from numpy import linspace
def f(u, t):
return -u + np.sqrt(u)
times = linspace(0.0001, 7 * np.pi, 1000)
y0 = 1.49907
yprime0 = 0
yvals = odeint(f, yprime0, times)
sol = odeint(yvals, y0, times)
x = 1 / sol * np.cos(times)
y = 1 / sol * np.sin(times)
plot(x,y)
plt.show()
**Edit**
I am trying to construct the plot on page 9
[Classical Mechanics
Taylor](http://www.colorado.edu/physics/phys3210/phys3210_fa05/Homework/phys3210_fa05_homework10_solutions.pdf)
Here is the plot with Mathematica

In[27]:= sol =
NDSolve[{y''[t] == -y[t] + Sqrt[y[t]], y[0] == 1/.66707928,
y'[0] == 0}, y, {t, 0, 10*\[Pi]}];
In[28]:= ysol = y[t] /. sol[[1]];
In[30]:= ParametricPlot[{1/ysol*Cos[t], 1/ysol*Sin[t]}, {t, 0,
7 \[Pi]}, PlotRange -> {{-2, 2}, {-2.5, 2.5}}]
Answer:
import scipy.integrate as integrate
import matplotlib.pyplot as plt
import numpy as np
pi = np.pi
sqrt = np.sqrt
cos = np.cos
sin = np.sin
def deriv_z(z, phi):
u, udot = z
return [udot, -u + sqrt(u)]
phi = np.linspace(0, 7.0*pi, 2000)
zinit = [1.49907, 0]
z = integrate.odeint(deriv_z, zinit, phi)
u, udot = z.T
# plt.plot(phi, u)
fig, ax = plt.subplots()
ax.plot(1/u*cos(phi), 1/u*sin(phi))
ax.set_aspect('equal')
plt.grid(True)
plt.show()

|
Naive multiprocessing in Python with NumPy
Question: Despite the warnings and confused feelings I got from the ton of questions
that have been asked on the subject, especially on StackOverflow, I
paralellized a naive version of an embarassingly parallel problem (basically
**read-image-do-stuff-return** for a list of many images), returned the
resulting NumPy array for each computation and updated a global NumPy array
via the `callback` parameter, and immediately got a **x5 speedup** on a 8-core
machine.
Now, I probably didn't get x8 because of the lock required by each callback
call, but what I got is encouraging.
I'm trying to find out if this can be improved upon, or if this is a good
result. Questions :
* I suppose the returned NumPy arrays got pickled?
* Were the underlying NumPy buffers _copied_ or just _passed by reference_?
* How can I find out what the bottleneck is? Any particularly useful technique?
* Can I improve on that or is such an improvement pretty common in such cases?
Answer: I've had great success sharing large NumPy arrays (by reference, of course)
between multiple processes using `sharedmem` module:
<https://bitbucket.org/cleemesser/numpy-sharedmem>. Basically it suppresses
pickling that normally happens when passing around NumPy arrays. All you have
to do is, instead of:
import numpy as np
foo = np.empty(1000000)
do this:
import sharedmem
foo = sharedmem.empty(1000000)
and off you go passing `foo` from one process to another, like:
q = multiprocessing.Queue()
...
q.put(foo)
Note however, that this module has a known possibility of a memory leak upon
ungraceful program exit, described to some extent here:
<http://grokbase.com/t/python/python-list/1144s75ps4/multiprocessing-shared-
memory-vs-pickled-copies>.
Hope this helps. I use the module to speed up live image processing on multi-
core machines (my project is <https://github.com/vmlaker/sherlock>.)
|
manage.py syncdb not working
Question:
DJANGO@linux-l94a:~/Desktop/myblog> ./manage.py syncdb
Traceback (most recent call last):
File "./manage.py", line 10, in
execute_from_command_line(sys.argv)
File "/usr/lib/python2.7/site-packages/django/core/management/init.py", line 443, in execute_from_command_line
utility.execute()
File "/usr/lib/python2.7/site-packages/django/core/management/init.py", line 382, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 196, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 231, in execute
self.validate()
File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 266, in validate
num_errors = get_validation_errors(s, app)
File "/usr/lib/python2.7/site-packages/django/core/management/validation.py", line 30, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "/usr/lib/python2.7/site-packages/django/db/models/loading.py", line 158, in get_app_errors
self._populate()
File "/usr/lib/python2.7/site-packages/django/db/models/loading.py", line 64, in _populate
self.load_app(app_name, True)
File "/usr/lib/python2.7/site-packages/django/db/models/loading.py", line 88, in load_app models = import_module('.models', app_name)
File "/usr/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/home/DJANGO/Desktop/myblog/blog/models.py", line 4, in
class Post(models.Model):
File "/home/DJANGO/Desktop/myblog/blog/models.py", line 5, in Post
title = modles.CharField(max_lenght=100)
NameError: name 'modles' is not defined
models.py
from django.db import models
from taggit.managers import TaggableManager
class Post(models.Model): title = modles.CharField(max_lenght=100)
body = modles.TextField()
created = models.DateTimeField()
tags = TaggableManager()
def __unicode__(self):
return self.title
urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('', # Examples: # url(r'^$', 'myblog.views.home', name='home'),
# url(r'^myblog/', include('myblog.foo.urls')),
url(r'^admin/', include(admin.site.urls)),
)
admin.py
from django.contrib import admin
from blog.models import Post
admin.site.register(Post)
settings.py
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',
'taggit',
'blog',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
)
Answer: `body = modles.TextField()` should be `body = models.TextField()`
and `title = modles.CharField(max_lenght=100)` should also be
`title = models.CharField(max_length=100)`
|
tornado.database Importerror: No module named database
Question: I'm using a fork of Bret Taylor's 'socialcookbook'
(<https://github.com/finiteloop/socialcookbook>) which uses "import
tornado.database" - and it's worked perfectly until yesterday (the 3.01
build?) and now I'm getting an ImportError: no module named database when I
compile on Heroku (using Python).
My **requirements.txt** file is simple:
mysql-python
tornado
My **import** statements:
import base64
import datetime
import functools
import json
import hashlib
import hmac
import time
import logging
import os
import smtplib #for mandrill email notifications
import httplib #for custom error handler
import re
import string
import tornado.database
import tornado.escape
import tornado.httpclient
import tornado.ioloop
import tornado.web
import urllib
import urllib2
import urlparse
from tornado.options import define, options
import facebook
Any thoughts? I'm having a hard time troubleshooting this one and I can't push
new builds (old builds work fine if I rollback on Heroku, though, oddly..)
Answer: As it turns out, Tornado 3.0 has deprecated tornado.database and replace it
with torndb: <https://github.com/bdarnell/torndb>
So the fix is to simply replace all tornado.database references with torndb
and add torndb to the requirements.txt file.
|
Error importing pymongo in my django app
Question: I'm trying to insert documents into mongodb from django and I'm getting an
error on the import statement for pymongo. I don't have a duplicate file
anywhere called pymongo and I'm pretty sure my virtualenv is set up correctly.
(django-sample-app)ubuntu@django (884) ~ $ python
Python 2.7.3 (default, Aug 1 2012, 05:14:39)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import bson
>>> import pymongo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/ubuntu/.virtualenvs/django-sample-app/local/lib/python2.7/site-packages/pymongo/__init__.py", line 80, in <module>
from pymongo.connection import Connection
File "/home/ubuntu/.virtualenvs/django-sample-app/local/lib/python2.7/site-packages/pymongo/connection.py", line 39, in <module>
from pymongo.mongo_client import MongoClient
File "/home/ubuntu/.virtualenvs/django-sample-app/local/lib/python2.7/site-packages/pymongo/mongo_client.py", line 45, in <module>
from pymongo import (auth,
File "/home/ubuntu/.virtualenvs/django-sample-app/local/lib/python2.7/site-packages/pymongo/database.py", line 22, in <module>
from pymongo.collection import Collection
File "/home/ubuntu/.virtualenvs/django-sample-app/local/lib/python2.7/site-packages/pymongo/collection.py", line 25, in <module>
from pymongo.cursor import Cursor
File "/home/ubuntu/.virtualenvs/django-sample-app/local/lib/python2.7/site-packages/pymongo/cursor.py", line 19, in <module>
from bson import RE_TYPE
ImportError: cannot import name RE_TYPE
Answer: This error happened to me after `pip install` (in virtualenv) both `pymongo`
and `bson`.
Uninstall `pymongo` and `bson` and install again just `pymongo` \- it ships
with its own version of `bson` not compatible with the `bson` package.
<http://stackoverflow.com/a/12983651/196206>
|
How to get UTC time in Python?
Question: I've search a bunch on StackExchange for a solution but nothing does quite
what I need. In JavaScript, I'm using the following to calculate UTC time
since Jan 1st 1970:
function UtcNow() {
var now = new Date();
var utc = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds(), now.getUTCMilliseconds());
return utc;
}
What would be the equivalent Python code?
Answer: Try this code that uses
[datetime.utcnow()](http://docs.python.org/2/library/datetime.html#datetime.datetime.utcnow):
from datetime import datetime
datetime.utcnow()
For your purposes when you need to calculate an amount of time spent between
two dates all that you need is to substract end and start dates. The results
of such substraction is a [timedelta
object.](http://docs.python.org/2/library/datetime.html#timedelta-objects)
From the python docs:
class datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
And this means that by default you can get any of the fields mentioned in it's
definition - days, seconds, microseconds, milliseconds, minutes, hours, weeks.
Also timedelta instance has total_seconds() method that:
> Return the total number of seconds contained in the duration. Equivalent to
> (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10*_6) / 10_ *6
> computed with true division enabled.
|
Bugs drawing with turtle(python) using onkey() and dictionaries
Question: I decided redo this question as per advice I received, This is an assignment
question I have been given for 1st year uni, python coding. I have bugs in my
code and Can't figure out where to fix them. BUG 1 The turtle starts drawing
when program is ran even though pen is up. BUG 2 undefined key such as 's, 7,
tab' trigger space_bar function
COLOURING BOOK
In this task you create a children's colouring game in which given pictures
can be coloured by tracing around a shape and then filling it. The controls
are as follows.
ARROW KEYS - Move the "brush" (turtle cursor) left, right, up or down by a
fixed small amount.
'z' - Undo the last step.
'r', 'g', 'b' - Change the brush colour to red, green or blue, respectively.
(You can define more colours if you like, but we expect at least these three.)
SPACE BAR - Toggle the painting mode. In "move" mode, which is the initial
mode, the "brush" (turtle) moves around the screen without drawing. In "paint"
mode the brush leaves a coloured line as it moves. Most importantly, when the
mode is changed from "paint" to "move", the area traced out by the brush is
filled with colour.
from turtle import *
from functools import partial
bgpic("Colour_A_Turkey.gif") # change this to change the picture
#control the accuracy/speed of the drawing
step_size =8
pensize(4)
penup()
# whenever spacebar is pressed the current state and next state switch values
current_state = penup
next_state = pendown
def space_bar():
global current_state, next_state
next_state()
current_state, next_state = next_state, current_state
#if the current stat is penup fill in with current colour
if current_state == penup:
end_fill()
else:
begin_fill()
onkey(space_bar, " ")
# undo do a mistake function
def mistake():
undo()
onkey(mistake, "z")
#using partial function to store the following functions
#so they can be called as arguments from a dictionary
#movement
strait = partial(fd, step_size)
reverse = partial(bk, step_size)
turn_rt = partial(rt, step_size)
turn_lf = partial(lt, step_size)
#colour
brow = partial(color, "brown")
gree = partial(color, "green")
yell = partial(color, "yellow")
oran = partial(color, "orange")
purp = partial(color, "purple")
red = partial(color, "red")
blue = partial(color, "blue")
#create a dictionary to store all the keys and there abilities
key_action = {"b" : blue, "r" : red, "p" : purp, "o" : oran,\
"y" : yell, "g" : gree, "w" : brow, "Right" : turn_rt , "Up" : strait,\
"Down" : reverse, "Left" : turn_lf, "z" : undo()}
#when a key in then above dictionary
#is pressed it's function is activated
for pressed_key, activated_key in key_action.items():
onkey(activated_key, pressed_key)
#make turtle look for key strokes with predefined function
listen()
#finish
done()
Answer: Remember, in Python, _everything is an object and we really mean that_.
Functions are objects too. We can store functions in a dictionary, and in fact
that's exactly what you seem to want to do here.
turn_lf = lt(step_size )
The key problem here is that you want to store "a function that calls `lt`
with `step_size` as the argument", but here you have just called `lt` with
`step_size` as an argument immediately, and stored the return value.
Arguably the simplest way to get what you want is to use `functools.partial`
to "bind" the `step_size` argument.
from functools import partial
turn_lf = partial(lt, step_size) # `lt` is not called yet.
# Now, later on, we can do
turn_lf() # and it's just as if we did `lt(step_size)`.
# So now we can store `turn_lf` in a dict, look it up and call it later, etc.
# Similarly for all the other functions you want to make.
(Another problem is that you haven't been consistent with this; if you want
everything to go in one dict, then you need to indicate the bindings for the
`color` function as well. `'brown'` is just a string, after all. Fortunately,
this is just as simple as with the other functions: we just make our
`partial(color, 'brown')`.
As for `"z" : delete`, well - we don't have any arguments to bind to `undo`.
So while we _could_ follow the pattern and write `partial(undo)` (notice, no
more arguments, because we aren't binding anything), it makes much more sense
to just write `undo` directly.
As an aside, we can simplify this:
for key in key_action:
pressed_key = key
activated_key = key_action[key]
To this:
for pressed_key, activated_key in key_action.items():
|
Is there a way to add metadata in py files for grouping tests?
Question: Lets say I have the following testcases in different files
* TestOne.py {tags: One, Two}
* TestTwo.py {tags: Two}
* TestThree.py {tags: Three}
Each of which inherits from unittest.TestCase. Is there any ability in python
to embed metadata information within these files, so that I can have a main.py
script to search for those tags and execute only those testcases?
For Eg: If I want to execute testcases with {tags: Two} then only testcases
TestOne.py and TestTwo.py should be executed.
Answer: The [`py.test`](http://pytest.org/latest/contents.html) testing framework has
support for meta data, via what they call
[markers](http://pytest.org/latest/example/markers.html).
For `py.test` test cases are functions that have names starting with "test",
and which are in modules with names starting with "test". The tests themselves
are simple `assert` statements. `py.test` can also run tests for the
`unittest` library, and IIRC Nose tests.
The meta data consists of dynamically generated decorators for the test
functions. The decorators have the form: `@pytest.mark.my_meta_name`. You can
choose anything for `my_meta_name`. There are a few predefined markers that
you can see with `py.test --markers`.
Here is an adapted snippet from their documentation:
# content of test_server.py
import pytest
@pytest.mark.webtest
def test_send_http():
pass # perform some webtest test for your app
def test_always_succeeds():
assert 2 == 3 - 1
def test_will_always_fail():
assert 4 == 5
You select marked tests with the `-m` command line option of the test runner.
To selectively run `test_send_http()` you enter this into a shell:
py.test -v -m webtest
|
Python import module vs import _module
Question: While configuring PyDev's [Forced
Builtins](http://pydev.org/manual_101_interpreter.html#PyDevInterpreterConfiguration-
ForcedBuiltins) in Aptana I noticed that some modules were referenced by
default with an `_` (underscore) prefix.
So I open a Python interpreter and to my surprise, the imports below work:
import ast
import _ast
import bisect
import _bisect
import csv
import _csv
# ... and so on
Now if I do a `dir()` on the imported modules, I see different contents:
>>> dir(csv)
['Dialect', 'DictReader', 'DictWriter', 'Error', ...] # and so on
>>> dir(_csv)
['Dialect', 'Error', ...] # node that DictReader and DictWriter are missing
Finally, help() tells me they are clearly different modules:
>>> help(_csv)
Help on module _csv:
NAME
_csv - CSV parsing and writing.
FILE
/usr/lib64/python2.6/lib-dynload/_csv.so
...
>>> help(csv)
Help on module csv:
NAME
csv - CSV parsing and writing.
FILE
/usr/lib64/python2.6/csv.py
...
So, what's the difference between `import module` and `import _module`? Is
there a convention behind it or something like that?
Answer: Some modules use _some_ C code to implement parts that need the speed. The
_main_ module still uses Python glue, and the `_module` version contains the C
extension.
See for example the [`csv.py`
module](http://hg.python.org/cpython/file/2.7/Lib/csv.py); it imports from the
[`_csv.c` C library](http://hg.python.org/cpython/file/2.7/Modules/_csv.c) for
most of the functionality, with only the `Dialect`, `Sniffer`, `DictReader`
and `DictWriter` classes implemented in pure Python.
The `module` plus `_module` convention is just that, a convention. Not all C
extensions follow this pattern.
|
Plotting cosine with Python
Question: I plot a cosine sampled at 400 points in the interval -5 .. +5 using python
for n=1..4:
import matplotlib.pyplot as plt
import numpy
for n in range(1,5):
x = numpy.linspace(-5,5,num=400)
series = numpy.cos(1e4/n*x)
plt.figure()
plt.plot(series)
But for n = 3 the plot looks not like a cosine which I think is due to
sampling error. How can I achieve a smooth cosine plot with constant samples
for different frequencies (i.e. different n)?
Answer: Change your calculation to `series = numpy.cos(2*numpy.pi/n*x)`.
Multiplying by `1e4` means you have fewer than 2 points per cycle of your
cosine, thus causing [aliasing](http://en.wikipedia.org/wiki/Aliasing).
|
About piping stdio and subprocess.Popen
Question: I have one Python program, that is opening another Python program via
`subprocess.Popen`. The 1st is supposed to output some text into the console
(just for info), and write some text to the 2nd program it had spawned. Then,
it should wait for the 2nd program to respond (`read()` from it), and print
that response.
The 2nd one is supposed to listen to the first one's input (via `raw_input()`)
and then `print` text to the 1st.
To understand what exactly was happening, I had put a 5 second delay into the
2nd, and the result surprised me a bit.
Here's the code:
import subprocess
print "1st starting."
app = subprocess.Popen("name", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) #<--- B
print "Writing something to app's STDIN..."
app.stdin.write(some_text)
print "Reading something from my STDIN..." #<--- A
result = app.stdout.read()
print "Result:"
print result
And for the 2nd one:
import time
print "app invoked."
print "Waiting for text from STDIN..."
text = raw_input()
#process(text)
time.sleep(5)
print "magic"
When I ran this code, it paused at point A, as that was the last console
output.
After 5 seconds, the `"Result:\n"` line would be outputted, and everything the
2nd program had `print`ed would show up in the console.
Why did the 1st program pause when reading the stdout of the 2nd one? Does it
have to wait for its child to terminate before reading its output? How can
this be changed so I can pass messages between programs?
I'm running Debian Linux 7.0.
Answer: You are asking program 1 to read input from program 2. And you are pausing
program two for five seconds before it outputs anything. Obviously program 1
then needs to wait those five seconds. So what happens is perfectly expected.
> Does it have to wait for its child to terminate before reading its output?
To some extent, yes, because input and output is buffered, so it's possible
that even if you move the delay to _after_ you print something the same will
happen.
`raw_input()` will wait for a linefeed, in any case.
|
Why is my startup script not running
Question: Per various tutorials I've done the following:
created a file called `ftpserver.py` in `/home/root/`
created a file in `/etc/init.d/` called `ftpserver` that looks like this"
#!/bin/sh
python /home/root/ftpserver.py
Upon creation, I ran the following (to make it executable, apparently)
root@beaglebone1:/etc/init.d# chmod +x ftpserver
But it doesn't appear to be running on startup. However if I run the following
command:
root@beaglebone1:/etc/init.d# /etc/init.d/ftpserver
Then the script runs, exectuing ftpserver.py.
Interestingly, if I try to run `ftpserver` from within it's directory in the
following manner (not sure if this is relevant):
root@beaglebone1:/etc/init.d# ftpserver
It returns:
-sh: ftpserver: command not found
So I'm not certain why my script isn't running on startup.
For reference, ftpserver.py looks like this:
from pyftpdlib import ftpserver
authorizer = ftpserver.DummyAuthorizer()
authorizer.add_user("root", "12345", "/home/root", perm="elradfmw")
handler = ftpserver.FTPHandler
handler.authorizer = authorizer
address = ("", 21)
ftpd = ftpserver.FTPServer(address, handler)
ftpd.serve_forever(
Answer: Try running it with `./ftpserver`
Also, check if your script is configured to run in current runlevel - probably
/etc/rc.conf and there `DAEMONS` or something like that.
|
Issuing application-only requests in Twitter 1.1 using Python
Question: I want to access Twitter 1.1 search endpoint using application-only
authentication. To do the same, I'm trying to implement the steps given on
Twitter API's documentation here -
<https://dev.twitter.com/docs/auth/application-only-auth> (scroll to "Issuing
application-only requests")
I am not able to obtain the "bearer token" in Step 2. When I run the following
code, I receive "Response: 302 Found" which is a redirection to Location:
<https://api.twitter.com/oauth2/token> Ideally it should be "200 OK"
import urllib
import base64
import httplib
CONSUMER_KEY = 'my_key'
CONSUMER_SECRET = 'my_secret'
encoded_CONSUMER_KEY = urllib.quote(CONSUMER_KEY)
encoded_CONSUMER_SECRET = urllib.quote(CONSUMER_SECRET)
concat_consumer_url = encoded_CONSUMER_KEY + ":" + encoded_CONSUMER_SECRET
host = 'api.twitter.com'
url = '/oauth2/token'
params = urllib.urlencode({'grant_type' : 'client_credentials'})
req = httplib.HTTP(host)
req.putrequest("POST", url)
req.putheader("Host", host)
req.putheader("User-Agent", "My Twitter 1.1")
req.putheader("Authorization", "Basic %s" % base64.b64encode(concat_consumer_url))
req.putheader("Content-Type" ,"application/x-www-form-urlencoded;charset=UTF-8")
req.putheader("Content-Length", "29")
req.putheader("Accept-Encoding", "gzip")
req.endheaders()
req.send(params)
# get the response
statuscode, statusmessage, header = req.getreply()
print "Response: ", statuscode, statusmessage
print "Headers: ", header
I do not want to use any Twitter API wrappers to access this.
Answer: The problem was that the URL had to be called with an HTTPS connection. Please
check the modified code which works.
import urllib
import base64
import httplib
CONSUMER_KEY = 'my_key'
CONSUMER_SECRET = 'my_secret'
encoded_CONSUMER_KEY = urllib.quote(CONSUMER_KEY)
encoded_CONSUMER_SECRET = urllib.quote(CONSUMER_SECRET)
concat_consumer_url = encoded_CONSUMER_KEY + ":" + encoded_CONSUMER_SECRET
host = 'api.twitter.com'
url = '/oauth2/token/'
params = urllib.urlencode({'grant_type' : 'client_credentials'})
req = httplib.HTTPSConnection(host)
req.putrequest("POST", url)
req.putheader("Host", host)
req.putheader("User-Agent", "My Twitter 1.1")
req.putheader("Authorization", "Basic %s" % base64.b64encode(concat_consumer_url))
req.putheader("Content-Type" ,"application/x-www-form-urlencoded;charset=UTF-8")
req.putheader("Content-Length", "29")
req.putheader("Accept-Encoding", "gzip")
req.endheaders()
req.send(params)
resp = req.getresponse()
print resp.status, resp.reason
|
How do I parallely check for existence of an item across multiple lists in Python?
Question: As a part of my project, for every word in the dictionary d (shown in the
example code snippet below), I need to check for its existence across
different lists `f1, f2, f3`. I have shown only 3 lists here. And based on the
occurrence, I need to calculate two output values(rule inputs and weights).
The problem I am facing here is, the word can occur in any number of lists,
say word1 in dict d occurs in lists `f1, f2, f3` (shown below) and word2 in
dict d occurs in f1 and f2 and word3 occurs only in one list f3. I have 100s
of these individual lists. I need an efficient and straight forward method to
calculate output values(rule inputs and weights) for every word in dictionary
d based on their varying occurrences across these lists, so that I don't have
to check for every combination of occurrence and write a separate condition
for it, which would make things complicated and ugly.
**P.S.:** The lists are of different size. In example below, f1, f2 and f3 are
of different sizes.
**My Code:**
import itertools
d = {'Rosa': 0.023, 'code': 0.356, 'Syntel': 0.144, 'Robotics': 0.245, 'Web': .134, 'sanskrit': 0.23, 'Tamil': 0.23}
f1 = [['Syntel', 0.2, 4, 0.46, 7, 0.9], ['code', 0.45, 9, 0.43, 2, 0.23], ['Robotics', .43, 3, .1, 3, .73]]
f2 = [['Web', 0.5, 5, 0.06, 6, 0.9], ['code', 0.05, 1, 0.28, 2, 0.73]]
f3 = [['Web', 0.5, 5, 0.06, 6, 0.9], ['sanskrit', 0.05, 1, 0.28, 2, 0.73], ['Tamil', 0.23, 4, .13, 5, .23], ['code', 0.32, 4, 0.12, 4, .24]]
# specific case where I am checking if a word of the dictionary occurs in all of the lists f1, f2 and f3
# I have to write chunk of code for every possible combo of occurrence which I think is a bad approach
# I am brain stuck ! Help please !!
for word, score in d.iteritems():
for x in f1:
if word == x[0]:
for y in f2:
if word == y[0]:
for z in f3:
if word == z[0]:
A = x[2] * x[3]
B = x[4] * x[5]
C = y[2] * y[3] + 1
D = y[4] * y[5] + 1
E = z[2] * z[3] + 1
F = z[4] * z[5] + 1
mfs = [[A, B], [C, D], [E, F]]
weights = sum([x[3], x[5], y[3], y[5], z[3], z[5]])
rule_inputs = list(itertools.product(*mfs))
len_comb = len(rule_inputs)
# 6 --> need code to find this automatically
weight_factor = (len(mfs) * len_comb) / 6
weights *= weight_factor
rule_inputs = sum([sum(r) for r in rule_inputs])
print word, rule_inputs, weights
Answer: As Joel Cornett says, you probably should be using `dict`s rather than `list`s
in the first place.
But if you need the `list`s for some reason… well, if you're going to search
through a `list` multiple times, you probably want to build a `dict` to search
through:
d1 = {elem[0]: elem for elem in f1}
Then, instead of this:
for z in f3:
if word == z[0]:
… you can just do this:
z = d3.get(word)
if z is not None:
You may also want to follow EAFTP and just `try` the whole thing. Your whole
loop then looks like this:
for word, score in d.iteritems():
try:
x, y, z = d1[word], d2[word], d3[word]
except KeyError:
continue
A = x[2] * x[3]
# etc.
This is assuming you specifically need three lists, as opposed to an arbitrary
number. If you needed to be able to work with any number of lists, you'd do
this:
list_of_dicts = [{elem[0]: elem for elem in lst} for lst in list_of_lists]
for word, score in d.iteritems():
try:
values = [d[word] for d in list_of_dicts]
except KeyError:
continue
A = values[0][2] * values[0][3]
# etc.
* * *
There are a few alternatives to this, but this is probably the one you want.
You can `sort` each list and use `bisect` instead of an iterative linear
search, or use something like
[`SortedCollection`](http://code.activestate.com/recipes/577197-sortedcollection/)
to wrap that up for you, or
[`blist.sortedlist`](https://pypi.python.org/pypi/blist/) for a similar type.
This makes the search O(log N) instead of O(N), and makes the code simpler.
But a `dict` makes the search O(1) instead of O(N), and makes the code exactly
as simple as using a sorted list, so, unless you're dealing with keys that are
not hashable (and you're not), why bother?
You can also wrap up the `for`/`if` by writing a `find_in_list` function,
which gives you the same simplicity as a `dict` or `sortedlist`, but without
the performance gains. This could be useful if the keys are neither hashable
nor orderable, or if you had a huge number of tiny lists (so tiny that a
linear search is actually faster than a dict or tree lookup—maybe around size
2-3?). But otherwise, you're just doing extra work (to write the
`find_in_list` wrapper) to slow yourself down, so again, why bother?
|
Is there a builtin function version of `and` and/or `or` in Python?
Question: This question is for fun; I don't expect the answer to be useful.
When I see people doing things with `reduce()` in Python, they often take
advantage of a builtin function in Python, often from the `operator` module.
This works:
result = reduce(lambda a, b: a + b, range(5))
But usually you would see this:
from operator import add
result = reduce(add, range(5))
What's strange to me is that the `operator` module doesn't seem to have a
function for logical `and`. It does have _bitwise_ and, but not logical `and`.
So suppose you are doing this:
result = reduce(lambda a, b: a and b, range(1, 6))
Is there a builtin function that can be used here?
I'm also wondering if there is a builtin function that can replace `or`.
If you map the arguments to Booleans first, you can use the bitwise and from
`operator`, or just directly use `bool.__and__`, like so:
from operator import and_
result = reduce(and_, map(bool, range(1, 6)))
result = reduce(bool.__and__, map(bool, range(1, 6)))
And likewise with `operator.or_()` or `bool.__or__` for the `or` operation.
But I am looking for a function that doesn't need the values mapped to
Booleans.
If you knew for certain that your values are all integers, you could use
`operator.mul` for `and` and `operator.add` for `or`. This would be a crude
hack and I don't want this answer... especially considering how expensive the
multiplications would get if many numbers were encountered and none of them
were zero!
Note: I am aware of `all()` and `any()`, which are better replacements for
this use of `reduce()`. As I said at the top, I'm asking this for fun.
Note: A function that has the side-effect of forcing all values to `bool`
would be an acceptable answer. The built-in `and` keyword doesn't do this:
x = 3 and 5 # sets x to 5, not to True
But for the purpose of this question I am just interested in a function that
can work with `reduce()` to do logical `and` or `or` operations.
Answer: I guess the actual reason why there's no `and` and `or` in the operator module
is that it's impossible to evaluate function arguments in a short-circuit
fashion - which is the whole point of boolean operators. So the answer to your
question is no, there's no built-in function that can mimic `and/or` nor is it
possible to write one.
`all/any` applied to generators are short-circuiting as well
def gen():
yield 1
yield this_wont_be_evaluated
print any(gen())
but I have no idea how make that work with run-time arguments
|
Adding quotes to words using regex in Python
Question: I am trying to replace each word in a sentence with the same word but quote
(by word I mean just letters, no numbers) using regex.
For example `4 python code` should be converted to `4 "python" "code"`.
But this code produce the wrong result
>>> import re
>>> s = "4 python code"
>>> re.sub(r'([a-z]*)', r'"\1"', s)
'""4"" "python" "code"'
Any ideas?
Answer: Change,
re.sub(r'([a-z]*)', r'"\1"', s)
to
re.sub(r'([a-z]+)', r'"\1"', s)
|
python try/except with urllib2 throwing odd exception
Question: Function looks like:
def fetchurl(url):
timeout = 10
try:
res = urllib2.urlopen(url, timeout=timeout)
reader = csv.reader(res)
reader.next() # Trim the CSV header
return reader
except urllib2.URLError, e:
print 'bailing on %s (timeout of %s exceeded)' % (url, timeout)
return None
Exception looks like:
File "scrape.py", line 35, in fetchurl
reader.next() # Trim the CSV header
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 530, in next
line = self.readline()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 447, in readline
data = self._sock.recv(self._rbufsize)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 541, in read
return self._read_chunked(amt)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 601, in _read_chunked
value.append(self._safe_read(chunk_left))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 647, in _safe_read
chunk = self.fp.read(min(amt, MAXAMOUNT))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 380, in read
data = self._sock.recv(left)
socket.timeout: timed out
Why isn't the try/except block catching the `socket.timeout` exception?
Answer: Because its got nothing to do with urllib2.URLError something to do with the
exception within the File "scrape.py".
Error cases within file "scrape.py" which you're using for csv.reader are not
handled well.
You use the following as prescribed
[here](http://heyman.info/2010/apr/22/python-urllib2-timeout-issue/):
import socket
try:
resp = urllib2.urlopen(req, timeout=5)
except urllib2.URLError:
print "Bad URL or timeout"
except socket.timeout:
print "socket timeout"
|
How to assign module name to a variable?
Question: I would like to dynamically let the user chose which body of data he/she would
like to work with. To do this, after the user identifies their "corpus" of
choice, I must import the appropriate corpus. (I am running on Python 2.7.3)
corpora_ls = ["gutenberg","inaugural","movie_reviews","state_union"]
import_validation = False
while not import_validation:
print "Corpora Options: \"gutenberg\", \"inaugural\", \"movie_reviews\", \"state_union\"."
import_option = str(raw_input("What corpus would you like to import? "))
if import_option in corpora_ls:
import_validation = True
if import_option == "gutenberg":
fname = "gutenberg"
from nltk.corpus import gutenberg as DATA
elif import_option == "inaugural":
fname = "inaugural"
from nltk.corpus import inaugural as DATA
elif import_option == "movie_reviews":
fname = "movie_reviews"
from nltk.corpus import movie_reviews as DATA
elif import_option == "state_union":
fname = "state_union"
from nltk.corpus import state_union as DATA
else:
print "Please enter one of the available corpora as listed.\n"
Frankly, this code looks cumbersome to me. I would like to be able to simply
say something to the effect of:
if import_option == "gutenberg":
fname = "gutenberg"
elif import_option == "inaugural":
fname = "inaugural"
etc....
from nltk.corpus import import_option as DATA
rather than having to do a separate `from nltk.corpus...etc.` for every
`if/elif`
Is something like this possible?
Thanks for the help!
Answer: Yes. You can use `getattr`:
import nltk.corpus
corpus_data = getattr(nltk.corpus, corpus_name)
|
OpenCV 2.4 estimateAffine3D in Python
Question: I'm trying to use the method cv2.estimateAffine3D but without success. Here is
my code sample :
import numpy as np
import cv2
shape = (1, 4, 3)
source = np.zeros(shape, np.float32)
# [x, y, z]
source[0][0] = [857, 120, 854]
source[0][1] = [254, 120, 855]
source[0][2] = [256, 120, 255]
source[0][3] = [858, 120, 255]
target = source * 10
retval, M, inliers = cv2.estimateAffine3D(source, target)
When I try to run this sample, I obtain the same error as this other post
[here](http://stackoverflow.com/questions/12620141/estimateaffine3d-opencv-2-4-cv-
are-sizes-eqm1-m2-cv-are-sizes-eqm1-mask).
I'm using OpenCV 2.4.3 and Python 2.7.3
Please help me!
Answer: This is a known bug that is fixed in `2.4.4`.
<http://code.opencv.org/issues/2375>
If you just need rigid (rotation + translation) alignment, here's the standard
method:
def get_rigid(src, dst): # Assumes both or Nx3 matrices
src_mean = src.mean(0)
dst_mean = dst.mean(0)
# Compute covariance
H = reduce(lambda s, (a,b) : s + np.outer(a, b), zip(src - src_mean, dst - dst_mean), np.zeros((3,3)))
u, s, v = np.linalg.svd(H)
R = v.T.dot(u.T) # Rotation
T = - R.dot(src_mean) + dst_mean # Translation
return np.hstack((R, T[:, np.newaxis]))
|
python numpy.convolve to solve convolution integral with limits from 0 to t instead -t to t
Question: I have a convolution integral of the type:

To solve this integral numerically, I would like to use `numpy.convolve()`.
Now, as you can see in the [online
help](http://docs.scipy.org/doc/numpy/reference/generated/numpy.convolve.html),
the convolution is formally done from -infinity to +infinity meaning that the
arrays are moved along each other completely for evaluation - which is not
what I need. I obviously need to be sure to pick the correct part of the
convolution - can you confirm that this is the right way to do it or
alternatively tell me how to do it right and (maybe even more important) why?
res = np.convolve(J_t, dF, mode="full")[:len(dF)]
J_t is an analytical function and I can evaluate as many points as I need, dF
are derivatives of measurement data. for this attempt I choose `len(J_t) =
len(dF)` because from my understanding I do not need more.
Thank you for your thoughts, as always, I appreciate your help!
* * *
**Background information** (for those who might be interested)
These type of integrals can be used to evaluate viscoelastic behaviour of
bodies (or the response of an electric circuit during change of voltage, if
you feel more familiar on this topic). For viscoelasticity, J(t) is the creep
compliance function and F(t) can be the deviatoric strains over time, then
this integral would yield the deviatoric stresses. If you now e.g. have a J(t)
of the form:
J_t = lambda p, t: p[0] + p[1]*N.exp(-t/p[2])
with `p = [J_elastic, J_viscous, tau]` this would be the "famous" [standard
linear solid](http://en.wikipedia.org/wiki/Standard_linear_solid_model). The
integral limits are the start of the measurement t_0 = 0 and the moment of
interest, t.
Answer: To get it right, I have chosen the following two functions:
a(t) = t
b(t) = t**2
It is easy to do the math and find that their "convolution" as defined in your
case, takes on the values:
c(t) = t**4 / 12
So lets try them out:
>>> delta = 0.001
>>> t = np.arange(1000) * delta
>>> a = t
>>> b = t**2
>>> c = np.convolve(a, b) * delta
>>> d = t**4 / 12
>>> plt.plot(np.arange(len(c)) * delta, c)
[<matplotlib.lines.Line2D object at 0x00000000025C37B8>]
>>> plt.plot(t[::50], d[::50], 'o')
[<matplotlib.lines.Line2D object at 0x000000000637AB38>]
>>> plt.show()

So by doing the above, if both your `a` and `b` have `n` elements, you get the
right convolution values in the first `n` elements of `c`.
Not sure if the following explanation will make any sense, but here it goes...
If you think of convolution as mirroring one of the functions along the
y-axis, then sliding it along the x axis and computing the integral of the
product at each point, it is easy to see how, since outside of the area of
definition numpy takes them as if padded with zeros, you are effectively
setting an integration interval from 0 to t, since the first function is zero
below zero, and the second is zero above t, since it originally was zero below
zero, but has been mirrored and moved t to the right.
|
Python Interpreter Mode - What are some ways to explore Python's modules and its usage
Question: While inside the Python Interpreter:
What are some ways to learn about the packages I have?
>>> man sys
File "<stdin>", line 1
man sys
^
SyntaxError: invalid syntax
>>> sys --help
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary -: '_Helper'
Corrected:
>>> help(sys)
...
Now, how do I see all the packages available to me on my sys.path? And see
their subsequent usage and documentation. I know that I can easily download a
PDF but all this stuff is already baked in, I'd like to not duplicate files.
Thanks!
Answer: You can look at `help("modules")`, it displays the list of available modules.
To explore a particular module/class/function use `dir` and `__doc__`:
>>> import sys
>>> sys.__doc__
"This module ..."
>>> dir(sys)
[..., 'setprofile', ...]
>>> print(sys.setprofile.__doc__)
setprofile(function)
Set the profiling function. It will be called on each function call
and return. See the profiler chapter in the library manual.
|
Matplotlib and subinterpreter for embedded python in c++
Question: I just added subinterpreter to my c++ embedded python editor to have a clean
interpreter for each execution.
PyThreadState* tmpstate = Py_NewInterpreter();
PyThreadState_Swap(tmpstate);
... run the script ...
Py_EndInterpreter(tmpstate);
My own module are working and I tested numpy without having any problem. The
problem is with matplotlib
if I run that the first time everything looks fine. The second time i get :
<class 'TypeError'>: attribute of type 'NoneType' is not callable: File "<string>", line 1, in <module>
File "C:\Python33\lib\site-packages\pylab.py", line 1, in <module>
from matplotlib.pylab import *
File "C:\Python33\lib\site-packages\matplotlib\__init__.py", line 152, in <module>
from matplotlib.rcsetup import (defaultParams,
File "C:\Python33\lib\site-packages\matplotlib\rcsetup.py", line 19, in <module>
from matplotlib.fontconfig_pattern import parse_fontconfig_pattern
File "C:\Python33\lib\site-packages\matplotlib\fontconfig_pattern.py", line 25, in <module>
from matplotlib.pyparsing_py3 import Literal, ZeroOrMore, \
File "C:\Python33\lib\site-packages\matplotlib\pyparsing_py3.py", line 3275, in <module>
_escapedHexChar = Combine( Suppress(_bslash + "0x") + Word(hexnums) ).setParseAction(lambda s,l,t:unichr(int(t[0],16)))
File "C:\Python33\lib\site-packages\matplotlib\pyparsing_py3.py", line 2961, in __init__
self.leaveWhitespace()
File "C:\Python33\lib\site-packages\matplotlib\pyparsing_py3.py", line 2587, in leaveWhitespace
self.expr = self.expr.copy()
File "C:\Python33\lib\site-packages\matplotlib\pyparsing_py3.py", line 705, in copy
cpy = copy.copy( self )
File "C:\Python33\lib\copy.py", line 89, in copy
rv = reductor(2)
Answer: This seem to be a bug in Python 3.3 : <http://bugs.python.org/issue17408>
The problem is :
The reason is in Objects/typeobject.c: import_copyreg() has a static cache of the copyreg module.
When the interpreter stops, the module is filled with None... but gets reused in the next instance.
Resetting this "mod_copyreg" variable to NULL fixes the issue.
pickle is also broken for the same reason.
|
Python Suds Soap Client Error
Question: I am trying to connect to a web service using Python/SUDS.
I have the following code in a single file and I am able to connect
successfully and I receive a response.
class Suds_Connect:
def __init__(self, url, q_user, q_passwd):
logging.basicConfig(level=logging.INFO)
logging.getLogger('suds.client').setLevel(logging.DEBUG)
try:
# fix broken wsdl
# add <s:import namespace="http://www.w3.org/2001/XMLSchema"/> to the wsdl
imp = Import('http://www.w3.org/2001/XMLSchema',
location='http://www.w3.org/2001/XMLSchema.xsd')
wsdl_url = url
self.client = Client(wsdl_url, doctor=ImportDoctor(imp))
t = HttpAuthenticated()
security = Security()
token = UsernameToken(q_user,q_passwd)
security.tokens.append(token)
self.client.set_options(wsse=security)
except Exception, e:
print "Unexpected error:", sys.exc_info()[0]
print str(e)
sys.exit()
def CallWebMethod():
try:
print ' SUDS Client'
print self.client
Person= self.client.factory.create('ns0:Person')
Person.name= 'bob'
Person.age= '34'
Person.address= '44, river lane'
print self.client.service.AddPerson(Person)
except WebFault, f:
print str(f.fault)
except Exception, e:
print str(e)
if __name__ == '__main__':
errors = 0
sudsClient = Suds_Connect('url','user','password')
sudsClient.CallWebMethod()
print '\nFinished:'
I want to use this code in a Python client app that will be called from a
button click event. I have tried to implement this and I am able to print out
the client but when I make the web service call (`print
self.client.service.AddPerson(Person)`) I get the following error.
unsupported operand type(s) for +: 'NoneType' and 'str'
How do I go about fixing this error?
Answer: Looks like webservice call returns None. Additional information is required to
identify what went wrong.
First of all - enable suds logging by adding before calling Suds_Connect. This
should provide you information about what's going on in suds under the hood.
import logging
logging.basicConfig(level=logging.DEBUG)
Another thing to try for getting more debug information - please try the
following instead of `print self.client.service.AddPerson(Person)`
result = self.client.service.AddPerson(Person)
print str(result)
Also it would be helpful to get full stack trace for exception - which line it
happens at and what is the call stack. Please try to comment out exception
handling for `except Exception, e:` case and post here the exception you'll
get.
|
get value of a variable from a python script
Question: I have a python script that returns a json object. Say, for example i run the
following:
exec('python /var/www/abc/abc.py');
and it returns a json object, how can i assign the `json` object as a variable
in a php script.
### Example python script:
#!/usr/bin/python
import sys
def main():
data = {"Fail": 35}
sys.stdout.write(str(data))
main()
### Example PHP script:
<?php
exec("python /home/amyth/Projects/test/variable.py", $output, $v);
echo($output);
?>
The above returns an empty Array. Why so ?
I want to call the above script from php using the `exec` method and want to
use the json object returned by the python script. How can i achieve this ?
Update:
The above works if i use another shell command, For Example:
<?php
exec("ls", $output, $v);
echo($output);
?>
Anyone knows the reason ?
Answer: If the idea is you'll have a Python script which prints JSON data to standard
out, then you're probably looking for [`popen`](http://php.net/popen).
Something like...
<?php
$f = popen('python /var/www/abc/abc.py', 'r');
if ($f === false)
{
echo "popen failed";
exit 1;
}
$json = fgets($f);
fclose($f);
...will grab the output into the `$json` variable.
As for your example Python script, if the idea is you're trying to convert the
Python dictionary `{"tests": "35"}` to JSON, and print to standard out, you
need to change `loads` to `dumps` and `return` to `print`, so it looks like...
import simplejson
def main():
data = simplejson.dumps({"tests": "35"})
print data
main()
|
Orange Python data load error: "example of invalid length"
Question: I am trying to load a .csv file using python & Orange (machine learning
package) and getting an error. I have 208 columns but in the error I only see
few columns and after that nothing. What does the error mean?
example of invalid length: (0 REAL P 16 0 1 0 112.11.119.78 Mozilla/5.0 (Linux; U; Android 4.0.3; zh-cn; HTC Sensation Z710e Build/IML74K) AppleWebKit/534.30 (KHTML like Gecko) Ve android_android23 Droid Smartphone Android 4.0.3 0 1 1 0 0 0 1 Android_Phones Null Null Null Null Null Null Null Null Null Null Null Null Null Null Null wifi Null Null pyramid 0 1 1 26 0 0 0 8 0 7 0 0 0 0 0 0 0 0 0 0 Null Null Null Null en 1 CN Null FALSE ANDROID_APPLICATION ANDROID_APPLICATION
Answer: I just recently worked through this error myself when trying to import a bunch
of data into Orange. The problem with my data was that there were commas in
some of the field information, and the Orange data importer kept thinking
these were extra delimiters. This happened when trying to import both comma
and tab-separated data files.
My solution was to pre-process the data file before it went into Orange, and
replace all commas with another character which did not appear in the rest of
the data, and would not be considered a delimiter by Orange (for me a ':'
character worked out just fine).
I would say check your data and make sure there are no stray tabs or commas
that may get picked up as extra delimiters.
Also, is the data you included just from the error message, or is that a full
line of your data?
|
ipython install new modules
Question: I am used to the R functionality of installing packages and I am trying to do
the same thing with ipython. Sometimes the following method works but then
again sometimes it doesn't and I would like to finally find out why it only
works half the time.
Normally to install a module (like the `requests` module for example) I would
type the following after opening a fresh terminal:
$ sudo pip install requests
Password: *******
This would then be followed by a message indicating that the install was
succesfull or that it has already been installed.
Requirement already satisfied (use --upgrade to upgrade):
requests in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages
Cleaning up...
Which suggests that the code can be accessed. And indeed if I run python now
from the terminal it shows a good response without any errors whatsoever.
$ python
ActivePython 2.7.2.5 (ActiveState Software Inc.) based on
Python 2.7.2 (default, Jun 24 2011, 12:20:15)
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import requests
>>>
I now open PyLab through Alfred and it gives me an error.
Welcome to pylab, a matplotlib-based Python environment [backend: WXAgg].
For more information, type 'help(pylab)'.
In [1]: import requests
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
/Users/vincentwarmerdam/<ipython-input-1-686486c241c8> in <module>()
----> 1 import requests
ImportError: No module named requests
I've read some help from another question on stackoverflow (here
<http://bit.ly/1148FRL>) which suggests that I install the module from ipython
shell. This gives an even more baffeling response:
In [2]: !pip install requests
Requirement already satisfied (use --upgrade to upgrade): requests in
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages
Cleaning up...
In [3]: import requests
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
/Users/vincentwarmerdam/<ipython-input-3-686486c241c8> in <module>()
----> 1 import requests
ImportError: No module named requests
This seems very strange to me. Are there multiple versions of python installed
on the system? How could I check this? Do I need to point ipython to the
location of the installed code?
Answer: actually there is a much much much more elegant solution. when pip is
installed then within python you can do things like this as well:
import pip
def install(package):
pip.main(['install', package])
install('requests')
which is easier. once logged into a virtualenv you can just make sure that you
have what you need in the session you are in. easy.
### edit
Another alternative would be to use the `%%bash` magic.
%%bash
pip install requests
### edit2
If you want the standard output, one could even use the exclamation bang.
! pip install requests
|
Django CMS Custom Plugin doesn't render the template
Question: Running a fresh install of django-cms 2.4.0-RC1, django 1.5.1 and python 2.7.
I'm trying to create a very simple custom plugin with a single field. The
plugin registers in the admin and works fine. It successfully stores in the
database. It's just not rendered in my template.
I have verified the render_template path and also tried using a hardcoded
absolute path. I have tried overriding the render method in
CMSSelectDegreeLevelPlugin.
Am I overlooking something obvious? I've made very similar plugins before (in
different versions of django-cms) and had no trouble.
**models.py:**
from cms.models.pluginmodel import CMSPlugin
from django.db import models
class SelectDegreeLevel(CMSPlugin):
degree_level = models.CharField('Degree Level', max_length=50)
**cms-plugins.py**
from cms.plugin_base import CMSPluginBase
from cms.plugin_pool import plugin_pool
from django.utils.translation import gettext_lazy as _
from models import SelectDegreeLevel
class CMSSelectDegreeLevelPlugin(CMSPluginBase):
model = SelectDegreeLevel
name = _('Degree Level')
render_template = "cms/plugins/select_degree_level.html"
plugin_pool.register_plugin(CMSSelectDegreeLevelPlugin)
**select_degree_level.html**
<h1>static text test {{ instance.degree_level }}</h1>
Answer: I think you field is not in the context. I do it normally over this way. Add
this function to you CMSSelectDegreeLevelPlugin Class
# Way to decide what comes in the context
def render(self, context, instance, placeholder):
extra_context = {
'degree_level': instance. degree_level,
}
context.update(extra_context)
return context
# Simplest Way
def render(self, context, instance, placeholder):
context['instance'] = instance
return context
[Also you can read more here in docs](http://docs.django-
cms.org/en/2.4.0.rc1/extending_cms/custom_plugins.html#storing-configuration)
|
getting an error while using time sleep method in python
Question: There is a weblogic python script that takes a thread dump and sleeps for 10
or 20 seconds then takes another one after time.sleep(30), thread dumps are
working fine, but the sleep method time.sleep(20) is not working.
Tried both `import time` and `from time import sleep` as well.
Getting this error below
AttributeError: java package 'weblogic.time' has no attribute 'sleep'
Answer: The problem here is that the `weblogic.time` package is shadowing the stdlib
`time` module. So, when you try to `import time`, you're getting the former,
not the latter.
(And `weblogic.time` has nothing in it but a subpackage or module
`weblogic.time.common`, so you get an error trying to use its `sleep`
function. But that's probably a good thing—better than it had a function named
`sleep` that didn't do what you expected.)
If you were developing `weblogic` itself, I could explain how to not do that…
but if you're just using `weblogic`, that's not going to help you.
If you're doing something like `from weblogic import *` earlier, the solution
is simple: Just don't do that. Otherwise… it will be more complicated to work
around.
But if all you need to do is block your interpreter thread for 20 seconds, you
can do that with the Java `Thread.sleep(20000)`. See [this
tutorial](http://docs.oracle.com/javase/tutorial/essential/concurrency/sleep.html),
but really, you don't need to know much more than that the Java method takes
integer milliseconds instead of float seconds. And then you don't need `time`.
|
Django/Python: How to group queryset results by date?
Question: I have a model for image uploads, that looks something like this:
from django.db import models
from django.contrib.auth.models import User
import datetime
class ImageItem(models.Model):
user = models.ForeignKey(User)
upload_date = models.DateTimeField(auto_now_add = True)
last_modified = models.DateTimeField(auto_now = True)
original_img = models.ImageField(upload_to = img_get_file_path)
I want to query all instances of ImageItem that belong to a particular user,
and group them according to _date uploaded_. For example, for some user, I
want a group for April 9 2013, another for April 12 2013, etc. (assuming that
they uploaded one or more images on those dates).
I'm thinking I run a simple query, like,
joes_images = ImageItem.objects.filter(user__username='joe')
**But then how could I group them by day published?** (assuming he did not
publish every day, only on some days)
The function would have to return all the groups of images.
Answer: why don't you do as following?
joes_images = ImageItem.objects.filter(user__username='joe') # your code
upload_dates = set([(i.year, i.month, i.day) for i in joes_images]) # set of upload_date
joes_images_separated = dict([(d, []) for d in upload_dates])
for d in upload_dates:
for i in joes_images:
if (i.year, i.month, i.day) == d:
joes_images_separated[d].append(i)
Here, `upload_dates` is a set of dates in `joes_images` and you get
`joes_images_separated` as a dict (keys are dates, values are lists of
`joes_images` for each date).
I'm sorry for a little dirty code. I think this works. for your information.
|
Python won't run due to ImportError: cannot import MAXREPEAT
Question: I am new to python but have been using both IDLE and EricIDE for a few weeks
without any major problems.
I was editing a program I had written that called `random.randint()` function
and it wouldn't work.
Previously, this program had been working and I had not changed that call out.
I then loaded another program that uses the same function that had been
working and it would not run either.
I tried to load the program in IDLE but IDLE wouldn't load. After trying
several reboots and reloads EricIDE wouldn't load either. I noticed a black
window popping up and disappearing quickly when I try to launch either IDE
from my previously working desktop shortcuts.
Searching for help led me to run python shell from the windows command line by
going to `C:\python33\ and typing "python" to run python shell`, I get:
File "C:\python33\lib\sre_constants.py", line 18, in (module)
from _sre import MAXREPEAT
ImportError: cannot import name MAXREPEAT
I am using Windows 8 (new to it as well and still trying to figure it out).
At this point I'm assuming my problem is with my python installation since the
python shell won't work. I have uninstalled and reinstalled Python 3.3.1 but
the problem persists. I also deleted the .idlerc folder from my Users
directory as suggested in another thread that was similar to my problem but
that doesn't seem to have helped either.
Thank you for any help you can provide.
* * *
response to eryksun:
C:\Python33>python.exe -c "import sys; print(sys.path)"
Traceback (most recent call last):
File "C:\Python33\lib\site.py", line 70, in <module>
import re
File "C:\Python33\lib\re.py", line 122, in <module>
import sre_compile
File "C:\Python33\lib\sre_compile.py", line 14, in <module>
import sre_parse
File "C:\Python33\lib\sre_parse.py", line 17, in <module>
from sre_constants import *
File "C:\Python33\lib\sre_constants.py", line 18, in <module>
from _sre import MAXREPEAT
ImportError: cannot import name MAXREPEAT
C:\Python33>python.exe -S -c "import sys; print(sys.path)"
['', 'C:\\Python33\\python33.zip', 'C:\\Python33\\DLLs',
'C:\\Python33\\lib', 'C:\\Python33']
Follow up to to eryksun:
C:\Python33>python.exe -S -c "import _imp; _sre = _imp.init_builtin('_sre');
print(_sre.MAXREPEAT)"
Traceback (most recent call last):
File "<string>", line 1, in <module>
AttributeError: 'module' object has no attribute 'MAXREPEAT'
Answer: I suggest you uninstall. Completely remove `C:\Python33` and also
`C:\Windows\System32\python33.dll`. `_sre` is built in to the latter DLL.
`MAXREPEAT` is set by its initialization
function[`PyInit__sre`](http://hg.python.org/cpython/file/d9893d13c628/Modules/_sre.c#l3950)
(Modules/_sre.c). Clearly, something is wrong there.
When you download the 3.3.1 installer, make sure you get the right binary for
your platform, i.e. x86 for 32-bit Windows and X86-64 for 64-bit Windows.
|
os.walk to find path to file issue (Python 2.7)
Question: I've just starting using python 2.7 and was using the following code to
ascertain the path to a file:
import os, fnmatch
#find the location of sunnyexplorer.exe
def find_files(directory, pattern):
for root, dirs, files in os.walk(directory):
for basename in files:
if fnmatch.fnmatch(basename, pattern):
filename = os.path.join(root, basename)
yield filename
for filename in find_files('c:\users','*.sx2'):
print ('Found Sunny Explorer data in:', filename)
everthing seemed to be working fine until I tried to use the path and noticed
an error. The program reports the path as:
c:\users\woody\Documents\SMA\Sunny Explorer
whereas the correct path is:
c:\users\woody\My Documents\SMA\Sunny Explorer
Answer: All versions of MS Windows since Vista store a user's documents in
`C:\Users\%username%\Documents` by default.
However, they also include an [NTFS junction
point](http://en.wikipedia.org/wiki/NTFS_junction_point)
`C:\Users\%username%\My Documents` which points to the same location for
backward compatibility.
The problem is, as I understand it, that you can't work with junction points
with standard POSIX calls, so Python will not be able to use them without some
Windows-specific extension module.
See also [this question](http://superuser.com/questions/194500/how-to-link-my-
documents-folder-to-the-logical-documents-folder-in-windows-7) on
superuser.com.
|
Python lambda to print formatted nested list
Question: Practicing a couple things: lambda functions and string manipulations. I want
to find the most efficient ways of doing this without importing anything.
so here's a short script that reorders a word alphabetically:
def alphabeticalOrder(word):
lst = [l for l in word]
return sorted(lst)
def main ():
word = raw_input('enter word: ')
print "".join(alphabeticalOrder(word))
if __name__ == '__main__':
main()
and I wanted to do this for all words in a sentence:
def alphabeticalOrder(line):
lst = []
for word in line.split(" "):
lst.append(sorted(list(word)))
print lst # trouble here
def main ():
line = raw_input('enter sentence: ')
print alphabeticalOrder(line)
if __name__ == '__main__':
main()
So my question is; can you write a lambda function to iterate through the
nested lists in `lst` that prints out each item as a just a string of
alphabetically reordered words?
Answer: List comprehensions are much easier here:
' '.join([''.join(sorted(word)) for word in sentence.split()])
Note that we can pass the string to `sorted()` _directly_.
A lambda is nothing more than a function with a single expression, which can
be defined as an expression itself; here I assign the lambda result to a
variable first:
alphabeticalWord = lambda w: ''.join(sorted(word))
' '.join([alphabeticalWord(word) for word in sentence.split()])
|
Efficiently Reading Large Files with ATpy and numpy?
Question: I've looked all over for an answer to this one, but nothing really seems to
fit the bill. I've got very large files that I'm trying to read with ATpy, and
the data comes in the form of numpy arrays. For smaller files the following
code has been sufficient:
sat = atpy.Table('satellite_data.tbl')
From there I build up a number of variables that I have to manipulate later
for plotting purposes. It's lots of these kinds of operations:
w1 = np.array([sat['w1_column']])
w2 = np.array([sat['w2_column']])
w3 = np.array([sat['w3_column']])
colorw1w2 = w1 - w2 #just subtracting w2 values from w1 values for each element
colorw1w3 = w1 - w3
etc.
But for very large files the computer can't handle it. I think all the data is
getting stored in memory before parsing begins, and that's not feasible for
2GB files. So, what can I use instead to handle these large files?
I've seen lots of posts where people are breaking up the data into chunks and
using `for` loops to iterate over each line, but I don't think that's going to
work for me here given the nature of these files, and the kinds of operations
I need to do on these arrays. I can't just do a single operation on every line
of the file, because each line contains a number of parameters that are
assigned to columns, and in some cases I need to do multiple operations with
figures from a single column.
Honestly I don't really understand everything going on behind the scenes with
ATpy and numpy. I'm new to Python, so I appreciate answers that spell it out
clearly (i.e. not relying on lots of implicit coding knowledge). There has to
be a clean way of parsing this, but I'm not finding it. Thanks.
Answer: For very large arrays (larger than your memory capacity) you can use
[pytables](http://pytables.org) which stores arrays on disk in some clever
ways (using the HDF5 format) so that manipulations can be done on them without
loading the entire array into memory at once. Then, you won't have to manually
break up your datasets or manipulate them one line at a time.
I know nothing about ATpy so you might be better off asking on an ATpy mailing
list or at least some astronomy python users mailing list, as it's possible
that ATpy has another solution built in.
* * *
From the pyables website:
> PyTables is a package for managing hierarchical datasets and designed to
> efficiently and easily cope with extremely large amounts of data.
>
> PyTables is built on top of the HDF5 library, using the Python language and
> the NumPy package.
>
> ... fast, yet extremely easy to use tool for interactively browse, process
> and search very large amounts of data. One important feature of PyTables is
> that it optimizes memory and disk resources so that data takes much less
> space...
|
python list to dictionary with dates as keys
Question: I'm trying to create a dictionary from this list using dates as keys and
successive items as its value.
lst = ['Thu Apr 04', ' Weigh In', 'Sat Apr 06', ' Collect NIC', ' Finish PTI Video', 'Wed Apr 10', ' Serum uric acid test', 'Sat Apr 13', ' 1:00pm', 'Get flag from dhariwal', 'Sun Apr 14', ' Louis CK Oh My God', ' 4:00pm', 'UPS Guy']
dict = {}
for item in lst:
if item.startswith(('Mon','Tue','____Wed','Thu','Fri','Sat','Sun'__))__:
dict[item] = []
saveItem = item
else:
dict[saveItem].append(item.____strip())
Keeps giving me syntax error.
P.S. not my code
Answer:
import itertools as IT
items = ['Thu Apr 04', ' Weigh In', 'Sat Apr 06', ' Collect NIC', ' Finish PTI Video', 'Wed Apr 10', ' Serum uric acid test', 'Sat Apr 13', ' 1:00pm', 'Get flag from dhariwal', 'Sun Apr 14', ' Louis CK Oh My God', ' 4:00pm', 'UPS Guy']
date_word = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')
def isdate(datestring):
return any(datestring.startswith(d) for d in date_word)
items = (item.strip() for item in items)
data = (list(group) for key, group in IT.groupby(items, key=isdate))
for date, items in IT.izip(*[data]*2):
print('{d} {i}'.format(d=date[0], i=items))
yields
Thu Apr 04 ['Weigh In']
Sat Apr 06 ['Collect NIC', 'Finish PTI Video']
Wed Apr 10 ['Serum uric acid test']
Sat Apr 13 ['1:00pm', 'Get flag from dhariwal']
Sun Apr 14 ['Louis CK Oh My God', '4:00pm', 'UPS Guy']
* * *
* You could use [IT.groupby](http://docs.python.org/2/library/itertools.html#itertools.groupby) to group the items as desired.
* If you don't don't dump the items into a dict, you can preserve the order in which the items appear.
* You can use the `zip(*[iterator]*2)` [grouper recipe](http://docs.python.org/2/library/itertools.html#itertools.izip) to group items in pairs.
* Avoid using variable names like `dict` since they shadow the Python builtin object of the same name.
|
Fast, small, and repetitive matrix multiplication in Python
Question: I'm looking for a way to very quickly multiply together many 4x4 matrices
using Python/Cython/Numpy, can anyone give any suggestions?
To show my current attempt, I have an algorithm which needs to compute
A_1 * A_2 * A_3 * ... * A_N
where every
A_i != A_j
An example of it in Python:
means = array([0.0, 0.0, 34.28, 0.0, 0.0, 3.4])
stds = array([ 4.839339, 4.839339, 4.092728, 0.141421, 0.141421, 0.141421])
def fn():
steps = means+stds*numpy.random.normal(size=(60,6))
A = identity(4)
for step in steps:
A = dot(A, transform_step_to_4by4(step))
%timeit fn()
1000 loops, best of 3: 570 us per loop
Implementing this algorithm in Cython/Numpy is approximately 100x slower than
the equivalent code using Eigen/C++ with all optimizations. I really don't
want to use C++, though.
Answer: If you are having to make a Python function call to produce each of the
matrices you want to multiply, then you are basically screwed performance-
wise. But if you can vectorize the `transform_step_to_4by4` function, and have
it return an array with shape `(n, 4, 4)` then you can save some time using
`matrix_multiply`:
import numpy as np
from numpy.core.umath_tests import matrix_multiply
matrices = np.random.rand(64, 4, 4) - 0.5
def mat_loop_reduce(m):
ret = m[0]
for x in m[1:]:
ret = np.dot(ret, x)
return ret
def mat_reduce(m):
while len(m) % 2 == 0:
m = matrix_multiply(m[::2], m[1::2])
return mat_loop_reduce(m)
In [2]: %timeit mat_reduce(matrices)
1000 loops, best of 3: 287 us per loop
In [3]: %timeit mat_loop_reduce(matrices)
1000 loops, best of 3: 721 us per loop
In [4]: np.allclose(mat_loop_reduce(matrices), mat_reduce(matrices))
Out[4]: True
You now have log(n) Python calls instead of n, good for a 2.5x speed-up, which
will get close to 10x for n = 1024. Apparently `matrix_multiply` is a ufunc,
and as such has a `.reduce` method, which would allow your code to run no
loops in Python. I have not been able to make it run though, keep getting an
arcane error:
In [7]: matrix_multiply.reduce(matrices)
------------------------------------------------------------
Traceback (most recent call last):
File "<ipython console>", line 1, in <module>
RuntimeError: Reduction not defined on ufunc with signature
|
ComplexWarning when calling convolve2d() in SciPy, why?
Question: When I run
from scipy.signal import convolve2d
convolve2d([[2, 2, 2], [1, 2, 3], [0, 1, 0]], [[0.5], [0.5]], 'valid')
I get
Warning (from warnings module):
File "C:\Program Files\Python 2.7\lib\site-packages\scipy\signal\signaltools.py", line 422
return sigtools._convolve2d(in1, in2, 1, val, bval, fillvalue)
ComplexWarning: Casting complex values to real discards the imaginary part
Why am I getting this, and how do I properly prevent it?
Answer: This is a bug that was fixed in release 0.12.0.
|
Python 3.3 undefined references with static linking
Question: Operating System: Ubuntu 12.04 x86_64
I've compiled libpython3.3m.a from source, along with the related headers. I
wrote the following Makefile (specifically, look at my CFLAGS variable, which
includes -lpython3.3m)...
BINS=python python-d
SOURCES=python.cpp
LIBROOT=/home/uberblah/lib/cpp
LIBDIR=$(LIBROOT)/lib
BINDIR=$(LIBROOT)/bin
INCDIR=$(LIBROOT)/include
CFLAGS= -I$(INCDIR)/python3.3m -L$(LIBDIR) -lpython3.3m
all: $(BINS)
python-d: $(SOURCES)
g++ $(CFLAGS) -g -o $@ $^
python: $(SOURCES)
g++ $(CFLAGS) -o $@ $^
clean::
rm -r -f *~ $(BINS)
edit::
gedit $(SOURCES) Makefile &
And I wrote the following .cpp source file...
#include <Python.h>
int main(int argc, char** argv)
{
Py_SetProgramName((wchar_t*)argv[0]); /* optional but recommended */
Py_Initialize();
PyRun_SimpleString("from time import time,ctime\n"
"print 'Today is',ctime(time())\n");
Py_Finalize();
return 0;
}
Typing make in the Makefile's directory results in the following messages.
g++ -I/home/uberblah/lib/cpp/include/python3.3m -L/home/uberblah/lib/cpp/lib -lpython3.3m -o python python.cpp
/tmp/ccBD4sLY.o: In function `main':
python.cpp:(.text+0x1a): undefined reference to `Py_SetProgramName'
python.cpp:(.text+0x1f): undefined reference to `Py_Initialize'
python.cpp:(.text+0x2e): undefined reference to `PyRun_SimpleStringFlags'
python.cpp:(.text+0x33): undefined reference to `Py_Finalize'
collect2: ld returned 1 exit status
make: *** [python] Error 1
Based on my understanding of the '-l' argument for g++, it is finding
libpython3.3m.a, because otherwise it would tell me it was unable to find the
library and exit.
So, if it's finding the library, why aren't these functions defined?
ADDITIONAL NOTES...
Built Python using --prefix and altinstall to have it install to a new
directory (the one I'm pointing LIBROOT to in my makefile).
I have confirmed that libpython3.3m.a is in $(LIBDIR)
using nm to check for Py_SetProgramName...
uberblah@uberblah-N80Vm:~/lib/cpp/lib$ nm libpython3.3m.a | grep Py_SetProgramName
U Py_SetProgramName
0000000000001c00 T Py_SetProgramName
U Py_SetProgramName
Running Make verbosely...
...
Finished prerequisites of target file `python'.
Must remake target `python'.
g++ -I/home/uberblah/lib/cpp/include/python3.3m -L/home/uberblah/lib/cpp/lib -lpython3.3m -o python python.cpp
Putting child 0x00a585b0 (python) PID 16811 on the chain.
Live child 0x00a585b0 (python) PID 16811
/tmp/cc2dom1S.o: In function `main':
python.cpp:(.text+0x1a): undefined reference to `Py_SetProgramName'
python.cpp:(.text+0x1f): undefined reference to `Py_Initialize'
python.cpp:(.text+0x2e): undefined reference to `PyRun_SimpleStringFlags'
python.cpp:(.text+0x33): undefined reference to `Py_Finalize'
collect2: ld returned 1 exit status
Reaping losing child 0x00a585b0 PID 16811
make: *** [python] Error 1
Removing child 0x00a585b0 PID 16811 from chain.
If I split the compilation into an object stage then a binary stage, the
binary stage fails with the same error message as originally mentioned.
Answer: Found the solution: Python actually installs with its own solution to this.
It's talked about in this post (I knew my header wasn't missing, but I was
being dumb and trying to link it all up myself, thinking "Oh, this is just
what anyone needs to do to get Python working on my platform")...
[Python.h header missing](http://stackoverflow.com/questions/10622668/python-
h-header-missing)
|
Pylint - How to print Pylint's sys.path?
Question: I'm attempting to add modules to my Pylint path so they can be imported by
using the solution as [seen in this
question](http://stackoverflow.com/questions/1899436/pylint-unable-to-import-
error-how-to-set-pythonpath). Unfortunately, the modules I expect should be
available for import after using this solution still don't seem to be there. I
want to check if the path's I'm trying to add to Pylint were actually added or
not. Is there a simple way to print out the sys.path of Pylint? Thank you
much!
Answer: Pylint should use `PYTHONPATH` in the same way as the Python interpreter. If
not, it may be considered as a bug and reported as such.
You may want to try `pylint --init-hook 'print(sys.path)'` to run pylint while
displaying its Python path at first.
|
LinkedIn API Python Key Error 2.7
Question: This code is available online to run a map of your connections in linkedin
This uses linkedin api. I'm able to connect fine and everything runs okay till
the last script of actually writing the data to a csv.
Whenever I run the code
import oauth2 as oauth
import urlparse
import simplejson
import codecs
CONSUMER_KEY = "xxx"
CONSUMER_SECRET = "xxx"
OAUTH_TOKEN = "xxx"
OAUTH_TOKEN_SECRET = "xxx"
OUTPUT = "linked.csv"
def linkedin_connections():
# Use your credentials to build the oauth client
consumer = oauth.Consumer(key=CONSUMER_KEY, secret=CONSUMER_SECRET)
token = oauth.Token(key=OAUTH_TOKEN, secret=OAUTH_TOKEN_SECRET)
client = oauth.Client(consumer, token)
# Fetch first degree connections
resp, content = client.request('http://api.linkedin.com/v1/people/~/connections?format=json')
results = simplejson.loads(content)
# File that will store the results
output = codecs.open(OUTPUT, 'w', 'utf-8')
# Loop thru the 1st degree connection and see how they connect to each other
for result in results["values"]:
con = "%s %s" % (result["firstName"].replace(",", " "), result["lastName"].replace(",", " "))
print >>output, "%s,%s" % ("John Henry", con)
# This is the trick, use the search API to get related connections
u = "https://api.linkedin.com/v1/people/%s:(relation-to-viewer:(related-connections))?format=json" % result["id"]
resp, content = client.request(u)
rels = simplejson.loads(content)
try:
for rel in rels['relationToViewer']['relatedConnections']['values']:
sec = "%s %s" % (rel["firstName"].replace(",", " "), rel["lastName"].replace(",", " "))
print >>output, "%s,%s" % (con, sec)
except:
pass
if __name__ == '__main__':
linkedin_connections()
for result in results["values"]:
KeyError: 'values'
When I run this I get an error message:
Traceback (most recent call last):
File "linkedin-2-query.py", line 51, in <module>
linkedin_connections()
File "linkedin-2-query.py", line 35, in linkedin_connections
for result in results["values"]:
KeyError: 'values'
Any suggestions or help would be greatly appreciated!
Answer: I encountered the same issue working through the post [Visualizing your
LinkedIn graph using Gephi – Part 1](http://dataiku.com/visualizing-your-
linkedin-graph-using-gephi-part-1/#comment-723).
> Python raises a KeyError whenever a dict() object is requested (using the
> format a = adict[key]) and the key is not in the dictionary. [KeyError -
> Python Wiki](http://wiki.python.org/moin/KeyError)
After searching a bit and adding some print statements, I realize that my
OAuth session has expired, so the OAuth token in my
[`linkedin-2-query.py`](https://gist.github.com/micahstubbs/5744765) script
was is longer valid.
Since the OAuth token is invalid, the LinkedIn API does not return a
dictionary with the key `"values"` like the script expects. Instead, the API
returns the string `'N'`. Python tries to find the dict key `"values"`in the
string `'N'`, fails, and generates the `KeyError: 'values'`.
So a new, valid OAuth token & secret should get the API to return a dict
containing connection data.
* * *
I run the [`linkedin-1-oauth.py`](https://gist.github.com/micahstubbs/5744717)
script again, and then visit the LinkedIn [Application details
page](https://www.linkedin.com/secure/developer) to find my new OAuth token.
(The screenshot omits the values for my app. You should see alphanumeric
values for each Key, Token, & Secret.)

**...**

I then update my
[`linkedin-2-query.py`](https://gist.github.com/micahstubbs/5744765) script
with the new **OAuth User Token** and **OAuth User Secret**
OAUTH_TOKEN = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" # your updated OAuth User Token
OAUTH_TOKEN_SECRET = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" # your updated OAuth User Secret
After updating the OAuth token & secret, I immediately run my
[`linkedin-2-query.py`](https://gist.github.com/micahstubbs/5744765) script.
Hooray, it runs without errors and retrieves my connection data from the API.
|
Importing django modules from java
Question: I am trying to call some classes from my django project using Java. Here is my
code:
PythonInterpreter interpreter = new PythonInterpreter();
PySystemState sys = Py.getSystemState();
sys.path.append(new PyString("/Library/Python/2.7/site-packages/"));
sys.path.append(new PyString("/myApps/categoryApp/review/"));
interpreter.exec("from products.models import Category");
But I got this error:
Exception in thread "main" Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/myApps/categoryApp/review/products/models.py", line 4, in <module>
from django.core.exceptions import ValidationError
File "/Library/Python/2.7/site-packages/django/core/exceptions.py", line 4, in <module>
from functools import reduce
ImportError: cannot import name reduce
Any idea solving it? I believe there is something wrong with the imports
Answer: The standard version of Jython is compatible with Python 2.5. As described in
the [documentation on running Django on
Jython](https://docs.djangoproject.com/en/1.5/howto/jython/), Django 1.5 only
compatible in Python 2.6 upwards. You will need to run the 2.7 beta version of
Jython, or the older 1.4 version of Django.
|
How to print commands in Python?
Question: I'm not in the programming area but I recently got interested in Python. I was
writing some functions but for debugging I need to see what commands are
running. For instance:
def foo():
for i in xrange(0,5):
a = 1 + i
Is it possible to make the interpreter output
>>> for i in xrange(0,5)
>>> a = 1 + 0
>>> a = 1 + 1
>>> a = 1 + 2
>>> a = 1 + 3
>>> a = 1 + 4
For
>>> foo()
Or at least write to a file what is happening? I did some scripting in the
past and I remember that this was possible in DOS, using @ECHO ON or
something. I did some reading and I feel like it's related to stdin and stdout
in Python so I tried
import sys
def foo():
for i in xrange(0,5):
a = 1 + i
sys.stdin.flush()
sys.stdout.flush()
But I get nothing... I also tried
import sys
# foo()
sys.stdin.read()
sys.stdout.read()
and <http://stackoverflow.com/a/3289051/2032568>, but it just hangs. Sorry if
this is not the right place for beginners. I couldn't find anything that
answers my question.
Answer: To make the interpreter print out expression values during runtime you can use
the [print](http://docs.python.org/2/reference/simple_stmts.html#print)
statement. Also take a note of Python's [string formatting
facilities](http://stackoverflow.com/q/5082452/1025391).
Example:
for i in xrange(0,5):
a = 1 + i
# print the value of a:
print "the current value of variable 'a':", a
There is no need to flush stdout explicitly, unless you want to enforce to
print out lines without a terminating newline:
import sys
import time
for i in xrange(0,5):
a = 1 + i
# print the value of a:
# the trailing comma prevents 'print' from adding a newline
print "\rthe current value of variable 'a':", a,
sys.stdout.flush()
# short pause for purposes of demonstration
time.sleep(1)
# finally print a newline
print
* * *
To print each statement before it's executed have a look at the
[trace](http://docs.python.org/2/library/trace.html) module.
Example:
y = 0
for xi in range(3):
y += xi
print y
The output:
$ python -m trace -t tt.py
--- modulename: tt, funcname: <module>
tt.py(2): y = 0
tt.py(3): for xi in range(3):
tt.py(4): y += xi
tt.py(3): for xi in range(3):
tt.py(4): y += xi
tt.py(3): for xi in range(3):
tt.py(4): y += xi
tt.py(3): for xi in range(3):
tt.py(5): print y
3
--- modulename: trace, funcname: _unsettrace
trace.py(80): sys.settrace(None)
* * *
What you are looking for in the first place, might also be a debugger, e.g.
[pdb](http://docs.python.org/2/library/pdb.html). You get an interactive
session, where you can step through the code, and have a look at the data
interactively.
Example:
$ python -m pdb tt.py
> /home/moooeeeep/tt.py(2)<module>()
-> y = 0
(Pdb) n
> /home/moooeeeep/tt.py(3)<module>()
-> for xi in range(3):
(Pdb) n
> /home/moooeeeep/tt.py(4)<module>()
-> y += xi
(Pdb) n
> /home/moooeeeep/tt.py(3)<module>()
-> for xi in range(3):
(Pdb) n
> /home/moooeeeep/tt.py(4)<module>()
-> y += xi
(Pdb) print y, xi
0 1
(Pdb)
...
Most Python IDEs (e.g., [PyDev](http://pydev.org/)) have nicely integrated
debugging functionality. So my suggestion: go and get a debugger.
|
Python: How to hash a string into 8 digits?
Question: Is there anyway that I can hash a random string into a 8 digit number without
implementing any algorithms myself? Thanks.
Answer: Yes, you can use the built-in
[_hashlib_](http://docs.python.org/2.7/library/hashlib.html#module-hashlib)
modules or the built-in
[_hash_](http://docs.python.org/2.7/library/functions.html#hash) function.
Then, chop-off the last eight digits using modulo operations or string slicing
operations on the integer form of the hash:
>>> s = 'she sells sea shells by the sea shore'
>>> # Use hashlib
>>> import hashlib
>>> int(hashlib.sha1(s).hexdigest(), 16) % (10 ** 8)
58097614L
>>> # Use hash()
>>> abs(hash(s)) % (10 ** 8)
82148974
|
What's the best way to find unique unhashable unorderable types in Python 3
Question: So in Python 2 you could use something like
>>> items = [[1, 2], [3], [3], 4, 'a', 'b', 'a']
>>> from itertools import groupby
>>> [k for k, g in groupby(sorted(items))]
[4, [1, 2], [3], 'a', 'b']
Which works well, in `O(N log N)` time. However Python 3 exclaims `TypeError:
unorderable types: int() < list()`. So What's the best way to do it in Python
3? (I know best is a subjective term but really there should be one way of
doing it according to Python)
EDIT: It doesn't have to use a sort, but I'm guessing that would be the best
way
Answer: In 2.x, values of two incomparable built-in types are ordered by type. The
order of the types is not defined, except that it will be consistent during
one run of the interpreter. So, `2 < [2]` may be true or false, but it will be
_consistently_ true or false.
In 3.x, values of incomparable built-in types are incomparable—meaning they
raise a `TypeError` if you try to compare them. So, `2 < [2]` is an error.
And, at least as of 3.3, the types themselves aren't even comparable. But if
all you want to reproduce is the 2.x behavior, their `id`s are definitely
comparable, and consistent during a run of the interpreter. So:
sorted(items, key=lambda x: (id(type(x)), x))
For your use case, that's all you need.
* * *
However, this won't be exactly the same thing that 2.x does, because it means
that, for example, `1.5 < 2` may be `False` (because `float` > `int`). If you
want to duplicate the exact behavior, you need to write a key function that
first tries to compare the values, then on `TypeError` falls back to comparing
the types.
This is one of the few cases where an old-style `cmp` function is a lot easier
to read than a new-style `key` function, so let's write one of those, then use
[`cmp_to_key`](http://docs.python.org/3.3/library/functools.html#functools.cmp_to_key)
on it:
def cmp2x(a, b):
try:
if a==b: return 0
elif a<b: return -1
elif b<a: return 1
except TypeError:
pass
return cmp2x(id(type(a)), id(type(b)))
sorted(items, key=functools.cmp_to_key(cmp2x))
This still doesn't guarantee the same order between two values of different
types that 2.x would give, but since 2.x didn't define any such order (just
that it's consistent within one run), there's no way it could.
There is still one real flaw, however: If you define a class whose objects are
not fully-ordered, they will end up sorting as equal, and I'm not sure this is
the same thing 2.x would do in that case.
|
Decoding JSON with Python
Question: Why do I get
> ValueError: No JSON object could be decoded
from this code:
import urllib.request,json
n = urllib.request.urlopen("http://graph.facebook.com/55")
d = json.loads(str(n.readall()))
The full error:
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
d= json.loads(str(n.readall()))
File "C:\Python33\lib\json\__init__.py", line 309, in loads
return _default_decoder.decode(s)
File "C:\Python33\lib\json\decoder.py", line 352, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Python33\lib\json\decoder.py", line 370, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
The output of `str(n.readall())`:
'b\'{"id":"55","name":"Jillian Copeland","first_name":"Jillian","last_name":"Copeland","username":"JCoMD","gender":"female","locale":"en_US"}\''
Maybe the `b` is throwing it off?
If that is the issue, how do I convert the binary stream from the `readall` to
a string and not have that `b`?
I am trying to learn a little python so please keep that in mind.
I am using Python 3.3 in Windows.
Answer: I believe that this is an exact duplicate of [this
question](http://stackoverflow.com/questions/10846112/use-byte-like-object-
from-urlopen-read-with-json), but sadly there's no accepted answer.
On my end, this works:
import urllib.request,json
n = urllib.request.urlopen("http://graph.facebook.com/55")
d= json.loads(n.readall().decode('utf-8'))
|
Reading Web-Based XML file and parsing it in Python
Question: I am very new to Python and GAE but I am attempting to download an XML file
from the eventful.com api (in XML), parsing it and I will then storing this
information within a database on Google Cloud SQL.
My code so far is as follows which I have managed to write after looking at
various online tutorials however I keep receiving many errors and the code
will not work for me at all. If anyone has any pointers on where I am going
wrong please let me know, Karen.
My Attempt to call the eventful xml file and parse it:
import webapp2
from google.appengine.ext.webapp import template
import os
import datetime
from google.appengine.ext import db
from google.appengine.api import urlfetch
import urllib #import python library which does http requests
from xml.dom import parseString #imports xml parser called minidom
class XMLParser(webapp2.RequestHandler):
def get(self):
base_url = fetch('http://api.eventful.com/rest/events/search?app_key=zGtDX6cwQ=dublin&?q=music')
#downloads data from xml file
response = urllib.urlopen(base_url)
#converts data to string:
data = response.read()
#closes file
response.close()
#parses xml downloaded
dom = parseString(data)
#retrieves the first xml tag that the parser finds with name tag
xmlTag = dom.getElementsByTagName('title')[0].toxml()
#strip off the tag to just reveal event name
xmlData = xmlTag.replace('<title>', '').replace('</title>', '')
#print out the xml tag and data in this format:
print xmlTag
#just print the data
print xmlData
I receive the following errors when I try to run this code however in Google
App Engine user the GAE launcher -
2013-04-15 16:52:05 Running command: "['C:\\Python27\\python.exe', 'C:\\Program Files (x86)\\Google\\google_appengine\\dev_appserver.py', '--skip_sdk_update_check=yes', '--port=8080', '--admin_port=8002', u'C:\\Users\\Karen\\Desktop\\Development\\own_tada']"
INFO 2013-04-15 16:52:17,944 devappserver2.py:498] Skipping SDK update check.
WARNING 2013-04-15 16:52:18,005 api_server.py:328] Could not initialize images API; you are likely missing the Python "PIL" module.
INFO 2013-04-15 16:52:18,065 api_server.py:152] Starting API server at: http://localhost:54619
INFO 2013-04-15 16:52:18,085 dispatcher.py:150] Starting server "default" running at: http://localhost:8080
INFO 2013-04-15 16:52:18,095 admin_server.py:117] Starting admin server at: http://localhost:8002
ERROR 2013-04-15 15:52:35,767 wsgi.py:219]
Traceback (most recent call last):
File "C:\Program Files (x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line 196, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "C:\Program Files (x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line 255, in _LoadHandler
handler = __import__(path[0])
File "C:\Users\Karen\Desktop\Development\own_tada\own.py", line 8, in <module>
from xml.dom import parseString #imports xml parser called minidom
ImportError: cannot import name parseString
INFO 2013-04-15 16:52:35,822 server.py:561] default: "GET / HTTP/1.1" 500 -
ERROR 2013-04-15 15:52:37,586 wsgi.py:219]
Traceback (most recent call last):
File "C:\Program Files (x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line 196, in Handle
handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
File "C:\Program Files (x86)\Google\google_appengine\google\appengine\runtime\wsgi.py", line 255, in _LoadHandler
handler = __import__(path[0])
File "C:\Users\Karen\Desktop\Development\own_tada\own.py", line 8, in <module>
from xml.dom import parseString #imports xml parser called minidom
ImportError: cannot import name parseString
INFO 2013-04-15 16:52:37,617 server.py:561] default: "GET /favicon.ico HTTP/1.1" 500 -
One such tutorial I used for the above code comes from the following URL:
<http://www.travisglines.com/web-coding/python-xml-parser-tutorial>
EDIT:
Thanks to the help provided by Josh below I now am not receiving any errors
when I launch my code with my code, however I only see a blank screen and want
it to print out the parsed information (or its progress this far). I know this
may seem like a very stupid question but I really am a beginner so I'm sorry!
Fixed code (minus errors) is :
import webapp2
from google.appengine.ext.webapp import template
import os
import datetime
from google.appengine.ext import db
from google.appengine.api import urlfetch
import urllib #import python library which does http requests
import xml.dom.minidom as mdom #imports xml parser called minidom
class XMLParser(webapp2.RequestHandler):
def get(self):
base_url = 'http://api.eventful.com/rest/events/search?app_key=zGtDX6cwQjCRdkf6&l=dublin&?q=music'
#downloads data from xml file
response = urllib.urlopen(base_url)
#converts data to string:
data = response.read()
#closes file
response.close()
#parses xml downloaded
dom = mdom.parseString(data)
#retrieves the first xml tag that the parser finds with name tag
xmlTag = dom.getElementsByTagName('title')[0].toxml()
#strip off the tag to just reveal event name
xmlData = xmlTag.replace('<title>', '').replace('</title>', '')
#print out the xml tag and data in this format:
print xmlTag
#just print the data
print xmlData
app = webapp2.WSGIApplication([('/', XMLParser),
],
debug=True)
Any guidelines on what to do next would be greatly appreciated or anything on
what you can spot is wrong with my python code, Thank you!
Answer: Appengine supports [lxml](http://lxml.de/parsing.html) it is very simple to
[include](https://developers.google.com/appengine/docs/python/python25/diff27#Supported_Third-
Party_Libraries) it and parse your document with it.
In your app.yaml file
libraries:
- name: lxml
- version: latest
and then `import lxml` and follow the [parsing](http://lxml.de/parsing.html)
instructions
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.