text
stringlengths 226
34.5k
|
---|
Python SFTP download files older than x and delete networked storage
Question: I'd like to download some files via sftp that are older than say 2 hours. Then
I'd like to delete them from the network site. I can use the following code
for sftp but handling objects on the remote machine is giving me problems. The
code below fails at the 'timestamp = os.stat" line I believe it is an os
module issue?
import paramiko, sys, os,time
host = 'ftp address'
port = 22
transport = paramiko.Transport((host, port))
password = "pass" #hard-coded
username = "user" #hard-coded
transport.connect(username = username, password = password)
sftp = paramiko.SFTPClient.from_transport(transport)
print 'SFTP Client initiated'
remotepath = "/remote folder/"
localpath = '/local folder/'
for file in sftp.listdir('.'):
fullpath = os.path.join('.',file)
timestamp = os.stat(fullpath).st_ctime # get timestamp of file
createtime = datetime.datetime.fromtimestamp(timestamp)
now = datetime.datetime.now()
delta = now -createtime
if delta.hours > 2:
sftp.get(file,localpath)
sftp.remove(file)
sftp.close()
transport.close()
Answer: The bit required for getting the timestamp of the file on remote machine and
then comparing it to now is below. Hacked together by a non-programmer (me)
but it works.
timestamp = sftp.stat(fullpath).st_atime # get timestamp of file in epoch seconds
createtime = datetime.datetime.now()
now = time.mktime(createtime.timetuple())
datetime.timedelta = now - timestamp
if datetime.timedelta> x:
do something
|
NameError at / name 'editareapage' is not defined
Question: Ok so i am a noob building a basic site in django with python. I am trying to
implement a new page in my site called edit area. Whenever i visit the page
all i get is this...
NameError at /
name 'editareapage' is not defined
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.4.1
Exception Type: NameError
Exception Value:
name 'editareapage' is not defined
My views.py
from django.http import HttpResponse
from django.shortcuts import render_to_response
import datetime
def hello(request):
return HttpResponse("Hello, World!")
def mainpage(request):
return render_to_response('mainpage.html')
def current_datetime(request):
now = datetime.datetime.now()
return render_to_response('current_datetime.html', {'current_time':now})
def hours_ahead(request,offset):
try:
offset= int(offset)
except ValueError:
raise Http404()
dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
html = "<html><body>In %s hour(s), it will be %s.</body></html>" % (offset,dt)
return HttpResponse(html)
def editareapage(request):
return render_to_response('editareapage.html')
Also it is worth noting that editareapage is the one i am trying to access.
Here is my urls.py
from django.conf.urls import patterns, include, url
from MyProj.views import hello,mainpage, current_datetime, hours_ahead
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^hello/$', hello),
(r'^$', mainpage),
(r'^time/$',current_datetime),
(r'^time/plus/(\d{1,2})/$', hours_ahead),
(r'^editareapage/$', editareapage),
# Examples:
# url(r'^$', 'MyProj.views.home', name='home'),
# url(r'^MyProj/', include('MyProj.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
(r'^admin/', include(admin.site.urls)),
)
Hopefully this is enough for somone to help me, thanks!
Answer: You should import editareapage in `urls.py`
from MyProj.views import hello, mainpage, current_datetime, hours_ahead, editareapage
|
Python - importing a module from same directory
Question: > **Possible Duplicate:**
> [Using the Python NLTK (2.0b5) on the Google App
> Engine](http://stackoverflow.com/questions/1286301/using-the-python-
> nltk-2-0b5-on-the-google-app-engine)
I was adding my script to the Google App Engine and I needed to get some
modules to work. So I found the plain old file (in my case "NLTK" module) and
I added it to the same directory as my Google App Engine project. Currently
all my errors are coming from the importing of nltk, and when I try it
completely ignoring the google app enging by testing it in another file I
still get an import error.
So how can I import the NLTK module when it is in a folder in the same
directory as my python file without getting an error.
**Edit:** So I got the import line to work in IDLE...
from nltk.corpus import wordnet
But I still get a server error when trying to use the program with Google app
engine
Answer: This question is too vague, you need to include more details.
It sounds like you're trying to include nltk in your GAE project and you've
copied one file into your GAE project folder.
You'll need to include the entire nltk folder in your GAE project. If there
are any other dependencies that nltk requires, you'll need to include those in
your GAE project too.
|
Using variables in creating a file name
Question: I'm pretty new to python, and am wondering if there's any way to put a
variable into a file name, so that you can create files with different names
each time.
In my particular case, I'd like to add date and time to the file name. If it
was possible, this would work perfectly:
example = open("Path/to/file%s", "w") % str(datetime.now())
...but it doesn't. Is there any way to get that sort of functionality using a
different approach? I've tried searching for an answer either way using
multiple phrasings, but I can't find a yea or nay on it.
Thanks in advance guys.
EDIT: That was supposed to be an open() function, adjusted accordingly.
Answer: This should work. `format()` will replace the placeholder `{0}` in the string
with the formatted `datetime` string (`datestr`).
>>> from datetime import datetime
>>> datestr = datetime.strftime(datetime.today(), "%Hh %Mm %Ss %A, %B %Y")
>>> examplefile = open("/home/michael/file{0}".format(datestr), 'w')
>>> print(examplefile)
<open file '/home/michael/file21h 20m 34s Monday, September 2012', mode 'w' at 0x89fcf98>
|
python does not connect to local XMPP server
Question: i'm trying to connect my local XMPP server by the code coming below
import xmpp
client = xmpp.Client('localhost',debug=[])
client.connect(server=('localhost',5222))
but i always get this message :
> An error occurred while looking up _xmpp-client._tcp.localhost
i've checked that the port 5222 is already opened(by using telnet). (i have to
mention that the firewall on the localhost is off) now what should i add to
this code to make it work ?
Answer: This message (a warning, not an error as pointed out in xinox's answer) is
indicating that a DNS SRV record lookup failed. DNS SRV records are used to
find services that are associated with a certain domain (eg. `localhost` in
this case, so not really a domain at all which is why the lookup is failing),
but which delegate their responsibility to a server living somewhere else.
For instance, if I have a server at `example.net`, making my Jabber ID (JID):
`[email protected]`, but my XMPP server lived at `chat.example.net` I could
construct an SRV record on `example.net` to point to `chat.example.net`. There
are other ways to delegate responsibility, but this is the preferred one.
XMPPs use of SRV records is defined in [RFC 6120
§3.2.1](https://tools.ietf.org/html/rfc6120#section-3.2).
To actually get rid of this error you can use the `use_srv` kwarg, making your
initial example:
import xmpp
client = xmpp.Client('localhost',debug=[])
client.connect(server=('localhost',5222), use_srv=False)
|
Parse xsd:dateTime formatted string to python datetime
Question: Given a string in [xsd:dateTime
format](http://books.xmlschemata.org/relaxng/ch19-77049.html) I want to create
a python datetime object. I especially need to be able to parse for example a
string like this '2012-09-23T09:55:00', but also all other defined examples
should be parsed correctly, and also use timezones.
Answer: Use the [`datetime.datetime.strptime` class
method](http://docs.python.org/library/datetime.html#datetime.datetime.strptime)
to parse these:
dt = datetime.datetime.strptime(xsdDateTime, '%Y-%m-%dT%H:%M:%S')
Your example does _not_ include a timezone however. If you really do need
timezone support, best resort to the [`python-dateutil`
module](http://labix.org/python-
dateutil#head-c0e81a473b647dfa787dc11e8c69557ec2c3ecd2):
from dateutil.parser import parse
dt = parse(xsdDateTime)
|
Matplotlib: Repositioning a subplot in a grid of subplots
Question: I am trying to make a plot with 7 subplots. At the moment I am plotting two
columns, one with four plots and the other with three, i.e. like this:
I am constructing this plot in the folowing way:
#! /usr/bin/env python
import numpy as plotting
import matplotlib
from pylab import *
x = np.random.rand(20)
y = np.random.rand(20)
fig = figure(figsize=(6.5,12))
subplots_adjust(wspace=0.2,hspace=0.2)
iplot = 420
for i in range(7):
iplot += 1
ax = fig.add_subplot(iplot)
ax.plot(x,y,'ko')
ax.set_xlabel("x")
ax.set_ylabel("y")
savefig("subplots_example.png",bbox_inches='tight')
However, for publication I think this looks a bit ugly -- what I would like to
do is move the last subplot into the centre between the two columns. So, what
is the best way to adjust the position of the last subplot so that it is
centred? I.e. to have the first 6 subplots in a 3X2 grid and the last subplot
underneath centred between the two columns. If possible, I'd like to be able
to keep the `for` loop so that I can simply use:
if i == 6:
# do something to reposition/centre this plot
Thanks,
Alex
Answer: Use grid spec [(doc)](http://matplotlib.sourceforge.net/users/gridspec.html)
with a 4x4 grid, and have each plot span 2 columns as such:
import matplotlib.gridspec as gridspec
gs = gridspec.GridSpec(4, 4)
ax1 = plt.subplot(gs[0, 0:2])
ax2 = plt.subplot(gs[0,2:])
ax3 = plt.subplot(gs[1,0:2])
ax4 = plt.subplot(gs[1,2:])
ax5 = plt.subplot(gs[2,0:2])
ax6 = plt.subplot(gs[2,2:])
ax7 = plt.subplot(gs[3,1:3])
fig = gcf()
gs.tight_layout(fig)
ax_lst = [ax1,ax2,ax3,ax4,ax5,ax6,ax7]
|
smtp proxy in python requires root authentication to run
Question: I have the following simple python code on Linux
import smtpd
proxy = smtpd.PureProxy(('0.0.0.0',25), None)
which runs fine when run as sudo, but gives an `socket.error: [Errno 13]
Permission denied` error when running as standard user. My question: How can I
make this snippet to run with a normal user.
Thanks,
Alex
Answer: If you want to bind to port 25 (or any port under 1024) you MUST be root. You
can however, change to a different user once the socket bind is complete.
>>> import os
>>> import smtpd
>>> import pwd
>>> uid = pwd.getpwnam('nobody').pw_uid
>>> gid = pwd.getpwnam('nobody').pw_gid
>>> proxy = smtpd.PureProxy(('0.0.0.0',25), None)
>>> os.setgid(gid)
>>> os.setuid(uid)
>>> os.system('whoami')
nobody
0
>>>
This is, of course, a one way operation. Once you change to another user, you
can't change users again.
|
ttk.Entry not behaving the same way that tk.Entry does
Question: I'm switching over a small app (Python 2.7.3/32 on Win 7/64) to use ttk and
I'm having trouble making ttk.Entry work the way tk.Entry does; ttk.Entry
isn't updating the displayed entry box when I set its contents:
import Tkinter as tk
import ttk
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
part_num = '1234'
newPNVar = tk.StringVar()
newPN = ttk.Entry(self, width=13, textvariable=newPNVar)
newPNVar.set(part_num)
newPN.pack()
#newPN.insert(0, part_num) also didn't work
print newPNVar.get()
app = SampleApp()
app.mainloop()
If i replace ttk.Entry with tk.Entry and run the example, 1234 shows up in the
Entry box, but not if it is a ttk.Entry. How do I get them to behave the same
way?
Answer: It appears that ttk and tk hold on to the text variable a little differently.
It appears that the root cause is that `newPNVar` is getting garbage collected
since you aren't holding on to a reference. This doesn't seem to affect
`tk.Entry`, but does affect `ttk.Entry`.
The quick fix is to keep a reference to `newPNVar` (eg: `self.newPNVar`),
which is probably a wise thing regardless of this difference in behavior.
This works for me on Windows:
import Tkinter as tk
import ttk
class SampleApp(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
part_num = '1234'
self.newPNVar = tk.StringVar()
newPN = ttk.Entry(self, width=13, textvariable=self.newPNVar)
self.newPNVar.set(part_num)
newPN.pack()
#newPN.insert(0, part_num) also didn't work
print self.newPNVar.get()
app = SampleApp()
app.mainloop()
|
How to get % usage of a network card on Windows 7 using Python
Question: How do I get % usage of one or many network cards on Windows 7 using Python? I
tried using psutil library but it returns only transfered data.
I would like to get list of network cards and their usage
Network card 1 - 1%
Network card 2 - 0%
Network card 3 - 5%
Answer: You can't get percentage but you can get bytes sent and received, install
[psutil](https://github.com/giampaolo/psutil), import psutil and re (regex
module). See example code below on how I did it.
import psutil # http://code.google.com/p/psutil/
import re # Regular expression
#Percentage function
def percentage(part, whole):
return 100 * float(part)/float(whole)
if __name__ == '__main__':
#Retrieve all stats for all Network Cards using psutil
Stats = psutil.net_io_counters(pernic=True)
#Just showing printed values for Stats, useful for new coders :)
for key, val in Stats.items():
print key, val
#Filter Starts, convert to string for use with Regular expression
LanString = str(Stats['Local Area Connection'])
WirelessString = str(Stats['Wireless Network Connection'])
#Regular expression pattern that collects values between = character and , character
pattern = re.compile("\=(.*?)\,")
#Find all values matching the pattern
LanResult = re.findall(pattern, LanString)
WirelessResult = re.findall(pattern, WirelessString)
#Select values bytes_sent + bytes_recieved, convert to integers, add together
LanSumUsage = int(LanResult[0]) + int(LanResult[1])
WirelessSumUsage = int(WirelessResult[0]) + int(WirelessResult[1])
#Calculate and print percentages
TotalUsage = LanSumUsage + WirelessSumUsage
LanCardPercentage = percentage(LanSumUsage, TotalUsage)
WirelessCardPercentage = percentage(WirelessSumUsage, TotalUsage)
print("\nLan Card: %d%%") % LanCardPercentage
print("Wireless Card: %d%%") % WirelessCardPercentage
Take this code with a grain of salt, new to programming (a week in). Also no
error handling.
Oh and my Output is below, my lan card isn't being used.
Wireless Network Connection iostat(bytes_sent=801853517, bytes_recv=2106217519, packets_sent=4655581, packets_recv=6351113, errin=0, errout=0, dropin=0, dropout=0)
isatap.{10384343-0618-4406-B3D9-DA096A39B0DC} iostat(bytes_sent=0, bytes_recv=0, packets_sent=0, packets_recv=0, errin=0, errout=0, dropin=0, dropout=0)
Teredo Tunneling Pseudo-Interface iostat(bytes_sent=3358183, bytes_recv=27088294, packets_sent=40579, packets_recv=33727, errin=0, errout=1474, dropin=0, dropout=0)
Local Area Connection iostat(bytes_sent=0, bytes_recv=0, packets_sent=0, packets_recv=0, errin=0, errout=0, dropin=0, dropout=0)
Loopback Pseudo-Interface 1 iostat(bytes_sent=0, bytes_recv=0, packets_sent=0, packets_recv=0, errin=0, errout=0, dropin=0, dropout=0)
isatap.{109E44C6-1D07-4E41-A7EA-FCFF2284A1DB} iostat(bytes_sent=0, bytes_recv=0, packets_sent=0, packets_recv=0, errin=0, errout=0, dropin=0, dropout=0)
Lan Card: 0%
Wireless Card: 100%
|
How to scrape multiple HTML tables with Beautiful Soup parser?
Question: sorry for the stupid question ... just started using python (but I love it).
**The problem:** I want to scrape data from the [center for documentation of
violism in syria](http://vdc-
sy.org/index.php/en/martyrs/1/c29ydGJ5PWEua2lsbGVkX2RhdGV8c29ydGRpcj1ERVNDfGFwcHJvdmVkPXZpc2libGV8c2hvdz0xfGV4dHJhZGlzcGxheT0wfA==).
currently I'm using this scraper to collect the data. the problem is that I
can access only one row instead of scraping all rows from the table. the
preferred output should look like
name status sex province area dateofdeath causeofdeath
import urllib2
from BeautifulSoup import BeautifulSoup
f = open('syriawar.tsv', 'w')
f.write("Row" + "\t" + "Data" + "\n")
for x in range (0,249):
syria = "file" + "\t" + str(x)
print "fetching data ... " + syria
url ='http://vdc-sy.org/index.php/en/martyrs/' + str(x) + '/c29ydGJ5PWEua2lsbGVkX2RhdGV8c29ydGRpcj1ERVNDfGFwcHJvdmVkPXZpc2libGV8c2hvdz0xfGV4dHJhZGlzcGxheT0wfA=='
page = urllib2.urlopen(url)
soup = BeautifulSoup(page)
sentence = soup.findAll('tr')[3].text
words = sentence
Data = str(words)
f.write(str(x) + "\t" + Data + "\n" )
f.close()
Answer: You need another layer of iteration. You should first call findAll('tr') to
get all the rows. Then remove the rows that are headers and empty and then
loop through the remaining rows and call .text on those elements to get the
text of the rows you want. Write each row to the file from within your inner
loop.
Here is the script fixed. Note that the utf-8 codec had to used because the
page contains unicode in the text. You should verify that this is getting
everything you want. The empty tags were causing Beautiful Soup some problems.
import urllib2
from bs4 import BeautifulSoup
import codecs
f = codecs.open('syriawar.tsv', 'w', 'utf-8')
f.write("Row" + "\t" + "Data" + "\n")
for x in range (0,249):
syria = "file" + "\t" + str(x)
print "fetching data ... " + syria
url ='http://vdc-sy.org/index.php/en/martyrs/' + str(x) + '/c29ydGJ5PWEua2lsbGVkX2RhdGV8c29ydGRpcj1ERVNDfGFwcHJvdmVkPXZpc2libGV8c2hvdz0xfGV4dHJhZGlzcGxheT0wfA=='
page = urllib2.urlopen(url)
soup = BeautifulSoup(page)
rows = soup.findAll('tr')
i = 0;
for row in rows[3:]:
if i%2 == 0:
f.write(str(i/2) + "\t" + row.text + "\n" )
i += 1
f.close()
Another spiffy way to do this is to use
[Scrapemark](http://arshaw.com/scrapemark/). It works great for tables and
lists.
|
IntegrityError using q.save(): may not be NULL
Question: I'm not sure why I'm getting the error. Here are the views and clesses
from polls.models import Word, Results
def detail(request):
q = Word(type="How do you like")
q.save()
Word.objects.get(pk=1)
q.score_set.create(score=5)
q.score_set.create(score=4)
q.score_set.create(score=3)
q.score_set.create(score=2)
q.score_set.create(score=1)
return render_to_response('/$')
Models.py
from django.db import models
class Word(models.Model):
type = models.CharField(max_length=200)
def __unicode__(self):
return self.type
class Results(models.Model):
word = models.ForeignKey(Word)
score = models.IntegerField()
def __unicode__(self):
return self.score
Error:
IntegrityError at /
polls_word.score may not be NULLRequest Method: GET
Request URL: Django Version: 1.4.1
Exception Type: IntegrityError
Exception Value: polls_word.score may not be NULL
Exception Location: /home/oveledar/.virtualenvs/django/lib/python2.6/site-packages/django/db/backends/sqlite3/base.py in execute, line 337
Python Executable: /home/oveledar/.virtualenvs/django/bin/python
Python Version: 2.6.6
Python Path: ['/home/oveledar/django/mysite',
'/home/oveledar/.virtualenvs/django/lib/python2.6/site-packages/setuptools-0.6c11-py2.6.egg',
'/home/oveledar/.virtualenvs/django/lib/python2.6/site-packages/pip-1.0.2-py2.6.egg',
'/home/oveledar/.virtualenvs/django/lib64/python26.zip',
'/home/oveledar/.virtualenvs/django/lib64/python2.6',
'/home/oveledar/.virtualenvs/django/lib64/python2.6/plat-linux2',
'/home/oveledar/.virtualenvs/django/lib64/python2.6/lib-tk',
'/home/oveledar/.virtualenvs/django/lib64/python2.6/lib-old',
'/home/oveledar/.virtualenvs/django/lib64/python2.6/lib-dynload',
'/usr/lib/python2.6',
'/usr/lib64/python2.6',
'/home/oveledar/.virtualenvs/django/lib/python2.6/site-packages']
Answer: You table structure incorrect, you need:
class Results(models.Model):
word = models.ForeignKey(Word)
score = models.IntegerField(blank=True, null=True)
after, remove this table and run command:
python manange.py syncdb
#`blank` option it`s required or not this node for form validate
#`null` option it`s for you database (Null true or false)
|
Does sphinx run my code on executing 'make html'?
Question: I inherited a rather large codebase that I want to create html-documentation
for. Since it is written in Python I decided to use sphinx because the users
of the code are accustomed to the design and functionality of the python-
documention that's created with sphinx. I used the command `sphinx-apidoc` to
automatically create the rst-files. I imported the module path into `sys.path`
so that sphinx can find the code.
So far so good. However, when I try to create the html using the command `make
html`, there are many tracebacks poping up and some of the examples in the
codebase seem to get executed. What can be the reason for that and how can I
prevent that from happening?
Answer: When using [autodoc](http://sphinx.pocoo.org/ext/autodoc.html#module-
sphinx.ext.autodoc), Sphinx imports the documented modules, so all module-
level code is executed. This happens every time you do "make html". In that
sense, Sphinx does "run" your code.
You may have to organize your code a bit differently to make the errors go
away (move module-level code to functions). See [this
question](http://stackoverflow.com/q/6912025/407651) for an example of what
can happen.
This is my guess but it may not be the whole story. It's hard to say more
without additional information.
|
Python Merge 2 Dictionaries without overwriting
Question: If a and b are 2 dictionaries:
a = {'UK':'http://www.uk.com', 'COM':['http://www.uk.com','http://www.michaeljackson.com']}
bb = {'Australia': 'http://www.australia.com', 'COM':['http://www.Australia.com', 'http://www.rafaelnadal.com','http://www.rogerfederer.com']}
I want to merge them to get
{'Australia': ['http://www.australia.com'], 'COM': ['http://www.uk.com', 'http://www.michaeljackson.com', 'http://www.Australia.com', 'http://www.rafaelnadal.com', 'http://www.rogerfederer.com'], 'UK': ['http://www.uk.com']}
I want to union them i.e.
**How to do it in Python without overwwriting and replacing any value?**
Answer: Use a defaultdict:
from collections import defaultdict
d = defaultdict(list)
for dd in (a,bb):
for k,v in dd.items():
#Added this check to make extending work for cases where
#the value is a string.
v = (v,) if isinstance(v,basestring) else v #basestring is just str in py3k.
d[k].extend(v)
(but this is pretty much what I told you in [my earlier
answer](http://stackoverflow.com/a/12389519/748858))
This now works if your input dictionaries look like
{'Australia':['http://www.australia.com']}
or like:
{'Australia':'http://www.australia.com'}
However, I would advise against the latter form. In general, I think it's a
good idea to keep all the keys/values of a dictionary looking the same (at
least if you want to treat all the items the same as in this question). That
means that if one value is a list, it's a good idea for _all of them_ to be a
list.
If you really insist on keeping things this way:
d = {}
for dd in (a,b):
for k,v in dd.items():
if(not isinstance(v,list)):
v = [v]
try:
d[k].extend(v)
except KeyError: #no key, no problem, just add it to the dict.
d[k] = v
|
Trouble using scriptedmain in MinGW
Question: I want to reproduce [this Perl
code](https://github.com/mcandre/scriptedmain/tree/master/perl) in C, bundling
API and CLI in the same C source code file
([scriptedmain](http://rosettacode.org/wiki/Scripted_Main#C)). This is done in
Python with `if __name__=="__main__": main()` and in gcc/Unix, this looks
like:
$ gcc -o scriptedmain scriptedmain.c scriptedmain.h
$ ./scriptedmain
Main: The meaning of life is 42
$ gcc -o test test.c scriptedmain.c scriptedmain.h
$ ./test
Test: The meaning of life is 42
scriptedmain.h
int meaning_of_life();
scriptedmain.c
#include <stdio.h>
int meaning_of_life() {
return 42;
}
int __attribute__((weak)) main() {
printf("Main: The meaning of life is %d\n", meaning_of_life());
return 0;
}
test.c
#include "scriptedmain.h"
#include <stdio.h>
extern int meaning_of_life();
int main() {
printf("Test: The meaning of life is %d\n", meaning_of_life());
return 0;
}
However, when I try to compile with gcc/Strawberry, I get:
C:\>gcc -o scriptedmain scriptedmain.c scriptedmain.h
c:/strawberry/c/bin/../lib/gcc/i686-w64-mingw32/4.4.3/../../../../i686-w64-mingw32/lib/libmingw32.a(lib32_libmingw32_a-crt0_c.o): In function `main':
/opt/W64_156151-src.32/build-crt/../mingw-w64-crt/crt/crt0_c.c:18: undefined reference to `WinMain@16'
collect2: ld returned 1 exit status
And when I try to compile with gcc/MinGW, I get:
$ gcc -o scriptedmain -mwindows scriptedmain.c scriptedmain.h
c:/mingw/bin/../lib/gcc/mingw32/4.5.2/../../../libmingw32.a(main.o):main.c:(.text+0x104): undefined reference to `WinMain@16'
collect2: ld returned 1 exit status
How can I get GCC in Windows to recognize the `__attribute__((weak))` syntax?
Also, G++ shows the same error.
Answer: I found a solution that works in Windows and in Unix: Simply wrap `main()` in
preprocessor instructions that omits it unless explicit compiler flags are
set.
scriptedmain.c:
#include <stdio.h>
int meaning_of_life() {
return 42;
}
#ifdef SCRIPTEDMAIN
int main() {
printf("Main: The meaning of life is %d\n", meaning_of_life());
return 0;
}
#endif
Now `main()` will be entirely omitted unless you compile with
gcc -o scriptedmain -DSCRIPTEDMAIN scriptedmain.c scriptedmain.h
This code is safe to import into other C code, because the preprocessor will
strip out `main()`, leaving you to code your own main. The best part is that
this solution no longer depends on obscure compiler macros, only simple
preprocessor instructions. This solution works for
[C++](http://rosettacode.org/wiki/Scripted_main#C.2B.2B) as well.
|
Error when importing programs IDLE
Question: Im new to Python but Im getting on pretty well, however I cannot seem to
import save programs into IDLE. Could someone assist me where that is
concerned, please. This is one of the errors no matter how simple the program
is:
>>> import dinner
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
import dinner
File "C:\Python25\dinner.py", line 1
Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32
^
SyntaxError: invalid syntax
Answer: This is the error you would get if your `dinner.py` program actually started
with the line
Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32
But that's not a line of valid Python code, that's the message that the
interpreter gives on startup. For example, mine says
~/coding$ python
Python 2.7.3 (default, Aug 1 2012, 05:16:07)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
and it's then that I start typing things like `print 2+2`, etc. You can open
`dinner.py` in IDLE and remove any parts which look like this welcome message
at the start.
Incidentally, I see you're using Python 2.5.4. This is pretty old now, and a
lot of neat things have been added since. I would suggest switching to 2.7.3
instead.
|
Python Ncurses printing a single char to position
Question: I am not so into ncurses, but it should be working on C, I do not know what is
wrong, I just want to print some character to screen continuosly but I cannot
find how to fix this error:
File "capture.py", line 37, in <module>
stdscr.move(y,x)
_curses.error: wmove() returned ERR
**Code:**
(irrelevant parts of the code are removed)
import curses
stdscr = curses.initscr()
curses.noecho();
palette = [' ', ' ', '.', '.', '/', 'c', '(', '@', '#', '8']
# index is something between 0 and len(palette), not important
for x in xrange(50):
for y in xrange(30):
stdscr.move(y,x)
sdtscr.addch(palette[index])
stdscr.refresh()
Answer: If you read the documentation for curses move (e.g.,
<http://linux.die.net/man/3/move>):
> These routines return ERR upon failure and OK (SVr4 specifies only "an
> integer value other than ERR") upon successful completion.
>
> Specifically, they return an error if the window pointer is null, or if the
> position is outside the window.
The first doesn't seem likely to come up in Python, so the second is probably
your problem. And a quick test shows that running your code works fine on a
terminal that's 30 rows or taller, but fails on a typical 24- or 25-row
terminal.
If you want to make it easier to debug, first wrap the whole thing in a
`try`/`finally:` `curses.endscr()` (so your terminal isn't left in a mess,
possibly making it impossible to see the output). Then wrap the call to
`stdscr.move` in a `try`/`except:` that logs x and y so you know where it
fails. I'd also make the "30" into a command-line argument for quicker
testing. Here's a version with all those changes:
#!/usr/bin/python
import sys
import curses
height = int(sys.argv[1]) if len(sys.argv) > 1 else 24
try:
stdscr = curses.initscr()
curses.noecho();
palette = [' ', ' ', '.', '.', '/', 'c', '(', '@', '#', '8']
index = 0
for x in xrange(50):
for y in xrange(height):
index = (index + 1) % len(palette)
try:
stdscr.move(y,x)
except Exception as e:
stdscr.refresh()
curses.endwin()
print
print x, y, e
sys.exit(1)
stdscr.addch(palette[index])
stdscr.refresh()
finally:
curses.endwin()
Now `python cursetest 30` prints:
0 25 wmove() returned ERR
So, as I suspected, it's failing at x=0, y=25.
And if I stretch my terminal out to 80x50, it works, but now `python cursetest
60` fails:
0 50 wmove() returned ERR
For that matter, if I shrink my terminal to 40x50, `python cursetest 30` fails
at the horizontal edge rather than the vertical:
40 0 wmove() returned ERR
If you want to check for this in advance rather than trying to catch the error
when it happens, try calling `getmaxyx()` on the window; if y<30 you can
display a nice error message and quit (or do something different, or
whatever).
Finally, a quick check shows that this doesn't work in C either. Of course
there's no exception thrown, and you can ignore the error that's returned if
you want, but you just end up writing to position (24, 49) 300 times in a row.
(And you could do the same thing in Python by doing a try/catch/pass around
the move, if you really wanted…)
|
Mapping Unicode to ASCII in Python
Question: I receive strings after querying via urlopen in JSON format:
def get_clean_text(text):
return text.translate(maketrans("!?,.;():", " ")).lower().strip()
for track in json["tracks"]:
print track["name"].lower()
get_clean_text(track["name"].lower())
For the string "türlich, türlich (sicher, dicker)" I then get
> File "main.py", line 23, in get_clean_text
>
>
> return text.translate(maketrans("!?,.;():", " ")).lower().strip()
>
>
> TypeError: character mapping must return integer, None or unicode
I want to format the string to be "türlich türlich sicher dicker".
Answer: The question is not a complete self-contained example; I can't be sure whether
it's Python 2 or 3, where `maketrans` came from, etc. There's a good chance I
will guess wrong, which is why you should be sure to tag your questions
appropriately and provide a [short, self contained, correct
example](http://sscce.org). (That, and the fact that various other people—some
of them probably smarter than me—likely ignored your question because it was
ambiguous.)
Assuming you're using 2.x, and you've done a `from string import *` to get
`maketrans`, and `json["name"]` is unicode rather than str/bytes, here's your
problem:
There are two kinds of translation tables: old-style 8-bit tables (which are
just an array of 256 characters) and new-style sparse tables (which are just a
dict mapping one character's ordinal to another). The `str.translate` function
can use either, but `unicode.translate` can only use the second (for reasons
that should be obvious if you think about it for a bit).
The `string.maketrans` function makes old-style 8-bit translation tables. So
you can't use it with `unicode.translate`.
You can always write your own "makeunitrans" function as a drop-in
replacement, something like this:
def makeunitrans(frm, to):
return {ord(f):ord(t) for (f,t) in zip(frm, to)}
But if you just want to map out certain characters, you could do something a
bit more special purpose:
def makeunitrans(frm):
return {ord(f):ord(' ') for f in frm}
However, from your final comment, I'm not sure `translate` is even what you
want:
> I want to format the string to be "türlich türlich sicher dicker"
If you get this right, you're going to format the string to be "türlich
türlich sicher dicker ", because you're mapping all those punctuation
characters to spaces, not nothing.
With new-style translation tables you can map anything you want to None, which
solves that problem. But you might want to step back and ask why you're using
the `translate` method in the first place instead of, e.g., calling `replace`
multiple times (people usually say "for performance", but you wouldn't be
building the translation table in-line every time through if that were an
issue) or using a trivial regular expression.
|
Python- how to use while loop to return longest line of code
Question: I just started learning python 3 weeks ago, I apologize if this is really
basic. I needed to open a .txt file and print the length of the longest line
of code in the file. I just made a random file named it myfile and saved it to
my desktop.
myfile= open('myfile', 'r')
line= myfile.readlines()
len(max(line))-1
#the (the "-1" is to remove the /n)
Is this code correct? I put it in interpreter and it seemed to work OK.
But I got it wrong because apparently I was supposed to use a while loop. Now
I am trying to figure out how to put it in a while loop. I've read what it
says on python.org, watched videos on youtube and looked through this site. I
just am not getting it. The example to follow that was given is this:
import os
du=os.popen('du/urs/local')
while 1:
line= du.readline()
if not line:
break
if list(line).count('/')==3:
print line,
Answer:
print max([len(line) for line in file(filename).readlines()])
|
Python function to extract multiple segments of a file path
Question: I would like to write a Python function that is capable of taking a file path,
like:
> /abs/path/to/my/file/file.txt
And returning three string variables:
* `/abs` \- the root directory, plus the "top-most" directory in the path
* `file` \- the "bottom-most" directory in the path; the parent of `file.txt`
* `path/to/my` \- everything in between the top- and bottom-most directories in the path
So something with the following pseudo-code:
def extract_path_segments(file):
absPath = get_abs_path(file)
top = substring(absPath, 0, str_post(absPath, "/", FIRST))
bottom = substring(absPath, 0, str_post(absPath, "/", LAST))
middle = str_diff(absPath, top, bottom)
return (top, middle, bottom)
Thanks in advance for any help here!
Answer: You are looking for [`os.sep`](http://docs.python.org/library/os.html#os.sep),
together with various `os.path` module functions. Simply split the path by
that character, then re-assemble the parts you want to use. Something like:
import os
def extract_path_segments(path, sep=os.sep):
path, filename = os.path.split(os.path.abspath(path))
bottom, rest = path[1:].split(sep, 1)
bottom = sep + bottom
middle, top = os.path.split(rest)
return (bottom, middle, top)
This does _not_ deal very well with Windows paths, where both `\` _and_ `/`
are legal path separators. In that case you _also_ have a drive letter, so
you'd have to special-case that as well anyway.
Output:
>>> extract_path_segments('/abs/path/to/my/file/file.txt')
('/abs', 'path/to/my', 'file')
|
Apache not getting access to virtual environment set up for Django project
Question: I created a virtualenv named '`pyapps`' and installed pinax and django in
it.I've installed apache 2 and mod_wsgi.I created a directory named '`apache`'
inside my django project(`testproject`) and put '`django.wsgi`' file inside
that directory.Here is the content of my wsgi file:
import os
import sys
# put the Django project on sys.path
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "../../")))
os.environ['DJANGO_SETTINGS_MODULE'] = 'textpisodes.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
Then I created a directory '`/check/www`' and put my project folder and
`pyapps` folder inside '`/check/www`'.I chmoded 777 on `/check/www`.
Finally I created a virtual host,it's content is as follows:
<VirtualHost *:80>
ServerAdmin myemail
ServerName djangoserver
WSGIDaemonProcess textpisodes user=rajat threads=10 python-path=/check/www
WSGIProcessGroup textpisodes
WSGIScriptAlias / /check/www/textpisodes/apache/django.wsgi
<Directory /check/www/textpisodes/apache>
Order deny,allow
Allow from all
</Directory>
ErrorLog /var/log/apache2/error.log
LogLevel warn
CustomLog /var/log/apache2/access.log combined
</VirtualHost>
Now when I try to access 'http://djangoserver',all I'm getting is `Internal
Server Error`.Here are the contents of my apache log file.
[Thu Sep 13 18:39:51 2012] [error] [client 127.0.0.1] mod_wsgi (pid=4890): Target WSGI script '/check/www/textpisodes/apache/django.wsgi' cannot be loaded as Python module.
[Thu Sep 13 18:39:51 2012] [error] [client 127.0.0.1] mod_wsgi (pid=4890): Exception occurred processing WSGI script '/check/www/textpisodes/apache/django.wsgi'.
[Thu Sep 13 18:39:51 2012] [error] [client 127.0.0.1] Traceback (most recent call last):
[Thu Sep 13 18:39:51 2012] [error] [client 127.0.0.1] File "/check/www/textpisodes/apache/django.wsgi", line 9, in <module>
[Thu Sep 13 18:39:51 2012] [error] [client 127.0.0.1] import django.core.handlers.wsgi
[Thu Sep 13 18:39:51 2012] [error] [client 127.0.0.1] ImportError: No module named django.core.handlers.wsgi
Answer: You need to add your virtual environment path so that apache/python can find
modules there.
Either put this in your apache configuration (outside of `VirtualHost` entry)
WSGIPythonPath /home/me/virtualenv/env1/lib/python2.7/site-packages
Or put it in the `sys.path` in your wsgi file.
|
Python scipy modules can't be imported with macports install
Question: I've just reinstalled OSX Lion and decided to use macports to get an updated
python, plus numpy, scipy, matplotlib, ipython, etc. After some fuss
everything looks installed correctly in the /opt/ folder, and numpy,
matplotlib, and ipython are running correctly, but when I try to import
modules in scipy I get a failure that seems to go back to the sparse module:
>>> import scipy.sparse as sparse
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scipy/sparse/__init__.py", line 175, in <module>
from csr import *
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scipy/sparse/csr.py", line 12, in <module>
from sparsetools import csr_tocsc, csr_tobsr, csr_count_blocks, \
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scipy/sparse/sparsetools/__init__.py", line 4, in <module>
from csr import *
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scipy/sparse/sparsetools/csr.py", line 25, in <module>
_csr = swig_import_helper()
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scipy/sparse/sparsetools/csr.py", line 21, in swig_import_helper
_mod = imp.load_module('_csr', fp, pathname, description)
ImportError: dlopen(/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scipy/sparse/sparsetools/_csr.so, 2): Symbol not found: ___emutls_get_address
Referenced from: /opt/local/lib/gcc45/libstdc++.6.dylib
Expected in: /usr/lib/libSystem.B.dylib
in /opt/local/lib/gcc45/libstdc++.6.dylib
Import scipy.stats or such things ends up in the same place. I've googled a
bunch and tried fixing various PATH variables (in the python interpreter and
out), as well as hiding the default python install(s? what's the difference
between the one in the main Library and the one in /usr/?) and reinstalling
scipy but that's done nothing.
I'm not very familiar or comfortable with this stuff - I was working with the
EPD before I wiped and reinstalled, but had run into problems getting new
packages to recognize that. I use python for scientific stuff, hence not
really understanding its guts! So answers assuming I barely understand what a
PATH variable is are much appreciated.
So (a) Is there an easy way to fix whatever is going on above? (b) Should I
delete some stuff and start from scratch? (c) Is there a non-painful way to
get scipy, numpy, matplotlib, and ipython (plus the things it needs for the
qtconsole and the html notebook), AND be able to install new packages in the
right place? Should I go back to EPD if possible (their academic email thing
failed for me, so I moved on)?
Answer: You could try the [ Enthought Python Free
distribution](http://www.enthought.com/products/epd_free.php), its free and
generally is an easy install, and comes with Numpy, Scipy, matplotlib etc.
|
how the python interpreter find the modules path?
Question: I'm new to python, and I find that to see the import search paths, you have to
import the `sys` module and than access the list of paths using `sys.path`, if
this list is not available until I explicitly import the `sys` module, so how
the interpreter figure out where this module resides. thanks for any
explanation.
Answer: The module search path always exists, even before you import the sys module.
The sys module just makes it available for you.
It reflects the contents of the system variable `$PYTHONPATH`, or a system
default, if you have not set that environment variable.
|
Suds ignoring proxy setting
Question: I'm trying to use the salesforce-python-toolkit to make web services calls to
the Salesforce API, however I'm having trouble getting the client to go
through a proxy. Since the toolkit is based on top of suds, I tried going down
to use just suds itself to see if I could get it to respect the proxy setting
there, but it didn't work either.
This is tested on suds 0.3.9 on both OS X 10.7 (python 2.7) and ubuntu 12.04.
an example request I've made that did not end up going through the proxy (just
burp or charles proxy running locally):
import suds
ws = suds.client.Client('file://sandbox.xml',proxy={'http':'http://localhost:8888'})
ws.service.login('user','pass')
I've tried various things with the proxy - dropping http://, using an IP,
using a FQDN. I've stepped through the code in pdb and see it setting the
proxy option. I've also tried instantiating the client without the proxy and
then setting it with: ws.set_options(proxy={'http':'http://localhost:8888'})
Is proxy not used by suds any longer? I don't see it listed directly here
<http://jortel.fedorapeople.org/suds/doc/suds.options.Options-class.html>, but
I do see it under transport. Do I need to set it differently through a
transport? When I stepped through in pdb it did look like it was using a
transport, but I'm not sure how.
Thank you!
Answer: I went into #suds on freenode and Xelnor/rbarrois provided a great answer!
Apparently the custom mapping in suds overrides urllib2's behavior for using
the system configuration environment variables. This solution now relies on
having the http_proxy/https_proxy/no_proxy environment variables set
accordingly.
I hope this helps anyone else running into issues with proxies and suds (or
other libraries that use suds). <https://gist.github.com/3721801>
from suds.transport.http import HttpTransport as SudsHttpTransport
class WellBehavedHttpTransport(SudsHttpTransport):
"""HttpTransport which properly obeys the ``*_proxy`` environment variables."""
def u2handlers(self):
"""Return a list of specific handlers to add.
The urllib2 logic regarding ``build_opener(*handlers)`` is:
- It has a list of default handlers to use
- If a subclass or an instance of one of those default handlers is given
in ``*handlers``, it overrides the default one.
Suds uses a custom {'protocol': 'proxy'} mapping in self.proxy, and adds
a ProxyHandler(self.proxy) to that list of handlers.
This overrides the default behaviour of urllib2, which would otherwise
use the system configuration (environment variables on Linux, System
Configuration on Mac OS, ...) to determine which proxies to use for
the current protocol, and when not to use a proxy (no_proxy).
Thus, passing an empty list will use the default ProxyHandler which
behaves correctly.
"""
return []
client = suds.client.Client(my_wsdl, transport=WellBehavedHttpTransport())
|
add file name without file path to csv in python
Question: I am using Blair's Python script which modifies a CSV file to add the filename
as the last column (script appended below). However, instead of adding the
file name alone, I also get the Path and File name in the last column.
I run the below script in windows 7 `cmd` with the following command:
python C:\data\set1\subseta\add_filename.py C:\data\set1\subseta\20100815.csv
The resulting ID field is populated by the following
`C:\data\set1\subseta\20100815.csv`, although, all I need is `20100815.csv`.
I'm new to python so any suggestion is appreciated!
import csv
import sys
def process_file(filename):
# Read the contents of the file into a list of lines.
f = open(filename, 'r')
contents = f.readlines()
f.close()
# Use a CSV reader to parse the contents.
reader = csv.reader(contents)
# Open the output and create a CSV writer for it.
f = open(filename, 'wb')
writer = csv.writer(f)
# Process the header.
header = reader.next()
header.append('ID')
writer.writerow(header)
# Process each row of the body.
for row in reader:
row.append(filename)
writer.writerow(row)
# Close the file and we're done.
f.close()
# Run the function on all command-line arguments. Note that this does no
# checking for things such as file existence or permissions.
map(process_file, sys.argv[1:])
Answer: Use `os.path.basename(filename)`. See
<http://docs.python.org/library/os.path.html> for more details.
|
Can't import logging.handlers inside a nose test
Question: I'm writing a basic test with nose to call a single function from a logging
wrapper, but once I got the test to be discovered I started getting standard
library module import errors.
This is code I'm trying to write some tests for and has been in production and
hasn't changed in a long time, so I'm sure the there's something wrong when
how I'm trying to use nose.
Failure: ImportError (cannot import name WatchedFileHandler) ... ERROR
======================================================================
ERROR: Failure: ImportError (cannot import name WatchedFileHandler)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/opt/local/lib/python2.4/site-packages/nose/loader.py", line 389, in loadTestsFromName
module = self.importer.importFromPath(
File "/opt/local/lib/python2.4/site-packages/nose/importer.py", line 39, in importFromPath
return self.importFromDir(dir_path, fqname)
File "/opt/local/lib/python2.4/site-packages/nose/importer.py", line 86, in importFromDir
mod = load_module(part_fqname, fh, filename, desc)
File "/Users/jolson/project/qworker/tests/unit/test_qscript_log.py", line 2, in ?
from logging.handlers import WatchedFileHandler, TimedRotatingFileHandler
ImportError: cannot import name WatchedFileHandler
What could cause this?
**Update:** I've simplified it to the following and the test still fails, but
outside of nose this all works as expected.
from logging.handlers import WatchedFileHandler, TimedRotatingFileHandler
def test_INFO():
assert 0 == 0
** Update 2 ** I've checked my paths. Inside the nosetests my path looks like
this.
['/Users/jolson/project/qworker/tests', '/Users/jolson/project/qworker',
'/opt/local/bin', '/opt/local/lib/python24.zip', '/opt/local/lib/python2.4',
'/opt/local/lib/python2.4/plat-darwin', '/opt/local/lib/python2.4/plat-mac',
'/opt/local/lib/python2.4/plat-mac/lib-scriptpackages', '/opt/local/lib/python2.4/lib-tk',
'/opt/local/lib/python2.4/site-packages/readline', '/opt/local/lib/python2.4/lib-dynload',
'/opt/local/lib/python2.4/site-packages', '/opt/local/lib/python2.4/site-packages/setuptools-0.6c11-py2.4.egg-info']
but my normal path inside the python interpreter is
['', '/usr/local/bin', '/Library/Python/2.7/site-packages/pip-1.2.1-py2.7.egg',
'/Library/Python/2.7/site-packages/virtualenv-1.8.2-py2.7.egg',
'/Library/Python/2.7/site-packages/virtualenvwrapper-3.6-py2.7.egg',
'/Library/Python/2.7/site-packages/stevedore-0.3-py2.7.egg',
'/Library/Python/2.7/site-packages/virtualenv_clone-0.2.4-py2.7.egg',
'/Library/Python/2.7/site-packages/distribute-0.6.28-py2.7.egg',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
'/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload',
'/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC',
'/Library/Python/2.7/site-packages', '/Library/Python/2.7/site-packages/setuptools-0.6c11-py2.7.egg-info',
'/Library/Python/2.7/site-packages/IPython/extensions']
I'm running `nosetests-2.4 tests`
which has one file in tests/unit/test_log.py.
Answer: My os was defaulting to `nosetests-2.4` which uses python 2.4, but all our
code is python 2.7, so that's why the path was wrong and nothing was working
and logging.handlers was just the first package that was missing from 2.4 libs
that was needed.
|
Python with SimPy on Eclipse installation error (Windows 7)
Question: I have been using the PyDev in eclipse for quite a while with no problem.
Today I installed SimPy in my Python and I think it is installed ok, meaning
that in idle commands like:
>>> from SimPy.Simulation import *
>>> now()
works fine.
Then I tried to configure the PyDev again so that I can use SimPy with
eclipse. In eclipse I chose Windows->Preferences->PyDev->Interpreter – Python.
Then new, gave the name Python 2.7 and added the C:\Python27\python.exe as
Interpreter executable. This is what I have done in the past and worked fine.
But now I get an error message “Error getting info on the interpreter”. From
ErrorLog I get:No output was in the standard output when trying to create the
interpreter info. The error output contains: `ImportError: No module named
site`
In my home variables I have:
`PYTHONHOME -> C:\Python27`
`PYTHONPATH -> C:\Python27\Lib;C:\Python27\Lib;C:\Python27\SimPy`
can anyone tell me what is wrong? My system is Windows 7. Thank you!
Answer: Found it after hours. It seems that in the \eclipse\plugins there were some
com.python.pydev. folders left. Removed them gone through the whole process
again. It seems to work now.
|
what's the fastest way of converting a string time stamp into epoch time with python?
Question: I need to do lots of conversation from string time stamp like '2012-09-08
12:23:33' into a seconds which is based on epoch time.Then i need to get time
gap between two timestamp.I tried two different ways:
date1 = '2012-09-08'
time2 = '12:23:33'
timelist1 = map(int, date1.split('-') + time1.split(':'))
date2 = '2012-09-08'
time2 = '12:23:33'
timelist2 = map(int, date2.split('-') + time2.split(':'))
delta = datetime.datetime(*timelist2) - datetime.datetime(*timelist1)
print delta.seconds
The second way is:
date1 = '2012-09-08'
time1 = '12:23:33'
d1 = datetime.datetime.strptime(date1 + ' ' + time1, "%Y-%m-%d %H:%M:%S")
seconds1 = time.mktime(d1.timetuple())
....
seconds2 = time.mktime(d2.timetuple())
print seconds2-deconds1
However these two ways are not fast enough because I have almost 100 millions
actions to do.Any suggestion?
Answer: You'd be much better off using the [`datetime.datetime.strptime()`
function](http://docs.python.org/library/datetime.html#datetime.datetime.strptime),
then subtract the two results:
import datetime
date1, time1 = '2012-09-08', '12:23:33'
date2, time2 = '2012-09-08', '12:23:33'
dt1 = datetime.datetime.strptime(date1 + ' ' + time1, "%Y-%m-%d %H:%M:%S")
dt2 = datetime.datetime.strptime(date2 + ' ' + time2, "%Y-%m-%d %H:%M:%S")
print (dt1 - dt2).total_seconds()
Note that `datetime.timedelta.seconds` gives you just the _remainder_ in
seconds, there is also a `.days` attribute. Use
[`.total_seconds()`](http://docs.python.org/library/datetime.html#datetime.timedelta.total_seconds)
instead, it's much more convenient and saves you having to take the `.days`
value into account.
Using the `datetime.datetime.strptime()` method, plus `timedelta` methods, is
keeping the majority of the work in C code and should be faster.
Note that neither method is very fast because of the parsing step. Time tests:
>>> import timeit
>>> def parse_datetime():
... date1, time1 = '2012-09-08', '12:23:33'
... date2, time2 = '2012-09-08', '12:23:33'
... dt1 = datetime.datetime.strptime(date1 + ' ' + time1, "%Y-%m-%d %H:%M:%S")
... dt2 = datetime.datetime.strptime(date2 + ' ' + time2, "%Y-%m-%d %H:%M:%S")
... (dt1 - dt2).total_seconds()
...
>>> def parse_time():
... d1 = time.strptime(date1 + ' ' + time1, "%Y-%m-%d %H:%M:%S")
... d2 = time.strptime(date2 + ' ' + time2, "%Y-%m-%d %H:%M:%S")
... seconds1 = time.mktime(d1)
... seconds2 = time.mktime(d2)
... seconds1 - seconds2
...
>>> timeit.timeit('test()', 'from __main__ import parse_datetime as test', number=10000)
0.6590030193328857
>>> timeit.timeit('test()', 'from __main__ import parse_time as test', number=10000)
0.7742340564727783
where the second method just uses the `time.strptime()` function (which
outputs a timetuple directly).
There are no faster avenues to parsing a date-time string that I am aware of
though.
|
Understanding "self" in Python
Question: I saw this example from udacity.com :
def say_hi():
return 'hi!'
i = 789
class MyClass(object):
i = 5
def prepare(self):
i = 10
self.i = 123
print i
def say_hi(self):
return 'Hi there!'
def say_something(self):
print say_hi()
def say_something_else(self):
print self.say_hi()
**output:**
>>> print say_hi()
hi!
>>> print i
789
>>> a = MyClass()
>>> a.say_something()
hi!
>>> a.say_something_else()
Hi there!
>>> print a.i
5
>>> a.prepare()
10
>>> print i
789
>>> print a.i
123
I understand everything, except why `a.say_something()` equals `hi!` and not
`Hi there!`. That is strange for me, because it calls `say_something()` which
is inside the class when it calls `say_hi()` after that. Guess I missed
something important..
Answer: Class scopes aren't considered when looking up a name in enclosing scopes. You
should always qualify with `self.` to get a name from the class scope.
See [The scope of names defined in class block doesn't extend to the methods'
blocks. Why is that?](http://stackoverflow.com/questions/9505979/the-scope-of-
names-defined-in-class-block-doesnt-extend-to-the-methods-blocks) for a more
detailed discussion of this behaviour.
|
SQLAlchemy won't update my database
Question: I'm making a Pyramid app using SQLAlchemy-0.7.8. I'm using 64bit Python3.2.
The question is, why does the following function not commit anything to the
database?
def create_card(sText,sCard):
"""
create a wildcard instance if all is well (ie,sCard match in sText)
return
oCard, dCard
otherwise return False,False
"""
oMatch = re.search(sCard,sText)
if oMatch:
oCard = WildCard()
#set up some stuff about the WildCard
DBSession.add(oCard)
DBSession.flush()
dCard = {
'id' : oCard.id,
'span' : oMatch.span(),
'card' : oCard.card_string,
}
return oCard,dCard
return False,False
I import DBSession form another script. it is defined as follows:
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Here's some background info:
The app I'm making is to be used to characterize large blocks of HTML through
use of regular expressions. If the app gets stuck and thinks there should be a
wilcard match for a piece of text then the user is given a little form to fill
in. Once the form is committed create_card is called. If the wildcard is
matched against the string then a WildCard instance is created.
The WildCard class is nothing special, it just stores a string and a few
integers. If I print out dCard it looks like the WildCard was sucessfully
committed because it has an integer id. If I don't call flush on the database
session then dCard['id'] is None.
the id field looks like:
id = Column(Integer,Sequence('wild_seq'), primary_key=True)
The add and flush lines cause the following console output:
2012-09-16 12:30:34,845 INFO [sqlalchemy.engine.base.Engine][Dummy-2] INSERT INTO wildcard_wildcards (card_string, range_id, brand_id, category_id, group_cat_map_id, heading_group_id, heading_to_grp_map_id, heading_id, value_map_id, igneore_match) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2012-09-16 12:30:34,845 INFO [sqlalchemy.engine.base.Engine][Dummy-2] ('sCard contents', None, None, None, None, None, None, None, None, 0)
So up until this point everything is behaving pretty as is expected.
Here's the problem: Even though the WildCard instance looks like it has been
committed to the database, and no Exceptions are raised, direct examination of
the database shows that no changes are made.
replacing flush() with commit() raises the following exception:
AssertionError: Transaction must be committed using the transaction manager
Answer: You need to _commit_ your transaction.
You can do this explicitly (by calling `DBSession.commit()` or by using the
[`pyramid_tm`
middleware](http://docs.pylonsproject.org/projects/pyramid_tm/en/latest/); the
latter commits transactions automatically on successful responses (with a 2xx
HTTP response).
The latter only commits transactions for SQLAlchemy if you use the
`ZopeTransactionExtension` extension with your session maker:
from zope.sqlalchemy import ZopeTransactionExtension
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
If you are already using the `ZopeTransactionExtension` and want to explicitly
commit your transactions, you need to use the `transaction` package: import
transaction
transaction.commit()
|
How to sort and keep the integrity of the list?
Question: So I have a minor issue with a script I'm writing. I have a text file that
looks something like:
'20 zebra 12 bear'
That's just an example, the format is 1 line all items separated by spaces.
The script works to sort them out and do a couple of other things to the
strings but what I can't figure out is how to keep it set the way it is. For
example the above line should sort like this:
12
bear
20
zebra
I need to keep a number in the number place and a string in a strings place
but they should be sorted alphanumerically. Here is my script so far:
#!/usr/bin/python
# Make sure you use the proper modules.
import sys, string
# This area defines the arguments and returns a usage message should it be used incorrectly.
try:
infilename = sys.argv[1]; outfilename = sys.argv[2]
except:
print "Usage:",sys.argv[0], "infile outfile"; sys.exit(1)
ifile = open(infilename, 'r') # Opens the input file for reading
ofile = open(outfilename, 'w') # Opens the output file for writing
data = ifile.readlines()[0].split() # Reads the lines on the input file
# The items in the list are sorted here and defined by a space.
sort = sorted(data, key=lambda item: (int(item.partition(' ')[0])
if item[0].isdigit() else float('inf'), item))
# Use this to remove any special characters in the list
filtered = [s.translate(None, string.punctuation) for s in sort]
ofile.write('\n'.join(filtered)) # Writes the final output to file (one on each line)
ifile.close() # Closes the input file
ofile.close() # Closes the output file
I know it's not the prettiest but I haven't been using Python long so if you
have suggestions on how to make it prettier, I'm all ears. All I really need
is to keep a number a number and a string a string but swap them around to
sort. Thanks for any assistance given.
Answer: What you need to do is to create 3rd list. With 1 for number and 2 for string.
So your example would be
1, 2, 1, 2.
Than you put all numbers in one list, and strings in second. Sort them.
Than you replace each 1 in 3rd string with next number and each 2 with next
string.
It should work perfectly.
|
Generate all strings up to desired length
Question: I want to generate all the random strings having length varying from 1 till
max_length. Is is there an in-built function in python that would do that? If
not, please tell me how to do this or direct me to posts which covers this
type of problem. Thanks in advance.
Answer: Random strings:
import random
def get_random_string(alphabet, slen):
return ''.join(random.choice(alphabet) for _ in xrange(slen))
print get_random_string('0123456789', 5) # prints e.g. 62247
All strings in lexicographical order (thanks @DSM for reminding me about
`itertools`):
import itertools
def gen_all_strings(alphabet, slen):
it = itertools.product(alphabet, repeat=slen)
return (''.join(s) for s in it)
print list(gen_all_strings('abc', 2)) # prints ['aa', 'ab', 'ac', 'ba', 'bb', 'bc', 'ca', 'cb', 'cc']
|
How to color character linux terminal
Question: I would like your your help writing some code: I would like Ubuntu 12.04.1
Terminal to color "/" character opposite as other text.
This could be very important for pretty much everyone, who writes bash/python
directly in console...
**Any ideas where to start?**
I'm thinking of a custom plugin fo terminal, that could parse text right
before it is printed?
Answer: The `tput` command is your friend (assuming you want to stay in shell-script
land).
$ tput smso; echo Bold text; tput rmso
Q: What will highlighting _/_ characters give you?
|
Does Python 3.3's support of xz-compressed zipfiles extend to zipimport?
Question: Python 3.3's zipfile module understands .zip archives that have been
compressed with bzip2 or xz instead of the traditional deflate algorithm. Does
this extended compression support extend to the zipimport functionality?
Answer: No, the [`zipimport.c`
source](http://hg.python.org/cpython/file/tip/Modules/zipimport.c) is
implemented independently from the stdlib `zipfile` module and only supports
ZLIB compressed data or uncompressed archives.
Specifically, the heavy lifting is done in the [`get_data`
function](http://hg.python.org/cpython/file/tip/Modules/zipimport.c#l1026)
which has `/* data is not compressed */` and `/* Decompress with zlib */`
branches.
|
from . import * from module
Question: there is a script in the working directory which I can access with
from . import core.py
but if I would also like to import * from core.py, how would I write this in
python?
Answer: I'm pretty sure it's just:
from core import *
Assuming `core.py` is in your current working directory or where the script is
running from.
|
OSError, [Errno 13] Permission denied, thrown when I try to upload load file in django with apache/mod_wsgi server
Question: Here is the trace back
Environment:
Request Method: POST
Request URL: http://mysite.com/admin/content/author/add/
Django Version: 1.4.1
Python Version: 2.7.3
Installed Applications:
('grappelli',
'filebrowser',
'south',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'tinymce',
'mailchimp',
'content',
'categorization',
'mptt')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in wrapper
366. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view
91. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
89. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/sites.py" in inner
196. return view(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapper
25. return bound_func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view
91. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/utils/decorators.py" in bound_func
21. return func(self, *args2, **kwargs2)
File "/usr/local/lib/python2.7/dist-packages/django/db/transaction.py" in inner
209. return func(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in add_view
955. self.save_model(request, new_object, form, False)
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py" in save_model
709. obj.save()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in save
463. self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/base.py" in save_base
551. result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/manager.py" in _insert
203. return insert_query(self.model, objs, fields, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/query.py" in insert_query
1576. return query.get_compiler(using=using).execute_sql(return_id)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py" in execute_sql
909. for sql, params in self.as_sql():
File "/usr/local/lib/python2.7/dist-packages/django/db/models/sql/compiler.py" in as_sql
872. for obj in self.query.objs
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/files.py" in pre_save
249. file.save(file.name, file, save=False)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/files.py" in save
86. self.name = self.storage.save(name, content)
File "/usr/local/lib/python2.7/dist-packages/django/core/files/storage.py" in save
45. name = self._save(name, content)
File "/usr/local/lib/python2.7/dist-packages/django/core/files/storage.py" in _save
168. os.makedirs(directory)
File "/usr/lib/python2.7/os.py" in makedirs
150. makedirs(head, mode)
File "/usr/lib/python2.7/os.py" in makedirs
157. mkdir(name, mode)
Exception Type: OSError at /admin/content/author/add/
Exception Value: [Errno 13] Permission denied: '//media/uploads'
Here is my model
class ArticleImage(models.Model):
title = models.CharField(
verbose_name = _(u'Title'),
help_text = _(u'The title for this article image'),
max_length = 255,
)
alt_text = models.CharField(
verbose_name = _(u'Alt. Text'),
help_text = _(u'The alt text for this article image'),
max_length = 255,
)
image = models.ImageField(
verbose_name = _(u'Image'),
upload_to = 'uploads/articleimages/'
)
article = models.ForeignKey(
Article,
verbose_name = _(u'Article'),
help_text = _(u'The article to which this image belongs'),
)
class Meta:
verbose_name = _(u'Image')
verbose_name_plural = _(u'Images')
def __unicode__(self):
return u'%s'%self.title
Here are related settings
MEDIA_ROOT = os.getcwd() + '/media/'
MEDIA_URL = '/media/'
DEBUG = False
Here is my httpd.conf for the media directory
Alias /media/ /home/quinton/Sites/prod/media/
<Directory /home/quinton/Sites/prod/media>
Order deny,allow
Allow from all
</Directory>
This is not a problem when I run everything locally. Only when I push to my
server and restart Apache does this occur. I have tried changing the file
permission to 777 for the media directory, but still no luck.
Answer: `os.getcwd()` might not give you what you want. There's no guarantee that the
working directory is, say, the one your settings.py file is in.
If you want to work from your settings file's location, then you can use
`os.path` and `__file__` in your `settings.py` file:
import os.path
# Get the directory the settings.py file is located in.
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
As a bonus, other modules in your project can use this as well:
from django.conf import settings
print "Base directory:", settings.BASE_DIR
|
Text of a Python Function
Question: > **Possible Duplicate:**
> [How can I get the source code of a Python
> function?](http://stackoverflow.com/questions/427453/how-can-i-get-the-
> source-code-of-a-python-function)
First, let me define my problem. I will give a motivation afterward.
## Problem:
def map(doc):
yield doc['type'], 1
# How do I get the textual representation of the function map above,
# as in getting the string "def map(doc):\n yield doc['yield'], 1"?
print repr(map) # Does not work. It prints <function fun at 0x10049c8c0> instead.
## Motivation:
For those of you familiar with CouchDB views, I am writing a Python script to
generate CouchDB views, which are JSON with the map and reduce functions
embedded. For example,
{
"language": "python",
"views": {
"pytest": {
"map": "def fun(doc):\n yield doc['type'], 1",
"reduce": "def fun(key, values, rereduce):\n return sum(values)"
}
}
}
However, for readability, I would prefer to write the `map` and `reduce`
function natively in the Python script first, then construct the above JSON
using the answer to this question.
## Solution:
By [BrenBarn's response](http://stackoverflow.com/a/12452106/560074), use
`inspect.getsource`.
#!/usr/bin/env python
import inspect
def map(doc):
yield doc['type'], 1
def reduce(key, values, rereduce):
return sum(values)
couchdb_views = {
"language": "python",
"views": {
"pytest": {
"map": inspect.getsource(map),
"reduce": inspect.getsource(reduce),
}
}
}
# Yay!
print couchdb_views
Answer: You can use the
[`inspect.getsource`](http://docs.python.org/library/inspect.html#inspect.getsource)
function to get the source of a function. Note that for this to work the
function has to be loaded from a file (e.g., it won't work for functions
defined in the interactive interpreter).
|
In PyCharm, I have an unresolved reference when calling nose.tools.assert_equals?
Question: When I try to use pycharm with nose, I get red underlines with "unresolved
reference" when calling assert_raises. I'm using a virtualenv interpreter, but
nose is installed and can be run from ipython. Also, running nosetests on
actual tests shows no error.
The code I'm running is:
from nose.tools import *
def test1():
assert_equals(1,1)
Again, nose runs fine, but the linting mechanism in pycharm thinks this is an
error. Any help on configuring pycharm?
Answer: I've reproduced the problem and [submitted a
bug](http://youtrack.jetbrains.com/issue/PY-7614) to YouTrack, please
star/vote the issue to track the progress.
|
Python - List of Lists Slicing Behavior
Question: When I define a list and try to change a single item like this:
list_of_lists = [['a', 'a', 'a'], ['a', 'a', 'a'], ['a', 'a', 'a']]
list_of_lists[1][1] = 'b'
for row in list_of_lists:
print row
It works as intended. But when I try to use list comprehension to create the
list:
row = ['a' for range in xrange(3)]
list_of_lists = [row for range in xrange(3)]
list_of_lists[1][1] = 'b'
for row in list_of_lists:
print row
It results in an entire column of items in the list being changed. Why is
this? How can I achieve the desired effect with list comprehension?
Answer: Think about if you do this:
>>> row = ['a' for range in xrange(3)]
>>> row2 = row
>>> row2[0] = 'b'
>>> row
['b', 'a', 'a']
This happens because `row` and `row2` are two different names for _the same
list_ (you have `row is row2`) - your example with nested lists only obscures
this a little.
To make them different lists, you can cause it to re-run the list-creation
code each time instead of doing a variable assignment:
list_of_lists = [['a' for range in xrange(3)] for _ in xrange(3)]
or, create a new list each time by using a slice of the full old list:
list_of_lists = [row[:] for range in xrange(3)]
Although this isn't guaranteed to work in general for all sequences - it just
happens that list slicing makes a new list for the slice. This doesn't happen
for, eg, numpy arrays - a slice in those is a view of part of the array rather
than a copy. If you need to work more generally than just lists, use the
`copy` module:
from copy import copy
list_of_lists = [copy(row) for range in xrange(3)]
Also, note that `range` isn't the best name for a variable, since it shadows
the builtin - for a throwaway like this, `_` is reasonably common.
|
Sklearn: ValueError: X and Y have incompatible shapes
Question: I am new to sklearn and in general to python as well. Can you help me figure
out if this script is leading to some solution? Basically I am using an hue
extractor on an Imageset: load iset for training, extract features, define
classifier and then classify.
#load beach for training
iset = ImageSet('/Users/Arenzky/Desktop/img_dirs/supervised/beach/') #load Image database
hue = HueHistogramFeatureExtractor() # define extractor
edge = EdgeHistogramFeatureExtractor()
x = []
y = []
for b in iset:
...: x.append(hue.extract(b))
hset = ImageSet('/dir/.../h01/')
hue = HueHistogramFeatureExtractor() # define extractor
edge = EdgeHistogramFeatureExtractor()
for h01 in hset:
...: y.append(hue.extract(h01))
dataset = np.array(x)
targets = np.array(y)
print 'Training Machine Learning'
clf = LinearSVC()
clf = clf.fit(x, y)
clf2 = LogisticRegression().fit(x, y)
#predict
... after loading clf I get:
ValueError:
X and Y have incompatible shapes. X has 20 samples, but Y has 286.
Answer: The error message is pretty explicit: you have 20 samples (rows) in your input
datasets and 286 labels hence the mismatch. Each sample should be labeled once
hence `y.shape[0]` should be equal to `x.shape[0]`. I don't know how your
feature extractors work (and you did not put the import lines but by googling
it's from SimpleCV). Please refer to the documentation of this module to
understand the nature of their output and how to transform them to something
that satisfy the sklearn shapes assumptions.
|
XML header getting removed after processing with elementtree
Question: i have an xml file and i used Elementtree to add a new tag to the xml file.My
xml file before processing is as follows
<?xml version="1.0" encoding="utf-8"?>
<PackageInfo xmlns="http://someurlpackage">
<data ID="http://someurldata1">data1</data >
<data ID="http://someurldata2">data2</data >
<data ID="http://someurldata3">data3</data >
</PackageInfo>
I used following python code to add a new data tag and write it to my xml file
tree = ET.ElementTree(xmlFile)
root = tree.getroot()
elem= ET.Element('data')
elem.attrib['ID']="http://someurldata4"
elem.text='data4'
root[1].append(elem)
tree = ET.ElementTree(root)
tree.write(xmlFile)
But the resultant xml file have `<?xml version="1.0" encoding="utf-8"?>`
absent and the file looks as below
<PackageInfo xmlns="http://someurlpackage">
<data ID="http://someurldata1">data1</data >
<data ID="http://someurldata2">data2</data >
<data ID="http://someurldata3">data3</data >
</PackageInfo>
Is there any way to include the xml header rather than hardcoding the line
Answer: It looks like you need optional arguments to the `write` method to output the
declaration.
<http://docs.python.org/library/xml.etree.elementtree.html#elementtree-
elementtree-objects>
tree.write(xmlfile,xml_declaration=True)
* * *
I'm afraid I'm not that familiar with `xml.etree.ElementTree` and it's
variation between python releases.
Here's it working with `lxml.etree`:
>>> from lxml import etree
>>> sample = """<?xml version="1.0" encoding="utf-8"?>
... <PackageInfo xmlns="http://someurlpackage">
... <data ID="http://someurldata1">data1</data >
... <data ID="http://someurldata2">data2</data >
... <data ID="http://someurldata3">data3</data >
... </PackageInfo>"""
>>>
>>> doc = etree.XML(sample)
>>> data = doc.makeelement("data")
>>> data.attrib['ID'] = 'http://someurldata4'
>>> data.text = 'data4'
>>> doc.append(data)
>>> etree.tostring(doc,xml_declaration=True)
'<?xml version=\'1.0\' encoding=\'ASCII\'?>\n<PackageInfo xmlns="http://someurlpackage">\n<data ID="http://someurldata1">data1</data>\n<data ID="http://someurldata2">data2</data>\n<data ID="http://someurldata3">data3</data>\n<data ID="http://someurldata4">data4</data></PackageInfo>'
>>> etree.tostring(doc,xml_declaration=True,encoding='utf-8')
'<?xml version=\'1.0\' encoding=\'utf-8\'?>\n<PackageInfo xmlns="http://someurlpackage">\n<data ID="http://someurldata1">data1</data>\n<data ID="http://someurldata2">data2</data>\n<data ID="http://someurldata3">data3</data>\n<data ID="http://someurldata4">data4</data></PackageInfo>'
|
Live Profiling of Python Server
Question: I want to know where the python interpreter spends the most time. I use it on
a live django application, but it should work for all long running python
processes.
I answer my own question.
Answer:
import os, re, sys, time, datetime, collections, thread, threading, atexit, traceback
u'''
debug_live.start(seconds_float) starts a monitor thread which print
the stacktrace of all threads into a logfile.
You can report which lines are executed the most with this script:
app_foo_d@server:~$ python djangotools/utils/debug_live.py -h
usage: debug_live.py [-h] [--most-common N] {sum-all-frames,sum-last-frame}
Read stacktrace log
positional arguments:
{sum-all-frames,sum-last-frame}
optional arguments:
-h, --help show this help message and exit
--most-common N Display the N most common lines in the stacktraces
---------------------------------
You can start the watching thread your django middleware like this:
class FOOMiddleware:
def __init__(self):
u'This code gets executed once after the start of the wsgi worker process. Not for every request!'
seconds=getattr(settings, 'debug_live_interval', None)
if seconds:
seconds=float(seconds)
from djangotools.utils import debug_live
debug_live.start(seconds)
# settings.py
debug_live_interval=0.3 # ever 0.3 second
# Inspired by http://code.google.com/p/modwsgi/wiki/DebuggingTechniques
You can get a simple report of the log file of stacktraces like below. The lines
which are not from django are marked with "<====". That's most likely your code
and this could be a bottle neck.
python ..../debug_live.py read
1971 File: "/home/foo_bar_p/django/core/handlers/wsgi.py", line 272, in __call__
response = self.get_response(request)
1812 File: "/home/foo_bar_p/django/core/handlers/base.py", line 111, in get_response
response = callback(request, *callback_args, **callback_kwargs)
1725 File: "/home/foo_bar_p/django/db/backends/postgresql_psycopg2/base.py", line 44, in execute
return self.cursor.execute(query, args)
1724 File: "/home/foo_bar_p/django/db/models/sql/compiler.py", line 735, in execute_sql
cursor.execute(sql, params)
1007 File: "/home/foo_bar_p/django/db/models/sql/compiler.py", line 680, in results_iter
for rows in self.execute_sql(MULTI):
796 File: "/home/foo_bar_p/django/db/models/query.py", line 273, in iterator
for row in compiler.results_iter():
763 File: "/home/foo_bar_p/foo/utils/ticketutils.py", line 135, in __init__ <====
filter=type_filter(root_node=self.root_node)
684 File: "/home/foo_bar_p/django/db/models/query.py", line 334, in count
return self.query.get_count(using=self.db)
679 File: "/home/foo_bar_p/django/db/models/sql/query.py", line 367, in get_aggregation
result = query.get_compiler(using).execute_sql(SINGLE)
677 File: "/home/foo_bar_p/django/db/models/sql/query.py", line 401, in get_count
number = obj.get_aggregation(using=using)[None]
'''
from django.conf import settings
outfile = os.path.expanduser('~/tmp/debug_live.log')
other_code=re.compile(r'/(django|python...)/')
def stacktraces():
code=[]
now=datetime.datetime.now()
pid=os.getpid()
my_thread_id=thread.get_ident()
for thread_id, stack in sys._current_frames().items():
if thread_id==my_thread_id:
continue # Don't print this monitor thread
code.append("\n\n#START date: %s\n# ProcessId: %s\n# ThreadID: %s" % (now, pid, thread_id))
for filename, lineno, name, line in traceback.extract_stack(stack):
code.append('File: "%s", line %d, in %s' % (filename, lineno, name))
if line:
code.append(" %s" % (line.strip()))
code.append('#END')
if not code:
return
fd=open(outfile, 'at')
fd.write('\n'.join(code))
fd.close()
def monitor(interval):
while monitor_thread:
stacktraces()
time.sleep(interval)
monitor_thread=None
def exiting():
global monitor_thread
monitor_thread=None
def start(interval):
global monitor_thread
if monitor_thread:
return
assert not os.path.islink(outfile), outfile # well known temporary name.... symlink attack...
monitor_thread = threading.Thread(target=monitor, args=[interval])
monitor_thread.setDaemon(True)
atexit.register(exiting)
monitor_thread.start()
def read_logs(args):
# The outfile can be huge, don't read the whole file into memory.
counter=collections.Counter()
cur_stack=[]
py_line=''
code_line=''
if args.action=='sum-all-frames':
sum_all_frames=True
else:
sum_all_frames=False
for line in open(outfile):
if line.startswith('#END'):
if sum_all_frames:
frames=cur_stack
else:
frames=cur_stack[-1:]
counter.update(frames)
cur_stack=[]
continue
if line[0] in '\n#':
continue
if line.startswith('File:'):
py_line=line.rstrip()
continue
if line.startswith(' '):
code_line=line.rstrip()
if not (py_line, code_line) in cur_stack:
# If there is a recursion, count the line only once per stacktrace
cur_stack.append((py_line, code_line))
continue
print 'ERROR unparsed', line
for (py, code), c in counter.most_common(args.most_common):
if not other_code.search(py):
py='%s <====' % py
print '% 5d %s\n %s' % (c, py, code)
def main():
import argparse
parser=argparse.ArgumentParser(description='Read stacktrace log')
parser.add_argument('action', choices=['sum-all-frames', 'sum-last-frame'])
parser.add_argument('--most-common', metavar='N', default=30, type=int, help='Display the N most common lines in the stacktraces')
args=parser.parse_args()
return read_logs(args)
if __name__=='__main__':
main()
|
Jenkins: HTTP error 403 when getting config
Question: I try to update Jenkins jobs' config programmatically, and the [python Jenkins
api](http://packages.python.org/jenkinsapi/index.html) looked ok, but I can't
retrieve a config because of HTTP error 403 (forbidden):
from jenkinsapi import api
j = api.Jenkins('https://server.test.com/hudson', 'fp12210', 'xxxxxxxx')
job = j.get_job('BBB-100-CheckStatusAll')
conf = job.get_config()
Traceback (most recent call last):
...
File "C:\Python27\lib\urllib2.py", line 521, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 403: Forbidden
Adding user and password in URL, [as mentionned in another SO
post](http://stackoverflow.com/questions/7427557/jenkins-and-github-webhook-
http-403), fails too:
j = api.Jenkins('https://fp12210:[email protected]/hudson')
Traceback (most recent call last):
...
File "build\bdist.win32\egg\jenkinsapi\utils\retry.py", line 39, in retry_function
raise e
InvalidURL: nonnumeric port: '[email protected]/hudson'
Do you have any idea ?
Answer: This [SO post](http://stackoverflow.com/questions/635113/python-urllib2-basic-
http-authentication-and-tr-im) is the solution. I now get an error 500, but
this is another story...
|
Python's multiprocessing map_async generates error on Windows
Question: The code below works perfectly on Unix but generates a
multiprocessing.TimeoutError on Windows 7 (both OS use python 2.7).
Any idea why? Thanks.
from multiprocessing import Pool
def increment(x):
return x + 1
def decrement(x):
return x - 1
pool = Pool(processes=2)
res1 = pool.map_async(increment, range(10))
res2 = pool.map_async(decrement, range(10))
print res1.get(timeout=1)
print res2.get(timeout=1)
Answer: You need to put your actual program logic in side a `if __name__ ==
'__main__':` block.
On Unixy systems, Python forks, producing multiple processes to work from.
Windows doesn't have fork. Python has to launch a new interpreter and re-
import all your modules instead. This means that each subprocess will reimport
your main module. For the code you've written reimporting the module will
cause each newly launched processes to launch processes of its own.
See: <http://docs.python.org/library/multiprocessing.html#windows>
**EDIT** this works for me:
from multiprocessing import Pool
def increment(x):
return x + 1
def decrement(x):
return x - 1
if __name__ == '__main__':
pool = Pool(processes=2)
res1 = pool.map_async(increment, range(10))
res2 = pool.map_async(decrement, range(10))
print res1.get(timeout=1)
print res2.get(timeout=1)
|
python regular expression substitute
Question: I need to find the value of "taxid" in a large number of strings similar to
one given below. For this particular string, the 'taxid' value is '9606'. I
need to discard everything else. The "taxid" may appear anywhere in the text,
but will always be followed by a ":" and then number.
score:0.86|taxid:9606(Human)|intact:EBI-999900
How to write regular expression for this in python.
Answer:
>>> import re
>>> s = 'score:0.86|taxid:9606(Human)|intact:EBI-999900'
>>> re.search(r'taxid:(\d+)', s).group(1)
'9606'
If there are multiple taxids, use `re.findall`, which returns a list of all
matches:
>>> re.findall(r'taxid:(\d+)', s)
['9606']
|
Getting a tweet's ID with Twython?
Question: I'm using Twython (Python wrapper for Twitter API, found
[here](https://github.com/ryanmcgrath/twython "Link to Twython's GitHub
page").)
Objective: I'm trying to make a simple bot that searches for a keyword and
replies to tweets with the keyword in them.
Example: Send search request to search for `#stackoverflow`, reply to tweets
that have `#stackoverflow` in them with "StackOverflow is the best!"
Problem: Can't reply to a tweet without the tweet id (found in the url of any
permalinked tweet). An example of this would be to take any tweet and link
someone to it. The number at the end of the link is the tweet id.
What I've Tried: There's not much I _can_ try. I want this to be as simple as
possible, with no complex workarounds. I'm sure there's some way to do this
without having to go too far out of my way. I've exhausted Google and
Twython's documentation and Twitter's API documentation. =/ Anyone
Answer: Tweets are just python dictionaries, and their contents echo the [`Tweet`
resource](https://dev.twitter.com/docs/platform-objects/tweets) exactly. Each
tweet thus has an `id_str` key:
print tweet['id_str']
You can always print data structures if things are not clear; I can recommend
the [`pprint.pprint()`
function](http://docs.python.org/library/pprint.html#pprint.pprint) to make
nested python structures extra readable:
import pprint
pprint.pprint(tweet)
Example session:
>>> from twython import Twython
>>> t = Twython()
>>> res = t.search(q='python')
>>> res.keys()
[u'next_page', u'completed_in', u'max_id_str', u'since_id_str', u'refresh_url', u'results', u'since_id', u'results_per_page', u'query', u'max_id', u'page']
>>> from pprint import pprint
>>> pprint(res[u'results'][0])
{u'created_at': u'Mon, 17 Sep 2012 21:01:12 +0000',
u'from_user': u'Me_Craay_GOOFY',
u'from_user_id': 230100184,
u'from_user_id_str': u'230100184',
u'from_user_name': u'\u06deSuperFLY_PUER\u06de\u2122',
u'geo': None,
u'id': 247802407529115649,
u'id_str': u'247802407529115649',
u'iso_language_code': u'en',
u'metadata': {u'result_type': u'recent'},
u'profile_image_url': u'http://a0.twimg.com/profile_images/2617747450/345616051_normal.jpg',
u'profile_image_url_https': u'https://si0.twimg.com/profile_images/2617747450/345616051_normal.jpg',
u'source': u'<a href="http://globalgrind.com">UncleUber for Blackberry</a>',
u'text': u'RT @Mr_Oyato: #ViolentPrayers May the python of breakthrough swallow you and your household today.',
u'to_user': None,
u'to_user_id': 0,
u'to_user_id_str': u'0',
u'to_user_name': None}
>>> res[u'results'][0]['id_str']
u'247802407529115649'
|
Python: Way to speed up a repeatedly executed eval statement?
Question: In my code, I'm using `eval` to evaluate a string expression given by the
user. Is there a way to compile or otherwise speed up this statement?
import math
import random
result_count = 100000
expression = "math.sin(v['x']) * v['y']"
variable = dict()
variable['x'] = [random.random() for _ in xrange(result_count)]
variable['y'] = [random.random() for _ in xrange(result_count)]
# optimize anything below this line
result = [0] * result_count
print 'Evaluating %d instances of the given expression:' % result_count
print expression
v = dict()
for index in xrange(result_count):
for name in variable.keys():
v[name] = variable[name][index]
result[index] = eval(expression) # <-- option ONE
#result[index] = math.sin(v['x']) * v['y'] # <-- option TWO
For a quick comparison option ONE takes 2.019 seconds on my machine, while
option TWO takes only 0.218 seconds. Surely Python has a way of doing this
without hard-coding the expression.
Answer: You can also trick python:
expression = "math.sin(v['x']) * v['y']"
exp_as_func = eval('lambda: ' + expression)
And then use it like so:
exp_as_func()
Speed test:
In [17]: %timeit eval(expression)
10000 loops, best of 3: 25.8 us per loop
In [18]: %timeit exp_as_func()
1000000 loops, best of 3: 541 ns per loop
* * *
As a side note, if `v` is not a global, you can create the lambda like this:
exp_as_func = eval('lambda v: ' + expression)
and call it:
exp_as_func(my_v)
|
Why doesn't strip method in python take the two "\n" in a text file
Question:
import pdb
input_file_eng = open('engltreaty.txt')
word_list_eng = input_file_eng.read()
pure_word_list_eng = word_list_eng.strip("\n").strip("\r").strip('-').strip('.').strip(',').strip('(').strip(')').strip('[').strip(']')
pdb.set_trace()
input_file_eng.close()
and at the break point, I inspect the string pure_word_list_eng, it still
contains '[',']',"\n" "\n\n"
and I below is the text file:
> HER MAJESTY VICTORIA Queen of the United Kingdom of Great Britain and
> Ireland regarding with Her Royal Favour the Native Chiefs and Tribes of New
> Zealand and anxious to protect their just Rights and Property and to secure
> to them the enjoyment of Peace and Good Order has deemed it necessary in
> consequence of the great number of Her Majesty's Subjects who have already
> settled in New Zealand and the rapid extension of Emigration both from
> Europe and Australia which is still in progress to constitute and appoint a
> functionary properly authorised to treat with the Aborigines of New Zealand
> for the recognition of Her Majesty's Sovereign authority over the whole or
> any part of those islands - Her Majesty therefore being desirous to
> establish a settled form of Civil Government with a view to avert the evil
> consequences which must result from the absence of the necessary Laws and
> Institutions alike to the native population and to Her subjects has been
> graciously pleased to empower and to authorise me William Hobson a Captain
> in Her Majesty's Royal Navy Consul and Lieutenant-Governor of such parts of
> New Zealand as may be or hereafter shall be ceded to her Majesty to invite
> the confederated and independent Chiefs of New Zealand to concur in the
> following Articles and Conditions.
>
> Article the first [Article 1] The Chiefs of the Confederation of the United
> Tribes of New Zealand and the separate and independent Chiefs who have not
> become members of the Confederation cede to Her Majesty the Queen of England
> absolutely and without reservation all the rights and powers of Sovereignty
> which the said Confederation or Individual Chiefs respectively exercise or
> possess, or may be supposed to exercise or to possess over their respective
> Territories as the sole sovereigns thereof.
>
> Article the second [Article 2] Her Majesty the Queen of England confirms and
> guarantees to the Chiefs and Tribes of New Zealand and to the respective
> families and individuals thereof the full exclusive and undisturbed
> possession of their Lands and Estates Forests Fisheries and other properties
> which they may collectively or individually possess so long as it is their
> wish and desire to retain the same in their possession; but the Chiefs of
> the United Tribes and the individual Chiefs yield to Her Majesty the
> exclusive right of Preemption over such lands as the proprietors thereof may
> be disposed to alienate at such prices as may be agreed upon between the
> respective Proprietors and persons appointed by Her Majesty to treat with
> them in that behalf.
>
> Article the third [Article 3] In consideration thereof Her Majesty the Queen
> of England extends to the Natives of New Zealand Her royal protection and
> imparts to them all the Rights and Privileges of British Subjects.
>
> (signed) William Hobson, Lieutenant-Governor.
>
> Now therefore We the Chiefs of the Confederation of the United Tribes of New
> Zealand being assembled in Congress at Victoria in Waitangi and We the
> Separate and Independent Chiefs of New Zealand claiming authority over the
> Tribes and Territories which are specified after our respective names,
> having been made fully to understand the Provisions of the foregoing Treaty,
> accept and enter into the same in the full spirit and meaning thereof in
> witness of which we have attached our signatures or marks at the places and
> the dates respectively specified. Done at Waitangi this Sixth day of
> February in the year of Our Lord one thousand eight hundred and forty.
Answer: From [the docs](http://docs.python.org/library/stdtypes.html#str.strip):
> Return a copy of the string **with the leading and trailing characters
> removed**.
Try `str.replace()` instead.
|
Making a Point Class in Python
Question: I am trying to create a class in python titled "Point." I am trying to create
a point on a coordinate plane x and y and track them. As well as find the
distance between the points. I have to use functions and methods. I have
started and here is my code. I am just not sure how to use it when I go to
execute the program. Any help will be appreciated.
EDIT: Updated Code
import math
class Point(object):
'''Creates a point on a coordinate plane with values x and y.'''
COUNT = 0
def __init__(self, x, y):
'''Defines x and y variables'''
self.X = x
self.Y = y
def move(self, dx, dy):
'''Determines where x and y move'''
self.X = self.X + dx
self.Y = self.Y + dy
def __str__(self):
return "Point(%s,%s)"%(self.X, self.Y)
def getX(self):
return self.X
def getY(self):
return self.Y
def distance(self, other):
dx = self.X - other.X
dy = self.Y - other.Y
return math.sqrt(dx**2 + dy**2)
def testPoint(x=0,y=0):
'''Returns a point and distance'''
p1 = Point(3, 4)
print p1
p2 = Point(3,0)
print p2
return math.hypot(dx, dy)
print "distance = %s"%(testPoint())
I still need help understanding how to actually use the code. That's why I
created the `testPoint` function. When I actually go to execute the code in
IDLE, how do I prove that everything works? Thanks a bunch guys!!
I also need to add code to the constructor to increment `COUNT` by 1 every
time a Point object is created. I also need to add appropriate code so that
points can be compared using the comparison operators while 'points' are
compared based on their distance from the origin.
Answer: Don't forget `math.hypot`
def distance(self, p):
dx = self.X - p.X
dy = self.Y - p.Y
return hypot(dx, dy)
|
Python Requests logging to file
Question: How can I configure logging to file requests's get or post?
my_config = {'verbose': sys.stderr}
requests.get('http://httpbin.org/headers', config=my_config)
What should I use in verbose?
Answer: Have you tried simply opening a file?
>>> import sys
>>> type(sys.stderr)
file
>>> f = open('test.log', 'w')
>>> type(f)
f
So the example above will look like this:
my_config = { 'verbose': open('/path/to/file', 'w') }
requests.get('http://httpbin.org/headers', config = my_config)
HTH
|
import variable
Question: attrubuI'm new to python but don't know how to solve this:
import wx
class myclass(wx.Frame):
def __init__(self,parent,id):
wx.Frame.__init__(self,parent,id,'Frame',size=(300,200))
panel=wx.Panel(self)
button=wx.Button(panel,label="click me",size=(120,60))
self.Bind(wx.EVT_BUTTON, self.clickbutton, button)
value=1
def clickbutton(self, event):
if self.value == 1:
print("success")
if __name__=='__main__':
app=wx.PySimpleApp()
frame=myclass(parent=None,id=-1)
frame.Show()
app.MainLoop()
When I click the button I receive this error: "AttributeError: 'myclass'
object has no attribute 'value'". What am I doing wrong? / How do I import
"value" into my "clickbutton"-function?
Edit: OK, this one was solved. After that I wanted to modify it a little:
self.dropdown=wx.Choice(panel,pos=(130,60))
list = ['banana', 'apple', 'strawberry']
self.dropdown.AppendItems(strings=list)
def clickbutton(self, event):
if self.dropdown.GetStringSelection() == 'apple':
print("success")
Actually this works.... but it took me a long time to figure out that I have
to use "GetStringSelection()" in the last but one line. How can i display a
list with possible attributes (like "GetStringSelection()") for "wx.Choice"
(and other wx-classes) ? Or does a good website for this exists?
Edit 2: Thanks again! And I have a last question (sorry for asking step by
step):
dir(wx.Choice)
works, but I have a given code with an obejct called "VarDecl". For this I get
an error if I ask
dir(wx.VarDecl)
I'm lookin for an attribute like "HasChanged" for this VarDecl-object.
Traceback (most recent call last):
File [...]
if self.theVariable.HasChanged():
AttributeError: 'VarDecl' object has no attribute 'HasChanged'
Edit3: OK, I think it has nothing to do with "wx", I think it comes from "re".
(or still "wx"? I'm confused)
Answer: Change `value=1` to `self.value = 1`. The `value` you have now is a local
variable, which is discarded upon exiting the constructor.
**EDIT:** As for your second question, the built-in function `dir(object)`
will give you a list of names (including methods) in the scope of the given
object. [More information available
here](http://docs.python.org/library/functions.html#dir)
**EDIT 2:** [The wxPython documentation may also be of use to
you](http://wxpython.org/docs/api/)
**EDIT 3:** About the theVariable thing: Have you tried
`dir(self.theVariable)`?
|
Compare multiple file in python
Question: i have a set of directories with `n` number of files, I need to compare each
of those files (within one directory) and find if there is any difference in
them. I tried `filecmp` and `difflib` but they only support two files.
Is there anything else I can do to compare/diff the files ?
This file contain hosts name
--------------------------------
Example :- Dir -> Server.1
|-> file1
|-> file2
|-> file3
file1 <- host1
host2
host3
file2 <- host1
host2
host3
host4
file3 <- host1
host2
host3
Answer: I thought I'd share how combining the md5 hash compare with os.path.walk() can
help you ferret out all the duplicates in a directory tree. The larger the
number of directories and files gets, the more helpful it might be to first
sort files by size to rule out any files that can't duplicates because they
are of different size. Hope this helps.
import os, sys
from hashlib import md5
nonDirFiles = []
def crawler(arg, dirname, fnames):
'''Crawls directory 'dirname' and creates global
list of paths (nonDirFiles) that are files, not directories'''
d = os.getcwd()
os.chdir(dirname)
global nonDirFiles
for f in fnames:
if not os.path.isfile(f):
continue
else:
nonDirFiles.append(os.path.join(dirname, f))
os.chdir(d)
def startCrawl():
x = raw_input("Enter Dir: ")
print 'Scanning directory "%s"....' %x
os.path.walk(x, crawler, nonDirFiles)
def findDupes():
dupes = []
outFiles = []
hashes = {}
for fileName in nonDirFiles:
print 'Scanning file "%s"...' % fileName
f = file(fileName, 'r')
hasher = md5()
data = f.read()
hasher.update(data)
hashValue = hasher.digest()
if hashes.has_key(hashValue):
dupes.append(fileName)
else:
hashes[hashValue] = fileName
return dupes
if __name__ == "__main__":
startCrawl()
dupes = findDupes()
print "These files are duplicates:"
for d in dupes:print d
|
Given a .torrent file how do I generate a magnet link in python?
Question: I need a way to convert .torrents into magnet links. Would like a way to do so
in python. Are there any libraries that already do this?
Answer: You can do this with the [bencode](http://pypi.python.org/pypi/bencode/1.0)
module, extracted from BitTorrent.
To show you an example, I downloaded a torrent ISO of Ubuntu from here:
http://releases.ubuntu.com/12.04/ubuntu-12.04.1-desktop-i386.iso.torrent
Then, you can parse it in Python like this:
>>> import bencode
>>> torrent = open('ubuntu-12.04.1-desktop-i386.iso.torrent', 'r').read()
>>> metadata = bencode.bdecode(torrent)
A magnet hash is calculated from only the "info" section of the torrent
metadata and then encoded in base32, like this:
>>> hashcontents = bencode.bencode(metadata['info'])
>>> import hashlib
>>> digest = hashlib.sha1(hashcontents).digest()
>>> import base64
>>> b32hash = base64.b32encode(digest)
>>> b32hash
'CT76LXJDDCH5LS2TUHKH6EUJ3NYKX4Y6'
You can verify that this is correct by looking
[here](http://www.linux23.com/torrent/ubuntu-12-04-1-desktop-i386-iso:14ffe5dd23188fd5cb53a1d47f1289db70abf31e)
and you will see the magnet link is:
magnet:?xt=urn:btih:CT76LXJDDCH5LS2TUHKH6EUJ3NYKX4Y6
If you want to fill in some extra parameters to the magnet URI:
>>> params = {'xt': 'urn:btih:%s' % b32hash,
... 'dn': metadata['info']['name'],
... 'tr': metadata['announce'],
... 'xl': metadata['info']['length']}
>>> import urllib
>>> paramstr = urllib.urlencode(params)
>>> magneturi = 'magnet:?%s' % paramstr
>>> magneturi
'magnet:?dn=ubuntu-12.04.1-desktop-i386.iso&tr=http%3A%2F%2Ftorrent.ubuntu.com%3A6969%2Fannounce&xl=729067520&xt=urn%3Abtih%3ACT76LXJDDCH5LS2TUHKH6EUJ3NYKX4Y6'
|
Finding if a string exists in a nested tuple in Python
Question: What is the best (and fastest) way, in Python 2.7.x, to check if a string (or
any other data type) exists in a nested tuple?
For example:
RECIPES = (
('apple', 'sugar', 'extreme_Force'),
('banana', 'syrup', 'magical_ends'),
('caramel', 'chocolate', 'pancake_MONSTER'),
('banana',('someAnother','banana'))
)
This tuples needs to be checked if `banana` appears in any of the nested tuple
and return the location index, in this case `1,0`.
Also, the tuples could be nested to any depth.
Answer: Recursive multi-location indexing:
import sys
from collections import Sequence,defaultdict
#making code python3-compatible
if sys.version_info[0] == 3:
basestring = str
def buildLocator(tree):
locator = defaultdict(list)
def fillLocator(tree, locator,location):
for index,item in enumerate(tree):
if isinstance(item,basestring):
locator[item].append(location+(index,))
elif isinstance(item,Sequence):
fillLocator(item,locator, location+(index,))
fillLocator(tree,locator,())
return locator
RECIPES = (
('apple', 'sugar', 'extreme_Force'),
('banana', 'syrup', 'magical_ends'),
('caramel', 'chocolate', 'pancake_MONSTER'),
('banana',('someAnother','banana'))
)
locator = buildLocator(RECIPES)
print(locator['banana'])
prints
[(1, 0), (3, 0), (3, 1, 1)]
|
Any examples of SQLalchemy 0.7, UPDATE using from_statement()
Question: I'm writing a quick one-off migration script that updates a single field in a
table with half a million rows.
Since I hadn't planned on writing out full models for the joins I'm doing to
fetch the initial ~25000 rows of data, I've been trying to figure out how to
do an UPDATE statement using a from_statement() call and using my own raw sql,
but I can't find any examples.
Along with that, SQLalchemy is throwing an error. Here's an example of my call
and error:
mydb = self.session()
mydb.query().from_statement(
"""
UPDATE my_table
SET settings=mysettings
WHERE user_id=myuserid AND setting_id=123
""").params(mysettings=new_settings, myuserid=user_id).all()
The error I get:
Traceback (most recent call last):
File "./sample_script.py", line 111, in <module>
main()
File "./sample_script.py", line 108, in main
migrate.set_migration_data()
File "./sample_script.py", line 100, in set_migration_data
""").params(mysettings=new_settings, myuserid=user_id).all()
File "/usr/lib/pymodules/python2.6/sqlalchemy/orm/query.py", line 1267, in all
return list(self)
File "/usr/lib/pymodules/python2.6/sqlalchemy/orm/query.py", line 1361, in __iter__
return self._execute_and_instances(context)
File "/usr/lib/pymodules/python2.6/sqlalchemy/orm/query.py", line 1364, in _execute_and_instances
result = self.session.execute(querycontext.statement, params=self._params, mapper=self._mapper_zero_or_none())
File "/usr/lib/pymodules/python2.6/sqlalchemy/orm/query.py", line 251, in _mapper_zero_or_none
if not getattr(self._entities[0], 'primary_entity', False):
IndexError: list index out of range
**UPDATE**
I'm using MySQL.
Per Samy's suggestion, I tried this:
mydb.execute(
"UPDATE mytable SET settings=:mysettings WHERE user_id=:userid AND setting_id=123",
{'userid': user_id, 'mysettings': new_settings}
)
This had no effect. I don't get any errors, but the statement doesn't seem to
actually execute, as the row does not change. If I manually cut and paste the
query that gets logged from the echo=True option, the row updates in the
database just fine.
**UPDATE - SOLVED**
Samy's suggestion was correct but the .execute() call only works on 'engine',
not 'session', so this worked just fine:
self.engine.execute(
"UPDATE mytable SET settings=:mysettings WHERE user_id=:userid AND setting_id=123",
{'userid': user_id, 'mysettings': new_settings}
)
Answer: Well this is rather strange, according to the docs, the
[from_statement](http://docs.sqlalchemy.org/en/rel_0_7/orm/query.html?highlight=from_statement#sqlalchemy.orm.query.Query.from_statement)
is used for `SELECT` statements.
> Execute the given SELECT statement and return results.
I could be looking at the wrong function, or it may be possible to use other
type of statements, Im not really sure.
You could just use `execute` since it can do any type of statement, heres a
quick example.
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
session = sessionmaker(bind = create_engine('sqlite://'), autocommit = True)()
_ = session.execute('CREATE TABLE my_table (user_id int, setting_id int, settings string)')
for id in xrange(200):
_ = session.execute('INSERT INTO my_table (user_id, setting_id) VALUES (:user_id, :setting_id)',
{'user_id':id, 'setting_id':id})
_ = session.execute(
"""
UPDATE my_table
SET settings = :mysettings
WHERE user_id = :user_id AND setting_id = 123
""", {'user_id':123, 'mysettings':'test'})
r = session.execute('SELECT * FROM my_table WHERE user_id = :user_id', {'user_id':123}).fetchall()
print r
[(123, 123, u'test')]
note that this isn't really the best way to use `sqlalchemy`, which was
designed to create a dry environment, decoupled from a specific db backend,
though you probably have your reasons for using raw sql versus its ORM.
|
SciPy and scikit-learn - ValueError: Dimension mismatch
Question: I use [SciPy](http://scipy.org/) and [scikit-learn](http://scikit-
learn.org/stable/) to train and apply a Multinomial Naive Bayes Classifier for
binary text classification. Precisely, I use the module
[`sklearn.feature_extraction.text.CountVectorizer`](http://scikit-
learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html#sklearn.feature_extraction.text.CountVectorizer)
for creating sparse matrices that hold word feature counts from text and the
module [`sklearn.naive_bayes.MultinomialNB`](http://scikit-
learn.org/stable/modules/generated/sklearn.naive_bayes.MultinomialNB.html#sklearn.naive_bayes.MultinomialNB)
as the classifier implementation for training the classifier on training data
and applying it on test data.
The input to the `CountVectorizer` is a list of text documents represented as
unicode strings. The training data is much larger than the test data. My code
looks like this (simplified):
vectorizer = CountVectorizer(**kwargs)
# sparse matrix with training data
X_train = vectorizer.fit_transform(list_of_documents_for_training)
# vector holding target values (=classes, either -1 or 1) for training documents
# this vector has the same number of elements as the list of documents
y_train = numpy.array([1, 1, 1, -1, -1, 1, -1, -1, 1, 1, -1, -1, -1, ...])
# sparse matrix with test data
X_test = vectorizer.fit_transform(list_of_documents_for_testing)
# Training stage of NB classifier
classifier = MultinomialNB()
classifier.fit(X=X_train, y=y_train)
# Prediction of log probabilities on test data
X_log_proba = classifier.predict_log_proba(X_test)
**Problem:** As soon as [`MultinomialNB.predict_log_proba()`](http://scikit-
learn.org/stable/modules/generated/sklearn.naive_bayes.MultinomialNB.html#sklearn.naive_bayes.MultinomialNB.predict_log_proba)
is called, I get `ValueError: dimension mismatch`. According to the IPython
stacktrace below, the error occurs in SciPy:
/path/to/my/code.pyc
--> 177 X_log_proba = classifier.predict_log_proba(X_test)
/.../sklearn/naive_bayes.pyc in predict_log_proba(self, X)
76 in the model, where classes are ordered arithmetically.
77 """
--> 78 jll = self._joint_log_likelihood(X)
79 # normalize by P(x) = P(f_1, ..., f_n)
80 log_prob_x = logsumexp(jll, axis=1)
/.../sklearn/naive_bayes.pyc in _joint_log_likelihood(self, X)
345 """Calculate the posterior log probability of the samples X"""
346 X = atleast2d_or_csr(X)
--> 347 return (safe_sparse_dot(X, self.feature_log_prob_.T)
348 + self.class_log_prior_)
349
/.../sklearn/utils/extmath.pyc in safe_sparse_dot(a, b, dense_output)
71 from scipy import sparse
72 if sparse.issparse(a) or sparse.issparse(b):
--> 73 ret = a * b
74 if dense_output and hasattr(ret, "toarray"):
75 ret = ret.toarray()
/.../scipy/sparse/base.pyc in __mul__(self, other)
276
277 if other.shape[0] != self.shape[1]:
--> 278 raise ValueError('dimension mismatch')
279
280 result = self._mul_multivector(np.asarray(other))
I have no idea why this error occurs. Can anybody please explain it to me and
provide a solution for this problem? Thanks a lot in advance!
Answer: Sounds to me, like you just need to use `vectorizer.transform` for the test
dataset, since the training dataset fixes the vocabulary (you cannot know the
full vocabulary including the training set afterall). Just to be clear, thats
`vectorizer.transform` instead of `vectorizer.fit_transform`.
|
Incorporating striplist() into python3 code?
Question: I have a csv reader that pulls data values into a list, once this data has
been put into a list I would like to strip the whitespace in the list. I have
looked online and seen people using `striplist()`
e.g
def striplist(l):
return([x.strip() for x in l])
However, being a novice and attempting to incorporate the code, I'm not having
much luck, guidance on the issue or some understanding about what I'm doing
wrong would be greatly appreciated. My code is below:
import csv
import time
csvfile = open("example.csv")
filetype = csv.Sniffer().has_header(csvfile.read(1024))
csvfile.seek(0)
reader = csv.reader(csvfile,filetype)
csvreaderlist = []
csvfilecounter = 0
if filetype:
next(reader)
print("CSV file located, headers present, importing data")
time.sleep(3)
for data in reader:
csvreaderlist.append(data)
print(data)
csvfilecounter = csvfilecounter +1
summarycounter = summarycounter +1
else:
print("CSV file located, no headers found, importing data")
time.sleep(3)
for data in reader:
csvreaderlist.append(data)
csvfilecounter = csvfilecounter +1
summarycounter = summarycounter +1
print(data)
if csvfilecounter == csvfilecounter:
print(len(csvreaderlist),'Lines were successfully imported from the CSV file')
time.sleep(3)
def striplist(csvreaderlist):
return([data.strip() for data in csvreaderlist])
Answer: an example of your function:
def strip_list(the_list):
return [line.strip() for line in the_list]
lines = ['foo\n', 'bar\r\n', 'baz']
stripped_list = strip_list(lines)
print(stripped_list)
would output:
['foo', 'bar', 'baz']
* * *
and here as an ugly memory inefficient one-liner, just to show using
`splitlines()` :)
return ''.join(csvreaderlist).splitlines()
|
Python find ALL combinations of a list
Question: > **Possible Duplicate:**
> [Power set and Cartesian Product of a set
> python](http://stackoverflow.com/questions/10342939/power-set-and-cartesian-
> product-of-a-set-python)
scratch the old problem. I figured everything out. Now I have an even crazier
issue. Here is what I should be getting:
Input: scoreList(["a", "s", "m", "t", "p"])
output: [['a', 1], ['am', 4], ['at', 2], ['spam', 8]]
This I/O works GREAT, but if I add a 6th element like this:
Input: scoreList(["a", "s", "m", "t", "p", "e"])
The program bugs out like crazy. Please tell me how to fix this. Appreciate
any help
My code:
from itertools import chain, combinations
def ind(e,L):
if L==[] or L=="":
return 0
elif L[0]==e:
return 0
else:
return ind(e,L[1:])+1
def letterScore(letter, scorelist):
if scorelist[0][0] == letter:
return scorelist[0][1]
elif (len(scorelist) == 1) and (scorelist[0][0] != letter):
return 'lol. stop trying to crash my program'
else:
return letterScore(letter, scorelist[1:])
scorelist = [ ["a", 1], ["b", 3], ["c", 3], ["d", 2], ["e", 1], ["f", 4], ["g", 2], ["h", 4], ["i", 1], ["j", 8], ["k", 5], ["l", 1], ["m", 3], ["n", 1], ["o", 1], ["p", 3], ["q", 10], ["r", 1], ["s", 1], ["t", 1], ["u", 1], ["v", 4], ["w", 4], ["x", 8], ["y", 4], ["z", 10] ]
def wordScore(S, scorelist):
if (len(S) == 1):
return letterScore(S[0],scorelist)
elif (letterScore(S[0],scorelist) == 'lol. stop trying to crash my program'):
return 'you really want to crash me, dont you'
else:
return letterScore(S[0],scorelist) + wordScore(S[1:], scorelist)
def perm(l):
sz = len(l)
if sz <= 1:
return [l]
return [p[:i]+[l[0]]+p[i:]
for i in xrange(sz) for p in perm(l[1:])]
from itertools import combinations, permutations
def findall(my_input):
return [''.join(p) for x in range(len(my_input)) for c in combinations(my_input, x+1)
for p in permutations(c)]
d = ["a", "am", "cab", "apple", "at", "bat", "bar", "babble", "can", "foo", "spam", "spammy", "zzyzva"]
def match(lis):
return match2(findall(lis))
def match2(lis):
if lis == []:
return []
elif(len(d) != ind(lis[0],d)):
return [lis[0]] + match2(lis[1:])
else:
return match2(lis[1:])
def scoreList(lis):
return match3(match(lis))
def match3(lis):
if (lis == []):
return []
else:
return [[lis[0],wordScore(lis[0],scorelist)]] + match3(lis[1:])
Answer: Is this homework, or can you use itertools?
>>> my_input = ['a','b','c']
>>> from itertools import combinations, permutations
>>> [''.join(p) for x in range(len(my_input)) for c in combinations(my_input, x+1)
for p in permutations(c)]
['a', 'b', 'c', 'ab', 'ba', 'ac', 'ca', 'bc', 'cb', 'abc', 'acb', 'bac', 'bca', 'cab', 'cba']
|
Boto and Python on AWS
Question: I am trying to get boto to work, but I am getting an error.
Installed boto via `easy_install`, or simply `python ./setup.py install`
cat boto.py
#!/usr/bin/python
import boto
conn = boto.connect_ec2()
3c075474c10b% ./boto.py
Traceback (most recent call last):
File "./boto.py", line 2, in <module>
import boto
File "/Users/vasiliyb/scripts/boto.py", line 3, in <module>
conn = boto.connect_ec2()
AttributeError: 'module' object has no attribute 'connect_ec2'
Answer: Just change the name of your module from "boto.py" to "myboto.py" (or whatever
you like) and it will magically work.
You are basically redefining "boto" by naming your module boto.py.
|
Python: How can I make the ANSI escape codes to work also in Windows?
Question: If I run this in python under linux it works:
start = "\033[1;31m"
end = "\033[0;0m"
print "File is: " + start + "<placeholder>" + end
But if I run it in Windows it doesn't work, how can I make the ANSI escape
codes work also on Windows?
Answer: You could check [Python module to enable ANSI for stdout on
Windows?](http://stackoverflow.com/questions/8358533/python-module-to-enable-
ansi-for-stdout-on-windows) to see if it's useful.
The [colorama](http://pypi.python.org/pypi/colorama) module seems to be cross-
platform.
You install colorama:
pip install colorama
Then:
import colorama
colorama.init()
start = "\033[1;31m"
end = "\033[0;0m"
print "File is: " + start + "<placeholder>" + end
|
Debug python and Java at the same time
Question: I am using Python to invoke many of my Java programs. Is it possible to use
debug perspective for both Python and Java and trace the progress in both
languages at the same time? Thanks
Answer: I downloaded two different Eclipse, one for JavaSE and when for PyDev. A
Python script starts a JVM in remote debugging mode, then the other Eclipse
instance connects via remote debugging to this JVM. This way you are able to
debug both Python and Java code, even if in two different IDEs (I don't know
if this can be done in the same instance, ie if two debugging session can
exist in the same Eclipse instance, however I don't care because I use
different Eclipse instances for Python, Java, Scala, Android...)
Create the following Java program and export a runnable JAR, for example at
the location `/home/raffaele/hello.jar`, and set a breakpoint at the line with
`System.out.println()`
public class HelloWorld {
public static void main(String[] args) {
for (int i = 0; i < 10; i++)
System.out.println(i);
}
}
Create a Python script, add a breakpoint at line `print i` and hit _Debug as
Python script_. The subprocess output should be redirected to the Eclipse
console and you should see the message **Listening for transport dt_socket at
address: 8000**
import subprocess
subprocess.call(["java", "-jar", "-Xdebug",
"-Xrunjdwp:transport=dt_socket,address=8000,server=y",
"/home/raffaele/hello.jar"])
for i in range(1, 10):
print i
At this point, in the JavaSE Eclipse instance, create a Remote Debug
configuration: _Run_ > _Debug Configuration_ , in the left column select
_Remote Java Application_ and in the right one choose a name, host
`localhost`, transport `socket` port `8000`. Hit _Apply_ , then _Debug_. The
Debug perspective in the JavaSE instance will be opened, and you'll see your
code suspended at `System.out.println`. In the right pane, you can inspect
local variable, for example `i = 0`. Hit _Resume_ for 10 times and the PyDev
instance will blink, because the Python breakpoint has been hit.
|
How to get the type of change in P4Python
Question: I'm trying to work with P4Python, and hoping to find a way to be able to check
what's the type of change of each file in the changelist. I mean, I'd like to
know if it's a modification, or whether this file has **Marked for Add** or
**Marked for Delete**.
My code is something like
p4.connect()
clientSpec = p4.fetch_client()
depotList = p4.run_opened("-c", changelistNumber)
p4.disconnect()
So, I have the list of files in the changelist, and now I can iterate over
them, and I wish to remove the ones which are **Marked for delete** for
example.
Your help is very appreciated!
Answer: The result of `p4.run_opened` is an array that has a map for each opened file.
This map has the following keys:
'haveRev'
'rev'
'clientFile'
'client'
'user'
'action'
'type'
'depotFile'
'change'
In order to find out the type of change, iterate over the array and ask each
item for the 'action'. In one of my current changelists, the first file is
opened for 'edit':
import P4
p4 = P4.P4()
p4.connect()
p4.run_opened()[0]['action']
p4.disconnect()
will return: 'edit'
|
Pygment lexer multiple tokens
Question: I'm using the lexer of Pygments, a Python plugin. I want to get tokens for a
C++ code, in particular when a new variable is declared, e.g.
int a=3,b=5,c=4;
Here a,b,c should be given the type "Declared variables", which is different
from
a=3,b=5,c=4;
Here a,b,c should simply be given type "Variables", since they have been
declared before.
I'd like to use the ability of the lexer to scan multiple tokens at once ([See
Pygments documentation](http://pygments.org/docs/lexerdevelopment/#scanning-
multiple-tokens-at-once)) I want to write a regex along the lines of
(int)(\s)(?:([a-z]+)(=)([0-9]+)(,))*, bygroups(Type,Space,Name,Equal,Number,Comma)
(The "?:" is just to tell Pygments that this grouping shouldn't be used in the
bygroups.)
However, instead of matching any number of declarations in the line, it only
returns tokens for the last declaration in the line (In the case, the "c=4"
portion.) How can I make it return the tokens for all declarations in the
line?
Answer: What you need is a stateful lexer. The reason why your regexp won't work is
because the groups aren't continuous.
int a=3,b=5,c=4;
Here you want the chars 0..2 to be Type, 3..3 Space, 4..7 Name, Equal Number
and Comma then again Name, Equal, Number and Comma. That's no good.
The solution is to remember when a type declaration has been seen, enter a new
lexer mode which continues until the next semicolon. See [Changing
states](http://pygments.org/docs/lexerdevelopment/#changing-states) in the
pygments documentation.
Below is a solution that uses CFamilyLexer and adds three new lexer states. So
when it sees a line like this while in the `function` state:
int m = 3 * a + b, x = /* comments ; everywhere */ a * a;
First it consumes:
int
It matches the new rule I added, so it enters the `vardecl` state:
m
Oh a name of a variable! Since the lexer is in the `vardecl` state, this is a
newly defined variable. Emit it as a `NameDecl` token. Then enter the
`varvalue` state.
3
Just a number.
*
Just an operator.
a
Oh a name of a variable! But now we are in the `varvalue` state so it is _not_
a variable declaration, just a regular variable reference.
+ b
An operator and another variable reference.
,
Value of variable `m` fully declared. Go back to the `vardecl` state.
x =
New variable declaration.
/* comments ; everywhere */
Another state gets pushed on the stack. In comments tokens that would
otherwise have significance such as `;` are ignored.
a * a
Value of `x` variable.
;
Return to the `function` state. The special variable declaration rules are
done.
from pygments import highlight
from pygments.formatters import HtmlFormatter, TerminalFormatter
from pygments.formatters.terminal import TERMINAL_COLORS
from pygments.lexer import inherit
from pygments.lexers.compiled import CFamilyLexer
from pygments.token import *
# New token type for variable declarations. Red makes them stand out
# on the console.
NameDecl = Token.NameDecl
STANDARD_TYPES[NameDecl] = 'ndec'
TERMINAL_COLORS[NameDecl] = ('red', 'red')
class CDeclLexer(CFamilyLexer):
tokens = {
# Only touch variables declared inside functions.
'function': [
# The obvious fault that is hard to get around is that
# user-defined types won't be cathed by this regexp.
(r'(?<=\s)(bool|int|long|float|short|double|char|unsigned|signed|void|'
r'[a-z_][a-z0-9_]*_t)\b',
Keyword.Type, 'vardecl'),
inherit
],
'vardecl' : [
(r'\s+', Text),
# Comments
(r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline),
(r';', Punctuation, '#pop'),
(r'[~!%^&*+=|?:<>/-]', Operator),
# After the name of the variable has been tokenized enter
# a new mode for the value.
(r'[a-zA-Z_][a-zA-Z0-9_]*', NameDecl, 'varvalue'),
],
'varvalue' : [
(r'\s+', Text),
(r',', Punctuation, '#pop'),
(r';', Punctuation, '#pop:2'),
# Comments
(r'/(\\\n)?[*](.|\n)*?[*](\\\n)?/', Comment.Multiline),
(r'[~!%^&*+=|?:<>/-\[\]]', Operator),
(r'\d+[LlUu]*', Number.Integer),
# Rules for strings and chars.
(r'L?"', String, 'string'),
(r"L?'(\\.|\\[0-7]{1,3}|\\x[a-fA-F0-9]{1,2}|[^\\\'\n])'", String.Char),
(r'[a-zA-Z_][a-zA-Z0-9_]*', Name),
# Getting arrays right is tricky.
(r'{', Punctuation, 'arrvalue'),
],
'arrvalue' : [
(r'\s+', Text),
(r'\d+[LlUu]*', Number.Integer),
(r'}', Punctuation, '#pop'),
(r'[~!%^&*+=|?:<>/-\[\]]', Operator),
(r',', Punctuation),
(r'[a-zA-Z_][a-zA-Z0-9_]*', Name),
(r'{', Punctuation, '#push'),
]
}
code = '''
#include <stdio.h>
void main(int argc, char *argv[])
{
int vec_a, vec_b;
int a = 3, /* Mo;yo */ b=5, c=7;
int m = 3 * a + b, x = /* comments everywhere */ a * a;
char *myst = "hi;there";
char semi = ';';
time_t now = /* Null; */ NULL;
int arr[10] = {1, 2, 9 / c};
int foo[][2] = {{1, 2}};
a = b * 9;
c = 77;
d = (int) 99;
}
'''
for formatter in [TerminalFormatter, HtmlFormatter]:
print highlight(code, CDeclLexer(), formatter())
|
How do I find the salesforce package prefix using the sforce or suds python libraries?
Question: I need to update some custom fields of `salesforce` objects. For that I am
trying to use the `upsert` method. I am little confused on choosing the
module; `SforceEnterpriseClient` or `SforcePartnerClient` of `sforce`. I think
I am gonna need the name of the `package prefix` first to `upsert`. I need to
do these things using `sforce` or `suds`. A little explanation on the `sforce`
and `suds` tricks will be helpful.
Answer: Did you try [beatbox](http://code.google.com/p/salesforce-beatbox/) library ?
It is simpler than salesforce-python-toolkit
[This is a full sample](http://code.google.com/p/salesforce-
beatbox/source/browse/trunk/examples/demo.py) of how to upsert a custom field:
import sys
import beatbox
import xmltramp
import datetime
sf = beatbox._tPartnerNS
svc = beatbox.Client()
class BeatBoxDemo:
def login(self, username, password):
self.password = password
loginResult = svc.login(username, password)
print "sid = " + str(loginResult[sf.sessionId])
print "welcome " + str(loginResult[sf.userInfo][sf.userFullName])
def upsert(self):
print "\nupsert"
t = { 'type': 'Task',
'ChandlerId__c': '12345',
'subject': 'BeatBoxTest updated',
'ActivityDate' : datetime.date(2006,2,20) }
ur = svc.upsert('ChandlerId__c', t)
print str(ur[sf.success]) + " -> " + str(ur[sf.id])
t = { 'type': 'Event',
'ChandlerId__c': '67890',
'durationinminutes': 45,
'subject': 'BeatBoxTest',
'ActivityDateTime' : datetime.datetime(2006,2,20,13,30,30),
'IsPrivate': False }
ur = svc.upsert('ChandlerId__c', t)
if str(ur[sf.success]) == 'true':
print "id " + str(ur[sf.id])
else:
print "error " + str(ur[sf.errors][sf.statusCode]) + ":" + str(ur[sf.errors][sf.message])
if __name__ == "__main__":
if len(sys.argv) != 3:
print "usage is demo.py <username> <password>"
else:
demo = BeatBoxDemo()
demo.login(sys.argv[1], sys.argv[2])
demo.upsert()
|
SQLAlchemy MetaData.reflect not finding tables in Oracle db
Question: I'm attempting to reverse engineer an existing Oracle schema into some
declarative SQLAlchemy models. My problem is that when I use
[`MetaData.reflect`](http://docs.sqlalchemy.org/en/rel_0_7/core/schema.html?highlight=metadata.reflect#sqlalchemy.schema.MetaData.reflect),
it doesn't find the tables in my schema, just a Global Temp Table. However, I
can still query against the other tables.
I'm using SQLAlchemy 0.7.8, CentOS 6.2 x86_64, python 2.6, cx_Oracle 5.1.2 and
Oracle 11.2.0.2 Express Edition. Here's a quick sample of what I'm talking
about:
>>> import sqlalchemy
>>> engine = sqlalchemy.create_engine('oracle+cx_oracle://user:pass@localhost/xe')
>>> md = sqlalchemy.MetaData(bind=engine)
>>> md.reflect()
>>> md.tables
immutabledict({u'my_gtt': Table(u'my_gtt', MetaData(bind=Engine(oracle+cx_oracle://user:pass@localhost/xe)), Column(u'id', NUMBER(precision=15, scale=0, asdecimal=False), table=<my_gtt>), Column(u'parent_id', NUMBER(precision=15, scale=0, asdecimal=False), table=<my_gtt>), Column(u'query_id', NUMBER(precision=15, scale=0, asdecimal=False), table=<my_gtt>), schema=None)})
>>> len(engine.execute('select * from my_regular_table').fetchall())
4
Answer: Thanks to some quick help from @zzzeek I discovered (by using the
`echo='debug'` argument to `create_engine`) that my problem was caused by the
tables being owned by an old user, even though the current user could access
them from the default schema without requiring any explicit synonyms.
|
Python app which reads and writes into its current working directory as a .app/exe
Question: I have a python script which reads a text file in it's current working
directory called "data.txt" then converts the data inside of it into a json
format for another separate program to handle.
The problem i'm having is that i'm not sure how to read the .txt file (and
write a new one) which is in the same directory as the .app when the python
script is all bundled up. The current method i'm using doesn't work because of
something to do with it using the fact that it's ran from the terminal instead
of executed as a .app?
Any help is appreciated!
Answer: A .app on the Mac doesn't have any reasonable current working directory when
launched.
Of course it has _some_ working directory, and you can easily find out what it
is at runtime by `os.getcwd()`, and you can test on a variety of different
ways of launching on different versions of OS X to figure out all of the
patterns, but what good does that do you?
The good news is, you apparently don't actually want the current working
directory; you need the directory of the .app bundle or .exe.
In other words, if someone does this:
C:\Users\foo> C:\Stuff\MyProgram.exe
You want `C:\Stuff` (the executable's directory), not `C:\Users\foo` (the
working directory).
On Windows, this is easy. An .exe is just a file, and its path will be the
`__path__` you get in Python, so:
import os
pathToApp = os.path.dirname(__path__)
On Mac, it's harder. A .app is a bundle—a directory containing other files and
directories. Somewhere in there is an executable interpreter and a copy of
your script, and `__path__` is going to give you the latter, not the path to
the .app.
The correct way to get that is to use Cocoa (or CoreFoundation):
import Cocoa
pathToApp = Cocoa.NSBundle.mainBundle().bundlePath()
If you don't want to do that, you pretty much have to rely on some information
that the documentation says you can't rely on and could change some day. But
the following code should be safe:
import os
pathToApp = __file__
while not pathToApp.endswith('.app'):
path = os.path.dirname(path)
In order for this to stop working, either the script would have to be outside
the .app bundle, or inside another .app inside the one you're looking for, or
bundles would have to stop being named .app, or they'd have to stop being
structured as normal directories; none of this seems likely to change in OS X
10.*, or even OS Y 11.
As a side issue: what you're trying to do is most likely a bad idea in the
first place. A Mac application shouldn't be working with files alongside it.
Conversely, if users are going to expect to work on files alongside it, you
probably want a simple Unix executable (or just a plain Python script with
chmod +x), not an application.
|
python master/child looping unintentionally
Question: Problem: I expect child to time out and be done. but instead it times out and
begins to run again.
Can anyone tell me why this program runs forever? I expect it to run one time
and exit...
Here is a working program. Master threads a function to spawn a child. Works
great except it ends up looping.
Here is the master:
# master.py
import multiprocessing, subprocess, sys, time
def f():
p = subprocess.Popen(["C:\\Python32\\python.exe", "child.py"])
# wait until child ends and check exit code
while p.poll() == None:
time.sleep(2)
if p.poll() != 0:
print("something went wrong with child.py")
# multithread a function process to launch and monitor a child
p1 = multiprocessing.Process(target = f())
p1.start()
and the child:
# child.py
import socket, sys
def main(args):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.settimeout(10)
sock.bind(('', 54324))
data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
print(data)
sock.close()
return 0
except KeyboardInterrupt as e:
try:
sock.close()
return 0
except:
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
Answer: The problem is that your `master.py` doesn't have an `if __name__ ==
'__main__'` guard. On Windows, `multiprocessing` has to be able to reimport
the `main` module in the child process, and if you don't use this `if` guard,
you will re-execute the `multiprocessing.Process` in the child (resulting in
an accidental forkbomb).
To fix, simply put all of the commands in `master.py` in the `if` guard:
if __name__ == '__main__':
# multithread a function process to launch and monitor a child
p1 = multiprocessing.Process(target = f())
p1.start()
|
Finding out which module is setting the root logger
Question: How would I be able to find which module is overriding the Python root logger?
My Django project imports from quite a few external packages, and I have tried
searching for all instances of logging.basicConfig and logging.root setups,
however most of them are in tests and should not be overriding it unless
specifically called.
Django's logging config does not specify a root logger.
Answer: Well the solution was to do some monkey patching of the Python logging module.
I just wrapped a decorator around the logging.root.addHandler function that
printed the stack and voila, I found my culprit who was calling
logging.getLogger(). If you call getLogger without any parameters, you get the
root logger.
import logging
import sys
import traceback
def tracer(func):
def new_func(*args, **kwargs):
try:
traceback.print_stack(sys.stderr)
except:
traceback.print_exc(sys.stderr)
return func(*args, **kwargs)
return new_func
old_addHandler = logging.root.addHandler
logging.root.addHandler = tracer(old_addHandler)
# run your code
|
pysnmp 4.2.3: pysnmp.smi.error.SmiError: importSymbols: empty MIB module name
Question: I have two scenarios, both reference [`SNMP.py` in this
answer](http://stackoverflow.com/a/7791143/667301):
**pysnmp (v4.2.3) and pysnmp-mibs (v0.1.4)** :
>>> # pysnmp-mibs 0.1.4 and pysnmp 4.2.3
>>> from SNMP import v2c
>>> snmp = v2c('172.16.1.1', 'public')
>>> snmp.walk('ifName')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "SNMP.py", line 115, in walk
(('', oid),),
File "/usr/local/lib/python2.6/dist-packages/pysnmp-4.2.3-py2.6.egg/pysnmp/entity/rfc3413/oneliner/cmdgen.py", line 449, in nextCmd
File "/usr/local/lib/python2.6/dist-packages/pysnmp-4.2.3-py2.6.egg/pysnmp/entity/rfc3413/oneliner/cmdgen.py", line 150, in makeReadVarBinds
File "/usr/local/lib/python2.6/dist-packages/pysnmp-4.2.3-py2.6.egg/pysnmp/entity/rfc3413/oneliner/mibvar.py", line 161, in resolveWithMib
File "/usr/local/lib/python2.6/dist-packages/pysnmp-4.2.3-py2.6.egg/pysnmp/smi/builder.py", line 295, in importSymbols
pysnmp.smi.error.SmiError: importSymbols: empty MIB module name
>>>
**pysnmp (v4.2.2) and pysnmp-mibs (v0.1.3)** :
>>> # After removing pysnmp / pysnmp-mibs / pyasn.1 and installing with:
>>> # easy_install pysnmp==4.2.2 pysnmp-mibs==0.1.3
>>> snmp = v2c('172.16.1.1', 'public')
>>> snmp.walk('ifName')
[SNMPObject(modName='IF-MIB', symName='ifName', index=1, value='Null0'), SNMPObject(modName='IF-MIB', symName='ifName', index=2, value='Internal-Data0/0'), SNMPObject(modName='IF-MIB', symName='ifName', index=3, value='Ethernet0/0'), SNMPObject(modName='IF-MIB', symName='ifName', index=4, value='Ethernet0/1'), SNMPObject(modName='IF-MIB', symName='ifName', index=5, value='Ethernet0/2'), SNMPObject(modName='IF-MIB', symName='ifName', index=11, value='Internal-Data0/1'), SNMPObject(modName='IF-MIB', symName='ifName', index=12, value='_internal_loopback'), SNMPObject(modName='IF-MIB', symName='ifName', index=13, value='Virtual254'), SNMPObject(modName='IF-MIB', symName='ifName', index=14, value='Vlan1'), SNMPObject(modName='IF-MIB', symName='ifName', index=15, value='OUTSIDE'), SNMPObject(modName='IF-MIB', symName='ifName', index=16, value='INSIDE')]
>>>
**Question**
What is wrong when I use pysnmp v4.2.3? Is the issue in `SNMP.py` or somewhere
in the pysnmp libraries?
**Update 1**
When I use `cmdgen.MibVariable(oid).loadMibs(),` as suggested by Ilya, I still
get errors...
pysnmp.smi.error.NoSuchObjectError: NoSuchObjectError({'str': "Can't resolve node name ::('ifName',) at <pysnmp.smi.view.MibViewController instance at 0x2af9e60>"})
How can I resolve this error? I am using the following `SNMP.py` code:
* * *
from collections import namedtuple as NT
from datetime import datetime
import string
import re
from pysnmp.entity.rfc3413.oneliner import cmdgen
from pysnmp.smi import builder, view, error
from numpy import int64, float64
# NOTE!!!
# It is best to install the pysnmp-mibs package from pypi... this makes
# a lot of symbolic MIB names "just work"
# See this link below for many oneliner examples...
# http://pysnmp.sourceforge.net/examples/4.x/v3arch/oneliner/index.html
class v2c(object):
"""Build an SNMPv2c manager object"""
def __init__(self, ipaddr=None, device=None, community='Public',
retries=3, timeout=9):
self.device = device
self.ipaddr = ipaddr
self.community = community
self.SNMPObject = NT('SNMPObject', ['modName', 'datetime', 'symName',
'index', 'value'])
self.SNMPIndexed = NT('SNMPIndexed', ['modName', 'datetime', 'symName',
'index', 'value'])
self.query_timeout = float(timeout)/int(retries)
self.query_retries = int(retries)
self._index = None
self.cmdGen = cmdgen.CommandGenerator()
def index(self, oid=None):
"""Build an SNMP Manager index to reference in get or walk operations. First v2c.index('ifName'). Then, v2c.get_index('ifHCInOctets', 'eth0') or v2c.walk_index('ifHCInOctets'). Instead of referencing a numerical index, the index will refer to the value that was indexed."""
self._index = dict()
self._intfobj = dict()
snmpidx = self.walk(oid=oid)
for ii in snmpidx:
## the dicts below are keyed by the SNMP index number
# value below is the text string of the intf name
self._index[ii.index] = ii.value
# value below is the intf object
if not (self.device is None):
self._intfobj[ii.index] = self.device.find_match_intf(ii.value,
enforce_format=False)
def walk_index(self, oid=None):
"""Example usage, first index with v2c.index('ifName'), then v2c.get_index('ifHCInOctets', 'eth0')"""
if not (self._index is None):
tmp = list()
snmpvals = self.walk(oid=oid)
for idx, ii in enumerate(snmpvals):
tmp.append([ii.modName, datetime.now(), ii.symName,
self._index[ii.index], ii.value])
return map(self.SNMPIndexed._make, tmp)
else:
raise ValueError, "Must populate with SNMP.v2c.index() first"
def walk(self, oid=None):
if isinstance(self._format(oid), tuple):
errorIndication, errorStatus, errorIndex, \
varBindTable = self.cmdGen.nextCmd(
cmdgen.CommunityData('test-agent', self.community),
cmdgen.UdpTransportTarget((self.ipaddr, 161),
retries=self.query_retries,
timeout=self.query_timeout),
self._format(oid),
)
# Parsing only for now... no return value...
self._parse(errorIndication, errorStatus, errorIndex, varBindTable)
elif isinstance(oid, str):
errorIndication, errorStatus, errorIndex, \
varBindTable = self.cmdGen.nextCmd(
# SNMP v2
cmdgen.CommunityData('test-agent', self.community),
# Transport
cmdgen.UdpTransportTarget((self.ipaddr, 161)),
cmdgen.MibVariable(oid).loadMibs(),
)
return self._parse_resolve(errorIndication, errorStatus,
errorIndex, varBindTable)
else:
raise ValueError, "Unknown oid format: %s" % oid
def get_index(self, oid=None, index=None):
"""In this case, index should be similar to the values you indexed from... i.e. if you index with ifName, get_index('ifHCInOctets', 'eth0')"""
if not (self._index is None) and isinstance(index, str):
# Map the interface name provided in index to an ifName index...
snmpvals = None
for idx, value in self._index.items():
if index == value:
# if there is an exact match between the text index and the
# snmp index value...
snmpvals = self.get(oid=oid, index=idx)
break
else:
# TRY mapping the provided text index into an interface obj
_intfobj = self.device.find_match_intf(index)
if not (_intfobj is None):
for key, val in self._intfobj.items():
if (val==_intfobj):
snmpvals = self.get(oid=oid, index=key)
break
# Ensure we only parse a valid response...
if not (snmpvals is None):
tmp = [snmpvals.modName, datetime.now(), snmpvals.symName,
self._index[snmpvals.index], snmpvals.value]
return self.SNMPIndexed._make(tmp)
elif not isinstance(index, str):
raise ValueError, "index must be a string value"
else:
raise ValueError, "Must populate with SNMP.v2c.index() first"
def get(self, oid=None, index=None):
if isinstance(self._format(oid), tuple):
errorIndication, errorStatus, errorIndex, \
varBindTable = self.cmdGen.getCmd(
cmdgen.CommunityData('test-agent', self.community),
cmdgen.UdpTransportTarget((self.ipaddr, 161),
retries=self.query_retries,
timeout=self.query_timeout),
self._format(oid),
)
# Parsing only for now... no return value...
self._parse(errorIndication, errorStatus, errorIndex, varBindTable)
elif isinstance(oid, str) and isinstance(index, int):
errorIndication, errorStatus, errorIndex, \
varBindTable = self.cmdGen.getCmd(
# SNMP v2
cmdgen.CommunityData('test-agent', self.community),
# Transport
cmdgen.UdpTransportTarget((self.ipaddr, 161)),
cmdgen.MibVariable(oid).loadMibs(),
)
return self._parse_resolve(errorIndication, errorStatus,
errorIndex, [varBindTable])[0]
else:
raise ValueError, "Unknown oid format: %s" % oid
def bulkwalk(self, oid=None):
"""SNMP bulkwalk a device. NOTE: This often is faster, but does not work as well as a simple SNMP walk"""
if isinstance(self._format(oid), tuple):
errorIndication, errorStatus, errorIndex, varBindTable = self.cmdGen.bulkCmd(
cmdgen.CommunityData('test-agent', self.community),
cmdgen.UdpTransportTarget((self.ipaddr, 161),
retries=self.query_retries,
timeout=self.query_timeout),
0,
25,
self._format(oid),
)
return self._parse(errorIndication, errorStatus,
errorIndex, varBindTable)
elif isinstance(oid, str):
errorIndication, errorStatus, errorIndex, varBindTable = self.cmdGen.bulkCmd(
cmdgen.CommunityData('test-agent', self.community),
cmdgen.UdpTransportTarget((self.ipaddr, 161),
retries=self.query_retries,
timeout=self.query_timeout),
0,
25,
cmdgen.MibVariable(oid).loadMibs(),
)
return self._parse_resolve(errorIndication, errorStatus,
errorIndex, varBindTable)
else:
raise ValueError, "Unknown oid format: %s" % oid
def _parse_resolve(self, errorIndication=None, errorStatus=None,
errorIndex=None, varBindTable=None):
"""Parse MIB walks and resolve into MIB names"""
retval = list()
if errorIndication:
print errorIndication
else:
if errorStatus:
print '%s at %s\n' % (
errorStatus.prettyPrint(),
varBindTable[-1][int(errorIndex)-1]
)
else:
for varBindTableRow in varBindTable:
for oid, val in varBindTableRow:
(symName, modName), indices = cmdgen.mibvar.oidToMibName(
self.cmdGen.mibViewController, oid
)
val = cmdgen.mibvar.cloneFromMibValue(
self.cmdGen.mibViewController, modName, symName,
val)
# Try to parse the index as an int first,
# then as a string
try:
index = int(string.join(map(lambda v: v.prettyPrint(), indices), '.'))
except ValueError:
index = str(string.join(map(lambda v: v.prettyPrint(), indices), '.'))
# Re-format values as float or integer, if possible...
tmp = val.prettyPrint()
if re.search(r"""^\s*\d+\s*$""", tmp):
value = int64(tmp)
elif re.search(r"""^\s*\d+\.\d+\s*$""", tmp):
value = float64(tmp)
else:
value = tmp
retval.append(self.SNMPObject._make([modName,
datetime.now(), symName, index, value]))
return retval
def _parse(self, errorIndication, errorStatus, errorIndex,
varBindTable):
if errorIndication:
print errorIndication
else:
if errorStatus:
print '%s at %s\n' % (
errorStatus.prettyPrint(),
errorIndex and varBindTable[-1][int(errorIndex)-1] or '?'
)
else:
for varBindTableRow in varBindTable:
for name, val in varBindTableRow:
print '%s = %s' % (name.prettyPrint(), val.prettyPrint())
def _format(self, oid):
"""Format a numerical OID in the form of 1.3.4.1.2.1 into a tuple"""
if isinstance(oid, str):
if re.search('(\d+\.)+\d+', oid):
tmp = list()
for ii in oid.split('.'):
tmp.append(int(ii))
return tuple(tmp)
else:
return oid
Answer: Besides other changes to MIB access interface, pysnmp developers consider an-
empty-string-as-a-wildcard-indicator to be too error prone so they replaced it
with an explicit call `MibVariable.loadModules()`.
So in case is pysnmp.version exists and indicates it's 4.2.3 or greater, in
`SNMP.py` you should replace:
...
(('', oid),),
...
with something like:
...
cmdgen.MibVariable(oid).loadMibs(),
...
It's the `loadMibs()` method which does the magic. See more on MibVariable
usage
[here](http://pysnmp.sourceforge.net/examples/current/v3arch/oneliner/manager/getgen.html)
and other details
[here](http://pysnmp.sourceforge.net/docs/current/index.html#MANAGED-OBJECT-
NAME-VALUE).
BTW, MibVariable seems to handle OID detection and conversion all by itself so
you might not need to duplicate that logic in `SNMP.py`
|
Geektools and Python
Question: I have been playing with Python and geektools and I had the script working
before I tided up the code and used loops.
Now it will not display anything past the `lalala` method.
I am working on mac 10.8.1 with geektools 3.0.2.
#!/usr/bin/python
#Simple script that downloads runescape adventures log
#and outputs it to console
# Ashley Hughes 16/SEP/2012
import sys
import urllib2 #For HTTP access
from time import localtime, strftime #Time data functions
from xml.dom.minidom import parseString #XML parser
def lalala(n):
i = 0
while(i <= n):
xmlTag = dom.getElementsByTagName('description')[i].toxml()
xmlData = xmlTag.replace('<description>','').replace('</description>','').replace('\t','').replace('\n','')
#print (str(i) + ": " + xmlData)
print(xmlData)
i = i + 1
try:
f = urllib2.urlopen("http://services.runescape.com/m=adventurers-log/rssfeed?searchName=SIG%A0ZerO")
#f = urllib.urlopen("http://www.runescape.com/")
except Exception, e:
print "Could not connect"
sys.exit(1)
s = f.read()
f.close()
dom = parseString(s)
print strftime("%a, %d %b %Y %H:%M:%S", localtime())
print "Working"
lalala(6)
print "Still working"
sys.exit(0)
Answer: You have an unicode-ascii problem when your code is 'printing' to GeekTool.
Change:
xmlTag = dom.getElementsByTagName('description')[i].toxml()
to this:
xmlTag = dom.getElementsByTagName('description')[i].toxml().encode('ascii', 'ignore')
this is fine for me in mac 10.8.1 with GeekTool 3.0.3
Look at <http://docs.python.org/howto/unicode.html>
|
Extracting an element from XML with Python3?
Question: I am trying to write a Python 3 script where I am querying a web api and
receiving an XML response. The response looks like this –
<?xml version="1.0" encoding="UTF-8"?>
<ipinfo>
<ip_address>4.2.2.2</ip_address>
<ip_type>Mapped</ip_type>
<anonymizer_status/>
<Network>
<organization>level 3 communications inc.</organization>
<OrganizationData>
<home>false</home>
<organization_type>Telecommunications</organization_type>
<naics_code>518219</naics_code>
<isic_code>J6311</isic_code>
</OrganizationData>
<carrier>level 3 communications</carrier>
<asn>3356</asn>
<connection_type>tx</connection_type>
<line_speed>high</line_speed>
<ip_routing_type>fixed</ip_routing_type>
<Domain>
<tld>net</tld>
<sld>bbnplanet</sld>
</Domain>
</Network>
<Location>
<continent>north america</continent>
<CountryData>
<country>united states</country>
<country_code>us</country_code>
<country_cf>99</country_cf>
</CountryData>
<region>southwest</region>
<StateData>
<state>california</state>
<state_code>ca</state_code>
<state_cf>88</state_cf>
</StateData>
<dma>803</dma>
<msa>31100</msa>
<CityData>
<city>san juan capistrano</city>
<postal_code>92675</postal_code>
<time_zone>-8</time_zone>
<area_code>949</area_code>
<city_cf>77</city_cf>
</CityData>
<latitude>33.499</latitude>
<longitude>-117.662</longitude>
</Location>
</ipinfo>
This is the code I have so far –
import urllib.request
import urllib.error
import sys
import xml.etree.ElementTree as etree
…
try:
xml = urllib.request.urlopen(targetURL, data=None)
except urllib.error.HTTPError as e:
print("HTTP error: " + str(e) + " URL: " + targetURL)
sys.exit()
tree = etree.parse(xml)
root = tree.getroot()
The API query works and through the debugger I can see all of the information
inside the ‘root’ variable. My issue is that I have not been able to figure
out how to extract something like the ASN (`<asn></asn>`) from the returned
XML. I’ve been beating my head against this for a day with a whole wide
variety of finds, findalls and all other sorts of methods but not been able to
crack this. I think I have reached the point where I cannot see the wood for
all the trees and every example I have found on the internet doesn’t seem to
help. Can someone show me a code snippet which can extract the contents of a
XML element from inside the tree structure?
Many thanks
Tim
Answer: I would recommend using [Beautiful
Soup](http://www.crummy.com/software/BeautifulSoup/ "Beautiful Soup").
It's a very powerful when it comes to extracting data from xml-code.
Example:
from bs4 import BeautifulSoup
soup = BeautifulSoup(targetURL)
soup.find_all('asn') #Would return all the <asn></asn> tags found!
|
Access Chrome DOM tree with python
Question: Using Chrome DevTools you can see the DOM tree of a page. Is there a way to
access and pull out that tree using python?
Answer: Have you used BeautifulSoup library? This section on the tutorial may answer
your question.
<http://www.crummy.com/software/BeautifulSoup/bs3/documentation.html#The>
Parse Tree
Then, you also need to import Requests library.
from BeautifulSoup import BeautifulSoup
import requests
url = 'http://www.crummy.com/software/BeautifulSoup/bs3/documentation.html'
page = requests.get(url)
soup = BeautifulSoup(page.content)
print soup
|
KeyError when using DictReader()
Question: I have a series of .src files that I am trying to input into a dictionary
using DictReader(). The files look like the following (just the header and the
first row):
SRC V2.0.. ........Time Id Event T Conf .Northing ..Easting ...Depth Velocity .NN_Err .EE_Err .DD_Err .NE_Err .ND_Err .ED_Err Ns Nu uSt ....uMag Nt tSt ....tMag .MomMag SeiMoment ...Energy ...Es/Ep .SourceRo AspRadius .StaticSD AppStress DyStressD MaxDispla PeakVelPa PeakAccPa PSt
07-30-2010 07:43:56.543 ND 0 e 0.00 152.54 746.45 1686.31 6000 11.76 11.76 11.76 0.00 0.00 0.00 30 0 num -9.90 30 utm -3.21 -1.12 2.06e+007 2.22e+000 20.93 6.08e+000 0.00e+000 3.83e+004 1.49e+003 0.00e+000 1.52e-005 1.50e-003 0.00e+000 1
Anyways, the following is my code:
import csv
Time = {}
Northing = {}
source_file = open(NNSRC, 'rb')
for line in csv.DictReader(source_file, delimiter = '\t'):
Time = line['........Time'].strip()
Northing = line['.Northing'].strip()
print Time, Northing
It gives me the following error:
Traceback (most recent call last):
File "C:\Python26\Lib\site-packages\xy\NNFindStages.py", line 101, in <module>
Time = line['........Time'].strip()
KeyError: '........Time'
How can I account for the strange way the header is formatted in the file
without changing the file itself?
Any help is greatly appreciated!
Answer: Your header line is not using tabs.
When I recreate your data without tabs, the line returned by the `csv` module
contains just one (_long_) key. If I recreate it with actual tabs, then I get:
>>> source_file = open('out.csv', 'rb')
>>> reader = csv.DictReader(source_file, delimiter = '\t')
>>> line = reader.next()
>>> len(line)
37
>>> line.keys()
['Id', '..Easting', '.NE_Err', 'uSt', 'SeiMoment', 'MaxDispla', 'tSt', 'Ns', 'Nt', 'Nu', '.Northing', '.DD_Err', '...Energy', '....uMag', 'V2.0..', 'DyStressD', 'SRC', 'PeakAccPa', '.SourceRo', '........Time', '.EE_Err', 'T', 'Velocity', 'PeakVelPa', 'AspRadius', '...Depth', 'PSt', '....tMag', '.MomMag', 'AppStress', '...Es/Ep', '.ED_Err', 'Event', '.ND_Err', 'Conf', '.StaticSD', '.NN_Err']
>>> line['........Time']
'ND'
>>> line['.Northing']
'746.45'
Note that the values do not need stripping; the module takes care of
extraneous whitespace for you.
You can read your header separately, clean that up, then deal with the rest of
your data with the `csv` module:
source_file = open(NNSRC, 'rb')
header = source_file.readline()
source_file.seek(len(header)) # reset read buffer
headers = [h.strip('.') for h in header.split()]
headers = ['Date'] + headers[2:] # Replace ['SRC', 'V2.0'] with a Date field instead
for line in csv.DictReader(source_file, fieldnames=headers, delimiter = '\t'):
# process line
The above code reads the header line separately, splits it and removes the
extra `.` periods for you to make for more workable column keys, then sets the
file up for the `DictReader` by resetting the readline buffer (a side-effect
of the `.seek()` call).
|
1:1 call PHP from Python
Question: We're using Splunk (A tool to analyse machine data like log files) and have an
application in PHP. For some data we need to do a call to our application in
php (CLI-based). Unfortunately Splunk only supports Python calls.
Is there an easy way to 1:1 "forward/call" php with the same arguments and
return the output, like a "passthru". I've found only parts of the solution
with the socalled subprocess module but my python experience is zero, so can't
get it to work.
For example, splunk calls:
`python external_lookup.py argument1 argument2 argument3`
\- Then the python script should call (with the CLI arguments given to
python):
`php external_lookup.php argument1 argument2 argument3`
\- Then php writes its output
\- Python captures that output and outputs it itself
Any help much appreciated, or a working example script even better.
Thanks in advance,
Vince
Answer: Using `Popen` from the subprocess module:
import sys
from subprocess import Popen
output = subprocess.Popen(['php', 'path/to/script.php'] + sys.argv[1:], stdout=subprocess.PIPE).communicate()[0]
`sys.argv[1:]` contains every command line argument except the name of python
script itself.
|
Getting 'DatabaseOperations' object has no attribute 'geo_db_type' error when doing a syncdb
Question: I'm attempting to run `heroku run python manage.py syncdb` on my GeoDjango app
on Heroku, but I get the following error:
**AttributeError: 'DatabaseOperations' object has no attribute 'geo_db_type'**
[All](http://djangosaur.tumblr.com/post/409277054/geodjango-database-engine-
for-django-1-2) [of](https://code.djangoproject.com/ticket/12727)
[my](http://develissimo.com/forum/topic/110229/?page=1#post-267473)
[research](http://opensourcegeospatial.blogspot.com/2011/06/geodjango-object-
has-no-attribute.html) has yielded the same solution: make sure to use
`django.contrib.gis.db.backends.postgis` as the database engine. Funny thing
is that _I'm already doing this_ (and I also have `django.contrib.gis` in
`INSTALLED_APPS`):
settings.py
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': '...',
'HOST': '...',
'PORT': ...,
'USER': '...',
'PASSWORD': '...'
}
}
INSTALLED_APPS = (
...,
'django.contrib.gis',
)
Is there something else I am missing? Any help is greatly appreciated, below
is the full error trace for reference:
Running `python manage.py syncdb` attached to terminal... up, run.1
Creating tables ...
Creating table auth_permission
Creating table auth_group_permissions
Creating table auth_group
Creating table auth_user_user_permissions
Creating table auth_user_groups
Creating table auth_user
Creating table django_content_type
Creating table django_session
Creating table django_site
Creating table django_admin_log
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/app/lib/python2.7/site-packages/django/core/management/__init__.py", line 443, in execute_from_command_line
utility.execute()
File "/app/lib/python2.7/site-packages/django/core/management/__init__.py", line 382, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/app/lib/python2.7/site-packages/django/core/management/base.py", line 196, in run_from_argv
self.execute(*args, **options.__dict__)
File "/app/lib/python2.7/site-packages/django/core/management/base.py", line 232, in execute
output = self.handle(*args, **options)
File "/app/lib/python2.7/site-packages/django/core/management/base.py", line 371, in handle
return self.handle_noargs(**options)
File "/app/lib/python2.7/site-packages/django/core/management/commands/syncdb.py", line 91, in handle_noargs
sql, references = connection.creation.sql_create_model(model, self.style, seen_models)
File "/app/lib/python2.7/site-packages/django/db/backends/creation.py", line 44, in sql_create_model
col_type = f.db_type(connection=self.connection)
File "/app/lib/python2.7/site-packages/django/contrib/gis/db/models/fields.py", line 200, in db_type
return connection.ops.geo_db_type(self)
AttributeError: 'DatabaseOperations' object has no attribute 'geo_db_type'
**Update** : I followed the [GeoDjango
tutorial](https://docs.djangoproject.com/en/dev/ref/contrib/gis/tutorial/) and
[Heroku/Django tutorial](https://devcenter.heroku.com/articles/django), and
built a simple app that works on my dev machine. I pushed it to Heroku using a
[custom GeoDjango buildpack](https://github.com/cirlabs/heroku-buildpack-
geodjango), and tried syncdb, but get the same error. Is this an issue with
Django/GeoDjango, Heroku, or the buildpack? My dev environment is using
PostgreSQL 9.1 and PostGIS 2.0, but Heroku uses 9.0.9 and 1.5, could that be
the issue?
Answer: The OP was using the GeoDjango buildpack, but in case anyone gets here using
[Geo buildpack](https://github.com/cyberdelia/heroku-geo-buildpack/) and
`dj_database_url` like I was, in `settings.py` don't forget the last line:
import dj_database_url
DATABASES['default'] = dj_database_url.config()
DATABASES['default']['ENGINE'] = 'django.contrib.gis.db.backends.postgis'
|
How to organize multiple python files into a single module without it behaving like a package?
Question: Is there a way to use `__init__.py` to organize multiple files into a
**module**?
Reason: Modules are easier to use than packages, because they don't have as
many layers of namespace.
Normally it makes a package, this I get. Problem is with a package, 'import
thepackage' gives me an empty namespace. Users must then either use "from
thepackage import *" (frowned upon) or know exactly what is contained and
manually pull it out into a usable namespace.
What I want to have is the user do 'import thepackage' and have nice clean
namespaces that look like this, exposing functions and classes relevant to the
project for use.
current_module
\
doit_tools/
\
- (class) _hidden_resource_pool
- (class) JobInfo
- (class) CachedLookup
- (class) ThreadedWorker
- (Fn) util_a
- (Fn) util_b
- (Fn) gather_stuff
- (Fn) analyze_stuff
The maintainer's job would be to avoid defining the same name in different
files, which should be easy when the project is small like mine is.
It would also be nice if people can do `from doit_stuff import JobInfo` and
have it retrieve the class, rather than a module containing the class.
This is easy if all my code is in one gigantic file, but I like to organize
when things start getting big. What I have on disk looks sort of like this:
place_in_my_python_path/
doit_tools/
__init__.py
JobInfo.py
- class JobInfo:
NetworkAccessors.py
- class _hidden_resource_pool:
- class CachedLookup:
- class ThreadedWorker:
utility_functions.py
- def util_a()
- def util_b()
data_functions.py
- def gather_stuff()
- def analyze_stuff()
I only separate them so my files aren't huge and unnavigable. They are all
related, though someone (possible me) may want to use the classes by
themselves without importing everything.
I've read a number of suggestions in various threads, here's what happens for
each suggestion I can find for how to do this:
If I **do not use an`__init__.py`**, I cannot import anything because Python
doesn't descend into the folder from sys.path.
If I **use a blank`__init__.py`**, when I `import doit_tools` it's an empty
namespace with nothing in it. None of my files imported, which makes it more
difficult to use.
If I **list the submodules in`__all__`**, I can use the (frowned upon?) `from
thing import *` syntax, but all of my classes are behind unnecessary namespace
barriers again. The user has to (1) know they should use `from x import *`
instead of `import x`, (2) manually reshuffle classes until they can
reasonably obey line width style constraints.
If I **add`from thatfile import X` statements to `__init__.py`**, I get closer
but I have namespace conflicts (?) and extra namespaces for things I didn't
want to be in there. In the below example, you'll see that:
1. The class JobInfo overwrote the module object named JobInfo because their names were the same. Somehow Python can figure this out, because JobInfo is of type `<class 'doit_tools.JobInfo.JobInfo'>`. (doit_tools.JobInfo is a class, but doit_tools.JobInfo.JobInfo is that same class... this is tangled and seems very bad, but doesn't seem to break anything.)
2. Each filename made its way into the doit_tools namespace, which makes it more confusing to look through if anyone is looking at the contents of the module. I want doit_tools.utility_functions.py to hold some code, not define a new namespace.
.
current_module
\
doit_tools/
\
- (module) JobInfo
\
- (class) JobInfo
- (class) JobInfo
- (module) NetworkAccessors
\
- (class) CachedLookup
- (class) ThreadedWorker
- (class) CachedLookup
- (class) ThreadedWorker
- (module) utility_functions
\
- (Fn) util_a
- (Fn) util_b
- (Fn) util_a
- (Fn) util_b
- (module) data_functions
\
- (Fn) gather_stuff
- (Fn) analyze_stuff
- (Fn) gather_stuff
- (Fn) analyze_stuff
Also someone importing just the data abstraction class would get something
different than they expect when they do 'from doit_tools import JobInfo':
current_namespace
\
JobInfo (module)
\
-JobInfo (class)
instead of:
current_namespace
\
- JobInfo (class)
So, is this just a wrong way to organize Python code? If not, what is a
correct way to split related code up but still collect it in a module-like
way?
Maybe the best case scenario is that doing 'from doit_tools import JobInfo' is
a little confusing for someone using the package?
Maybe a python file called 'api' so that people using the code do the
following?:
import doit_tools.api
from doit_tools.api import JobInfo
============================================
Examples in response to comments:
Take the following package contents, inside folder 'foo' which is in python
path.
`foo/__init__.py`
__all__ = ['doit','dataholder','getSomeStuff','hold_more_data','SpecialCase']
from another_class import doit
from another_class import dataholder
from descriptive_name import getSomeStuff
from descriptive_name import hold_more_data
from specialcase import SpecialCase
`foo/specialcase.py`
class SpecialCase:
pass
`foo/more.py`
def getSomeStuff():
pass
class hold_more_data(object):
pass
`foo/stuff.py`
def doit():
print "I'm a function."
class dataholder(object):
pass
Do this:
>>> import foo
>>> for thing in dir(foo): print thing
...
SpecialCase
__builtins__
__doc__
__file__
__name__
__package__
__path__
another_class
dataholder
descriptive_name
doit
getSomeStuff
hold_more_data
specialcase
`another_class` and `descriptive_name` are there cluttering things up, and
also have extra copies of e.g. doit() underneath their namespaces.
If I have a class named Data inside a file named Data.py, when I do 'from Data
import Data' then I get a namespace conflict because Data is a class in the
current namespace that is inside module Data, somehow is also in the current
namespace. (But Python seems to be able to handle this.)
Answer: You can sort of do it, but it's not really a good idea and you're fighting
against the way Python modules/packages are supposed to work. By importing
appropriate names in `__init__.py` you can make them accessible in the package
namespace. By deleting module names you can make them inaccessible. (For why
you need to delete them, see [this
question](http://stackoverflow.com/questions/8541716/python-import-package-
subpackage-should-not-show-up-in-symbol-table)). So you can get close to what
you want with something like this (in `__init__.py`):
from another_class import doit
from another_class import dataholder
from descriptive_name import getSomeStuff
from descriptive_name import hold_more_data
del another_class, descriptive_name
__all__ = ['doit', 'dataholder', 'getSomeStuff', 'hold_more_data']
However, this will break subsequent attempts to `import
package.another_class`. In general, you can't import anything from a
`package.module` without making `package.module` accessible as an importable
reference to that module (although with the `__all__` you can block `from
package import module`).
More generally, by splitting up your code by class/function you are working
against the Python package/module system. A Python module should generally
contain stuff you want to import as a unit. It's not uncommon to import
submodule components directly in the top-level package namespace for
convenience, but the reverse --- trying to hide the submodules and allow
access to their contents _only_ through the top-level package namespace --- is
going to lead to problems. In addition, there is nothing to be gained by
trying to "cleanse" the package namespace of the modules. Those modules are
supposed to be in the package namespace; that's where they belong.
|
TypeError: 'encoding' is an invalid keyword argument for this function
Question: My python program has trouble opening a text file. When I use the basic open
file for read, I get an ascii error. Someone helped me out by having me add an
encoding parameter that works well in Idle, but when I run the program through
terminal, I get this error message: "TypeError: 'encoding' is an invalid
keyword argument for this function" How can I read this text file in to use
it's data?
try:
import tkinter as tk
from tkinter import *
except:
import Tkinter as tk
from Tkinter import *
import time
import sys
import os
import random
flashcards = {}
def Flashcards(key, trans, PoS):
if not key in flashcards:
flashcards[key] = [[trans], [PoS]]
else:
x = []
for item in flashcards[key][0]:
x.append(item)
x.append(trans)
flashcards[key][0] = x
x = []
for item in flashcards[key][1]:
x.append(item)
x.append(PoS)
flashcards[key][1] = x
def ImportGaeilge():
flashcards = {}
with open('gaeilge_flashcard_mode.txt','r', encoding='utf8') as file:
for line in file:
line1 = line.rstrip().split("=")
key = line1[0]
trans = line1[1]
PoS = line1[2]
Flashcards(key, trans, PoS)
def Gaeilge():
numberCorrect = 0
totalCards = 0
ImportGaeilge()
wrongCards = {}
x = input('Hit "ENTER" to begin. (Type "quit" to quit)')
while x != quit:
os.system('cls')
time.sleep(1.3)
card = flashcards.popitem()
if card == "":
## WRONG CARDS
print ("Deck one complete.")
Gaeilge()
print("\n\n")
print(str(card[0])+":")
x = input("\t:")
if x == 'quit':
break
else:
right = False
for item in card[1]:
if x == card[1]:
right = True
print("\nCorrect!")
numberCorrect += 1
if right == False:
print(card[0])
totalCards += 1
print("Correct answers:", str(numberCorrect) +"/"+str(totalCards))
Gaeilge()
gaeilge_flashcard_mode.txt:
I=mé=(pron) (emphatic)
I=mise=(n/a)
you=tú=(pron) (subject)
you=tusa=(emphatic)
y'all=sibh=(plural)
y'all=sibhse=(emphatic)
he=sé=(pron)
he=é=(n/a)
he=seisean=(emphatic)
he=eisean=(n/a)
she=sí=(pron)
she=í=(n/a)
she=sise=(emphatic)
she=ise=(emphatic)
him=é=(pron)
him=eisean=(emphatic)
her=í=(pron)
her=ise=(emphatic)
her=a=(adj)
Answer: The terminal you are trying to run this on probably uses Python 2.x as
standard.
Try using the command "Python3" specifically in the terminal:
`$ Python3 yourfile.py`
(Tested and confirmed that 2.7 will give that error and that Python3 handles
it just fine.)
|
How to custom sort a Django queryset
Question: Given a data model with Title strings, say:
class DVD(models.Model):
title = models.CharField(max_length=100)
class DVDAdmin(admin.ModelAdmin):
ordering = ('title',)
sample_titles = {"A Fish Called Wanda", "The Good, the Bad, and the Unsorted",
"A River Runs Upstream", "The Incredibles",}
I want to generate a queryset sorted by title, but considering the title as
minus any leading words that are in a list, such as ("a", "an", "the",). So
"The Incredibles" would sort before "A River Runs Upstream", etc. I don't want
to just _truncate_ the data, either in the database or in the resulting view.
I want to create an internal custom sort for querysets.
One approach that seems like it _might_ work, is to create a custom
Changelist, then sort the queryset there, as:
from django.contrib.admin.views.main import Changelist
class title_sortlist(Changelist):
def apply_special_ordering(self, queryset):
qs_desc = self.models.objects.all().order_by('-title')
return qs_desc
def get_query_set(self, request, *args, **kwargs):
queryset = super(title_sortlist, self).get_query_set(request)
queryset = self.apply_special_ordering(queryset)
return queryset
class DVDAdmin(admin.ModelAdmin):
ordering = ('title',)
def get_changelist(self, request, **kwargs):
return title_sortlist
This works for standard sorting - the descending sort does override the
model's ascending sort. However, I haven't figured out how take a queryset and
custom sort it.
Another possibility might be to _dynamically_ add a field to the model, call
it _cut_title_ , suitably edited, then just sort by that field. However, I've
just starting reading about dynamic model changes, and it's not clear how to
do it (not to mention, it seems slightly wonky, more so than regular monkey-
patching).
A third option, I was reading that Django has an `extra` option for querysets,
where you can add additional SQL, including new fields. I have no idea how to
add a new SQL field that represents the edited title, though - can Django SQL
call a Python function, maybe?
So what approach, if any, would be best for sorting a queryset by (modified)
title?
Answer: @bebraw in the comments is actually right.
Creating a special sort field is how it is done. This is custom for search
frameworks like SOLR, as well. You even might apply special text analysis to
sort according to language.
In your case, if it's just as simple as to remove the stop words (a short list
of articles), you would create a regular model field that copies the data from
the other field and removes the stop words.
The benefit from using a regular DB field: you can create a DB index (e.g. on
UPPER(value)) and be able to sort case insensitive supported by the DB index
(you will have to add an extra field with QuerySet.extra to sort on
UPPER(value)).
This will allow fast sorted and paged results. If you do everything in Django
you will have to retrieve the whole data. This might be fast enough for some
hundreds of rows but will not scale at all if the data increases.
HOWEVER: Be careful with stop words depending on your data. The anti example
to stop words is the title "To Be or Not To Be" which consists completely of
what you might easily classify as stop words and would simply be annihilated
when running through such a filter.
|
Parsing apache log files
Question: I just started learning Python and would like to read an Apache log file and
put parts of each line into different lists.
line from the file
> 172.16.0.3 - - [25/Sep/2002:14:04:19 +0200] "GET / HTTP/1.1" 401 - ""
> "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.1) Gecko/20020827"
according to [Apache website](http://httpd.apache.org/docs/1.3/logs.html) the
format is
> %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\
I'm able to open the file and just read it as it is but I don't know how to
make it read in that format so I can put each part in a list.
Answer: This is a job for [regular
expressions](http://docs.python.org/howto/regex.html).
For example:
line = '172.16.0.3 - - [25/Sep/2002:14:04:19 +0200] "GET / HTTP/1.1" 401 - "" "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.1) Gecko/20020827"'
regex = '([(\d\.)]+) - - \[(.*?)\] "(.*?)" (\d+) - "(.*?)" "(.*?)"'
import re
print re.match(regex, line).groups()
The output would be a tuple with 6 pieces of information from the line
(specifically, the groups within parentheses in that pattern):
('172.16.0.3', '25/Sep/2002:14:04:19 +0200', 'GET / HTTP/1.1', '401', '', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.1) Gecko/20020827')
|
Installing a django project, database issue
Question: I am installing the sunlight fondation's brisket and I am really new to
python, and even more to django. So I downloaded on github the project :
<https://github.com/sunlightlabs/brisket>.
So, when I run the ./manage.py run server command, I get an error message. But
I know nothing from python and django.
So now here's the error message, am I supposed to install a package ?
Could some one help ?
Unhandled exception in thread started by <bound method Command.inner_run of <django.core.management.commands.runserver.Command object at 0x976b84c>>
Traceback (most recent call last):
File "manage.py", line 11, in <module>
execute_manager(settings)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 438, in execute_manager
utility.execute()
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 379, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 191, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 219, in execute
self.validate()
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 249, in validate
num_errors = get_validation_errors(s, app)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/validation.py", line 36, in get_validation_errors
for (app_name, error) in get_app_errors().items():
File "/usr/local/lib/python2.7/dist-packages/django/db/models/loading.py", line 146, in get_app_errors
self._populate()
File "/usr/local/lib/python2.7/dist-packages/django/db/models/loading.py", line 61, in _populate
self.load_app(app_name, True)
File "/usr/local/lib/python2.7/dist-packages/django/db/models/loading.py", line 76, in load_app
app_module = import_module(app_name)
File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
ImportError: No module named brisket.influence
Answer: You do not have mysql for python installed. There are various ways to do this
but the most common are:
pip install MySQL-python
or
easy_install MySQL-python
|
Python: os.path.isdir /isfile /exists not working, returning False when they should return True
Question: So, here is my little program. It should print all files in a given directory
+ all files in every subdirectory.
import os
def listFiles(directory):
dirList = os.listdir(directory)
printList = []
for i in dirList:
i = os.path.join(directory,i)
# print(i)
if os.path.isdir(i):
printList[len(dirList):] = listFiles(i)
else:
printList.append(i)
return printList
directory = 'C:\Python32\Lib'
listFiles(directory)
a = listFiles(directory)
for i in a:
print(i)
What's the problem: os.path.isdir(i) isn't working properly - for example, if
I try
os.path.isfile('C:\Python32\Lib\concurrent\futures\process.py')
os.path.exists('C:\Python32\Lib\concurrent\futures\process.py')
os.path.isdir('C:\Python32\Lib\concurrent\futures')
I always get False instead of True (it works ok for some of the
subdirectories). If I uncomment print(i) it prints everything just fine but it
also prints directories - I want just to print files. What should I do?
Answer: Your `printList[len(dirList):] = listFiles(i)` is going to overwrite values
every loop.
If all your entries in `dirList` are directories, for example, you'll end up
with removing entries from `printList` as you loop over each subdir:
>>> printList = []
>>> len_dirlist = 2 # make up a size
>>> printList[len_dirlist:] = ['foo', 'bar', 'baz'] # subdir 1 read
>>> printList
['foo', 'bar', 'baz']
>>> printList[len_dirlist:] = ['spam', 'ham', 'eggs'] # subdir 2 read
>>> printList
['foo', 'bar', 'spam', 'ham', 'eggs'] # Wait, where did 'baz' go?
You want to use `.extend()` instead when adding items to the end of your list.
Note that on Windows, you don't have to use backslashes as path separators,
it's better to use forward slashes, as these do not have special meaning in
Python strings:
'C:/Python32/Lib/concurrent/futures/process.py'
Alternatively, use `r''` _raw_ string literals to remove the chance
backslashes are interpreted as character escapes:
r'C:\Python32\Lib\concurrent\futures\process.py'
|
wxpython setsizer
Question: The panel1 in page1 of the Notebook is defined with Size(400,100)..I don't
want the Sizer to resize my panel..
test.py
import random
import wx
########################################################################
class TabPanel1(wx.Panel):
#----------------------------------------------------------------------
def __init__(self, parent):
""""""
wx.Panel.__init__(self, parent=parent)
colors = ["red", "blue", "gray", "yellow", "green"]
self.SetBackgroundColour(random.choice(colors))
panel1 = wx.Panel(self,size=(400,100))
panel1.SetBackgroundColour('brown')
panel1gs = wx.GridSizer(2,2,1,2)
panel1gs.AddMany( [ (wx.StaticText(panel1,label='FirstLabel'),0,wx.EXPAND),
(wx.StaticText(panel1,label='SecondLabel'),0,wx.EXPAND),
(wx.StaticText(panel1,label='ThirdLabel'),0,wx.EXPAND),
(wx.StaticText(panel1,label='FourthLabel'),0,wx.EXPAND)
] )
panel1.SetSizer(panel1gs)
panel2 = wx.Panel(self,size=(400,100))
panel2.SetBackgroundColour('#4f5042')
panel3 = wx.Panel(self,size=(400,100))
panel3.SetBackgroundColour('#4f5042')
btn = wx.Button(self, label="Press Me")
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(btn, 0, wx.ALL, 5)
sizer.Add(panel1, 0, wx.ALL, 5)
sizer.Add(panel2, 0, wx.ALL, 5)
sizer.Add(panel3, 0, wx.ALL, 5)
self.SetSizer(sizer)
class TabPanel2(wx.Panel):
#----------------------------------------------------------------------
def __init__(self, parent):
""""""
wx.Panel.__init__(self, parent=parent)
colors = ["red", "blue", "gray", "yellow", "green"]
self.SetBackgroundColour(random.choice(colors))
btn = wx.Button(self, label="Press Me")
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(btn, 0, wx.ALL, 10)
self.SetSizer(sizer)
########################################################################
class DemoFrame(wx.Frame):
"""
Frame that holds all other widgets
"""
#----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
wx.Frame.__init__(self, None, wx.ID_ANY,
"Notebook Tutorial",
size=(800,600)
)
panel = wx.Panel(self)
notebook = wx.Notebook(panel)
tabOne = TabPanel1(notebook)
notebook.AddPage(tabOne, "Tab 1")
tabTwo = TabPanel2(notebook)
notebook.AddPage(tabTwo, "Tab 2")
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(notebook, 1, wx.ALL|wx.EXPAND, 5)
panel.SetSizer(sizer)
self.Layout()
self.Show()
#----------------------------------------------------------------------
if __name__ == "__main__":
app = wx.App(False)
frame = DemoFrame()
app.MainLoop()
Answer: There are two ways a sizer can change the size of an item inside it.
First is the [`wx.EXPAND` flag](http://wxpython.org/docs/api/wx.SizerFlags-
class.html#Expand) which "will cause the item to be expanded to fill as much
space as it is given by the sizer." You're using this flag but you don't want
this behaviour, so you should remove them.
Second, `wx.BoxSizer`s can resize objects using the `proportion` argument in
the [`Add()` and `AddMany()` methods](http://wxpython.org/docs/api/wx.Sizer-
class.html#Add). [`wx.BoxSizer`'s
documentation](http://wxpython.org/docs/api/wx.BoxSizer-class.html) states "
> [objects in the sizer] can grow in both directions (height and width) [...]
> This is determined by the proportion parameter give to items when they are
> added to the sizer. It is interpreted as a weight factor, i.e. it can be
> zero, **indicating that the window may not be resized at all** , or above
> zero.
(Emphasis added)
In your case, you are already setting the proportion to 0 and you aren't even
using a `wx.BoxSizer` so this isn't an issue for you, but it's something to
keep in mind in the future.
|
Cannot seem to crawl a deep directory with my Python script, any idea?
Question: The script is basically creating a list with all the files in all directories.
Any idea why is seems to crash when it has to scan a directory that is larger
than a few files?
import os
correctlyNamedDirectories = []
def crawlDirectories(directory):
for dirname, dirnames, filenames in os.walk(directory):
for subdirname in dirnames:
correctlyNamedDirectories.append(os.path.join(dirname, subdirname))
for filename in filenames:
correctlyNamedDirectories.append(os.path.join(dirname, filename))
crawlDirectories('.')
print correctlyNamedDirectories
Also, is there a cleaner way of writing this?
Answer: Shorter method with a list comprehension:
correctlyNamedDirectories = [os.path.join(path, subname) for path, dirnames, filenames in os.walk(directory) for subname in dirnames + filenames]
|
"ImportError: cannot import name ..." - raised on "import from" but not on direct import
Question: What is the precise rule under which this exception is raised by Python 3
interpreter?
There are plenty of SO questions about that, with excellent answers, but I
could not find one that gave a clear, general, and logically precise
definition of the circumstances when this exception occurs.
The documentation doesn't seem to be clear either. It says:
> exception `ImportError`
>
>> Raised when an import statement fails to find the module definition or when
a `from ... import` fails to find a name that is to be imported.
But this seems inconsistent with the following example.
I meant to ask for a general definition rather than a specific case, but to
clarify my concerns, here's an example:
# code/t.py:
from code import d
# code/d.py
from code import t
Running module `t.py` from the command line results in `ImportError: cannot
import name d`.
On the other hand, the following code doesn't raise exceptions:
# code/t.py:
import code.d
# code/d.py
import code.t
At all times, `__init__.py` is empty.
In this example, the only modules or names mentioned in the import statement
are `t` and `d`, and they were both clearly found. If the documentation
implies that some name _within_ the `d` module isn't found, it's certainly not
obvious; and on top of that, I'd expect it to raise `NameError: name ... is
not defined` exception rather than `ImportError`.
Answer: If `abc` is a package and `xyz` is a module, and if `abc`'s `__init__.py`
defines an `__all__` that does not include `xyz`, then you won't be able to do
`from abc import xyz`, but you'll still be able to do `import abc.xyz`.
Edit: The short answer is: your problem is that your imports are circular.
Modules t and d try to import each other. This won't work. Don't do it. I'm
going to explain the whole thing, below but the explanation is pretty long.
To understand why it gives an ImportError, try to follow the code execution.
If you look at the full traceback instead of just the final part, you can see
what it's doing. With your setup I get a traceback like this (I called the
package "testpack" instead of "code"):
Traceback (most recent call last):
File "t.py", line 1, in <module>
from testpack import d
File "C:\Documents and Settings\BrenBarn\My Documents\Python\testpack\d.py", line 1, in <module>
from testpack import t
File "C:\Documents and Settings\BrenBarn\My Documents\Python\testpack\t.py", line 1, in <module>
from testpack import d
ImportError: cannot import name d
You can see what Python is doing here.
1. In loading `t.py`, the first thing it sees is `from testpack import d`.
2. At that point, Python executes the `d.py` file to load that module.
3. But the first thing it finds there is `from testpack import t`.
4. It already is loading `t.py` once, but t as the main script is different than t as a module, so it tries to load `t.py` again.
5. The first thing it sees is `from testpack import d`, which would mean it should try to load `d.py` . . . but it already _was_ trying to load `d.py` back in step 2. Since trying to import `d` led back to trying to import `d` again, Python realizes it can't import `d` and throws ImportError.
Step 4 is kind of anomalous here because you ran a file in the package
directly, which isn't the usual way to do things. See [this
question](http://stackoverflow.com/questions/72852/how-to-do-relative-imports-
in-python) for an explanation of why importing a module is different from
running it directly. If you try to _import_ `t` instead (with `from testpack
import t`), Python realizes the circularity one step sooner, and you get a
simpler traceback:
>>> from testpack import t
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
from testpack import t
File "C:\Documents and Settings\BrenBarn\My Documents\Python\testpack\t.py", line 1, in <module>
from testpack import d
File "C:\Documents and Settings\BrenBarn\My Documents\Python\testpack\d.py", line 1, in <module>
from testpack import t
ImportError: cannot import name t
Notice that here the error is that it can't import _t_. It knows it can't,
because when I told it to import t, it found itself looping back to import t
again. In your original example, it didn't notice it was running t.py twice,
because the first time was the main script and the second was an import, so it
took one more step and tried to import d again.
Now, why doesn't this happen when you do `import code.d`? The answer is just
because you don't actually try to _use_ the imported modules In this case, it
happens as follows (I'm going to explain as if you did `from code import t`
rather than running it as a script):
1. It starts to import t. When it does this, it provisionally marks the module `code.t` as imported, even though it's not done importing yet.
2. It finds it has to do `import code.d`, so it runs d.
3. In d, it finds `import code.t`, but since `code.t` is already marked as imported, it doesn't try to import it again.
4. Since d finished without actually using `t`, it gets to go back and finish loading `t`. No problem.
The key difference is that the names `t` and `d` are not directly accessible
to each other here; they are mediated by the package `code`, so Python doesn't
actually have to finish "deciding what t is" until it is actually used. With
`from code import t`, since the value has to be assigned to the variable `t`,
Python has to know what it is right away.
You can see the problem, though if you make `d.py` look like this:
import code.t
print code.t
Now, after step 2, while running d, it actually tries to access the half-
imported module t. This will raise an AttributeError because, since the module
hasn't been fully imported yet, it hasn't been attached to the package `code`.
Note that it would be fine as long as the use of `code.t` didn't happen until
after `d` finished running. This will work fine in `d.py`:
import code.t
def f():
print code.t
You can call `f` later and it will work. The reason is that it doesn't need to
use `code.t` until after `d` finished executing, and after d finishes
executing, it can go back and finish executing t.
To reiterate, the main moral of the story is **don't use circular imports**.
It leads to all kinds of headaches. Instead, factor out common code into a
third module imported by both modules.
|
How to structure my code?
Question: Edit: I just combined all my questions to one big question: [Need tutorial for
menubar-handling & panel-
building](http://stackoverflow.com/questions/12604139/need-tutorial-for-
menubar-handling-panel-building)
I have a "bigger" question: I'm new to python and I started creating a little
program -> "learning by doing" ;) My program works (it's not too big yet), but
the code is already a little confusing: I have only 1 class in it and many,
many functions, which refer to each other. So my question is: Can anyone give
me hints how I can structure my code? I think I have to create more classes...
but where? Which part of my code should I combine to a new class? Short
description about my program (what it shall do when it's done): it is a kind
of soccer//football manager game; you create a team consisting of 3 player
which different attributes, you can coach them (improve their attributes) and
play against other (computer-) teams. You can also have a look at the code and
tell me how I can structe it and in which part I should create a new class:
# -*- coding: cp1252 -*-
import wx
class myclass(wx.Frame):
def __init__(self,parent,id):
self.title='Click Kick'
bgcolour=(170,255,170)
wx.Frame.__init__(self,parent,id,self.title,size=wx.DisplaySize())
self.displayw=wx.DisplaySize()[0]
self.displayh=wx.DisplaySize()[1]
self.startpanel=wx.Panel(self,size=wx.DisplaySize())
titlefont = wx.Font(10, wx.MODERN, wx.NORMAL, wx.NORMAL, False, u'Consolas')
self.SetBackgroundColour(bgcolour)
self.dateinewgamepanel=wx.Panel(self,size=wx.DisplaySize())
self.dateiloadgamepanel=wx.Panel(self,size=wx.DisplaySize())
self.teamoverviewpanel=wx.Panel(self,size=wx.DisplaySize())
self.trainingpanel=wx.Panel(self,size=wx.DisplaySize())
self.spielpanel=wx.Panel(self,size=wx.DisplaySize())
self.regelnpanel=wx.Panel(self,size=wx.DisplaySize())
self.infopanel=wx.Panel(self,size=wx.DisplaySize())
self.teamname=''
ID_newgame=01
ID_loadgame=02
ID_overview=11
ID_training=21
ID_spiel=31
ID_regeln=41
ID_ueber=42
#status=self.CreateStatusBar()
menubar=wx.MenuBar()
self.datei=wx.Menu()
self.team=wx.Menu()
self.training=wx.Menu()
self.spiel=wx.Menu()
self.info=wx.Menu()
self.datei.Append(ID_newgame,"Neues Spiel")
self.datei.Append(ID_loadgame,"Spiel laden...")
self.team.Append(ID_overview,"Übersicht")
self.training.Append(ID_training,"Trainieren")
self.spiel.Append(ID_spiel,"Spielen")
self.info.Append(ID_regeln,"Regeln")
self.info.Append(ID_ueber,"Info")
menubar.Append(self.datei,"Datei")
menubar.Append(self.team,"Mannschaft")
menubar.Append(self.training,"Training")
menubar.Append(self.spiel,"Spiel")
menubar.Append(self.info,"Info")
self.SetMenuBar(menubar)
self.titletext=wx.StaticText(self.startpanel, -1, self.title, (220,130))
self.titletext.SetFont(titlefont)
self.newgame = wx.Button(self.startpanel,label="Neues Spiel",pos=(215,160),size=(80,40))
self.loadgame = wx.Button(self.startpanel,label="Spiel laden",pos=(305,160),size=(80,40))
self.Bind(wx.EVT_BUTTON, self.dateinewgamepanelbuild, self.newgame)
self.Bind(wx.EVT_BUTTON, self.dateiloadgamepanelbuild, self.loadgame)
wx.EVT_MENU(self, ID_newgame, self.dateinewgamepanelbuild)
wx.EVT_MENU(self, ID_loadgame, self.dateiloadgamepanelbuild)
wx.EVT_MENU(self, ID_overview, self.teamoverviewpanelbuild)
wx.EVT_MENU(self, ID_ueber, self.infopanelbuild)
def hideallpanels(self):
self.startpanel.Hide()
self.dateinewgamepanel.Hide()
self.dateiloadgamepanel.Hide()
self.teamoverviewpanel.Hide()
self.trainingpanel.Hide()
self.spielpanel.Hide()
def infopanelbuild(self,event):
self.hideallpanels()
self.infopanel.Show()
wx.StaticText(self.infopanel,-1,"Autor: Steffen Becker")
def dateinewgamepanelbuild(self,event):
# panel neu zusammensetzen (mit aktuellen Werten), panel zeigen, alle anderen panels verstecken
w=0
h=-20
self.hideallpanels()
self.dateinewgamepanel.Show()
#wx.StaticBitmap(self.dateinewgamepanel).SetBitmap(wx.Bitmap('pics/defaultplayer.bmp'))
wx.StaticText(self.dateinewgamepanel, -1, "Neues Spiel", (5+w,25+h)).SetFont(wx.Font(16, wx.MODERN, wx.NORMAL, wx.BOLD))
wx.StaticText(self.dateinewgamepanel, -1, "Teamname:", (self.displayw/4+10+w,self.displayh/10+20+h))
self.teamnameinput = wx.TextCtrl(self.dateinewgamepanel, pos=(self.displayw/4+10+w,self.displayh/8+20+h), size=(280,22))
wx.StaticText(self.dateinewgamepanel, -1, "Name 1. Spieler", (self.displayw/16+w,self.displayh/2+h))
self.player1input = wx.TextCtrl(self.dateinewgamepanel, pos=(self.displayw/16+w,self.displayh/2+20+h), size=(130,20))
wx.StaticText(self.dateinewgamepanel, -1, "Spielertyp", (self.displayw/16+w,self.displayh/2+60+h))
self.player1typeinput = wx.Choice(self.dateinewgamepanel,id=-1,pos=(self.displayw/16+w,self.displayh/2+80+h))
player1typelist = ['Dribbler', 'Spielgestalter', 'Balleroberer']
self.player1typeinput.AppendItems(strings=player1typelist)
self.player1typeinput.SetSelection(0)
picplayer1=wx.Image("pics\defaultplayer.bmp", wx.BITMAP_TYPE_BMP).ConvertToBitmap()
picbutplayer1=wx.BitmapButton(self.dateinewgamepanel,-1,picplayer1,pos=(self.displayw/16+w,self.displayh/2-140+h))
wx.StaticText(self.dateinewgamepanel, -1, "Name 2. Spieler", (self.displayw*5/16+w,self.displayh/2+h))
self.player2input = wx.TextCtrl(self.dateinewgamepanel, pos=(self.displayw*5/16+w,self.displayh/2+20+h), size=(130,20))
wx.StaticText(self.dateinewgamepanel, -1, "Spielertyp", (self.displayw*5/16+w,self.displayh/2+60+h))
self.player2typeinput = wx.Choice(self.dateinewgamepanel,id=-1,pos=(self.displayw*5/16+w,self.displayh/2+80+h))
player2typelist = ['Dribbler', 'Spielgestalter', 'Balleroberer']
self.player2typeinput.AppendItems(strings=player2typelist)
self.player2typeinput.SetSelection(0)
picplayer2=wx.Image("pics\defaultplayer.bmp", wx.BITMAP_TYPE_BMP).ConvertToBitmap()
picbutplayer2=wx.BitmapButton(self.dateinewgamepanel,-1,picplayer2,pos=(self.displayw*5/16+w,self.displayh/2-140+h))
wx.StaticText(self.dateinewgamepanel, -1, "Name 3. Spieler", (self.displayw*9/16+w,self.displayh/2+h))
self.player3input = wx.TextCtrl(self.dateinewgamepanel, pos=(self.displayw*9/16+w,self.displayh/2+20+h), size=(130,20))
wx.StaticText(self.dateinewgamepanel, -1, "Spielertyp", (self.displayw*9/16+w,self.displayh/2+60+h))
self.player3typeinput = wx.Choice(self.dateinewgamepanel,id=-1,pos=(self.displayw*9/16+w,self.displayh/2+80+h))
player3typelist = ['Dribbler', 'Spielgestalter', 'Balleroberer']
self.player3typeinput.AppendItems(strings=player3typelist)
self.player3typeinput.SetSelection(0)
picplayer3=wx.Image("pics\defaultplayer.bmp", wx.BITMAP_TYPE_BMP).ConvertToBitmap()
picbutplayer3=wx.BitmapButton(self.dateinewgamepanel,-1,picplayer3,pos=(self.displayw*9/16+w,self.displayh/2-140+h))
#bmp = wx.Image('pics/defaultplayer.bmp', wx.BITMAP_TYPE_BMP).ConvertToBitmap()
#wx.StaticBitmap(self.dateinewgamepanel, -1, bmp, (1100, 500))
self.playerok = wx.Button(self.dateinewgamepanel,label="Team erstellen",pos=(self.displayw*5/16-20+w,self.displayh/2+170+h),size=(170,30))
self.Bind(wx.EVT_BUTTON, self.onteamok, self.playerok)
self.teamnameerror=wx.StaticText(self.dateinewgamepanel, -1, "Gib bitte überall einen Namen ein!", (self.displayw*5/16-15+w,self.displayh/2+210+h))
self.teamnameerror.Hide()
def dateiloadgamepanelbuild(self,event):
self.hideallpanels()
self.dateiloadgamepanel.Show()
wx.StaticText(self.dateiloadgamepanel, -1, "Noch nicht implementiert", (20,70))
def teamoverviewpanelbuild(self,event):
self.hideallpanels()
self.teamoverviewpanel.Show()
wx.StaticText(self.teamoverviewpanel, -1, self.teamname, (120,10))
wx.StaticText(self.teamoverviewpanel, -1, self.player1, (40,40))
wx.StaticText(self.teamoverviewpanel, -1, self.player2, (120,40))
wx.StaticText(self.teamoverviewpanel, -1, self.player3, (200,40))
def onteamok(self,event):
if self.teamnameinput.GetValue() == '' or self.player1input.GetValue() == '' or self.player2input.GetValue() == '' or self.player3input.GetValue() == '':
self.teamnameerror.Show()
else:
self.teamname = self.teamnameinput.GetValue()
self.player1 = self.player1input.GetValue()
self.player2 = self.player2input.GetValue()
self.player3 = self.player3input.GetValue()
self.teamoverviewpanelbuild(event)
def onloadgame(self,event):
self.startpanel.Hide()
self.dateinewgamepanel.Hide()
self.dateiloadgamepanel.Show()
if __name__=='__main__':
app=wx.PySimpleApp()
frame=myclass(parent=None,id=-1)
frame.Show()
app.MainLoop()
Answer: Here are my suggestions:
* You're already familiar with deriving classes from `wx.Frame`. You can do the same for `wx.Panel` for the retrieving the player's data and parameterize it as you like. This would remove code duplication and make it more handy.
class PlayerPanel(wx.Panel):
def __init__(self, name, *args, **kwargs):
wx.Panel.__init__(self, *args, **kwargs)
wx.StaticText(self, -1, name)
..etc...
* Derive another class from `wx.Frame` and separate the aspects of game creation and actual playing; get rid of hiding / showing panels.
* Learn about layout management. When I want to get familiar with your code, the absolute calculation of the widget position is unacceptable to me. There are very nice examples on [Zetcode](http://zetcode.com/wxpython/).
* Refactor all game logic into separate a seperate module. This module could contain the model and control classes of the MVC (model-view-controller) pattern. The view is written in wxPython, the game logic could be in a separate class and the model is e.g. another class for the player (name, age, ...).
* Use a [`wx.MessageBox`](http://zetcode.com/wxpython/dialogs/) for error messages and the about dialog.
|
Python 3: Documenting modules
Question: I study how to document my code. So, I prepared a file docstrings.py and
placed it in a directory. Now I would like to have a look at what I
documented. In other words I want to type help(docstrings.square) and get the
documentation on square function in my module.
>>> import sys
>>> sys.path.append("C:\Users\Michael\PycharmProjects\Docstrings")
Result:
**SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in
position 2-4: truncated \UXXXXXXXX escape**
What's wrong?
Answer: Backslashes have to be doubled in [string
literals](http://docs.python.org/reference/lexical_analysis.html#string-
literals):
>>> sys.path.append("C:\\Users\\Michael\\PycharmProjects\\Docstrings")
Unless you use a _raw string_ :
>>> sys.path.append(r"C:\Users\Michael\PycharmProjects\Docstrings")
|
Creating a new file, filename contains loop variable, python
Question: I want to run a function over a loop and I want to store the outputs in
different files, such that the filename contains the loop variable. Here is an
example
for i in xrange(10):
f = open("file_i.dat",'w')
f.write(str(func(i))
f.close()
How can I do it in python?
Answer: Simply construct the file name with `+` and `str`. If you want, you can also
use [old-style](http://docs.python.org/library/stdtypes.html#string-
formatting) or [new-style
formatting](http://docs.python.org/library/stdtypes.html#str.format) to do so,
so the file name can be constructed as:
"file_" + str(i) + ".dat"
"file_%s.dat" % i
"file_{}.dat".format(i)
Note that your current version does not specify an encoding ([you
should](http://www.joelonsoftware.com/articles/Unicode.html)), and does not
correctly close the file in error cases (a `with` statement [does
that](http://docs.python.org/tutorial/inputoutput.html#methods-of-file-
objects)):
import io
for i in xrange(10):
with io.open("file_" + str(i) + ".dat", 'w', encoding='utf-8') as f:
f.write(str(func(i))
|
Encoding in python
Question: I have problem with comparing string from file with string I entered in the
program, I should get that they are equal but no matter if i use
decode('utf-8') I get that they are not equal. Here's the code:
final = open("info", 'r')
exported = open("final",'w')
lines = final.readlines()
for line in lines:
if line == "Wykształcenie i praca": #error
print "ok"
and how I save file that I try read:
comm_p = bs4.BeautifulSoup(comm)
comm_f.write(comm_p.prettify().encode('utf-8'))
for string in comm_p.strings:
#print repr(string).encode('utf-8')
save = string.encode('utf-8') # there is how i save
info.write(save)
info.write("\n")
info.close()
and at the top of file I have # -_\- coding: utf-8 -_ -
Any ideas?
Answer: This should do what you need:
# -- coding: utf-8 --
import io
with io.open('info', encoding='utf-8') as final:
lines = final.readlines()
for line in lines:
if line.strip() == u"Wykształcenie i praca": #error
print "ok"
You need to open the file with the right encoding, and since your string is
not ascii, you should mark it as unicode.
|
Take a screenshot of open website in python script
Question: I need to write a python script which opens a website and when the website is
completly opened it takes a screenshot of the opened website.
I wrote sth like this:
import webbrowser
import wx
wx.App()
link = "http://stackoverflow.com/questions"
webbrowser.get('firefox %s').open_new_tab(link)
screen = wx.ScreenDC()
size = screen.GetSize()
bmp = wx.EmptyBitmap(size[0], size[1])
mem = wx.MemoryDC(bmp)
mem.Blit(0, 0, size[0], size[1], screen, 0, 0)
del mem
bmp.SaveFile('screenshot.png', wx.BITMAP_TYPE_PNG)
It only opens a new tab in firefox but it doesnt take a screenshot of it :(
I want the solution to be cross-platform. Thanks for any help:)
**EDIT:**
**The main problem here is that the script musnt take a picture BEFORE my
webpage is completly opened. How to solve that issue?**
Answer: I believe that you need different solutions for different operating systems.
Use [`sys.platform`](http://docs.python.org/library/sys.html#sys.platform) to
find out on which platform you are on. The rest you have to figure out
yourself, but a quick internet search revealed:
* On Linux systems, you can then take a screenshot as described here:
[Take a screenshot via a python script.
[Linux]](http://stackoverflow.com/questions/69645/take-a-screenshot-via-a-
python-script-linux)
* On Windows systems, you can base your solution on this answer:
[Fastest way to take a screenshot with python on
windows](http://stackoverflow.com/questions/3586046/fastest-way-to-take-a-
screenshot-with-python-on-windows)
* On Mac systems, this will help:
[Take screenshot in Python on Mac OS
X](http://stackoverflow.com/questions/4524723/take-screenshot-in-python-on-
mac-os-x)
|
Finding duplicate files with python
Question: I'm trying to write a Python script that will crawl through a directory and
find all files that are duplicates and report back the duplicates. What's the
best was to solve this?
import os, sys
def crawlDirectories(directoryToCrawl):
crawledDirectory = [os.path.join(path, subname) for path, dirnames, filenames in os.walk(directoryToCrawl) for subname in dirnames + filenames]
return crawledDirectory
#print 'Files crawled',crawlDirectories(sys.argv[1])
directoriesWithSize = {}
def getByteSize(crawledDirectory):
for eachFile in crawledDirectory:
size = os.path.getsize(eachFile)
directoriesWithSize[eachFile] = size
return directoriesWithSize
getByteSize(crawlDirectories(sys.argv[1]))
#print directoriesWithSize.values()
duplicateItems = {}
def compareSizes(dictionaryDirectoryWithSizes):
for key,value in dictionaryDirectoryWithSizes.items():
if directoriesWithSize.values().count(value) > 1:
duplicateItems[key] = value
compareSizes(directoriesWithSize)
#print directoriesWithSize.values().count(27085)
compareSizes(directoriesWithSize)
print duplicateItems
Why does this throw back this error?
Traceback (most recent call last):
File "main.py", line 16, in <module>
getByteSize(crawlDirectories(sys.argv[1]))
File "main.py", line 12, in getByteSize
size = os.path.getsize(eachFile)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/genericpath.py", line 49, in getsize
OSError: [Errno 2] No such file or directory: '../Library/Containers/com.apple.ImageKit.RecentPictureService/Data/Documents/iChats'
Answer: It seems to me that your `crawledDirectory` function is too complicated:
def crawlDirectories(directoryToCrawl):
output = []
for path, dirnames, filenames in os.walk(directoryToCrawl):
for fname in filenames:
output.append(os.path.join(path,fname))
return output
|
Sum all columns with a wildcard name search using Python Pandas
Question: I have a dataframe in python pandas with several columns taken from a CSV
file.
For instance, data =:
Day P1S1 P1S2 P1S3 P2S1 P2S2 P2S3
1 1 2 2 3 1 2
2 2 2 3 5 4 2
And what I need is to get the sum of all columns which name starts with P1...
something like P1* with a wildcard.
Something like the following which gives an error:
> P1Sum = data["P1*"]
Is there any why to do this with pandas?
Answer: I found the answer.
Using the data, dataframe from the question:
from pandas import *
P1Channels = data.filter(regex="P1")
P1Sum = P1Channels.sum(axis=1)
|
Using Python with a set of not regular point X,Y,Z in order to create a regular grid where each pixel is the minimum value of the point
Question: I have a set of not-regular points with X,Y and Z value. I wish to create a
regular square grid (to export in `TIFF` format or `ASCII` format) with a
resolution of 0.5 x 0.5 and extension equal to the boundery box of my data-set
`[X_Min,Y_Min],[X_Max,Y_Min],[X_Max,Y_Max],[X_Min,Y_Max],[X_Min,Y_Min]`
The value of each pixel, where the points are present, need to be the low
value of the points in the pixel.
Sorry if i cannot post any Python code.
Thanks in advance for all Help, suggestions, and link where to solve this
problem
Answer: I assume your points are available in an array like this:
points = [(x1,y1,z1), (x2,y2,z2), ...]
To extract the x and y values you can use the zip trick:
points_zipped = zip(*points)
xvals = points_zipped[0]
yvals = points_zipped[1]
Getting the bounding box is then straightforward:
xmin, ymin = min(xvals), min(yvals)
xmax, ymax = max(xvals), max(yvals)
To get the minimum points I couldn't come up with something more inspiring
than using defaultdicts from the collections module:
from collections import defaultdict
minpoints = defaultdict(lambda: defaultdict(lambda : 0.)) # 0. or another suitable min value
for p in points:
minpoints[p[0]][p[1]] = min(p[2], minpoints[p[0]][p[1]])
From there one you could use scipy interpolation. There is a dedicated recipe
for 2d-interpolation of irregularly spaced data:
<http://www.scipy.org/Cookbook/Matplotlib/Gridding_irregularly_spaced_data>
|
mysql int being passed to python as long
Question: I have a mysql database in which I have defined a table as:
CREATE TABLE IF NOT EXISTS tblModel (
model_id int NOT NULL AUTO_INCREMENT,
model_file varchar(50) NOT NULL,
model_name varchar(50) NOT NULL,
model_descrip varchar(200) NOT NULL,
target_index char(6) NOT NULL,
training_days int NOT NULL,
trading_days int NOT NULL,
PRIMARY KEY(model_id));
Oddly enough, I noticed that though the mysql documentation says ints are
really int(4), I see that the int fields actually got created as int(11). This
is a bit disturbing, as it seems my instructions were not followed, per the
documentation.
When I query this table into python with a mysqldb.database_connection.cursor,
I see the ints are coming through as longs - not surprisingly.
My question is thus threefold (in order of increasing importance to me):
1) Any idea why int got created as int(11)?
2) The int fields in this table will hold a sequence #, and day counts - the
space allocated to a long is nowhere near necessary. Should I care about the
wasted space?
3) Assuming I'm stuck with the int(11)s (other tables have foreign keys into
this and it's a bit of a pain to break and recreate all that), is there any
better solution than doing an explicit cast to int of the cur.fetchall() or
cur.fetchone() returns?
Answer: 1. That is the default display width since an int can be in the range of -2147483648 to 2147483647 so max display width is 10 integers and a sign. The storage size of an int is 4 bytes regardless of its value. Don't confuse "display width" with storage size since display width is only if the number has a 'zerofill' option so int(4) zerofill will display 0004 while int(6) zerofill will display 000004; and this is a minimum display width so int(4) zerofill using 123456 will still yield 123456 and not 1234. Check out <http://dev.mysql.com/doc/refman/5.5/en/numeric-type-attributes.html>
2. The space may or may not be wasted and depends on the architecture and OS. In C, ints must be at least 16 bits and longs at least 32 bits, but may be larger. On a 64-bit system a long might actually be a long long and be 64 bits. Unless you are operating on a severely limited system, it's probably not worth the worry. This is only in memory since MySQL will store those ints as 4 bytes regardless of what Python does with them.
3. As stated previously, the number in the () is just a display width and doesn't affect the underlying range of the number in that column although if you do something like int(4) zerofill on one table with a foreign key and int(6) zerofill on another, joins may act weird but I haven't tested it. Adding "zerofill" to a MySQL number makes that column automatically unsigned. You don't need to cast anything when reading those out of MySQL; ints fit in a long and Python stores both as C longs regardless.
|
how to turn readlines into a string... perhaps?
Question: I think my largest problem is I don't know how to ask the question of what it
is exactly that I am looking for.
I stole most the code from a flashcard program from
<http://www.tuxradar.com/content/code-project-build-flash-card-app> and
modified it a bit to suit my own needs. However, when I get the answer correct
it still says I've gotten it wrong.
Here is my code:
#!/usr/bin/env python
import os
import random
import time
file1 = open('/root/first.txt', 'w')
file2 = open('/root/second.txt', 'w')
file1.writelines('1\n2\n3\n4\n5')
file2.writelines('0,2\n1,3\n2,4\n3,5\n4,6')
time.sleep(1)
file1.close
file2.close
time.sleep(1)
file1 = open('/root/first.txt', 'r')
file2 = open('/root/second.txt', 'r')
count = 0
score = 0
tries = int(raw_input('How many tries?'))
start_time = time.time()
f1content = file1.readlines()
f2content = file2.readlines()
try:
while count < tries:
os.system('clear')
wordnum = random.randint(0, len(f1content)-1)
correct = str(f2content[wordnum])
print 'Number:', f1content[wordnum], ''
answer = input('\nSurrounding numbers?')
if answer == correct:
raw_input('\nCorrect! Hit enter...')
score = score + 1
else:
print '\nNope, It\'s', correct
raw_input('Hit enter to try a new one...')
count = count + 1
except SyntaxError:
print 'you must enter a value, starting over'
os.system('./flash.py')
finally:
file1.close
file2.close
os.system('rm /root/first.txt')
os.system('rm /root/second.txt')
stop_time = time.time() - start_time
print '\nIt took you', stop_time / 60, 'minutes to get', score, 'out of', count, 'correct'
I postulate that my problem lies in Line 35 where I define correct as
correct = str(f2content[wordnum])
The reason I think this is because if it gives me `1` and I know that the
correct answer is `0,2` and I type that in, it say's nope, it's `0,2`. This
suggests that in plain text it is the exact same to the human eye but that the
computer is reading it as something different. I tried to make it a string
because of this and making it an integer causes an error. I'm really stuck and
am sure it's something so simple but I am just not seeing it. Any help would
be appreciated. Even if it is just a point in the right direction of where I
can find the answer.
Answer: First, I fixed all the problems given in the comments above.
Instead of `writeline`, use `write`:
file1.write('1\n2\n3\n4\n5')
file2.write('0,2\n1,3\n2,4\n3,5\n4,6')
Add the parentheses to `close`:
file1.close()
file2.close()
Indent everything between the `while` and the end of the `try`.
Debug by adding the following before the comparison:
print repr(answer), repr(correct)
Also, I went through and changed all the `/root/first.txt`, etc. into just
`first.txt`, so it'll work on a system that doesn't have a writable directory
named `/root` (which most systems won't).
So, when I run it, I see this:
Number: 4
Surrounding numbers?3,5
(3, 5) '3,5\n'
Nope, It's 3,5
Hit enter to try a new one...
So clearly, `answer` is the tuple `(3, 5)` rather than the string `3,5`, and
`correct` is the string `3,5\n` rather than the string `3,5`.
If you read [the documentation for
input](http://docs.python.org/library/functions.html#input), it should be
clear why `answer` is wrong. It's trying to interpret my `3,5` as a Python
expression, and it's a perfectly valid way to write the tuple `(3, 5)`, so
that's why I get. To fix that, you want to use `raw_input`.
If you read [the documentation for
readlines](http://docs.python.org/library/stdtypes.html#file.readlines), it
should be clear why each line has a newline at the end. There are a number of
ways around this.
Having fixed that, it still fails at the end, because it never creates the
files `table.txt` and `pocket.txt` that it tries to delete. Whatever you were
trying to do there, you appear to have missed something. I just commented out
those lines.
While you're at it, I'd change the `open`/`readlines`/`close` into a more
modern Python pattern, using `with` and treating the file as just a string
iterator. And hardcoding paths like `/root/first.txt` isn't a very good idea.
Anyway, I don't want to give the exact changes needed, because this feels like
homework, but I think the above is enough information for you to fix it
yourself, and hopefully learn a little about how to debug the next problem on
your own. If you still have problems, ask away.
|
ValueError: Too Many Values to Unpack Aptana Studio 3
Question: I am working on exercise 13 from learnpythonthehardway.org. I should run this
code:
from sys import argv
script, first, second, third = argv
print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third
Then enter "python ex13.py first 2nd 3rd" on command line and should output:
The script is called: ex13.py
Your first variable is: first
Your second variable is: 2nd
Your third variable is: 3rd
However, I am using Aptana Studio 3 on Vista and I get the "ValueError: too
many values to unpack" error.
I am new to Python and Aptana so how can I enter the separate arguments here?
Answer: It's because `len(argv)` might be greater than 4:
>>> w,x,y,z=[1,2,3,4,5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
Try printing `argv` to see what `argv` actually contains.
|
Matplotlib savefig to BytesIO is slightly wrong?
Question: I'm trying to save [matplotlib](/questions/tagged/matplotlib "show questions
tagged 'matplotlib'") figures to a memory stream, exactly as in another
example on SO:
import matplotlib.pyplot as plt
import io
plt.figure()
plt.plot([1, 2])
plt.title("test")
buf = io.BytesIO()
plt.savefig(buf, format = 'png')
plt.savefig("real.png", format = 'png')
buf.seek(0)
data = buf.read()
buf.close()
f = open('copy.png', 'w')
f.write(data)
f.close()
I find that copy.png is slightly larger in size and applications refuse to
open it. Is this some sort of encoding issue?
**Background** :
I'm trying to use python.net to render graphs with matplotlib and pass them
out to C# for drawing. I want to avoid writing the images to disk. Ideally, I
want to write to some sort of byte array that I can work with in C#.
Answer: Try opening the file in binary mode.
`f = open('copy.png', 'wb')`
From the documentation:
> Python on Windows makes a distinction between text and binary files; the
> end-of-line characters in text files are automatically altered slightly when
> data is read or written. This behind-the-scenes modification to file data is
> fine for ASCII text files, but it’ll corrupt binary data like that in JPEG
> or EXE files. Be very careful to use binary mode when reading and writing
> such files.
|
Bottle Microframework does not close the socket once is closed
Question: I ran an API RestFul with bottle and python, all works fine, the API is a
daemon running in the system, if I stop the daemon by command line the service
stop very well and closed all the port and connections, but when I go to close
the service through the API, the port keep alive in state LISTEN and later in
TIME_WAIT, it does not liberate the port. I've read for two days but the
problem is because bottle have a socket and it does not close the server well,
but I can find he solution
The code to close the API as a service is a subprocess launched by python like
this
@get('/v1.0/services/<id_service>/restart')
def restart_service(id_service):
try:
service = __find_a_specific_service(id_service)
if(service == None or len(service) < 1):
logging.warning("RESTful URI: /v1.0/services/<id_service>/restart " + id_service +" , restart a specific service, service does not exists")
response.status = utils.CODE_404
return utils.convert_to_json(utils.FAILURE, utils.create_failed_resource(utils.WARNING, utils.SERVICES_API_SERVICE_NOT_EXIST))
else:
if id_service != "API":
api.ServiceApi().restart(id_service)
else:
import subprocess
args='/var/lib/stackops-head/bin/apirestd stop; sleep 5; /var/lib/stackops-head/bin/apirestd start'
subprocess.Popen(args, shell=True)
logging.info("RESTful URI: /v1.0/services/<id_service>/restart " + id_service +" , restart a specific service, ready to construct json response...")
return utils.convert_to_json(utils.SERVICE, None)
except Exception, e:
logging.error("Services: Error during the process of restart a specific service. %r", e)
raise HTTPError(code=utils.CODE_500, output=e.message, exception=e, traceback=None, head
Answer: To terminate a bottle process from the outside, send SIGINT.
|
Python ValueError: too many values to unpack with glob
Question: I'm trying to load two sets of CSV files and do some calculations on both such
as difference of each set, mean absolute error `set1 - set2` exc.
I'm trying to load both sets like this:
import glob
for a, b in (glob.glob("*a.csv"), glob.glob("*b.csv")):
And I get the error:
ValueError: too many values to unpack
Answer: # The Problem
You are getting the `ValueError` because you are trying to assign more items
to the tuple than the number of target variables you provide. The for loop
tuple unpacking syntax will loop through each list in your tuple and attempt
to assign each value in the tuple to your targets (`a` and `b`). For instance,
this would work:
for a,b in (['0a.csv', '1a.csv'], ['0b.csv', '1b.csv']):
print a,b
It assigns the first value of each list to `a` and the second value to `b`.
The code above prints:
0a,csv 1a.csv
0b.csv 1b.csv
Thus, you are getting the `ValueError` because the results from at least one
of your `glob.glob` calls is a list longer than two elements.
# A Solution
Based on what you are trying to do, I think you want to use
[`zip`](http://docs.python.org/library/functions.html#zip).
import glob
for a,b in zip(glob.glob("*a.csv"), glob.glob("*b.csv")):
# whatever
That will take pairs of files matching the pattern you gave and assign them to
`a` and `b`. For example, if you have files `0a.csv`, `1a.csv`, `2a.csv`,
`0b.csv`, `1b.csv`, and `2b.csv` doing
for a,b in zip(glob.glob("*a.csv"), glob.glob("*b.csv")):
print a, b
results in
0a.csv 0b.csv
1a.csv 1b.csv
2a.csv 2b.csv
|
How to get pubsub to work with pyinstaller?
Question: I'm trying to use pyinstaller to build an exe from my python code. One of the
modules I'm using is pubsub (pypubsub really. It used to be a part of
wxpython). I'm getting errors when I try to run the exe. It complains
"ImportError: No module named listenerimpl".
I've seen some articles about getting wx.lib.pubsub to work (it has known
issues with pyinstaller). I've tried the solutions presented in those articles
(slightly modified to account for it not being a part of wx anymore) but no
luck.
I can get past the initial "ImportError: No module named listenerimpl" error
by adding the path to the right listenerimpl (the kwargs one) to the list of
files for Analysis in my spec file but then I hit further errors on importing
"publisher". That error isn't fixed by adding its path in the spec file.
I think the solution shouldn't involve adding the path to listenerimpl.py in
my spec file... but I'm not sure how to get this working happily.
extra info
* using pubsub version: 3.1.1b1.201005.r243
* using pyinstaller version: 2.0
* platform: win7
Answer: pubsub problems solved (although exe still not running).
So if you look at comments [here](http://www.pyinstaller.org/ticket/312)
(especially comment #15 by sebastian.hilbert) it mostly solves the problems
with some tweaking.
The necessary tweaks.
1. Change the names on the hook files to hook-pubsub.core.py and hook-pubsub.setuparg1.py.
2. Internal to those files you should get rid of references to wx.
3. Enable the hook files. You can do this one of two ways. The easy way is to drop these new hook files into 'pyinstaller-2.0\PyInstaller\hooks' which is where pyinstaller looks for hooks by default. The clean/nice way to do this is to put these hooks into their own folder and add that folder as hookspath in your spec file.
NB: It was not clear to me how to add a hookspath. In your specfile, in the
call to Analyze, there is a hookspath arg. It wants a list not a string. So
you want to do something like hookspath=['path1', 'path2', etc].
NB2: Additionally if you ask for "path.dirname(path.abspath(__file__))" you
will get the directory for pyinstaller not the location where your spec file
lives.
|
Installing a .tar.bz2 in windows
Question: I am a newbie to installing python extensions working on Windows 7, running
Python 2.6 - I need to install the Levenshtein library from
[http://code.google.com/p/pylevenshtein/downloads/detail?name=python-
Levenshtein-0.10.1.tar.bz2&can=2&q=](http://code.google.com/p/pylevenshtein/downloads/detail?name=python-
Levenshtein-0.10.1.tar.bz2&can=2&q=)
When I unzip the downloaded file, it gives me the following list of files:
* COPYING
* gendoc.sh
* Levenshtein.c
* Levenshtein.h
* MANIFEST
* NEWS
* PKG-INFO
* README
* setup.cfg
* setup.py
* StringMatcher.py
How do I install the Levenshtein library so I could import and use it into my
python code?
Answer: Here is quite a large section of the documentation easily found by doing some
**research**.
<http://docs.python.org/install/index.html>
It appears that you will want to run:
python setup.py install --prefix="\Temp\Python"
to install modules to the \Temp\Python directory on the current drive.
Some more info:
> If you don’t choose an installation directory—i.e., if you just run setup.py
> install—then the install command installs to the standard location for
> third-party Python modules.
>
> The default installation directory on Windows was C:\Program Files\Python
> under Python 1.6a1, 1.5.2, and earlier.
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.