text
stringlengths 226
34.5k
|
---|
closing files properly opened with urllib2.urlopen()
Question: I have following code in a python script
try:
# send the query request
sf = urllib2.urlopen(search_query)
search_soup = BeautifulSoup.BeautifulStoneSoup(sf.read())
sf.close()
except Exception, err:
print("Couldn't get programme information.")
print(str(err))
return
I'm concerned because if I encounter an error on `sf.read()`, then
`sf.clsoe()` is not called. I tried putting `sf.close()` in a `finally` block,
but if there's an exception on `urlopen()` then there's no file to close and I
encounter an exception in the `finally` block!
So then I tried
try:
with urllib2.urlopen(search_query) as sf:
search_soup = BeautifulSoup.BeautifulStoneSoup(sf.read())
except Exception, err:
print("Couldn't get programme information.")
print(str(err))
return
but this raised a invalid syntax error on the `with...` line. How can I best
handle this, I feel stupid!
As commenters have pointed out, I am using Pys60 which is python 2.5.4
Answer: I would use contextlib.closing (in combination with from __future__ import
with_statement for old Python versions):
from contextlib import closing
with closing(urllib2.urlopen('http://blah')) as sf:
search_soup = BeautifulSoup.BeautifulStoneSoup(sf.read())
Or, if you want to avoid the with statement:
try:
sf = None
sf = urllib2.urlopen('http://blah')
search_soup = BeautifulSoup.BeautifulStoneSoup(sf.read())
finally:
if sf:
sf.close()
Not quite as elegant though.
|
Python 2.6 to 2.5 cheat sheet
Question: I've written my code to target Python 2.6.5, but I now need to run it on a
cluster that only has 2.5.4, something that wasn't on the horizon when I wrote
the code. Backporting the code to 2.5 shouldn't be too hard, but I was
wondering if there was either a cheat-sheet or an automated tool that would
help me with this. For some things, like the `with` statement, the right
`__future__` imports will do the trick, but not for some other things.
Answer: Have you read the [What's New in Python
2.6](http://docs.python.org/whatsnew/2.6.html) document? It describes the
2.5->2.6 direction, but you should be able to figure out the reverse from it.
As far as I know, there are no automated tools for 2.6 to 2.5. The only tool I
know of is the 2to3 app for going to Python 3.
|
Google App Engine Python: sys.path.append not working online
Question: I have this
import sys
sys.path.append('extra_dir')
import extra_module
It work perfectly under Windows XP App Engine SDK (offline)
But when deploy online, it give me `<type 'exceptions.ImportError'>`, what am
I missing to deploy it online?
Answer: Try this:
sys.path.append(os.path.join(os.path.dirname(__file__), 'extra_dir'))
|
python - strtotime equivalent?
Question: I'm using this to convert date time strings to a unix timestamp:
str(int(time.mktime(time.strptime(date,"%d %b %Y %H:%M:%S %Z"))))
However often the date structure isn't the same so I keep getting the
following error message:
> time data did not match format: data=Tue, 26 May 2009 19:58:20 -0500 fmt=%d
> %b %Y %H:%M:%S %Z
Does anyone know of any simply function to convert a string representation of
a date/time to a unix timestamp in python? I really don't want to have to open
a process to call a php script to echo the timestamp everytime time in a loop
:)
Answer:
from dateutil.parser import parse
parse('Tue, 26 May 2009 19:58:20 -0500').strftime('%s')
# returns '1243364300'
|
Why the connect failed for ipv6 at python?
Question: Why the connect failed for ipv6 ??
# python
>>> import socket
>>> s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
>>> sa = ('2000::1',2000,0,0)
>>> s.connect(sa)
>>> sa = ('fe80::21b:78ff:fe30:7c6', 2000, 0, 0)
>>> s.connect(sa)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<string>", line 1, in connect
socket.error: (22, 'Invalid argument')
Answer: Link-local addresses (e.g. fe80::whatever) typically require a scope id to be
specified in order to work. Try
sa = ('fe80::21b:78ff:fe30:7c6%en0', 2000, 0, 0)
instead. (If the computer you're trying to connect() to is accessible via a
network interface other than en0, substitute in the name of the interface
where en0 is now)
|
Python threads and global vars
Question: Say I have the following function in a module called "firstModule.py":
def calculate():
# addCount value here should be used from the mainModule
a=random.randint(0,5) + addCount
Now I have a different module called "secondModule.py":
def calculate():
# addCount value here too should be used from the mainModule
a=random.randint(10,20) + addCount
I am running a module called "mainModule.py" which has the following (notice
the global "addCount" var):
import firstModule
import secondModule
addCount=0
Class MyThread(Thread):
def __init__(self,name):
Thread.__init__(self)
self.name=name
def run(self):
global addCount
if self.name=="firstModule":
firstModule.calculate()
if self.name=="secondModule":
secondModule.calculate()
def main():
the1=MyThread("firstModule");
the2=MyThread("secondModule");
the1.start()
the2.start()
the1.join()
the2.join()
# This part doesn't work:
print firstModule.a
print secondModule.a
Basically I want the "addCount" value in both modules to be the one from
"mainModule". After that, when the threads are finished, I want to print the
value of "a" in both of them. The example above doesn't work. I was wondering
how can I fix it.
Answer: Pass 'addCount' to the function 'calculate', return the value of 'a' in
'calculate', and assign it to a new attribute in MyThread instance.
def calculate(addCount):
a = random.randint(0, 5) + addCount
return a
|
Can't import comtypes.gen
Question: I have comtypes 0.6.2 installed on Python 2.6. If I try this:
import comtypes.gen
I get:
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
import comtypes.gen
ImportError: No module named gen
Other imports like `import comtypes` and `import comtypes.client`, however,
work fine.
What am I doing wrong?
From the name it seems `comtypes.gen` is generated code? If so, do I need
certain preparatory steps before importing? I'm _not_ logged in as
administrator. Could that cause code generation to fail?
**Edit:** The above problem is solved with a `reload(comtypes.gen)` (I don't
understand how, though). However, now `from comtypes.gen import
IWshRuntimeLibrary` is not working. This symbol should be part of a generated
code. So how do I get this code to be generated?
Answer: Well, after some experimentation, I have the solution.
I've found that:
1. Importing `comtypes.client` automatically creates the `comtypes.gen` subpackage.
2. Calling `comtypes.client.GetModule("MyComLib")` generates a wrapper for `"MyComLib"`.
So the following code did the job for me:
import os
import glob
import comtypes.client
#Generates wrapper for a given library
def wrap(com_lib):
try:
comtypes.client.GetModule(com_lib)
except:
print "Failed to wrap {0}".format(com_lib)
sys32dir = os.path.join(os.environ["SystemRoot"], "system32")
#Generate wrappers for all ocx's in system32
for lib in glob.glob(os.path.join(sys32dir, "*.ocx")):
wrap(lib)
#Generate for all dll's in system32
for lib in glob.glob(os.path.join(sys32dir, "*.tlb")):
wrap(lib)
Having the relevant COM lib wrapped, now I can access IWshRuntimeLibrary just
fine.
|
access to google with python
Question: how i can access to google !!
i had try that code
urllib.urlopen('http://www.google.com')
but it's show message `prove you are human` or some think like dat
some people say try user agent !! i dunno !
Answer: You should use the [Google API](http://code.google.com/apis/ajaxsearch/) for
accessing the search. [Here's an example for
python](http://dcortesi.com/2008/05/28/google-ajax-search-api-example-python-
code/). Unutbu provided a link to an [older SO
answer](http://stackoverflow.com/questions/1657570/google-search-from-a-
python-app/1657597#1657597) which contains a corrected version of the same
example code.
#!/usr/bin/python
import urllib, urllib2
import json
api_key, userip = None, None
query = {'q' : 'search google python api'}
referrer = "http://stackoverflow.com/q/3900610"
if userip:
query.update(userip=userip)
if api_key:
query.update(key=api_key)
url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % (
urllib.urlencode(query))
request = urllib2.Request(url, headers=dict(Referer=referrer))
json = json.load(urllib2.urlopen(request))
results = json['responseData']['results']
for r in results:
print r['title'] + ": " + r['url']
|
Apache Can't Access Django Applications
Question: so here's the setting:
The whole site is working fine if I remove the application (whose name is
myapp) in the INSTALLED_APPS section in the settings file I added
WSGIPythonHome in apache2.conf
I can successfully access the apps via the the interactive python shell in
Django (`python manage.py shell`). I can create, update and delete data.
I am using the standard Apache 2 setup for Ubuntu 10.04 Lucid Lynx(sites-
enabled, mods-enabled, apache2.conf, etc)
I am running a virtualenv located in /home/ygamretuta/dev/myproject
My django project is located in /home/ygamretuta/dev/site1
error Log file says this (last 2 lines):
File "/home/ygamretuta/dev/myproject/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module
TemplateSyntaxError: Caught ImportError while rendering: No module named myapp
my django.wsgi contains this:
import os, sys
sys.path.append('/home/ygamretuta/dev')
os.environ['DJANGO_SETTINGS_MODULE'] = 'site1.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
my virtual host file for site1.com (contained in the sites-available folder)
contains this (stripped of other details):
WSGIDaemonProcess ygamretuta processes=2 maximum-requests=500 threads=1
WSGIProcessGroup ygamretuta
WSGIScriptAlias / /home/ygamretuta/dev/site1/apache/django.wsgi
What could I have missed? I am getting e 500 Internal Server Error if the
custom apps (the ones I made with manage.py startapp) are not commented out
Answer: Append `/home/ygamretuta/dev/site1` to `sys.path`.
|
about textarea \r\n or \n in python
Question: i have tested code in firefox under ubuntu:
the frontend is a textarea,in textarea press the key ENTER,then submit to the
server,
on the backend you'll get find \r\n string
r=request.POST.get("t")
r.find("\r\n")>-1:
print "has \r\n"
my question is when we will get \r\n ,when we'll get \n?is this platform
independent?
this is important when want to use this string to use as a regular
expression,any adivse is welcome
Answer: Yes, you are correct, you are dealing with a platform-specific ways to encode
a newline:
* In Windows platforms, a newline is typically encoded as `\r\n`
* In Linux/Unix/OS X, a newline is typically encoded as `\n`
Similarly, web browsers tend to favor these conventions: IE uses `\r\n`
newlining, whereas Safari and Firefox use `\n`.
As a solution, considering using Python functions that are aware of different
new line encodings, e.g. provide a universal newline support.
For instance if you want to split a string into lines, use splitlines:
lines = r.splitlines()
|
bash/fish command to print absolute path to a file
Question: Question: is there a simple sh/bash/zsh/fish/... command to print the absolute
path of whichever file I feed it?
Usage case: I'm in directory `/a/b` and I'd like to print the full path to
file `c` on the command-line so that I can easily paste it into another
program: `/a/b/c`. Simple, yet a little program to do this could probably save
me 5 or so seconds when it comes to handling long paths, which in the end adds
up. So it surprises me that I can't find a standard utility to do this — is
there really none?
Here's a sample implementation, abspath.py:
#!/usr/bin/python
# Author: Diggory Hardy <diggory.hardy@gmail.com>
# Licence: public domain
# Purpose: print the absolute path of all input paths
import sys
import os.path
if len(sys.argv)>1:
for i in range(1,len(sys.argv)):
print os.path.abspath( sys.argv[i] )
sys.exit(0)
else:
print >> sys.stderr, "Usage: ",sys.argv[0]," PATH."
sys.exit(1)
Answer: Try `readlink` which will resolve symbolic links:
readlink -e /foo/bar/baz
|
using python module in java with jython
Question: I have a couple of python modules in an existing Python project that I wish to
make use of in my Java app.
I found an
[article](http://wiki.python.org/jython/JythonMonthly/Articles/October2006/3)
and followed the steps mentioned there. In particular, I need to import the
java interface:
package jyinterface.interfaces;
public interface EmployeeType {
.
.
}
into the module:
from jyinterface.interfaces import EmployeeType
class Employee(EmployeeType)
:
I have a question - With this method, does this means that I cannot use this
module in my existing python project after making the changes, even with a
Jython or Python interpreter?
Answer: You can use it with Jython but not with CPython, the standard implementation.
How ever, there is an effort to provide full access to java class libraries
when you use CPython.
* <http://jpype.sourceforge.net/>
|
"import numpy" results in error in one eclipse workspace, but not in another
Question: Whenever I try importing numpy in my new installation of Eclipse and Pydev, I
get the following error:
Traceback (most recent call last):
File "Q:\temp\test.py", line 1, in <module>
import numpy
File "C:\Python26\lib\site-packages\numpy\__init__.py", line 132, in <module>
import add_newdocs
File "C:\Python26\lib\site-packages\numpy\add_newdocs.py", line 9, in <module>
from lib import add_newdoc
File "C:\Python26\lib\site-packages\numpy\lib\__init__.py", line 4, in <module>
from type_check import *
File "C:\Python26\lib\site-packages\numpy\lib\type_check.py", line 8, in <module>
import numpy.core.numeric as _nx
File "C:\Python26\lib\site-packages\numpy\core\__init__.py", line 13, in <module>
import defchararray as char
File "C:\Python26\lib\site-packages\numpy\core\defchararray.py", line 23, in <module>
from numpy.core.multiarray import _vec_string
ImportError: cannot import name _vec_string
However, in a vanila python console and in IPython, import is successful
Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>>
Q:\Groups\Bioinformatics\HPLCautomatization\autohplc>ipython
Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)]
Type "copyright", "credits" or "license" for more information.
IPython 0.10 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object'. ?object also works, ?? prints more.
In [2]: import numpy
To make stuff even more complicated, in another Eclipse workspace, this import
works fine. Restarting eclipse didn't help. I also tried to re-config the
interpreter in Preferences->python->interpreter->python (as in [this
question](http://stackoverflow.com/questions/2767808/eclipse-and-python-
library-will-import-in-interprer-but-not-in-ide)), but the problem still
exists
Two additional similar problems were described on SO
([this](http://stackoverflow.com/questions/3613409/loading-numpy-into-
ironpython) and [this](http://stackoverflow.com/questions/3069820/ironpython-
call-numpy-problem)), but both of them were observed with IronPython and I
couldn't find anything I could use in the few answers that were provided.
**EDIT** As [suggested by
dutt](http://stackoverflow.com/questions/3921950/import-numpy-results-in-
error-in-one-eclipse-workspace-but-not-in-another/3922008#3922008), I checked
Preferences->Pydev->Interpreter python->libraries in both the tested
workspaces (the working one and the one that doesn't). The malfunctioning
workspace contained the following library in system libs C:\Python26\lib\site-
packages\numpy-1.5.0-py2.6-win32.egg . On the other hand, the working
workspace doesn't list any _numpy_ library in its system libraries list. I
have removed the above library from the list in the not working workspace.
Answer: (Assuming you'r using PyDev) Look in Preferences->Pydev->Interpreter-
Python->Libaries, you may have to add NumPy there. Should be located in your
python/lib/site-packages folder.
|
translating arrays from c to python ctypes
Question: I have the below arrays on C how can i interpert them to ctypes datatypes
inside structre
struct a {
BYTE a[30];
CHAR b[256];
};
should i interpert a fixed array as the datatype * the size i want like the
below and if yes how can i call this structure as a parameter to fun that
takes instance from this structure
class a(structure) :
_fields_ = [ ("a",c_bytes*30 ),
("b",c_char*256 ),]
Answer: You're on the right track. You're probably just missing the `byref()`
function. Assuming the function you want to call is named *print_struct*, do
the following:
from ctypes import *
class MyStruct(Structure):
_fields_ = [('a',c_byte*30), ('b',c_char*256)]
s = MyStruct() # Allocates a new instance of the structure from Python
s.a[5] = 10 # Use as normal
d = CDLL('yourdll.so')
d.print_struct( byref(s) ) # byref() passes a pointer rather than passing by copy
|
500 Error when sending file from python to django
Question: I've found a nice python module for sending data to remote servers via HTTP
POST called [**poster**](http://atlee.ca/software/poster/). So I've wrote a
simple view on my django app to receive and store data and then tried to send
some file. Unfortunately even though I've set everything as it was shown in
the instruction I'm getting `Internal Server Error`. Can anyone maybe see what
am I doing wrong ?
Here's the view function :
def upload(request):
for key, file in request.FILES.items():
path = '/site_media/remote/'+ file.name
dest = open(path.encode('utf-8'), 'wb+')
if file.multiple_chunks:
for c in file.chunks():
dest.write(c)
else:
dest.write(file.read())
dest.close()
Here's the module instruction : **<http://atlee.ca/software/poster/>** and
some instruction I was basing on **<http://www.laurentluce.com/?p=20>**
Here's the traceback:
In [15]: print urllib2.urlopen(request).read()
-------> print(urllib2.urlopen(request).read())
---------------------------------------------------------------------------
HTTPError Traceback (most recent call last)
/home/rails/ntt/<ipython console> in <module>()
/bin/python-2.6.2/lib/python2.6/urllib2.pyc in urlopen(url, data, timeout)
122 if _opener is None:
123 _opener = build_opener()
--> 124 return _opener.open(url, data, timeout)
125
126 def install_opener(opener):
/bin/python-2.6.2/lib/python2.6/urllib2.pyc in open(self, fullurl, data, timeout)
387 for processor in self.process_response.get(protocol, []):
388 meth = getattr(processor, meth_name)
--> 389 response = meth(req, response)
390
391 return response
/bin/python-2.6.2/lib/python2.6/urllib2.pyc in http_response(self, request, response)
500 if not (200 <= code < 300):
501 response = self.parent.error(
--> 502 'http', request, response, code, msg, hdrs)
503
504 return response
/bin/python-2.6.2/lib/python2.6/urllib2.pyc in error(self, proto, *args)
425 if http_err:
426 args = (dict, 'default', 'http_error_default') + orig_args
--> 427 return self._call_chain(*args)
428
429 # XXX probably also want an abstract factory that knows when it makes
/bin/python-2.6.2/lib/python2.6/urllib2.pyc in _call_chain(self, chain, kind, meth_name, *args)
359 func = getattr(handler, meth_name)
360
--> 361 result = func(*args)
362 if result is not None:
363 return result
/bin/python-2.6.2/lib/python2.6/urllib2.pyc in http_error_default(self, req, fp, code, msg, hdrs)
508 class HTTPDefaultErrorHandler(BaseHandler):
509 def http_error_default(self, req, fp, code, msg, hdrs):
--> 510 raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
511
512 class HTTPRedirectHandler(BaseHandler):
HTTPError: HTTP Error 500: Internal Server Error
I get the same error when I'm trying to send my file to a php function (from
**www.w3schools.com/php/php_file_upload.asp**
Also I've checked with wireshark and my POST request is sent without any
problems but then something bad happens and I'm getting this 500. May it be
that the server is somehow limited ? Uploading files in applications running
on it works fluently.
* * *
Placing this view function with url on different server, and running :
import httplib
conn = httplib.HTTPConnection("address")
f = open("file, "rb")
conn.request("POST","/upload", f, headers)
response = conn.getresponse()
Raised : `BadStatusLine` exception.
Answer: This is a basic Python question. You need to import a module before you can
use it. So just do `import urllib` at the top of the script and it should
work.
|
Python Method Placement
Question: Can someone give me a solution to this
dosomething()
def dosomething():
print 'do something'
I don't want my method defines up at the top of the file, is there a way
around this?
Answer: The "standard" way is to do things inside a `main` function at the top of your
file and then call `main()` at the bottom. E.g.
def main():
print 'doing stuff'
foo()
bar()
def foo():
print 'inside foo'
def bar():
print 'inside bar'
if __name__ == '__main__':
main()
if `if __name__ == '__main__':` part ensures that `main()` won't be called if
the file is imported into another python program, but is only called when the
file is run directly.
Of course, "main" doesn't mean anything... (`__main__` does, however!) It's a
psuedo-convention, but you could just as well call it `do_stuff`, and then
have `if __name__ == '__main__': do_stuff()` at the bottom.
Edit: You might also want to see [Guido's advice on writing
`main`'s](http://www.artima.com/weblogs/viewpost.jsp?thread=4829). Also,
Daenyth makes an excellent point (and beat me to answering): The reason why
you should do something like this isn't that is "standard" or even that it
allows you to define functions below your "main" code. The reason you should
do it is that it encourages you to write _modular and reusable_ code.
|
Python filter / max combo - checking for empty iterator
Question: (Using Python 3.1)
I know this question has been asked many times for the general question of
testing if iterator is empty; obviously, there's no neat solution to that (I
guess for a reason - an iterator doesn't really know if it's empty until it's
asked to return its next value).
I have a specific example, however, and was hoping I can make clean and
Pythonic code out of it:
#lst is an arbitrary iterable
#f must return the smallest non-zero element, or return None if empty
def f(lst):
flt = filter(lambda x : x is not None and x != 0, lst)
if # somehow check that flt is empty
return None
return min(flt)
Is there any better way to do that?
EDIT: sorry for the stupid notation. The parameter to the function is indeed
an arbitrary iterable, rather than a list.
Answer:
def f(lst):
flt = filter(lambda x : x is not None and x != 0, lst)
try:
return min(flt)
except ValueError:
return None
`min` throws `ValueError` when the sequence is empty. This follows the common
"Easier to Ask for Forgiveness" paradigm.
EDIT: A reduce-based solution without exceptions
from functools import reduce
def f(lst):
flt = filter(lambda x : x is not None and x != 0, lst)
m = next(flt, None)
if m is None:
return None
return reduce(min, flt, m)
|
Searching a normal query in an inverted index
Question: I have a full inverted index in form of nested python dictionary. Its
structure is :
**{word : { doc_name : [location_list] } }**
For example let the dictionary be called index, then for a word " spam ",
entry would look like :
{ spam : { doc1.txt : [102,300,399], doc5.txt : [200,587] } }
so that, the documents containing any word can be given by
_index[word].keys()_ , and frequency in that document by
_len(index[word][document])_
Now my question is, how do I implement a normal query search in this index.
i.e. given a query containing lets say 4 words, find documents containing all
four matches (ranked by total frequency of occurrence ), then docs containing
3 matches and so on ....
**
> Added this code, using S. Lott's answer. This is the code I have written.
> Its working exactly as I want, ( just some formatting of output is needed )
> but I know it could be improved.
**
from collections import defaultdict
from operator import itemgetter
# Take input
query = input(" Enter the query : ")
# Some preprocessing
query = query.lower()
query = query.strip()
# now real work
wordlist = query.split()
search_words = [ x for x in wordlist if x in index ] # list of words that are present in index.
print "\nsearching for words ... : ", search_words, "\n"
doc_has_word = [ (index[word].keys(),word) for word in search_words ]
doc_words = defaultdict(list)
for d, w in doc_has_word:
for p in d:
doc_words[p].append(w)
# create a dictionary identifying matches for each document
result_set = {}
for i in doc_words.keys():
count = 0
matches = len(doc_words[i]) # number of matches
for w in doc_words[i]:
count += len(index[w][i]) # count total occurances
result_set[i] = (matches,count)
# Now print in sorted order
print " Document \t\t Words matched \t\t Total Frequency "
print '-'*40
for doc, (matches, count)) in sorted(result_set.items(), key = itemgetter(1), reverse = True):
print doc, "\t",doc_words[doc],"\t",count
Pls comment .... Thanx.
Answer: Here's a start:
doc_has_word = [ (index[word].keys(),word) for word in wordlist ]
This will build an list of (word,document) pairs. You can't easily make a
dictionary out of that, since each document occurs many times.
But
from collections import defaultdict
doc_words = defaultdict(list)
for d, w in doc_has_word:
doc_words[tuple(d.items())].append(w)
Might be helpful.
|
Eclipse PyDev now shows all references to Tkinter as errors
Question: I've been using Eclipse with PyDev (on Windows, mind you) for my Python
Tkinter project for about a month now, and up until recently I've had no
complaints. I start the source for one module (my GUI) like so:
from Tkinter import *
Now, ever since I updated Eclipse to 3.6.1, it shows an error for every call
to the Tkinter module(`Frame()`, `Label()`, `Tk()`, etc.). I thought that
something might have gone wrong during the update, so I uninstalled Eclipse,
re-downloaded it (Eclipse 3.6.1 Classic), and reinstalled it. Then, seeing
that that gave me a bunch of errors with installing PyDev, I removed that, got
Eclipse 3.6.0 Classic, installed it, and got the same problem I was trying to
fix earlier.
I don't understand what's wrong here. It doesn't make any sense to me why all
of a sudden Eclipse would stop recognizing that I had imported Tkinter.
Can anyone offer any suggestions/input? I really want to stick with Eclipse,
I'm very happy with it, but I can't deal with it giving me about 200 bogus
errors.
Answer: You really shouldn't use wild imports. Consider `from Tkinter import Frame,
Label` or `import Tkinter as tk` instead.
Now to your problem: I have Eclipse Helios, too (3.6.0.v20100602). The problem
you describe clearly has to do with PyDev, not with the Eclipse base project.
I just tried the same import and didn't get error messages. My PyDev version
also retrieves the docstring of `Frame` correctly, for example.
I think it boils to just installing a newer version of PyDev (this is the
solution for many bugs ^^) - add "http://pydev.org/nightly" as an update site
and then upgrade to the latest version. I have version 1.6.3.20100922, by the
way. If that doesn't help, you should consider reporting it as a bug.
|
Does python urllib2 automatically uncompress gzip data fetched from webpage?
Question: I'm using
data=urllib2.urlopen(url).read()
I want to know:
1. How can I tell if the data at a URL is gzipped?
2. Does urllib2 automatically uncompress the data if it is gzipped? Will the data always be a string?
Answer: > 1. How can I tell if the data at a URL is gzipped?
>
This checks if the content is gzipped and decompresses it:
from StringIO import StringIO
import gzip
request = urllib2.Request('http://example.com/')
request.add_header('Accept-encoding', 'gzip')
response = urllib2.urlopen(request)
if response.info().get('Content-Encoding') == 'gzip':
buf = StringIO(response.read())
f = gzip.GzipFile(fileobj=buf)
data = f.read()
> 2. Does urllib2 automatically uncompress the data if it is gzipped? Will
> the data always be a string?
>
No. The urllib2 doesn't automatically uncompress the data because the 'Accept-
Encoding' header is not set by the urllib2 but by you using:
`request.add_header('Accept-Encoding','gzip, deflate')`
|
Is there a more Pythonic approach to this?
Question: This is my first python script, be ye warned.
I pieced this together from Dive Into Python, and it works great. However
since it is my first Python script I would appreciate any tips on how it can
be made better or approaches that may better embrace the Python way of
programming.
import os
import shutil
def getSourceDirectory():
"""Get the starting source path of folders/files to backup"""
return "/Users/robert/Music/iTunes/iTunes Media/"
def getDestinationDirectory():
"""Get the starting destination path for backup"""
return "/Users/robert/Desktop/Backup/"
def walkDirectory(source, destination):
"""Walk the path and iterate directories and files"""
sourceList = [os.path.normcase(f)
for f in os.listdir(source)]
destinationList = [os.path.normcase(f)
for f in os.listdir(destination)]
for f in sourceList:
sourceItem = os.path.join(source, f)
destinationItem = os.path.join(destination, f)
if os.path.isfile(sourceItem):
"""ignore system files"""
if f.startswith("."):
continue
if not f in destinationList:
"Copying file: " + f
shutil.copyfile(sourceItem, destinationItem)
elif os.path.isdir(sourceItem):
if not f in destinationList:
print "Creating dir: " + f
os.makedirs(destinationItem)
walkDirectory(sourceItem, destinationItem)
"""Make sure starting destination path exists"""
source = getSourceDirectory()
destination = getDestinationDirectory()
if not os.path.exists(destination):
os.makedirs(destination)
walkDirectory(source, destination)
Answer: As others mentioned, you probably want to use `walk` from the built-in `os`
module. Also, consider using [PEP 8 compatible
style](http://www.python.org/dev/peps/pep-0008/) (no camel-case but
`this_stye_of_function_naming()`). Wrapping directly executable code (i.e. no
library/module) into a `if __name__ == '__main__': ...` block is also a good
practice.
|
C++\IronPython integration example code?
Question: I'm looking for a **simple** example code for **C++\IronPython integration** ,
i.e. embedding python code inside a C++, or better yet, Visual C++ program.
The example code should include: how to share objects between the languages,
how to call functions\methods back and forth etc...
Also, an explicit setup procedure would help too. (How to include the Python
runtime dll in Visual Studio etc...)
I've found a nice example for C#\IronPython
[here](http://www.codeproject.com/KB/dotnet/ironpython.aspx), but couldn't
find C++\IronPython example code.
Answer: UPDATE - I've written a more generic example (plus a link to a zip file
containing the entire VS2008 project) as entry on my blog
[here.](http://oldschooldotnet.blogspot.com/2011/04/scripting-ccli-with-
ironpython-visual.html "here.")
Sorry, I am so late to the game, but here is how I have integrated IronPython
into a C++/cli app in Visual Studio 2008 - .net 3.5. (actually mixed mode app
with C/C++)
I write add-ons for a map making applicaiton written in Assembly. The API is
exposed so that C/C++ add-ons can be written. I mix C/C++ with C++/cli. Some
of the elements from this example are from the API (such as XPCALL and
CmdEnd() - please just ignore them)
///////////////////////////////////////////////////////////////////////
void XPCALL PythonCmd2(int Result, int Result1, int Result2)
{
if(Result==X_OK)
{
try
{
String^ filename = gcnew String(txtFileName);
String^ path = Assembly::GetExecutingAssembly()->Location;
ScriptEngine^ engine = Python::CreateEngine();
ScriptScope^ scope = engine->CreateScope();
ScriptSource^ source = engine->CreateScriptSourceFromFile(String::Concat(Path::GetDirectoryName(path), "\\scripts\\", filename + ".py"));
scope->SetVariable("DrawingList", DynamicHelpers::GetPythonTypeFromType(AddIn::DrawingList::typeid));
scope->SetVariable("DrawingElement", DynamicHelpers::GetPythonTypeFromType(AddIn::DrawingElement::typeid));
scope->SetVariable("DrawingPath", DynamicHelpers::GetPythonTypeFromType(AddIn::DrawingPath::typeid));
scope->SetVariable("Node", DynamicHelpers::GetPythonTypeFromType(AddIn::Node::typeid));
source->Execute(scope);
}
catch(Exception ^e)
{
Console::WriteLine(e->ToString());
CmdEnd();
}
}
else
{
CmdEnd();
}
}
///////////////////////////////////////////////////////////////////////////////
As you can see, I expose to IronPython some objects (DrawingList,
DrawingElement, DrawingPath & Node). These objects are C++/cli objects that I
created to expose "things" to IronPython.
When the C++/cli source->Execute(scope) line is called, the only python line
to run is the DrawingList.RequestData.
RequestData takes a delegate and a data type.
When the C++/cli code is done, it calls the delegate pointing to the function
"diamond"
In the function diamond it retrieves the requested data with the call to
DrawingList.RequestedValue() The call to DrawingList.AddElement(dp) adds the
new element to the Applications visual Database.
And lastly the call to DrawingList.EndCommand() tells the FastCAD engine to
clean up and end the running of the plugin.
import clr
def diamond(Result1, Result2, Result3):
if(Result1 == 0):
dp = DrawingPath()
dp.drawingStuff.EntityColor = 2
dp.drawingStuff.SecondEntityColor = 2
n = DrawingList.RequestedValue()
dp.Nodes.Add(Node(n.X-50,n.Y+25))
dp.Nodes.Add(Node(n.X-25,n.Y+50))
dp.Nodes.Add(Node(n.X+25,n.Y+50))
dp.Nodes.Add(Node(n.X+50,n.Y+25))
dp.Nodes.Add(Node(n.X,n.Y-40))
DrawingList.AddElement(dp)
DrawingList.EndCommand()
DrawingList.RequestData(diamond, DrawingList.RequestType.PointType)
I hope this is what you were looking for.
|
Is it possible to use Python to measure response time?
Question: I'm running some experiments and I need to precisely measure participants'
response time to questions. I know there are some commercial software, but I
was wondering if I can do this with Python. Does python provides suitable
functionality to measure the response time in millisecond unit?
Thank you, Joon
Answer: Just do something like this:
from time import time
starttime = time()
askQuestion()
timetaken = time() - starttime
|
python circular imports once again (aka what's wrong with this design)
Question: Let's consider python (3.x) scripts:
main.py:
from test.team import team
from test.user import user
if __name__ == '__main__':
u = user()
t = team()
u.setTeam(t)
t.setLeader(u)
test/user.py:
from test.team import team
class user:
def setTeam(self, t):
if issubclass(t, team.__class__):
self.team = t
test/team.py:
from test.user import user
class team:
def setLeader(self, u):
if issubclass(u, user.__class__):
self.leader = u
Now, of course, i've got circular import and splendid ImportError.
So, not being pythonista, I have three questions. First of all:
i. How can I make this thing work ?
And, knowing that someone will inevitably say "Circular imports always
indicate a design problem", the second question comes:
ii. Why is this design bad?
And the finally, third one:
iii. What would be better alternative?
To be precise, type checking as above is only an example, there is also a
index layer based on class, which permits ie. find all users being members of
one team (user class has many subclasses, so index is doubled, for users in
general and for each specific subclass) or all teams having given user as a
member
**Edit:**
I hope that more detailed example will clarify what i try to achieve. Files
omitted for readibility (but having one 300kb source file scares me somehow,
so please assume that every class is in different file)
# ENTITY
class Entity:
_id = None
_defs = {}
_data = None
def __init__(self, **kwargs):
self._id = uuid.uuid4() # for example. or randint(). or x+1.
self._data = {}.update(kwargs)
def __settattr__(self, name, value):
if name in self._defs:
if issubclass(value.__class__, self._defs[name]):
self._data[name] = value
# more stuff goes here, specially indexing dependencies, so we can
# do Index(some_class, name_of_property, some.object) to find all
# objects of some_class or its children where
# given property == some.object
else:
raise Exception('Some misleading message')
else:
self.__dict__[name] = value
def __gettattr__(self, name):
return self._data[name]
# USERS
class User(Entity):
_defs = {'team':Team}
class DPLUser(User):
_defs = {'team':DPLTeam}
class PythonUser(DPLUser)
pass
class PerlUser(DPLUser)
pass
class FunctionalUser(User):
_defs = {'team':FunctionalTeam}
class HaskellUser(FunctionalUser)
pass
class ErlangUser(FunctionalUser)
pass
# TEAMS
class Team(Entity):
_defs = {'leader':User}
class DPLTeam(Team):
_defs = {'leader':DPLUser}
class FunctionalTeam(Team):
_defs = {'leader':FunctionalUser}
and now some usage:
t1 = FunctionalTeam()
t2 = DLPTeam()
t3 = Team()
u1 = HaskellUser()
u2 = PythonUser()
t1.leader = u1 # ok
t2.leader = u2 # ok
t1.leader = u2 # not ok, exception
t3.leader = u2 # ok
# now , index
print(Index(FunctionalTeam, 'leader', u2)) # -> [t2]
print(Index(Team, 'leader', u2)) # -> [t2,t3]
So, it works great (implementation details ommitted, but there is nothing
complicated) besides of this unholy circular import thing.
Answer: Circular imports are not inherently a bad thing. It's natural for the `team`
code to rely on `user` whilst the `user` does something with `team`.
The worse practice here is `from module import member`. The `team` module is
trying to get the `user` class at import-time, and the `user` module is trying
to get the `team` class. But the `team` class doesn't exist yet because you're
still at the first line of `team.py` when `user.py` is run.
Instead, import only modules. This results in clearer namespacing, makes later
monkey-patching possible, and solves the import problem. Because you're only
importing the _module_ at import-time, you don't care than the _class_ inside
it isn't defined yet. By the time you get around to using the class, it will
be.
So, test/users.py:
import test.teams
class User:
def setTeam(self, t):
if isinstance(t, test.teams.Team):
self.team = t
test/teams.py:
import test.users
class Team:
def setLeader(self, u):
if isinstance(u, test.users.User):
self.leader = u
`from test import teams` and then `teams.Team` is also OK, if you want to
write `test` less. That's still importing a module, not a module member.
Also, if `Team` and `User` are relatively simple, put them in the same module.
You don't need to follow the Java one-class-per-file idiom. The `isinstance`
testing and `set` methods also scream unpythonic-Java-wart to me; depending on
what you're doing you may very well be better off using a plain, non-type-
checked `@property`.
|
Python codes runs using idle but fails on command line?
Question: I am learning Python, and I have written a script per an example in the book I
am reading where it imports the urllib library. This works fine when I run it
from IDLE, but if I go to the folder where the file is and run "python
test.py" I get an error where it tells me that
Traceback (most recent call last):
File "test.py", line 1, in ?
import urllib.request
ImportError: No module named request
I verified that I am using Python 3.1.2. Any suggestions or ideas why this
fails on the command line?
My code:
import urllib.request
import time
price = 99.99
while price > 1.01:
time.sleep(3)
page = urllib.request.urlopen("http://www.beans-r-us.biz/prices.html")
text = page.read().decode("utf8")
where = text.find('>$')
start_of_price = where + 2
end_of_price = start_of_price + 4
price = float(text[start_of_price:end_of_price])
print ("Buy!")
Answer: `urllib.request` was introduced with Python 3. It is very possible that when
you run the code from the command line, you are using an older, Python 2.x
binary.
Type `python --version` on the command line to see which Python is being used.
**Edit in response to Drewdin's comment**
Running the Python 3.1.2 installer for Mac OS X, I see this:
> NOTE: This package will by default not update your shell profile and will
> also not install files in /usr/local. Double-click Update Shell Profile at
> any time to make 3.1.2 the default Python.
>
> The installer puts the applications in "Python 3.1" in your Applications
> folder, and the underlying machinery in
> /Library/Frameworks/Python.framework. It can optionally place links to the
> command-line tools in /usr/local as well, by default you have to add the
> "bin" directory inside the framework to you shell's search path.
So depending on how you installed it, you may already have links placed in
`/usr/local/bin`, which will be in your path. If you chose this option at
install time, all you should have to do is type `python3` or `python3.1` in
your shell to get the updated version.
Otherwise, either double click that "Update Shell Profile", or add this to
your path:
`export PATH=$PATH:/Library/Frameworks/Python.framework/Versions/3.1/bin`
By default, Python 3.x does not make the `python` command alias in Unix/Linux
environments because it could possibly interfere with system
processes/commands dependent on the default-installed Python.
|
What are important languages to learn to understand different approaches and concepts?
Question: When all you have is a pair of bolt cutters and a bottle of vodka, everything
looks like the lock on the door of Wolf Blitzer's boathouse. (Replace that
with a hammer and a nail if you don't read xkcd)
I currently program Clojure, Python, Java and PHP, so I am familiar with the C
and LISP syntax as well as the whitespace thing. I know imperative,
functional, immutable, OOP and a couple type systems and other things. Now I
want more!
What are languages that take a different approach and would be useful for
either practical tool choosing or theoretical understanding?
I don't feel like learning another functional language(Haskell) or another
imperative OOP language(Ruby), nor do I want to practice impractical fun
languages like Brainfuck.
One very interesting thing I found myself are monoiconic stack based languages
like Factor.
Only when I feel I understand most concepts and have answers to all my
questions, I want to start thinking about my own toy language to contain all
my personal preferences.
Answer: Matters of practicality are highly subjective, so I will simply say that
learning different language paradigms will only serve to make you a better
programmer. What is more practical than that?
_Functional, Haskell_ \- I know you said that you didn't want to, but you
should really really reconsider. You've gotten some functional exposure with
Clojure and even Python, but you've not experienced it to its fullest without
Haskell. If you're really against Haskell then good compromises are either ML
or OCaml.
_Declarative, Datalog_ \- Many people would recommend Prolog in this slot, but
I think Datalog is a cleaner example of a declarative language.
_Array, J_ \- I've only just discovered J, but I find it to be a stunning
language. It will twist your mind into a pretzel. You will thank J for that.
_Stack, Factor/Forth_ \- Factor is very powerful and I plan to dig into it
ASAP. Forth is the grand-daddy of the Stack languages, and as an added bonus
it's [simple to implement](http://github.com/fogus/rforth) yourself. There is
something to be said about learning through implementation.
_Dataflow, Oz_ \- I think the influence of Oz is on the upswing and will only
continue to grow in the future.
_Prototype-based, JavaScript / Io / Self_ \- Self is the grand-daddy and
highly influential on every prototype-based language. This is not the same as
class-based OOP and shouldn't be treated as such. Many people come to a
prototype language and create an ad-hoc class system, but if your goal is to
expand your mind, then I think that is a mistake. Use the language to its full
capacity. Read [Organizing Programs without
Classes](http://labs.oracle.com/self/papers/organizing-programs.html) for
ideas.
_Expert System, CLIPS_ \- I always recommend this. If you know Prolog then you
will likely have the upper-hand in getting up to speed, but it's a very
different language.
_Frink_ \- Frink is a general purpose language, but it's famous for its system
of unit conversions. I find this language to be very inspiring in its
unrelenting drive to be the best at what it does. Plus... it's really fun!
_Functional+Optional Types, Qi_ \- You say you've experience with some type
systems, but do you have experience with "skinnable* type systems? No one
has... but they should. Qi is like Lisp in many ways, but its type system will
blow your mind.
_Actors+Fault-tolerance, Erlang_ \- Erlang's process model gets a lot of the
buzz, but its fault-tolerance and hot-code-swapping mechanisms are game-
changing. You will not learn much about FP that you wouldn't learn with
Clojure, but its FT features will make you wonder why more languages can't
seem to get this right.
Enjoy!
|
How to migrate a CSV file to Sqlite3 (or MySQL)? - Python
Question: I'm using Python in order to save the data row by row... but this is extremely
slow!
**The CSV contains _70million lines_ , and with my script _I can just store
1thousand a second_.**
* * *
This is what my script looks like
reader = csv.reader(open('test_results.csv', 'r'))
for row in reader:
TestResult(type=row[0], name=row[1], result=row[2]).save()
* * *
I reckon that for testing I might have to consider MySQL or PostgreSQL.
**Any idea or tips? This is the first time I deal with such massive volumes of
data. :)**
Answer: For MySQL imports:
mysqlimport [options] db_name textfile1 [textfile2 ...]
For SQLite3 imports:
ref <http://stackoverflow.com/questions/1045910/how-can-i-import-load-a-sql-
or-csv-file-into-sqlite>
|
missing messages when reading with non-blocking udp
Question: I have problem with missing messages when using nonblocking read in udp
between two hosts. The sender is on linux and the reader is on winxp. This
example in python shows the problem.
Here are three scripts used to show the problem.
**send.py** :
import socket, sys
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
host = sys.argv[1]
s.sendto('A'*10, (host,8888))
s.sendto('B'*9000, (host,8888))
s.sendto('C'*9000, (host,8888))
s.sendto('D'*10, (host,8888))
s.sendto('E'*9000, (host,8888))
s.sendto('F'*9000, (host,8888))
s.sendto('G'*10, (host,8888))
**read.py**
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('',8888))
while True:
data,address = s.recvfrom(10000)
print "recv:", data[0],"times",len(data)
**read_nb.py**
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('',8888))
s.setblocking(0)
data =''
address = ''
while True:
try:
data,address = s.recvfrom(10000)
except socket.error:
pass
else:
print "recv:", data[0],"times",len(data)
Example 1 (works ok):
ubuntu> **python send.py**
winxp > **read.py**
give this ok result from read.py:
recv: A times 10
recv: B times 9000
recv: C times 9000
recv: D times 10
recv: E times 9000
recv: F times 9000
recv: G times 10
Example 2 (**missing messages**):
in this case the short messages will often not be catched by read_nb.py I give
two examples of how it can look like.
ubuntu> **python send.py**
winxp > **read_nb.py**
give this result from read_nb.py:
recv: A times 10
recv: B times 9000
recv: C times 9000
recv: D times 10
recv: E times 9000
recv: F times 9000
above is the last 10 byte message missing
below is a 10 byte message in the middle missing
recv: A times 10
recv: B times 9000
recv: C times 9000
recv: E times 9000
recv: F times 9000
recv: G times 10
I have checked with wireshark on windows and every time all messages is
captured so they reach the host interface but is not captured by read_nb.py.
What is the explanation?
I have also tried with read_nb.py on linux and send.py on windows and then it
works. So I figure that this problem has something to do with winsock2
Or maybe I am using nonblocking udp the wrong way?
Answer: If the datagrams are getting to the host (as your wireshark log shows) then
the first place I'd look is the size of your socket recv buffer, make it as
big as you can, and run as fast as you can.
Of course this is completely expected with UDP. You should assume that
datagrams can be thrown away at any point and for any reason. Also you may get
datagrams more than once...
If you need reliability then you need to build your own, or use TCP.
|
How to display an image from web?
Question: I have written this simple script in python:
import gtk
window = gtk.Window()
window.set_size_request(800, 700)
window.show()
gtk.main()
now I want to load in this window an image from web ( and not from my PC )
like this:
<http://www.dailygalaxy.com/photos/uncategorized/2007/05/05/planet_x.jpg>
How can I do that ?
P.S. I don't want download the image ! I just want load the image from the
URL.
Answer: This downloads the image from a url, but writes the data into a
[gtk.gdk.Pixbuf](http://www.pygtk.org/docs/pygtk/class-gdkpixbuf.html) instead
of to a file:
import pygtk
pygtk.require('2.0')
import gtk
import urllib2
class MainWin:
def destroy(self, widget, data=None):
print "destroy signal occurred"
gtk.main_quit()
def __init__(self):
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.connect("destroy", self.destroy)
self.window.set_border_width(10)
self.image=gtk.Image()
response=urllib2.urlopen(
'http://www.dailygalaxy.com/photos/uncategorized/2007/05/05/planet_x.jpg')
loader=gtk.gdk.PixbufLoader()
loader.write(response.read())
loader.close()
self.image.set_from_pixbuf(loader.get_pixbuf())
# This does the same thing, but by saving to a file
# fname='/tmp/planet_x.jpg'
# with open(fname,'w') as f:
# f.write(response.read())
# self.image.set_from_file(fname)
self.window.add(self.image)
self.image.show()
self.window.show()
def main(self):
gtk.main()
if __name__ == "__main__":
MainWin().main()
|
Mark File For Removal from Python?
Question: In one of my scripts, I need to delete a file that could be in use at the
time. I know that I can't remove the file that is in use until it isn't
anymore, but I also know that I can mark the file for removal by the Operating
System (Windows XP). How would I do this in Python?
Answer: ...and another version which doesn't depend on pywin32 binaries.
import ctypes
MOVEFILE_DELAY_UNTIL_REBOOT = 4
ctypes.windll.kernel32.MoveFileExA("/path/to/lockedfile.ext", None,
MOVEFILE_DELAY_UNTIL_REBOOT)
|
NetworkX (Python): how to change edges' weight by designated rule
Question: I have a weighted graph:
F=nx.path_graph(10)
G=nx.Graph()
for (u, v) in F.edges():
G.add_edge(u,v,weight=1)
get the nodes list:
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)]
I want to change each edge's weight by this rule:
remove one node, such as node 5, clearly, edge (4, 5) and (5, 6) will be
delete, and the weight of each edge will turn to:
{# these edges are nearby the deleted edge (4, 5) and (5, 6)
(3,4):'weight'=1.1,
(6,7):'weight'=1.1,
#these edges are nearby the edges above mentioned
(2,3):'weight'=1.2,
(7,8):'weight'=1.2,
#these edges are nearby the edges above mentioned
(1,2):'weight'=1.3,
(8,9):'weight'=1.3,
# this edge is nearby (1,2)
(0,1):'weight'=1.4}
How to write this algorithm?
PS: path_graph is just an example. I need a program suit any graph type.
Furthermore, the program need to be iterable, it means I can remove one node
from origin graph each time.
Regards
Answer: You can access the edge weight as G[u][v]['weight'] or by iterating over the
edge data. So you can e.g.
In [1]: import networkx as nx
In [2]: G=nx.DiGraph()
In [3]: G.add_edge(1,2,weight=10)
In [4]: G.add_edge(2,3,weight=20)
In [5]: G[2][3]['weight']
Out[5]: 20
In [6]: G[2][3]['weight']=200
In [7]: G[2][3]['weight']
Out[7]: 200
In [8]: G.edges(data=True)
Out[8]: [(1, 2, {'weight': 10}), (2, 3, {'weight': 200})]
In [9]: for u,v,d in G.edges(data=True):
...: d['weight']+=7
...:
...:
In [10]: G.edges(data=True)
Out[10]: [(1, 2, {'weight': 17}), (2, 3, {'weight': 207})]
|
Showing the Foreign Key value in Django template
Question: Here is my issue. I am new to python/django (about 2 months in). I have 2
tables, Project and Status. I have a foreign key pointing from status to
project, and I am looking to try to display the value of the foreign key
(status) on my project template, instead of the address of the foreign key.
Here is my models.py
from django.db import models
from clients.models import Clients
from django.contrib.auth.models import User
from settings import STATUS_CHOICES
from django.db import models
from clients.models import Clients
from django.contrib.auth.models import User
from settings import STATUS_CHOICES
class Project(models.Model):
client = models.ForeignKey(Clients, related_name='projects')
created_by = models.ForeignKey(User, related_name='created_by')
#general information
proj_name = models.CharField(max_length=255, verbose_name='Project Name')
pre_quote = models.CharField(max_length=3,default='10-')
quote = models.IntegerField(max_length=10, verbose_name='Quote #', unique=True)
desc = models.TextField(verbose_name='Description')
starts_on = models.DateField(verbose_name='Start Date')
completed_on = models.DateField(verbose_name='Finished On')
def __unicode__(self):
return u'%s' % (self.proj_name)
class Status(models.Model):
project = models.ForeignKey(Project, related_name='status')
value = models.CharField(max_length=20, choices=STATUS_CHOICES, verbose_name='Status')
date_created= models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.value
class Meta:
verbose_name = ('Status')
verbose_name_plural = ("Status")
My views.py
@login_required
def addProject(request):
if request.method == 'POST':
form = AddSingleProjectForm(request.POST)
if form.is_valid():
project = form.save(commit=False)
project.created_by = request.user
project.save()
project.status.create(
value = form.cleaned_data.get('status', None)
)
return HttpResponseRedirect('/project/')
else:
form = AddSingleProjectForm()
return render_to_response('project/addProject.html', {
'form': form, 'user':request.user}, context_instance=RequestContext(request))
And finally my template:
{% if project_list %}
<table id="plist">
<tr id="plist">
<th>Quote #</th>
<th>Customer</th>
<th>Date</th>
<th>Project Name</th>
<th>Status</th>
<th>Contact</th>
</tr id="plist">
{% for p in project_list %}
<tr id="plist">
<td><a href="/project/{{ p.id }}/view">{{ p.pre_quote }}{{ p.quote }}</a></td>
<td>{{ p.client }}</td>
<td>{{ p.starts_on }}</td>
<td>{{ p.proj_name }}</td>
<td>{{ p.status_set.select_related }}</td>
<td>{{ p.created_by }}</td>
</tr>
{% endfor %}
</table>
{% else %}
<p>No projects available.</p>
{% endif %}
Any help would be much appreciated. Thank you!
Answer: I'm guessing you mean here:
<td>{{ p.status_set.select_related }}</td>
This doesn't do anything. `select_related` is an optimisation feature, it has
nothing to do with actually getting or displaying the related content. If you
want to do that, you will have to iterate through the result of
`p.status_set.all`.
|
How do I return a list as a variable in Python and use in Jinja2?
Question: I am a very young programmer and I am trying to do something in Python but I'm
stuck. I have a list of users in Couchdb (using python couchdb library & Flask
framework) who have a username (which is the _id) and email. I want to use the
list of email addresses in a select box in a jinja2 template.
My first problem is how to access the email addresses. If I do:
for user in db:
doc = db[user]
emails = doc['email']
print options
I get:
email@domain.com
otheremail@otherdomain.com
yetanotheremail@yetanotherdomain.com
So I can get my list of emails. But where my brutal inexperience is showing up
is that I don't know how to then use them. The list only exists in the for
loop. How do I return that list as a useable list of variables? And how do I
then make that list appear in my jinja2 template in an option dropdown. I
guess I need a function but I am a green programmer.
Would so appreciate help.
Answer:
# assuming you have something such as this:
class User(Document):
email = TextField()
# you can use the .load() method of the User class
users = [User.load(db, uid) for uid in db]
# now you can do this:
for user in users:
print user.id, user.email
# but you're using it in flask so, in your view you can send
# this list of users to your template using something like this:
from flask import render_template
@app.route("/users")
def show_users():
return render_template('users.html', users=users)
Now in your users.html jinja2 template the following will output a dropdown
listbox of each user's e-mail
<select>
{% for user in users %}
<option value="{{ user.id }}">{{ user.email }}</option>
{% endfor %}
</select>
Also, are you using the Flask-CouchDB extension? It might be helpful in
abstracting out some of the low level couchdb coding:
<http://packages.python.org/Flask-CouchDB/>
Disclaimer: The code above wasn't tested, but should work fine. I don't know
much about CouchDB, but I am familiar with Flask. Also, I obviously didn't
include a full Flask/CouchDB application here, so bits of code are missing.
|
How do you generate xml from non string data types using minidom?
Question: How do you generate xml from non string data types using minidom? I have a
feeling someone is going to tell me to generate strings before hand, but this
is not what I'm after.
from datetime import datetime
from xml.dom.minidom import Document
num = "1109"
bool = "false"
time = "2010-06-24T14:44:46.000"
doc = Document()
Submission = doc.createElement("Submission")
Submission.setAttribute("bool",bool)
doc.appendChild(Submission)
Schedule = doc.createElement("Schedule")
Schedule.setAttribute("id",num)
Schedule.setAttribute("time",time)
Submission.appendChild(Schedule)
print doc.toprettyxml(indent=" ",encoding="UTF-8")
This is the result:
<?xml version="1.0" encoding="UTF-8"?>
<Submission bool="false">
<Schedule id="1109" time="2010-06-24T14:44:46.000"/>
</Submission>
How do I get valid xml representations of non-string datatypes?
from datetime import datetime
from xml.dom.minidom import Document
num = 1109
bool = False
time = datetime.now()
doc = Document()
Submission = doc.createElement("Submission")
Submission.setAttribute("bool",bool)
doc.appendChild(Submission)
Schedule = doc.createElement("Schedule")
Schedule.setAttribute("id",num)
Schedule.setAttribute("time",time)
Submission.appendChild(Schedule)
print doc.toprettyxml(indent=" ",encoding="UTF-8")
File "C:\Python25\lib\xml\dom\minidom.py", line 299, in _write_data data =
data.replace("&", "&").replace("<", "<") AttributeError: 'bool' object has no
attribute 'replace'
Answer: The bound method `setAttribute` expects its second argument, the value, to be
a string. You can help the process along by converting the data to strings:
bool = str(False)
or, converting to strings when you call `setAttribute`:
Submission.setAttribute("bool",str(bool))
(and of course, the same must be done for `num` and `time`).
|
I have a text file of a paragraph of writing, and want to iterate through each word in Python
Question: How would I do this? I want to iterate through each word and see if it fits
certain parameters (for example is it longer than 4 letters..etc. not really
important though).
The text file is literally a rambling of text with punctuation and white
spaces, much like this posting.
Answer: Try [`split()`](http://docs.python.org/library/stdtypes.html#str.split)ing the
string.
f = open('your_file')
for line in f:
for word in line.split():
# do something
If you want it without punctuation:
f = open('your_file')
for line in f:
for word in line.split():
word = word.strip('.,?!')
# do something
|
Python 2.7: Themed "common dialog" tkinter interfaces via Ttk?
Question: Python 2.7 (32-bit) Windows: We're experimenting with Python 2.7's support for
themed Tkinter (`ttk`) for simple GUI's and have come away very impressed!!
The one area where the new theme support seems to have come up short is how OS
specific common dialogs are wrapped.
Corrected: In other words, the `MessageBox` and `ColorChooser` common dialogs
have "ugly" looking Win 95 style blocky looking buttons vs. the themed
(rounded/gradient) buttons that normally show up on these common dialogs under
XP, Vista, and Windows 7. (I'm testing on all 3 platforms with identical, un-
themed results).
Note: The filedialog common dialogs (`askopenfilename`, `askopenfilenames`,
`asksaveasfilename`, `askdirectory`) are all properly themed.
import tkMessageBox as messagebox
messagebox.showinfo()
import tkColorChooser as colorchooser
color = colorchooser.askcolor( parent=root, title='Customize colors' )
Any ideas on what's required to get Tkinter's `MessageBox` and `ColorChooser`
common dialogs to be OS theme compatible (at least under Windows XP or
higher)?
Answer: Your observation is mainly correct. I do see what you are referring to in the
`messagebox` and the `colorchooser`. However, my filedialogs all seem to have
properly rounded buttons, etc.
My recommendation for you on making the messagebox is to create your own
messagebox using the `TopLevel` widget, and then define what you need on it
and the appropriate behavior for the different buttons (it's definitely a bit
harder than just using a messagebox, but if you really need the new style
buttons, it'll work).
I don't think you can hack together a solution for the `colorchooser` problem,
however.
I though for a minute that perhaps Python 3.1 had fixed this problem, but
sadly, I tried and that isn't the case. I suppose if you need the user to pick
a color, the buttons will have to be ugly.
|
how to create file names from a number plus a suffix in python
Question: how to create file names from a number plus a suffix??.
for example I am using two programs in python script for work in a server, the
first creates a file x and the second uses the x file, the problem is that
this file can not overwrite.
no matter what name is generated from the first program. the second program of
be taken exactly from the path and file name that was assigned to continue the
script.
thanks for your help and attention
Answer: As far as I can understand you, you want to create a file with a unique name
in one program and pass the name of that file to another program. I think you
should take a look at the tempfile module,
<http://docs.python.org/library/tempfile.html#module-tempfile>.
Here is an example that makes use of NamedTemporaryFile:
import tempfile
import os
def produce(text):
with tempfile.NamedTemporaryFile(suffix=".txt", delete=False) as f:
f.write(text)
return f.name
def consume(filename):
try:
with open(filename) as f:
return f.read()
finally:
os.remove(filename)
if __name__ == '__main__':
filename = produce('Hello, world')
print('Filename is: {0}'.format(filename))
text = consume(filename)
print('Text is: {0}'.format(text))
assert not os.path.exists(filename)
The output is something like this:
Filename is: /tmp/tmpp_iSrw.txt
Text is: Hello, world
|
Help me understand my mod_wsgi Django config file
Question: I was wondering why this works:
sys.path.append('/home/user/django')
sys.path.append('/home/user/django/mysite')
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
but this doesn't?
sys.path.append('/home/user/django')
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
I thought that adding the django folder would automatically make all
projects/folders in it available to python? But apparantly I have to add the
project as well, or it gives me the error 'settings not found'.
Notice that it doesn't say 'mysite.settings not found' which would indicate it
_does_ find my 'mysite' folder..
Answer: Maybe if in your settings.py you have an import to a module that's inside the
mysite directory, this import fails and that's why you get the ImportError.
|
Class has method that shows in intellisense, but gives an error when running it
Question: I'm tring to set the default encoding of my console to UTF-8 so it can display
cyrillic letters and accented letters.
Here is my code:
from Parser import parser
import sys
print sys.getdefaultencoding()
sys.setdefaultencoding('utf-8')
Output:
ascii
Traceback (most recent call last):
File "C:\Users\Sergio.Tapia\Documents\NetBeansProjects\BabylonPython\src\TestingGrounds.py", line 5, in <module>
sys.setdefaultencoding('utf-8')
AttributeError: 'module' object has no attribute 'setdefaultencoding'
The weird thing is, when pressing the '.' after sys to see what method it has,
setdefaultencoding is shown as a possible choice. Any suggestion on what to
do?
Answer: The function `sys.setdefaultencoding()` does exist but [is
removed](http://blog.ianbicking.org/illusive-setdefaultencoding.html) from
`sys`' dictionary by `site.py` itself.
On my machine, `site.py` contains the following comment:
# Remove sys.setdefaultencoding() so that users cannot change the
# encoding after initialization. The test for presence is needed when
# this module is run as a script, because this code is executed twice.
|
extract a sentence using python
Question: I would like to extract the exact sentence if a particular word is present in
that sentence. Could anyone let me know how to do it with python. I used
concordance() but it only prints lines where the word matches.
Answer: If you have each sentence in a string you can use find() on your word and if
found return the sentence. Otherwise you could use a regex, something like
this
pattern = "\.?(?P<sentence>.*?good.*?)\."
match = re.search(pattern, yourwholetext)
if match != None:
sentence = match.group("sentence")
I havent tested this but something along those lines.
My test:
import re
text = "muffins are good, cookies are bad. sauce is awesome, veggies too. fmooo mfasss, fdssaaaa."
pattern = "\.?(?P<sentence>.*?good.*?)\."
match = re.search(pattern, text)
if match != None:
print match.group("sentence")
|
Handling dates prior to 1970 in a repeatable way in MySQL and Python
Question: In my MySQL database I have dates going back to the mid 1700s which I need to
convert somehow to ints in a format similar to Unix time. The value of the int
isn't important, so long as I can take a date from either my database or from
user input and generate the same int. I need to use MySQL to generate the int
on the database side, and python to transform the date from the user.
Normally, the [UNIX_TIMESTAMP
function](http://dev.mysql.com/doc/refman/5.1/en/date-and-time-
functions.html#function_unix-timestamp), would accomplish this in MySQL, but
for dates before 1970, it always returns zero.
The [TO_DAYS MySQL function](http://dev.mysql.com/doc/refman/5.1/en/date-and-
time-functions.html#function_to-days), also could work, but I can't take a
date from user input and use Python to create the same values as this function
creates in MySQL.
So basically, I need a function like UNIX_TIMESTAMP that works in MySQL and
Python for dates between 1700-01-01 and 2100-01-01.
Put another way, this MySQL pseudo-code:
select 1700_UNIX_TIME(date) from table;
Must equal this Python code:
1700_UNIX_TIME(date)
Answer: I don't have MySQL here installed, but when I look here:
<http://dev.mysql.com/doc/refman/5.1/en/date-and-time-
functions.html#function_to-days> \- I see an example `TO_DAYS('2008-10-07')`
returning 733687.
The following Python function returns `datetime(2008,10,7).toordinal()` =
733322, which is 365 less than the MySQL's output.
So take this:
from datetime import datetime
query = '2008-10-07'
nbOfDays = datetime.strptime(query, '%Y-%m-%d').toordinal() + 365
and it should work for dates between 1700 and 2100.
|
python popularity cloud not working
Question: I built a popularity cloud but it doesn't work properly. The txt file is;
1 Top Gear
3 Scrubs
3 The Office (US)
5 Heroes
5 How I Met Your Mother
5 Legend of the Seeker
5 Scrubs
.....
In my popularity cloud, names are written their frequency times. For example,
Legend of the Seeker is written 5 times and their size increases. Every word
is supposed to be written one time and the size must be according to
popularity number (5). But every word should be written one time and its size
must be according to its popularity. How can I fix it?
And also my program should provide that condition:
Terms with the same frequency are typically displayed in the same colour e.g.
Golf and Karate. Different frequencies are typically shown in different
colours e.g. Basketball, Cricket and Hockey. At the bottom of each cloud
output the frequency/count in the colour used to display the values in the
cloud.
My code follows here.
#!/usr/bin/python
import string
def main():
# get the list of tags and their frequency from input file
taglist = getTagListSortedByFrequency('tv.txt')
# find max and min frequency
ranges = getRanges(taglist)
# write out results to output, tags are written out alphabetically
# with size indicating the relative frequency of their occurence
writeCloud(taglist, ranges, 'tv.html')
def getTagListSortedByFrequency(inputfile):
inputf = open(inputfile, 'r')
taglist = []
while (True):
line = inputf.readline()[:-1]
if (line == ''):
break
(count, tag) = line.split(None, 1)
taglist.append((tag, int(count)))
inputf.close()
# sort tagdict by count
taglist.sort(lambda x, y: cmp(x[1], y[1]))
return taglist
def getRanges(taglist):
mincount = taglist[0][1]
maxcount = taglist[len(taglist) - 1][1]
distrib = (maxcount - mincount) / 4;
index = mincount
ranges = []
while (index <= maxcount):
range = (index, index + distrib-1)
index = index + distrib
ranges.append(range)
return ranges
def writeCloud(taglist, ranges, outputfile):
outputf = open(outputfile, 'w')
outputf.write("<style type=\"text/css\">\n")
outputf.write(".smallestTag {font-size: xx-small;}\n")
outputf.write(".smallTag {font-size: small;}\n")
outputf.write(".mediumTag {font-size: medium;}\n")
outputf.write(".largeTag {font-size: large;}\n")
outputf.write(".largestTag {font-size: xx-large;}\n")
outputf.write("</style>\n")
rangeStyle = ["smallestTag", "smallTag", "mediumTag", "largeTag", "largestTag"]
# resort the tags alphabetically
taglist.sort(lambda x, y: cmp(x[0], y[0]))
for tag in taglist:
rangeIndex = 0
for range in ranges:
url = "http://www.google.com/search?q=" + tag[0].replace(' ', '+') + "+site%3Asujitpal.blogspot.com"
if (tag[1] >= range[0] and tag[1] <= range[1]):
outputf.write("<span class=\"" + rangeStyle[rangeIndex] + "\"><a href=\"" + url + "\">" + tag[0] + "</a></span> ")
break
rangeIndex = rangeIndex + 1
outputf.close()
if __name__ == "__main__":
main()
Answer: I'm not sure this can categorize by color, but it only takes 4 lines of code
to generate a tag cloud in the directory you run the code in.
<https://github.com/atizo/PyTagCloud>
|
Find System Hard Disk Drive from Python?
Question: I am working on a software installer for my current application. It needs to
be installed to the System HDD. How owuld I detect the system drive and return
the letter from Python?
Would the win32 extensions be useful? How about the os module pre packaged
with Python?
Answer: **This is how to return the letter of the System drive on a Win32 platform:**
import os
print os.getenv("SystemDrive")
The above snippet returns the system drive letter. In my case ( and most cases
on windows) C:
|
how to iterate from a specific point in a sequence (Python)
Question: **[Edit]**
From the feedback/answers I have received, I gather there is some confusion
regarding the original question. Consequently, I have reduced the problem to
its most rudimentary form
Here are the relevant facts of the problem:
1. I have a sorted sequence: **S**
2. I have an item (denoted by **_i_**) that is GUARANTEED to be contained in **S**
3. I want a **find()** algorithm that returns an iterator (**_iter_**) that points to **_i_**
4. After obtaining the iterator, I want to be able to iterate FORWARD (BACKWARD?) over the elements in **_S_** , starting FROM (and including) **_i_**
For my fellow C++ programmers who can also program in Python, what I am asking
for, is the equivalent of:
const_iterator std::find (const key_type& x ) const;
The iterator returned can then be used to iterate the sequence. I am just
trying to find (pun unintended), if there is a similar inbuilt algorithm in
Python, to save me having to reinvent the wheel.
Answer: yes , you can do like this:
import itertools
from datetime import datetime
data = {
"2008-11-10 17:53:59":"data",
"2005-11-10 17:53:59":"data",
}
list_ = data.keys()
new_list = [datetime.strptime(x, "%Y-%m-%d %H:%M:%S") for x in list_]
begin_date = datetime.strptime("2007-11-10 17:53:59", "%Y-%m-%d %H:%M:%S")
for i in itertools.ifilter(lambda x: x > begin_date, new_list):
print i
|
Monitor ZIP File Extraction Python
Question: I need to unzip a .ZIP archive. I already know how to unzip it, but it is a
huge file and takes some time to extract. How would I print the percentage
complete for the extraction? I would like something like this:
Extracting File
1% Complete
2% Complete
etc, etc
Answer: here an example that you can start with, it's not optimized:
import zipfile
zf = zipfile.ZipFile('test.zip')
uncompress_size = sum((file.file_size for file in zf.infolist()))
extracted_size = 0
for file in zf.infolist():
extracted_size += file.file_size
print "%s %%" % (extracted_size * 100/uncompress_size)
zf.extract(file)
to make it more beautiful do this when printing:
print "%s %%\r" % (extracted_size * 100/uncompress_size),
|
What will a Python programmer gain by learning Ruby?
Question: I am going to be learning **Ruby** , **Haskell** and **Prolog** at university.
Now, I'm wondering what should get most of my attention. I have half a year to
do all three, which means I need to decide on one language to get my
extracurricular time. The others I will learn just enough to do very good in
the course.
I am familiar enough with Haskell and Prolog to know that learning them will
teach me a few very important concepts of computer science. I'm not so sure
about ruby.
Going through a few tutorials and introductions, I get the impression that
ruby is a lot of _shallow magic_. Now I'm asking the ruby people: What will I
have gained, should I decide never to use it again, after I've spent half a
year learning it, that Python didn't already teach me.
This question is not intended to "make the case" for ruby, although I realise
this is a potential topic of great argumentation.
I use Python for all my CS work now. I have done quite a bit of functional
programming with it as well. I am also, already, quite familiar with object
oriented programming (in Java, Python and C#). And I will, as I said, do some
Logical programming with Prolog.
**What then is left for Ruby to teach me?**
To further dilute the question:
* I'm not interested in writing fun programs, or cool web applications. I'm just interested in the Computer Science bits. Implementing algorithms, data structures and so on. (Although having fun surely won't hurt)
* Ideally, concepts discussed need to be learnable in about 1.000 hours.
* I'm not at all interested in _Rails_. Any technology that hides complexity is, in this case, detrimental.
I can't help this question being argumentative. But an ideal answer to this
question will mention a profoundly important concept of theoretical computer
science that ruby helps the programmer use and understand in order to gain
scientifically adjuvant knowledge.
To candidates I came up with are Meta-programming and Multi-threading. I don't
know if ruby is particularly great to learn either of them.
Answer: For the most part, nothing. Most of Ruby's strengths/weaknesses are the same
as Python's, except that Ruby is slightly more "functional". However if you
have Haskell as an option, much more can be learned about functional
programming from Haskell than from Ruby.
Second, if you're looking at things from a theoretical computer science
perspective, then Ruby is far from a language of choice. Ruby and a lot of its
libraries break a lot of standard OOP dogma which I believe many academics
would find repulsive (this is based mainly on my chats about languages with
various professors).
From an academic perspective I think Haskell would have the most appeal to
you. If you're interested in AI or logic, then Prolog is also an excellent
choice.
|
Dynamic image creation using Python over a web page
Question: I'm new to learning Python and I've been trying to implement a text to image
converter that runs on a web page.
1. I have succeeded in making the functional code that converts the text into image in Python, using the PIL module (i.e., user enters input text at run time and that gets converted into an image and is stored in the hard drive).
2. Now I want this code segment to work on a web page (something similar to feedback or comments form in websites).
a. That asks the user to enter a string in a text field and, on pressing a
button, it goes ahead and converts it into an image and reloads the page.
b. once reloaded it displays the string-converted-image, and also provides the
text box again for any new user to do the same.
3. I started with the Google Web Apps framework, and unfortunately I learnt that Google Web Apps can't support PIL module although it provides an image API, it can't support dynamic image generations based on user input.
4. So, can anyone guide me as to how I can go ahead and integrate a web page and the Python code that I have ready? So that it works?
5. Please guide me where I need to look and anything you consider is necessary to know in order to proceed ahead.
Answer: Check out [webpy](http://webpy.org/), just about the simplest Python web
framework. In the web.py module, import your PIL image converter, grab the
text from the submitted form (via `web.input()`), convert the text and render
a page with the new image on it. You should be able to get a simple page up in
a dozen or so lines.
|
Bash Script for MythTV which requires Python Dependencies
Question: I wrote a bash script which renames MythTV files based upon data it receives.
I wrote it in bash because bash has the strong points of textual data
manipulation and ease of use.
You can see the script itself here:
<http://code.google.com/p/mythicallibrarian/source/browse/trunk/mythicalLibrarian>
I have several users which are first time Linux users. I've created an
installation script here which checks dependencies and sets things up in a
graphical manner. You can see the setup script here:
<http://code.google.com/p/mythicallibrarian/source/browse/trunk/mythicalSetup.sh>
Recently, there were some changes to MythTV which require me to migrate the
mysql database access in mythicalLibrarian to a Python bindings script. here:
<http://code.google.com/p/mythicallibrarian/source/browse/trunk/pythonBindings/MythDataGrabber>
Previously, I've tested dependencies using a system like this:
test "`uname`" != "Darwin" && LinuxDep=1 || LinuxDep=0
if which agrep >/dev/null; then
echo "Verified agrep exists"
else
test "$LinuxDep" = "1" && echo "Please install 'agrep' on your system" || echo "Please obtain MacPorts and install package agrep"
d="agrep "
fi
.........................
if which agrep>/dev/null && which curl>/dev/null && which dialog>/dev/null; then
echo "All checks complete!!!"
else
echo "the proper dependencies must be installed..."
echo "The missing dependencies are $a$b$c$d$e"
test "$LinuxDep" = "1" && echo "Debian based users run: apt-get install $a$b$c$d$e" || echo "Please obtain MacPorts and run: port install $a$b$c"
if [ "$LinuxDep" = "0" ]; then
read -n1 -p " Would you like some help on installing MacPorts? Select: (y)/n" MacPortsHelp
The python dependencies make it a bit more difficult. I don't know how to test
if I have the linux pacakge "libmyth-python" and "python-lxml" on the system.
How, from BASH, can I test that my Python script MythDataGrabber has its
from MythTV import MythDB
requirement satisfied?
Answer: You can check the status code of:
python -c "import MythDB.MythTV"
If it returns non-zero, there was an error, likely an ImportError.
|
how do I generate a cartesian product of several variables using python iterators?
Question: Dear all, Given a variable that takes on, say, three values, I'm trying to
generate all possible combinations of, say, triplets of these variables.
While this code does the trick,
site_range=[0,1,2]
states = [(s0,s1,s2) for s0 in site_range for s1 in site_range for s2 in site_range]
it's somewhat, uhm, clumsy, and is only getting worse if I try to do the same
for combinations of more than three variables
Hence, my Python 101 questions:
1. How do I go about rewriting the code above using iterators? I mean, is it possible to have an iterator which would yield the elements of the "states" above?
2. Is it possible to extend this for generating not only triplets, but also 4-plets, 5-plets and so on?
Answer:
import itertools
site_range=[0,1,2]
[x for x in itertools.product(site_range, repeat=len(site_range))]
|
catching a broken socket in python
Question: I'm having problems detecting a broken socket when a broken pipe exception
occurs. See the below code for an example:
The Server:
import errno, select, socket, time, SocketServer
class MetaServer(object):
def __init__(self):
self.server = Server(None, Handler, bind_and_activate=False)
def run(self, sock, addr):
rfile = sock.makefile('rb', 1)
self.server.process_request(sock, addr)
while 1:
r, _, _ = select.select([rfile], [], [], 1.0)
if r:
print 'Got %s' % rfile.readline()
else:
print 'nothing to read'
class Server(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
allow_reuse_address = True
daemon_threads = True
class Handler(SocketServer.StreamRequestHandler):
def handle(self):
print 'connected!'
try:
while 1:
self.wfile.write('testing...')
time.sleep(1)
except socket.error as e:
if e.errno == errno.EPIPE:
print 'Broken pipe!'
self.finish()
self.request.close()
if __name__ == '__main__':
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 8081))
s.listen(5)
ms = MetaServer()
while 1:
client, address = s.accept()
ms.run(client, address)
The Client:
import select, socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1', 8081))
while 1:
r, _, _ = select.select([s], [], [], 1.0)
if not r:
continue
msg = s.recv(1024)
print 'Got %s' % (msg,)
Now, if I run the server and client, all is well, and I get a "nothing is
read" message every second. As soon as I CTRL-C out of the client, the server
goes crazy and starts to "read" from what should be a busted socket, dumping a
lot of "Got " messages.
Is there some way to detect this broken socket in the `MetaServer.run()`
function to avoid the above said behavior?
Answer: Yes, that's something which is not really in the documentation but old Un*x
behavior: You need to abort when you get an empty string.
|
convert string to datetime object
Question: I'd like to convert this string into a datetime object:
Wed Oct 20 16:35:44 +0000 2010
Is there a simple way to do this? Or do I have to write a RE to parse the
elements, convert Oct to 10 and so forth?
EDIT: strptime is great. However, with
datetime.strptime(date_str, "%a %b %d %H:%M:%S %z %Y")
I get
ValueError: 'z' is a bad directive in format '%a %b %d %H:%M:%S %z %Y'
even though %z seems to be correct.
EDIT2: The %z tag appears to not be supported. See
<http://bugs.python.org/issue6641>. I got around it by using a timedelta
object to modify the time appropriately.
Answer: No RE needed. Try this:
from dateutil import parser
yourDate = parser.parse(yourString)
for "Wed Oct 20 16:35:44 +0000 2010" returns `datetime.datetime(2010, 10, 20,
16, 35, 44, tzinfo=tzutc())`
|
python pty.fork - how does it work
Question: <http://docs.python.org/library/pty.html> says -
> pty.fork()¶ Fork. Connect the child’s controlling terminal to a pseudo-
> terminal. Return value is (pid, fd). Note that the child gets pid 0, and the
> fd is invalid. The parent’s return value is the pid of the child, and fd is
> a file descriptor connected to the child’s controlling terminal (and also to
> the child’s standard input and output).
What's does this mean ? Every process has 3 fd (stdin,stdout,stderr). Does
this affects these fds now ? will child process won't have any of these fds?
I'm confused.--totally.
Answer: I think I finally got a minimal example for `pty.fork` in Python - and since I
found it extremely difficult to find a similar example, I'm posting it here as
an illustration of @joni's answer. It is essentially based on:
* [pty - Python os.forkpty why can't I make it work - Stack Overflow](http://stackoverflow.com/questions/864826/python-os-forkpty-why-cant-i-make-it-work)
* [Weird platform dependent error: Using pty.fork()](http://www.velocityreviews.com/forums/t359698-weird-platform-dependent-error-using-pty-fork.html)
* [CodeIdol - Thinking about Programming Python, 3rd Edition - Parallel System Tools - Pipes](http://codeidol.com/python/python3/Parallel-System-Tools/Pipes/)
* [Python code coverage: Lib/test/test_pty.py](http://coverage.livinglogic.de/Lib/test/test_pty.py.html)
* [[Patches] [ python-Patches-656590 ] /dev/ptmx support for ptys (cygwin)](http://mail.python.org/pipermail/patches/2003-January/010849.html) ("_master_open() and slave_open have been deprecated since 2.0_ ")
Particularly nasty bits are finding documentation that still refers to
`master_open()` which is obsolete; and the fact that `pty.fork` will **not**
spawn a child process, _unless_ the file descriptor (returned by the fork
method) is read from by the parent process! (_note that in`os.fork` there is
no such requirement_) Also, it seems that `os.fork` is a bit more portable
(read a few comments noting that `pty.fork` doesn't work on some platforms).
Anyways, here's first a script (`pyecho.py`) that acts as an executable (it
simply reads lines from standard input, and writes them back in uppercase):
#!/usr/bin/env python
# pyecho.py
import sys;
print "pyecho starting..."
while True:
print sys.stdin.readline().upper()
... and then, here is the actual script (it will require that pyecho.py is in
the same directory):
#!/usr/bin/env python
import sys
import os
import time
import pty
def my_pty_fork():
# fork this script
try:
( child_pid, fd ) = pty.fork() # OK
#~ child_pid, fd = os.forkpty() # OK
except OSError as e:
print str(e)
#~ print "%d - %d" % (fd, child_pid)
# NOTE - unlike OS fork; in pty fork we MUST use the fd variable
# somewhere (i.e. in parent process; it does not exist for child)
# ... actually, we must READ from fd in parent process...
# if we don't - child process will never be spawned!
if child_pid == 0:
print "In Child Process: PID# %s" % os.getpid()
# note: fd for child is invalid (-1) for pty fork!
#~ print "%d - %d" % (fd, child_pid)
# the os.exec replaces the child process
sys.stdout.flush()
try:
#Note: "the first of these arguments is passed to the new program as its own name"
# so:: "python": actual executable; "ThePythonProgram": name of executable in process list (`ps axf`); "pyecho.py": first argument to executable..
os.execlp("python","ThePythonProgram","pyecho.py")
except:
print "Cannot spawn execlp..."
else:
print "In Parent Process: PID# %s" % os.getpid()
# MUST read from fd; else no spawn of child!
print os.read(fd, 100) # in fact, this line prints out the "In Child Process..." sentence above!
os.write(fd,"message one\n")
print os.read(fd, 100) # message one
time.sleep(2)
os.write(fd,"message two\n")
print os.read(fd, 10000) # pyecho starting...\n MESSAGE ONE
time.sleep(2)
print os.read(fd, 10000) # message two \n MESSAGE TWO
# uncomment to lock (can exit with Ctrl-C)
#~ while True:
#~ print os.read(fd, 10000)
if __name__ == "__main__":
my_pty_fork()
Well, hope this helps someone,
Cheers!
|
Python differences between running as script and running via interactive shell
Question: I am attempting to debug a problem with a ctypes wrapper of a windows DLL and
have noticed differences when I run tests via an interactive shell (python or
ipython) and when I run the scripts non-interactively.
I was wondering if there is any explanation for the differences I am seeing
here?
Specifically, when I interactively run a simple test, a DLL call will hang and
never return, where as exactly the same code run as a script will not exhibit
this problem.
To be more explicit with what I mean here, imagine you had the following code
from foobar import bar, foo
bar(foo(1,2,3))
When put in a file, say "myfoo.py", and excecuted via "python myfoo.py", the
above code executes as expected. However, if you type in the above into a
python/ipython shell, the code behaves differently (in my case, hangs when
calling a ctypes.WinDLL function)
Some additional details:
I am using the same interpreter and the same PYTHONPATH in both cases. The DLL
being wrapped is the Canon EDSDKv2.9, a SDK to remotely control cameras. It is
always hangs in the DLL, not in python code.
When initialised, my EDSDK wrapper launches a thread whose run method looks
like this:
def run(self):
sys.coinit_flags = 0 #use multithreaded mode
from pythoncom import PumpWaitingMessages
#^^ done here so this thread is correctly initialised
error(EDSDK.EdsInitializeSDK())
self.EDSDK_initialised = True
while self.active:
PumpWaitingMessages()
sleep(self.msg_sleep_time)
error(EDSDK.EdsTerminateSDK())
This threads purpose is basically to initialise the SDK, pump messages, and
allow other threads to call wrapped methods.
Note: this has worked, both interactively and non-interactively, in previous
EDSDK versions. My current problem only happens in the latest version of
EDSDK.
I suspect it may be something to do with threads (hence the snippet), but
can't find any information online to back up my suspicion.
So, is anyone aware of any differences when running python interactively and
non-interactively? Possibly related to windows threads? Any help, even wild
guesses, would be appreciated at this point, because I am completely stumped!
:)
Answer: The Python interactive interpreter is not thread safe. So, if you try to send
a blocking command, the whole interpreter will hang.
See [this article](http://mail.python.org/pipermail/python-bugs-
list/2000-November/002931.html) as to why this happens (tl; dr is that the
IDLE and threads don't mix). As for how to fix this, use the console rather
than the IDLE GUI. Or, you can just use a script.
|
Python 2.7/Windows resizable ttk progressbar?
Question: I'm experimenting with Python 2.7's new Tkinter Tile support (ttk). Is there a
way to make the ttk.Progressbar() control auto-resize in proportion to its
parent container? In reading the documentation on this control, it appears
that one must explicitly set this widget's height or width?
I'm looking for a way to place the ttk.Progressbar widget in a horizontally
resizable Tkinter dialog and have this widget resize as a user resize's the
parent dialog.
Is there a window or frame resize event that I can trap, a ttk.Progressbar
setting I can .config(), or .pack() option I can use to achieve my goal?
Any suggestions appreciated.
Answer: Try using the `fill` option of `pack` (or grid) to have the widget fill its
container.
import Tkinter as tk
import ttk
root=tk.Tk()
pb = ttk.Progressbar(mode="indeterminate")
pb.pack(side="bottom", fill="x")
pb.start()
root.wm_geometry("300x300")
root.mainloop()
|
Can't tell if a file exists on a samba share
Question: I know that the file name is `file001.txt` or `FILE001.TXT`, but I don't know
which. The file is located on a Windows machine that I'm accessing via samba
mount point.
The functions in `os.path` seem to be acting as though they were case-
insensitive, but the `open` function seems to be case-sensitive:
>>> from os.path import exists, isfile
>>> exists('FILE001.TXT')
True
>>> isfile('FILE001.TXT')
True
>>> open('FILE001.TXT')
Traceback (most recent call last):
File "<console>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'FILE001.TXT'
>>> open('file001.txt') # no problem
So, my questions are these:
1. Is there a way to determine what the file name is without opening the file (or listing the directory that it's in)?
2. Why is `open` case-sensitive when `os.path` isn't?
* * *
**Update:** thanks for the answers, but [this isn't a python
problem](http://stackoverflow.com/questions/4036637/case-sensitivity-issues-
with-mounted-samba-share) so I'm closing the question.
Answer: You might try adding nocase to the mount in your fstab, as in the example I
dug up below if it isn't already there:
//server/acme/app /home/joe/.wine/drive_c/App cifs guest,rw,iocharset=utf8,nocase,file_mode=0777,dir_mode=0777 0 0
[Found a link explaining
normcase](http://www.faqs.org/docs/diveintopython/fileinfo_os.html)
> normcase is a useful little function that compensates for case-insensitive
> operating systems that think that mahadeva.mp3 and mahadeva.MP3 are the same
> file. For instance, on Windows and Mac OS, normcase will convert the entire
> filename to lowercase; on UNIX-compatible systems, it will return the
> filename unchanged.
That tells you that open is probably _always_ expecting a lower case filename
on Windows filesystems.
As such, the reason os.path isn't case sensitive is that it probably calls
os.path.normcase before checking for the file, while open does not. Though,
that might also just be a bug.
|
Is it possible for my Mercurial hook to call code from another file?
Question: I have a hook function named `precommit_bad_branch` which imports
`hook_utils`. When invoking `precommit_bad_branch` via a commit I get the
following error message:
error: precommit.branch_check hook raised an exception: No module named hook_utils
abort: No module named hook_utils!
It looks like I'm not allowed to call `hook_utils` from
`precommit_bad_branch`. The code works fine if I call it explicitly without
involving Mercurial.
Is it possible for my hook to call code from another file?
My hgrc hook part looks like this:
[hooks]
precommit.branch_check = python:C:\workspaces\hg_hooks\next_hooks.py:precommit_bad_branch
precommit.debug_code_check = python:C:\workspaces\hg_hooks\common_hooks.py:precommit_contains_debug_code
preupdate.merge_check = python:C:\workspaces\hg_hooks\next_hooks.py:preupdate_bad_merge
Answer: Put the `C:\workspaces\hg_hooks` directory in your `PYTHONPATH` and you will
be able to write
[hooks]
precommit.branch_check = python:next_hooks.precommit_bad_branch
in your configuration file and you will also be able to do
import hook_utils
inside any Python file, including the `next_hooks.py` file.
Alternatively, you can modify `sys.path` from `next_hooks.py`, perhaps with
code like this:
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
import hook_utils
|
Python: 'import node.py' raises "No module named py"-error
Question: I have a file main.py like this:
import node.py
[my code...]
and a node.py like this:
[more of my code]
When executing main.py, I get this error:
File "/home/loldrup/repo/trunk/src/src/main.py", line 2, in <module>
import node.py
ImportError: No module named py
Answer: You should just say `import node`. The `.` in the name makes python think you
want to load a submodule named `py` of the package`node`, hence the error. All
of this is explained in detail in the [Python
Tutorial](http://docs.python.org/tutorial/modules.html).
|
Python/Tkinter window events and properties
Question: I've been searching for information on the following Tkinter window features
without success. Platform is Windows, Python 2.7. At the end of this post is
code that can be used to explore Tkinter window events.
1. How can one detect window minimize/maximize events? The event object returned by binding to a window's event does contain any information about these events. I've searched for protocols (like WM_DELETE_WINDOW) that might expose these events without success.
2. How can one determine window frame border sizes (not Tkinter frames, the frame the OS places around the container where Tkinter places its widgets)? Is there a non-platform specific way to discover these windows properties or do I need to use platform specific solutions like the win32 api under Windows?
3. How can one determine a window's visibility, eg. whether a window is invisible or not as set by .withdraw()?
4. Is it possible to cancel a window event, eg. if one wanted to constrain a window to a certain location on a user's desktop? Returning 'break' from a window's event does not cancel window move or resize events.
Here's sample code for experimenting with Tkinter window events.
def onFormEvent( event ):
for key in dir( event ):
if not key.startswith( '_' ):
print '%s=%s' % ( key, getattr( event, key ) )
print
import Tkinter as tkinter
root = tkinter.Tk()
lblText = tkinter.Label( root, text='Form event tester' )
lblText.pack()
root.bind( '<Configure>', onFormEvent )
root.mainloop()
Update: Here's what I learned about the following events:
1. event.type == 22 (one or more of following changed: width, height, x, y)
2. event.type == 18 (minimized) event.widget.winfo_viewable() = 0 (invisible)
3. event.type == 19 (restore after minimized)
4. event.type == 2 (maximize)
5. event.type == 22 (restore after maximized due to change in width and height)
Answer: Determining window visibility is done with a .winfo_viewable() call. Returns 1
if visible, 0 if not.
If you want to prevent the window from resizing, set up your window the way
you want, then use
self.root.minsize(self.root.winfo_reqwidth(), self.root.winfo_reqheight())
self.root.maxsize(self.root.winfo_reqwidth(), self.root.winfo_reqheight())
at the end of your `__init__` call.
To completely disable the window from being moved, then you probably just want
to remove the title bar and frame with `self.root.overrideredirect(True)`.
|
Convert xml to pdf in Python
Question: I have a problem when I try to convert a XML file in a PDF file, here I’m
going to explain briefly how I try to generate a PDF file.
We suppose I get the information from a database, then the code source is the
following:
import pyodbc,time,os,shutil,types
import cStringIO
import ho.pisa as pisa
import urllib
def HTML2PDF(data, filename, open=False):
"""
Simple test showing how to create a PDF file from
PML Source String. Also shows errors and tries to start
the resulting PDF
"""
pdf = pisa.CreatePDF(
cStringIO.StringIO(data),
file(filename, "wb"))
if open and (not pdf.err):
os.startfile(str(filename))
return not pdf.err
fout = open(BE_Full.xml","w")
fout.write("<?xml-stylesheet type='text/xsl' href='styles/Full_Report.xslt' alternate='no' title='Short' ?>")
fout.write("<files>")
fout.write("<validationreport>")
fout.write("xmlvalidations/" + row.country + "_validation_" + row.dbversion + ".xml")
fout.write("</validationreport>")
fout.write("<reportformat>reports/EN_Report.xml</reportformat>")
fout.write("</files>")
fout.write
fout.close()
f = urllib.urlopen("file:///C:/Documents%20and%20Settings/dmarban/Escritorio/python/BE_Full.xml")
s = f.read()
f.close()
HTML2PDF(s, "test.pdf", open=True)
The first I generate is an XML file that has the following content:
<?xml-stylesheet type='text/xsl' href='styles/Full_Report.xslt' alternate='no' title='Short' ?>
<files>
<validationreport>xmlvalidations/BE_validation_mid2010.xml</validationreport>
<reportformat>reports/EN_Report.xml</reportformat>
</files>
When I execute this code:
urllib.urlopen("file:///C:/Documents%20and%20Settings/dmarban/Escritorio/python/BE_Full.xml")
s = f.read()
f.close()
HTML2PDF(s, " BE_Full.pdf ", open=True)
It generates me the next file “BE_Full.pdf”, but instead of showing the
contents of the folder “xmlvalidations/BE_validation_mid2010.xml” show me the
contents of the labels that they are in pdf, It would show the following code:
xmlvalidations/BE_validation_mid2010.xml reports/EN_Report.xml
My question is, How I can parser a XML file in python, I read it as an HTML
file?
Answer: I'm not sure I understand the question fully, but are you expecting pisa to
apply the xslt transformation? I don't think it will do that (you might want
to look at [lxml](http://codespeak.net/lxml/) and use that to apply the xslt
_before_ converting to pdf with pisa)
|
wx.ProgressDialog not updating bar or newmsg
Question: The update method of wx.ProgressDialog has a newmsg argument that is
**supposed to give a textual update on what is happening in each step of the
process, but my code is not doing this properly.**
Here is the link to the documentation for wx.ProgressDialog
<http://www.wxpython.org/docs/api/wx.ProgressDialog-class.html>
Also, when I run my code, **the progress bar itself stops updating when it
looks to be about 50 percent complete.**
**Can anyone show me how to fix these two problems?**
Here is my code:
import wx
import time
class Frame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent, title="ProgressDialog sample")
self.progressMax = 4
self.count = 0
self.newstep='step '+str(self.count)
self.dialog = None
self.OnTimer(self.count)
def OnTimer(self, evt):
if not self.dialog:
self.dialog = wx.ProgressDialog("Progress in processing your data.",
self.newstep,
self.progressMax,
style=wx.PD_CAN_ABORT
| wx.PD_APP_MODAL
| wx.PD_SMOOTH
| wx.PD_AUTO_HIDE)
# Do Step One
print '----------------------------'
print 'Starting Step One now.'
self.count += 1
self.newstep='step '+str(self.count)
print 'self.count is: ',self.count
print 'self.newstep is: ',self.newstep
keepGoing = self.dialog.Update(self.count,self.newstep)
print '----------------------------'
time.sleep(5)
# Do Step Two
print '----------------------------'
print 'Starting Step Two now.'
self.count += 1
self.newstep='step '+str(self.count)
print 'self.count is: ',self.count
print 'self.newstep is: ',self.newstep
keepGoing = self.dialog.Update(self.count,self.newstep)
print '----------------------------'
time.sleep(5)
# Do Step Three
print '----------------------------'
print 'Starting Step Three now.'
self.count += 1
self.newstep='step '+str(self.count)
print 'self.count is: ',self.count
print 'self.newstep is: ',self.newstep
keepGoing = self.dialog.Update(self.count,self.newstep)
print '----------------------------'
time.sleep(5)
# Do Step Four
print '----------------------------'
print 'Starting Step Four now.'
self.count += 1
self.newstep='step '+str(self.count)
print 'self.count is: ',self.count
print 'self.newstep is: ',self.newstep
keepGoing = self.dialog.Update(self.count,self.newstep)
print '----------------------------'
time.sleep(5)
# Delete the progress bar when it is full
self.dialog.Update(self.progressMax)
time.sleep(3)
self.dialog.Destroy()
if __name__ == "__main__":
app = wx.PySimpleApp()
frame = Frame(None)
frame.Show()
app.MainLoop()
Notice that I am printing everything out in order to check progress. The
result of the print commands is different than what is shown in the progress
dialog. The print commands seem to be doing what the code is telling them to
do, but the progress dialog does not seem to be doing what the code is telling
it to do, and the progress dialog is not in agreement with the result of the
print commands.
This is in version 2.6 of Python.
## _**EDIT One:**_
##
\-------------------------------------------------------------------------------
I edited the code above to match adw's suggestions. The problem of not
updating newmsg seems to have been eliminated, but the progress bar itself
still seems to only get 50% full, and that happens when the newmsg output in
the dialog box says "step 3". The progress bar then disappears. A non-
computer-person using this software might realistically think that the process
only completed about 50% of its work, having quit early in step 3. **How can I
edit the code so that it shows "step 4" in the dialog box, and so that the
progress bar actually fills up to 100% for a second or two before the
ProgressDialog is killed?**
## _**Edit Two:**_
##
\------------------------------------------------------------------------------
I added the changes that ChrisC suggested to the code above, as you can see.
But running this newly altered code still gives the same problem. **So the
suggestion does not seem to work in the form that I understood when I edited
the code above. Can you suggest something specific I can do to the above code?
Is there anything that makes it work on your computer?**
Answer: Python identifiers are case sensitive, so `newstep` is different from
`newStep`.
As for the bar itself, that works properly when I run your code. Although I
had to change `(keepGoing, skip)` to `keepGoing` everywhere, probably a
version difference (I have `wx.VERSION_STRING == '2.6.3.2'`).
|
Execute an installed Python package as a script?
Question: Is there a way to enable a package to be executed as a script? For example:
[~]# easy_install /path/to/foo.egg
...
[~]# python -m foo --name World
Hello World
I've tried creating a `__main__.py` file inside my package but it's not being
executed (I'm using Python 2.6). The following error is raised:
foo is a package and cannot be directly executed
The structure of my package is as follows:
foo/
setup.py
foo/
__init__.py
__main__.py
Running `python -m foo.__main__ --name World` works as expected, but I would
prefer the former way of execution. Is this possible?
Answer: This is a regression in Python 2.6. See
[issue2571](http://bugs.python.org/issue2751):
> The ability to execute packages was never intended, since doing so breaks
> imports in a variety of subtle ways. It was actually a bug in 2.5 that it
> was permitted at all, so 2.6 not only disabled it again, but also added a
> test to make sure it stays disabled (2.4 correctly rejected it with an
> ImportError, just as 2.6 does).
You have a few options, you can either always run it specifying main:
$ python -m module.__main__
Or you can write a shell script wrapper that detects the python version and
then executes it in the different style.
Or you can execute code on the command line that will import and then run the
module, and then perhaps place that in a shell script:
$ python -c "import module; module.main()"
In my own command-line projects I have both the shell script that catches
errors (python not being installed, etc.) but the shell script will also
execute the import code and detect if the necessary modules have been
installed and prompt an error (with a helpful link or install text).
|
Using colons in ConfigParser Python
Question: According to the documentation:
> The configuration file consists of sections, led by a [section] header and
> followed by name: value entries, with continuations in the style of RFC 822
> (see section 3.1.1, “LONG HEADER FIELDS”); name=value is also accepted.
> [Python Docs](http://docs.python.org/library/configparser.html)
However, writing a config file always use the equal sign (=). Is there any
option to use the colon sign (:)?
Thanks in advance.
H
Answer: If you look at the code defining the `RawConfigParser.write` method inside
`ConfigParser.py` you'll see that the equal signs are hard-coded. So to change
the behavior you could subclass the ConfigParser you wish to use:
import ConfigParser
class MyConfigParser(ConfigParser.ConfigParser):
def write(self, fp):
"""Write an .ini-format representation of the configuration state."""
if self._defaults:
fp.write("[%s]\n" % DEFAULTSECT)
for (key, value) in self._defaults.items():
fp.write("%s : %s\n" % (key, str(value).replace('\n', '\n\t')))
fp.write("\n")
for section in self._sections:
fp.write("[%s]\n" % section)
for (key, value) in self._sections[section].items():
if key != "__name__":
fp.write("%s : %s\n" %
(key, str(value).replace('\n', '\n\t')))
fp.write("\n")
filename='/tmp/testconfig'
with open(filename,'w') as f:
parser=MyConfigParser()
parser.add_section('test')
parser.set('test','option','Spam spam spam!')
parser.set('test','more options',"Really? I can't believe it's not butter!")
parser.write(f)
yields:
[test]
more options : Really? I can't believe it's not butter!
option : Spam spam spam!
|
python class attributes not setting?
Question: I am having a weird problem with a chatbot I am writing that supports plugin
extensions. The base extension class have attributes and methods predefined
that will be inherited and can be overloaded and set. Here is the base class:
class Ext:
# Info about the extension
Name = 'Unnamed'
Author = 'Nobody'
Version = 0
Desc = 'This extension has no description'
Webpage = ''
# Determines whether the extension will automatically be on when added or not
OnByDefault = False
def __init__(self):
# Overwrite me! You can use me to load files and set attributes at startup
raise Exception('AbstractClassError: This class must be overloaded')
def SetName(self, name):
name = name.split(' ')
name = ''.join(name)
self.Name = name
def Load(self, file):
# Loads a file
return Misc.read_obj(file)
def Save(self, file, obj):
# Saves a file
return Misc.write_obj(file, obj)
def Activate(self, Komodo):
# When the extension is turned on, this is called
pass
def add_cmd(self, Komodo, name, callback, default=False, link=''):
# Add a command to the bot
if name in Komodo.Ext.commands:
Komodo.logger(msg = ">> Command '{0}' was already defined, so {1}'s version of the command couldn't be added".format(
name, self.meta.name))
else:
Komodo.Ext.commands[name] = callback
if default:
Komodo.Ext.default_commands.append(name)
if len(link) > 0:
Komodo.Ext.links[name] = link
def add_event(self, Komodo, type, callback):
# Add an event to the bot
if type not in Komodo.Ext.trigs:
Komodo.logger(msg =
">> Could not add '{0}' to event type '{1}' from extension '{2}' because that type does not exist".format(
str(callback), type, self.name))
else:
Komodo.Ext.trigs[type].append(callback)
This is what an extension normally looks like:
class Extension(Ext):
def __init__(self, K):
self.file = 'Storage/Extensions/AI.txt'
self.SetName('AI')
self.Version = 1.1
self.Author = 'blazer-flamewing'
self.Desc = 'An extension that lets you talk to an Artificial Intelligence program online called Kato.'
self.Webpage = 'http://botdom.com/wiki/Komodo/Extensions/AI'
try: self.AI = self.Load(file)
except: self.AI = {}
def Activate(self, K):
print(self.Version)
self.add_cmd(K, 'ai', self.cmd_AI, False, 'http://botdom.com/wiki/Komodo/Extensions/AI')
self.add_event(K, 'msg', self.msg_AI)
...more methods down here that aren't part of the base class
Every extension written like this works... except for one, the one mentioned
above. It only succeeds when setting it's Name attribute, and when the other
attributes are read they are still what the base class was set. At startup, I
looped through every extension to print the dict entry, the actual name, the
version, the author, and whether the extension was on or not and got this
result:
Responses Responses 1.2 blazer-flamewing OFF
Ai AI 0 Nobody ON
Notes Notes 1.2 blazer-flamewing OFF
Misc Misc 1.5 blazer-flamewing OFF
System System 2.2 blazer-flamewing ON
Helloworld HelloWorld 1.3 blazer-flamewing OFF
Goodbyes Goodbyes 0 blazer-flamewing OFF
Spamfilter Spamfilter 1.2 blazer-flamewing OFF
Damn dAmn 2.2 blazer-flamewing ON
Bds BDS 0.2 blazer-flamewing OFF
Fun Fun 1.6 blazer-flamewing OFF
Welcomes Welcomes 1.5 blazer-flamewing OFF
Cursefilter Cursefilter 1.7 blazer-flamewing OFF
Similarly, Extension.Activate() isn't working for AI when it is turned on. I
assume that has to do with the same sort of problem (not being set properly)
Any ideas as to why the class's attributes aren't setting? I've been stuck on
this for hours and the extension is set up the exact same way other extensions
are
EDIT: Here is another extension for comparison. This one actually works,
Activate() actually calls. everything is pretty much exactly the same other
than content
from komodo.extension import Ext
import time
class Extension(Ext):
def __init__(self, K):
self.SetName('dAmn')
self.Version = 2.2
self.Author = 'blazer-flamewing'
self.Desc = 'Module for all standard dAmn commands such as join, part, and say.'
self.Webpage = 'http://botdom.com/wiki/Komodo/Extensions/dAmn'
self.OnByDefault = True
def Activate(self, K):
self.add_cmd(K, 'action', self.cmd_action, False, "http://botdom.com/wiki/Komodo/Extensions/dAmn#Me_or_Action")
self.add_cmd(K, 'ban', self.cmd_ban, False, "http://botdom.com/wiki/Komodo/Extensions/dAmn#Ban_and_Unban")
self.add_cmd(K, 'chat', self.cmd_chat, True, "http://botdom.com/wiki/Komodo/Extensions/dAmn#Chat")
self.add_cmd(K, 'demote', self.cmd_demote, False, "http://botdom.com/wiki/Komodo/Extensions/dAmn#Demote_and_Promote")
self.add_cmd(K, 'join', self.cmd_join, False, "http://botdom.com/wiki/Komodo/Extensions/dAmn#Join_and_Part")
...etc
Answer: You forgot a 'self' in class Extension:
try: self.AI = self.Load(self.file)
also, maybe your printing test is inaccurate. Have you tried unit tests?
|
override multiprocessing in python
Question: how can i get variable in class which is override multiprocessing in python:
#!/usr/bin/env python
import multiprocessing
import os
class TestMultiprocess(multiprocessing.Process):
def __init__(self):
multiprocessing.Process.__init__(self)
self.myvar = ''
def myfunc(self):
return os.getpid()
def run(self):
self.myvar = self.myfunc()
mlist = []
for i in range(10):
t = TestMultiprocess()
mlist.append(t)
t.start()
for j in mlist:
t.join()
print t.myvar
i can not get value "myvar" from class TestMultiprocess, i just get blank. But
i already override the run() function from Process.
sorry if my spell very bad ...
Answer: The run() will executed in a separate process; processes don't share memory,
normally. multiprocessing does support shared variables, though, through the
explicit [Value](http://docs.python.org/library/multiprocessing.html#sharing-
state-between-processes) class:
#!/usr/bin/env python
import multiprocessing
import os
class TestMultiprocess(multiprocessing.Process):
def __init__(self):
multiprocessing.Process.__init__(self)
self.myvar = multiprocessing.Value('i',0)
def myfunc(self):
return os.getpid()
def run(self):
self.myvar.value = self.myfunc()
mlist = []
for i in range(10):
t = TestMultiprocess()
mlist.append(t)
t.start()
for j in mlist:
j.join()
print j.myvar.value
|
Using the RESTful interface to Google's AJAX Search API for "Did you mean"?
Question: Is it possible to get spelling/search suggestions (i.e. "Did you mean") via
the RESTful interface to Google's AJAX search API? I'm trying to access this
from Python, though the URL query syntax is all I really need.
Thanks!
Answer: the Google AJAX API don't have a spelling check feature see
[this](https://groups.google.com/group/google-ajax-search-
api/browse_thread/thread/61eb608918f00632/ee794142dbf87046?lnk=raot), you can
use the [SOAP
service](http://code.google.com/apis/soapsearch/reference.html#1_3) but i
think it's no longer available .
at last you can look at yahoo API they have a feature for [spelling
check](http://developer.yahoo.com/search/web/V1/spellingSuggestion.html).
**EDIT :** check this maybe it can help you:
import httplib
import xml.dom.minidom
data = """
<spellrequest textalreadyclipped="0" ignoredups="0" ignoredigits="1" ignoreallcaps="1">
<text> %s </text>
</spellrequest>
"""
word_to_spell = "gooooooogle"
con = httplib.HTTPSConnection("www.google.com")
con.request("POST", "/tbproxy/spell?lang=en", data % word_to_spell)
response = con.getresponse()
dom = xml.dom.minidom.parseString(response.read())
dom_data = dom.getElementsByTagName('spellresult')[0]
for child_node in dom_data.childNodes:
result = child_node.firstChild.data.split()
print result
|
compilation error. AttributeError: 'module' object has no attribute 'init'
Question: Here is my small program,
import pygame
pygame.init()
Here is my compilation command.
> python myprogram.py
Compilation error,
File "game.py", line 1, in
import pygame
File "/home/ubuntu/Documents/pygame.py", line 2, in
pygame.init()
AttributeError: 'module' object has no attribute 'init'
I have pygame installed in my ubuntu, It is installed in
/usr/lib/python2.6/dist-packages/pygame
I found tht from IDLE, If I execute both of this statements, It works fine.
Answer: Delete the "pygame.py" file in your Documents folder, it is shadowing the real
pygame you've installed.
It looks like you first saved your small test program as "pygame.py", then
renamed it to "game.py".
|
How to compare an item in a queue to an item in a set?
Question: REDIT: Was trying to avoid just placing the entire block of code on the forum
and saying fix it for me, but here it is, to simply the process of determining
the error:
#! /usr/bin/python2.6
import threading
import Queue
import sys
import urllib
import urllib2
from urlparse import urlparse
from lxml.html import parse, tostring, fromstring
THREAD_NUMBER = 1
class Crawler(threading.Thread):
def __init__(self, queue, mal_urls, max_depth):
self.queue = queue
self.mal_list = mal_urls
self.crawled_links = []
self.max_depth = max_depth
self.count = 0
threading.Thread.__init__(self)
def run(self):
while True:
if self.count <= self.max_depth:
self.crawled = set(self.crawled_links)
url = self.queue.get()
if url not in self.mal_list:
self.count += 1
self.crawl(url)
else:
#self.queue.task_done()
print("Malicious Link Found: {0}".format(url))
continue
else:
self.queue.task_done()
break
print("\nFinished Crawling! Reached Max Depth!")
sys.exit(2)
def crawl(self, tgt):
try:
url = urlparse(tgt)
self.crawled_links.append(tgt)
print("\nCrawling {0}".format(tgt))
request = urllib2.Request(tgt)
request.add_header("User-Agent", "Mozilla/5,0")
opener = urllib2.build_opener()
data = opener.open(request)
except: # TODO: write explicit exceptions the URLError, ValueERROR ...
return
doc = parse(data).getroot()
for tag in doc.xpath("//a[@href]"):
old = tag.get('href')
fixed = urllib.unquote(old)
self.queue_links(fixed, url)
def queue_links(self, link, url):
if link.startswith('/'):
link = "http://" + url.netloc + link
elif link.startswith("#"):
return
elif not link.startswith("http"):
link = "http://" + url.netloc + "/" + link
if link not in self.crawled_links:
self.queue.put(link)
self.queue.task_done()
else:
return
def make_mal_list():
"""Open various malware and phishing related blacklists and create a list
of URLS from which to compare to the crawled links
"""
hosts1 = "hosts.txt"
hosts2 = "MH-sitelist.txt"
hosts3 = "urls.txt"
mal_list = []
with open(hosts1) as first:
for line1 in first:
link = "http://" + line1.strip()
mal_list.append(link)
with open(hosts2) as second:
for line2 in second:
link = "http://" + line2.strip()
mal_list.append(link)
with open(hosts3) as third:
for line3 in third:
link = "http://" + line3.strip()
mal_list.append(link)
return mal_list
def main():
x = int(sys.argv[2])
queue = Queue.Queue()
mal_urls = set(make_mal_list())
for i in xrange(THREAD_NUMBER):
cr = Crawler(queue, mal_urls, x)
cr.start()
queue.put(sys.argv[1])
queue.join()
if __name__ == '__main__':
main()
So what I've got going on here is a web spider, which first creates a set made
of the lines of several text files which contain 'malicious links'. Then
starts a thread, passing both the set of bad links, and sys.argv[1]. The
started thread, then calls teh crawl function which retrieves an lxml.html
parse from sys.argv[1], and then after parsing all the links out of that
initial page, places them in the queue. The loop continues, with each link
placed in the queue being removed with self.queue.get(). The corresponding
link is then SUPPOSED to be compared against the set of bad links. If the link
in found to be bad, the loop is supposed to output it to the screen and then
continue on to the next link, UNLESS it has already crawled that link.
If it is not bad, crawl it, parse it, place its links into the queue, etc,
incrementing a counter each time a link is crawled, and continuing until the
counter reaches a limit determined by the value passed as sys.argv[2]. The
problem is that, items it should be triggering the if/else statement for 'if
url not in mal_list' are not, and links that have been placed in the
'crawled_already' list, are being crawled a 2nd, 3rd, and forth time anyhow.
Answer: I don't understand one detail of this code: the queue is marked as `task_done`
if there is any new link found in `self.queue_links`, but not as a matter of
course in `self.crawl`. I'd have thought that this code would make more sense:
def crawl(self, tgt):
try:
url = urlparse(tgt)
self.crawled_links.append(tgt)
print("\nCrawling {0}".format(tgt))
request = urllib2.Request(tgt)
request.add_header("User-Agent", "Mozilla/5,0")
opener = urllib2.build_opener()
data = opener.open(request)
doc = parse(data).getroot()
for tag in doc.xpath("//a[@href]"):
old = tag.get('href')
fixed = urllib.unquote(old)
self.queue_links(fixed, url)
self.queue.task_done()
except: # TODO: write explicit exceptions the URLError, ValueERROR ...
pass
def queue_links(self, link, url):
if not link.startswith("#"):
if link.startswith('/'):
link = "http://" + url.netloc + link
elif not link.startswith("http"):
link = "http://" + url.netloc + "/" + link
if link not in self.crawled_links:
self.queue.put(link)
I can't say, though, that I have a complete answer to your question.
* * *
Later: the [docs](http://docs.python.org/library/queue.html) for
`Queue.task_done` suggest that `task_done` should be 1:1 with `Queue.get`
calls:
> Queue.task_done()¶
>
> Indicate that a formerly enqueued task is complete. Used by queue consumer
> threads. For each get() used to fetch a task, a subsequent call to
> task_done() tells the queue that the processing on the task is complete.
>
> If a join() is currently blocking, it will resume when all items have been
> processed (meaning that a task_done() call was received for every item that
> had been put() into the queue).
>
> Raises a ValueError if called more times than there were items placed in the
> queue.
Were you getting [uncaught] `ValueError` exceptions? It looks like this might
be so.
|
Python Tkinter Embed Matplotlib in GUI
Question: I'm trying to embed a plot in my Tkinter GUI coded in Python. I believe the
code below succeeds in simply putting a graph into a canvas, but I don't have
any control of the canvas location within the GUI grid. I want to be able to
have a subsection of my GUI be the plot...not the entirety of it. How can I
position this canvas widget?
#!/usr/apps/Python/bin/python
import matplotlib, sys
matplotlib.use('TkAgg')
from numpy import arange, sin, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
from Tkinter import *
master = Tk()
master.title("Hello World!")
#-------------------------------------------------------------------------------
f = Figure(figsize=(5,4), dpi=100)
a = f.add_subplot(111)
t = arange(0.0,3.0,0.01)
s = sin(2*pi*t)
a.plot(t,s)
dataPlot = FigureCanvasTkAgg(f, master=master)
dataPlot.show()
dataPlot.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
#-------------------------------------------------------------------------------
master.mainloop()
Answer: You don't have any other widgets so it's hard to know where you want other
widgets. Here's what I can tell you though: by doing
`dataPlot.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)` you are asking
Tkinter to fill the screen with the plot. This, because you ask it to fill in
all directions (`fill=BOTH`) and expand to fill any extra space (`expand=1`).
However, you can still add other widgets. `pack` works by putting widgets on
one side of a container. Your container, `master`, always has four sides. So,
for example, if you wanted to create a toolbar you would do something like:
toolbar = tk.Frame(master)
button = tk.Button(toolbar, text="Push me")
button.pack(side="left") # left side of parent, the toolbar frame
toolbar.pack(side=TOP, fill="x") # top of parent, the master window
Notice that if you put this code _after_ the code where you `pack` the plot,
the toolbar shows up on the bottom! That's because `TOP`, `BOTTOM`, etc refer
to space left over by any other widgets that have already been `pack`ed. The
plot takes up the top, the space left over is at the bottom. So when you
specify `TOP` again it means "at the top of the area below whatever is already
at the top".
So, you have some choices. The best choice is to make your widgets in the
order you wish them to appear. If you `pack` the toolbar at the top before you
`pack` the plot, it will be the toolbar that shows up at the very top.
Further, you can place the plot at the bottom rather than the top and that
will solve the problem, too.
By the way, I typically create my widgets in one block, then lay them all out
in a separate block. I find it makes the code easier to maintain.
Another choice which may fit your mental model better is to `grid` _instead
of_ `pack`. With `grid` you can choose the row(s) and column(s) that the
widget occupies. This makes it easy to lay things out in a grid, but at the
expense of having to use a little more code.
For example, to put the toolbar at the top and the plot down below you might
do:
toolbar.grid(row=1, column=1, sticky="ew")
dataPlot.get_tk_widget().grid(row=1, column=1, sticky="nsew")
master.grid_rowconfigure(0, weight=0)
master.grid_rowconfigure(1, weight=1)
master.grid_columnconfigure(0, weight=1)
Notice that rows and columns start at zero. Also, "weight" refers to how much
this widget expands relative to other widgets. With two rows of equal weight,
they will expand equally when the window is resized. A weight of zero means no
expansion. A weight of 2 for one row, and 1 for another means that the former
will expand twice as much as the latter.
For more information see [this page on
grid](http://effbot.org/tkinterbook/grid.htm), and [this page on
pack](http://effbot.org/tkinterbook/pack.htm).
|
how do I modify the system path variable in python script?
Question: I'm trying to run a python script from cron, but its not running properly so
I'm assuming its the different path env variable. Is there anyway to change
the variable within a python script?
Answer: @ubuntu has the right approach, but for what it's worth, @Joe Schmoe, if you
ever need the info:
import sys
print sys.path
['.', '/usr/local/bin', '/usr/local/lib/python2.6/dist-packages',...]
sys.path.append('/home/JoeBlow/python_scripts')
print sys.path
['.', '/usr/local/bin', '/usr/local/lib/python2.6/dist-packages', '/home/JoeBlow/python_scripts',...]
sys.path is an array containing everything that was in your initiating
script's PYTHONPATH variable (or whatever your shell's default PYTHONPATH is).
|
Using Cython to expose functionality to another application
Question: I have this C++ code that shows how to extend a software by compiling it to a
DLL and putting it in the application folder:
#include <windows.h>
#include <DemoPlugin.h>
/** A helper function to convert a char array into a
LPBYTE array. */
LPBYTE message(const char* message, long* pLen)
{
size_t length = strlen(message);
LPBYTE mem = (LPBYTE) GlobalAlloc(GPTR, length + 1);
for (unsigned int i = 0; i < length; i++)
{
mem[i] = message[i];
}
*pLen = length + 1;
return mem;
}
long __stdcall Execute(char* pMethodName, char* pParams,
char** ppBuffer, long* pBuffSize, long* pBuffType)
{
*pBuffType = 1;
if (strcmp(pMethodName, "") == 0)
{
*ppBuffer = (char*) message("Hello, World!",
pBuffSize);
}
else if (strcmp(pMethodName, "Count") == 0)
{
char buffer[1024];
int length = strlen(pParams);
*ppBuffer = (char*) message(itoa(length, buffer, 10),
pBuffSize);
}
else
{
*ppBuffer = (char*) message("Incorrect usage.",
pBuffSize);
}
return 0;
}
Is is possible to make a plugin this way using Cython? Or even py2exe? The DLL
just has to have an entry point, right?
Or should I just compile it natively and embed Python using
[elmer](http://elmer.sourceforge.net/index.html)?
Answer: I think the solution is to use both. Let me explain.
Cython makes it convenient to make a fast plugin using python but inconvenient
(if at all possible) to make the right "kind" of DLL. You would probably have
to use the standalone mode so that the necessary python runtime is included
and then mess with the generated c code so an appropriate DLL gets compiled.
Conversely, elmer makes it convenient to make the DLL but runs "pure" python
code which might not be fast enough. I assume speed is an issue because you
are considering cython as opposed to simple embedding.
My suggestion is this: the pure python code that elmer executes should import
a standard cython python extension and execute code from it. This way you
don't have to hack anything ugly and you have the best of both worlds.
* * *
One more solution to consider is using
[shedskin](http://code.google.com/p/shedskin/), because that way you can get
c++ code from your python code that is independent from the python runtime.
|
python test script
Question: I am trying to automate a test script for a website
I have the following error
import urllib , urllib2 , cookielib , random ,datetime,time,sys
cookiejar = cookielib.CookieJar()
urlOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))
urllib2.install_opener(urlOpener)
username=username.strip()
values = {'username': username, 'password': 'password'} #user input
data = urllib.urlencode(values)
request = urllib2.Request('http://141.168.25.182/',data)
url = urlOpener.open(request)
File "<stdin>", line 1, in ?
File "/usr/lib/python2.4/urllib2.py", line 364, in open
response = meth(req, response)
File "/usr/lib/python2.4/urllib2.py", line 471, in http_response
response = self.parent.error(
File "/usr/lib/python2.4/urllib2.py", line 402, in error
return self._call_chain(*args)
File "/usr/lib/python2.4/urllib2.py", line 337, in _call_chain
result = func(*args)
File "/usr/lib/python2.4/urllib2.py", line 480, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden
Answer: A few suggestions that might help you
**urlencode function is different from what you think**
>>> from urllib import urlencode
>>> values = {'username': 'username', 'password': 'password'}
>>> data = urlencode(values)
>>> data
'username=username&password=password'
>>>
**request method arguments are again incorrect**
When you do this the, data is the request payload
request = urllib2.Request('http://141.168.25.182/',data)
**What you want to do is authenticate yourself.**
This will depend on what type of authentication server expects. The following
serves for basic authentication using urllib2. Read the module docs for more
detail.
import urllib2
auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(user='..', passwd='...')
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
urllib2.urlopen('url)
|
Django: Import CSV file and handle clash of unique values correctly
Question: I want to write a Python script to import the contents of CSV file into a
Django app's database. So for each CSV record, I create an instance of my
model, set the appropriate values from the parsed CSV line and call save on
the model instance. For example, see below:
for row in dataReader:
person=Person()
person.name=row[0]
person.age=row[1]
person.save()
Now, lets say that the name Field is marked as unique in the Model. What's the
best way to handle the situation where the record being imported has the same
Name value as one already in the database? Should I check for this before
calling save? How? Should I catch an exception? What would the code look like?
**EDIT:** If a record already exists in the db with the same name field, I
would still like to update the other fields. For example, if I was importing
Fred,43 and there was already a record Fred,42 in the db it should update the
db to Fred,43.
**EDIT:** Thanks for all the answers. This approach, pointed to by chefsmart,
is the one I think I will go with:
try:
obj = Person.objects.get(name=name)
except Person.DoesNotExist:
obj = Person()
obj.name = name
obj.age = age
obj.save()
Answer: One of the Django orm function that i love so much is
[get_or_create()](http://www.djangoproject.com/documentation/models/get_or_create/)
so i will suggest you do like this:
for row in dataReader:
person_record, created = person.get_or_create(name=row[0], age=row[1])
you can check after if you want to change the old record in `person_record` or
check if the record was created `if created:` and do what ever you want with
it ..
hope this will help
|
tkinter: grid method strange behavior
Question: I want this code to do this:
Create 4 frames with this layout (dashes mean the frame spans that column):
-X-
XXX
Within each of these frames (X's) there should be two rows like this:
cowN,1
cowN,2
It seems like the grid() method is _global_ **ONLY** and is never specific to
a single frame...
#!/usr/apps/Python/bin/python
from Tkinter import *
master = Tk()
frame1 = Frame(master).grid(row=0,columnspan=3)
frame2 = Frame(master).grid(row=1,column=0)
frame3 = Frame(master).grid(row=1,column=1)
frame4 = Frame(master).grid(row=1,column=2)
#->Frame1 contents
Label(frame1, text='cow1,1').grid(row=0)
Label(frame1, text='cow1,2').grid(row=1)
#->Frame2 contents
Label(frame2, text='cow2,1').grid(row=0)
Label(frame2, text='cow2,2').grid(row=1)
#->Frame3 contents
Label(frame3, text='cow3,1').grid(row=0)
Label(frame3, text='cow3,2').grid(row=1)
#->Frame4 contents
Label(frame4, text='cow4,1').grid(row=0)
Label(frame4, text='cow4,2').grid(row=1)
master.mainloop()
Answer: The problem with your code is that your are not keeping a reference to the
`Frame` objects on your `frameN` variables: you create the objects, and call
their `grid` method: you store the return of the grid method on the variables,
which is `None`.
So, your labels are being created with `None` as their master.
Just change your lines to read:
frame1 = Frame(master);
frame1.grid(row=0, columnspan=3)
|
Serializing a user-defined class in Python
Question: got a question regarding serializing classes that I've defined. I have some
classes like
class Foo:
def __init__(self, x, y):
self.x = x, self.y = y
def toDict(self):
return dict(Foo = dict(x = self.x, y = self.y))
then a class that can contain multiple Foos, such as:
class Bar:
def __init__(self):
self.foos = [Foo(a, b), Foo(1, 2)]
While that's a gross oversimplification of the real structure (it gets much,
much more nested than that), that's a pretty decent overview. The actual data
for this is coming from a pseudo-XML file without any actual structure, so I
wrote a parser according to the spec given to me, so I now have all the data
in a series of classes I've defined, with actual structure.
What I'm wanting to do is take this data I have and spit it out into JSON, but
I really don't see a good way (I'm new to Python, this is my first real
project with it).
I've defined a method in Foo, toDict(), that creates a dictionary out of the
information, but that obviously isn't going to work out like I hope when I try
to serialize Bar, with the multiple Foos.
Does anyone have a great way of doing this? This has been a pretty much non-
stop learning/codefest the past few days and I'm out of ideas for this, which
is the last part of the project. I know about the JSON module for Python, but
that doesn't help me with this particular problem of getting my data into a
dictionary (or something similar) that I can pass to json.dump().
Let me know if I can clarify in any way.
Thanks, T.J.
Answer: Several comments. First:
* [`xml.dom.minidom`](http://docs.python.org/library/xml.dom.minidom.html) is a built-in Python DOM implementation. Obviously if the file isn't actually XML you won't be able to use it's builtin parsing functions, but it looks like you're building a tree-like structure out of the file anyway, in which case you might as well use a `minidom`.
OK, henceforth I'll assume that you have a good reason for writing your own
tree-style structure instead of using the builtins.
* Are you sure the nodes should be classes? That seems like an awful lot of structure when all you really seem to need is a bunch of nested `dict`s:
root = {
"foo1": { "bar1": "spam", "bar2": "ham"},
"foo2": { "baz1": "spam", "baz2": "ham"},
}
You get the idea.
OK, maybe you're sure that you need the individual nodes to be classes. In
that case, they should all inherit from some `BaseNode` class, right? After
all, they are fundamentally similar things.
* In that case, define a `BaseNode.serialise` method which effectively prints some information about itself and then calls `serialise` on all of its children. This is a recursive problem; you might as well use a recursive solution unless your tree is really really _really_ nested.
The `json` library allows you to subclass the `JSONEncoder` to do this.
>>> import json
>>> class ComplexEncoder(json.JSONEncoder):
... def default(self, obj):
... if isinstance(obj, complex):
... return [obj.real, obj.imag]
... return json.JSONEncoder.default(self, obj)
...
>>> dumps(2 + 1j, cls=ComplexEncoder)
'[2.0, 1.0]'
>>> ComplexEncoder().encode(2 + 1j)
'[2.0, 1.0]'
>>> list(ComplexEncoder().iterencode(2 + 1j))
['[', '2.0', ', ', '1.0', ']']
|
How to save web page as image using python
Question: I am using python to create a "favorites" section of a website. Part of what I
want to do is grab an image to put next to their link. So the process would be
that the user puts in a URL and I go grab a screenshot of that page and
display it next to the link. Easy enough?
I have currently downloaded [pywebshot](http://www.coderholic.com/pywebshot-
generate-website-thumbnails-using-python/) and it works great from my terminal
on my local box. However, when I put it on the server, I get a Segmentation
Fault with the following traceback:
/usr/lib/pymodules/python2.6/gtk-2.0/gtk/__init__.py:57: GtkWarning: could not open display
warnings.warn(str(e), _gtk.Warning)
./pywebshot.py:16: Warning: invalid (NULL) pointer instance
self.parent = gtk.Window(gtk.WINDOW_TOPLEVEL)
./pywebshot.py:16: Warning: g_signal_connect_data: assertion `G_TYPE_CHECK_INSTANCE (instance)' failed
self.parent = gtk.Window(gtk.WINDOW_TOPLEVEL)
./pywebshot.py:49: GtkWarning: Screen for GtkWindow not set; you must always set
a screen for a GtkWindow before using the window
self.parent.show_all()
./pywebshot.py:49: GtkWarning: gdk_screen_get_default_colormap: assertion `GDK_IS_SCREEN (screen)' failed
self.parent.show_all()
./pywebshot.py:49: GtkWarning: gdk_colormap_get_visual: assertion `GDK_IS_COLORMAP (colormap)' failed
self.parent.show_all()
./pywebshot.py:49: GtkWarning: gdk_screen_get_root_window: assertion `GDK_IS_SCREEN (screen)' failed
self.parent.show_all()
./pywebshot.py:49: GtkWarning: gdk_window_new: assertion `GDK_IS_WINDOW (parent)' failed
self.parent.show_all()
Segmentation fault
I know that some things can't run in a pts environment, but honestly that's a
little beyond me right now. If I need to somehow pretend that my pts
connection is tty, I can try it. But at this point I'm not even sure what's
going on and I admit it's a bit over my head. Any help would be greatly
appreciated.
Also, if there's a web service that I can pass a url and receive an image,
that would work just as well. I am NOT married to the idea of pywebshot.
I do know that the server I'm on is running X and has all the necessary python
modules installed.
Thanks in advance.
Answer: I found [websnapr.com](http://websnapr.com) which is a web service that will
give you the image with just a little bit of work.
import subprocess
subprocess.Popen(['wget', '-O', MYFILENAME+'.png', 'http://images.websnapr.com/?url='+MYURL+'&size=s&nocache=82']).wait()
Easy as pie.
|
Python equivalent to Java's Class.getResource
Question: I have some XML files on my PYTHONPATH that I would like to load using their
path on the PYTHONPATH, rather than their (relative or absolute) path on the
filesystem. I could simply inline them as strings in a Python module (yay
multiline string literals), and then load them using a regular `import`
statement, but I'd like to keep them separated out as regular XML files, if
possible. In Java world, the solution to this would be to use the
[Class.getResource](http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Class.html#getResource%28java.lang.String%29)
method, and I'm wondering if something similar exists in Python.
Answer: Take a look at
[pkg_resources](http://packages.python.org/distribute/pkg_resources.html#resourcemanager-
api), it includes apis for the inclusion to generic resources. It is thought
to work with python eggs and so it could be much more of you need.
Just an example taken from the doc:
import pkg_resources
my_data = pkg_resources.resource_string(__name__, "foo.dat")
|
Puzzling Parallel Python Problem - TRANSPORT_SOCKET_TIMEOUT
Question: The following code doesn't appear to work properly for me. It requires
starting a ppserver on another computer on your network, for example with the
following command:
ppserver.py -r -a -w 4
Once this server is started, on my machine I run this code:
import pp
import time
job_server = pp.Server(ppservers = ("*",))
job_server.set_ncpus(0)
def addOneBillion(x):
r = x
for i in xrange(10**9):
r+=1
f = open('/home/tomb/statusfile.txt', 'a')
f.write('finished at '+time.asctime()+' for job with input '+str(x)+'\n')
return r
jobs = []
jobs.append(job_server.submit(addOneBillion, (1,), (), ("time",)))
jobs.append(job_server.submit(addOneBillion, (2,), (), ("time",)))
jobs.append(job_server.submit(addOneBillion, (3,), (), ("time",)))
for job in jobs:
print job()
print 'done'
The odd part: Watching the /home/tomb/statusfile.txt, I can see that it's
getting written to several times, as though the function is being run several
times. I've observed this continuing for over an hour before, and never seen a
`job()` return.
Odder: If I change the number of iterations in the testfunc definition to
10**8, the function is just run once, and returns a result as expected!
Seems like some kind of race condition? Just using local cores works fine.
This is with pp v 1.6.0 and 1.5.7.
Update: Around 775,000,000: I get inconsistent results: two jobs repeat once,
on finishes the first time.
Week later update: I've written my own parallel processing module to get
around this, and will avoid parallel python in the future, unless someone
figures this out - I'll get around to looking at it some more (actually diving
into the source code) at some point.
Months later update: No remaining hard feelings, Parallel Python. I plan to
move back as soon as I have time to migrate my application. Title edit to
reflect solution.
Answer: Answer from Bagira of the Parallel Python forum:
> How long does the calculation of every job take? Have a look at the variable
> `TRANSPORT_SOCKET_TIMEOUT` in /usr/local/lib/python2.6/dist-
> packages/pptransport.py.
>
> Maybe your job takes longer than the time in the variable above. Increase
> the value of it and try.
Turns out this was exactly the problem. In my application I'm using PP as a
batch scheduler of jobs that can take several minutes, so I need to adjust
this. (the default was 30s)
|
What is the difference between pickle and shelve?
Question: I am learning about object serialization for the first time. I tried reading
and 'googling' for differences in the modules pickle and shelve but I am not
sure I understand it. When to use which one? Pickle can turn every python
object into stream of bytes which can be persisted into a file. Then why do we
need the module shelve? Isn't pickle faster?
Answer: `pickle` is for serializing some object (or objects) as a single bytestream in
a file.
`shelve` builds on top of `pickle` and implements a serialization dictionary
where objects are pickled, but associated with a key (some string), so you can
load your shelved data file and access your pickled objects via keys. This
could be more convenient were you to be serializing many objects.
Here is an example of usage between the two. (should work in latest versions
of Python 2.7 and Python 3.x).
## `pickle` Example
import pickle
integers = [1, 2, 3, 4, 5]
with open('pickle-example.p', 'wb') as pfile:
pickle.dump(integers, pfile)
This will dump the `integers` list to a binary file called `pickle-example.p`.
Now try reading the pickled file back.
import pickle
with open('pickle-example.p', 'rb') as pfile:
integers = pickle.load(pfile)
print integers
The above should output `[1, 2, 3, 4, 5]`.
## `shelve` Example
import shelve
integers = [1, 2, 3, 4, 5]
# If you're using Python 2.7, import contextlib and use
# the line:
# with contextlib.closing(shelve.open('shelf-example', 'c')) as shelf:
with shelve.open('shelf-example', 'c') as shelf:
shelf['ints'] = integers
Notice how you add objects to the shelf via dictionary-like access.
Read the object back in with code like the following:
import shelve
# If you're using Python 2.7, import contextlib and use
# the line:
# with contextlib.closing(shelve.open('shelf-example', 'r')) as shelf:
with shelve.open('shelf-example', 'r') as shelf:
for key in shelf.keys():
print(repr(key), repr(shelf[key])))
The output will be `'ints', [1, 2, 3, 4, 5]`.
|
isFollowingCamelCaseConventionInCPlusPlus more_import_than_readability?
Question: I'm moving back from Python to C++ for my next project.
I know [why I shouldn't](http://yosefk.com/c++fqa/) and I know [why I
should](http://stackoverflow.com/questions/3175072/performance-of-c-vs-
virtual-machine-languages-in-high-frequency-finance). Never mind that debate.
[C++
conventionForVariablesIsCamelCase](http://geosoft.no/development/cppstyle.html#Naming%20Conventions)AndI'mHavingTrouble[AcceptingIt](http://stackoverflow.com/questions/608443/underscore-
or-camelcase) as,
at_least_for_my_eyes_it's_less_readable_than_the_lower_case_underscored_convention.
Did any of you encounter an article or information claiming programmers should
adopt lower_case_underscored convention and abandon the camelCase, even in C++
projects? Or perhaps research that shows that one is indeed scientifically
more readable than the other?
Answer: If coding in a team, consistency is probably more important than personal
preference; team members should not have to context switch between reading
Joe's code and reading Jane's code. Equally if coding academic assignments,
course style like team style should be adhered to (for right or wrong), simply
because the person awarding the marks will be used to reading that, and you
need to extract the best possible mark for your work!
I would suggest otherwise that one convention has little advantage over
another. CamelCase does provide a certain efficiency of symbol length.
|
forms.ValidationError not working
Question: i have a fileinput field for uploading files ... the view file looks like this
...
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from forms import RegisterForm
from django.views.decorators.csrf import csrf_protect
from django.template import RequestContext
from django import forms
from django.contrib.auth import authenticate
from django.contrib import auth
from settings import MEDIA_ROOT
class UploadFileForm(forms.Form):
file = forms.Field(widget=forms.FileInput, required=True)
@csrf_protect
def register(request):
if request.method == 'POST':
form = RegisterForm(request.POST)
if form.is_valid():
new_user = form.save()
'''
just added the late three lines for check
'''
username = request.POST['username']
password = request.POST['password1']
user = authenticate(username=username, password=password)
auth.login(request, user)
request.session['username'] = username
return HttpResponseRedirect("/file_check/")
else:
form = RegisterForm()
return render_to_response("register.html", RequestContext(request, {'form':form}))
@csrf_protect
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password1']
form = UserCreationForm(request.POST)
user = authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
request.session['username'] = username
return HttpResponseRedirect('/file_check/')
else:
form = UserCreationForm()
return render_to_response("login.html", RequestContext(request, {'form':form}))
def logout(request):
auth.logout(request)
#del request.session['username']
return HttpResponseRedirect("/")
@csrf_protect
def file_check(request):
if not request.user.is_authenticated():
return HttpResponseRedirect('/accounts/login/')
if 'file' in request.FILES:
file = request.FILES['file']
if file.content_type != 'application/octet-stream':
raise forms.ValidationError('File Type Not Supported!!!')
request.session['contentType'] = file.content_type
filename = file.name
fp = open('%s/%s' % (MEDIA_ROOT, filename), 'wb')
for chunk in file.chunks():
fp.write(chunk)
fp.close()
return HttpResponseRedirect('/result/')
else:
form = UploadFileForm()
username = request.session['username']
return render_to_response('file_check.html', RequestContext(request, {'form':form, 'username':username}))
def result(request):
username = request.session['username']
content_type = request.session['contentType']
return render_to_response('result.html', {'username':username, 'content_type':content_type})
However, when i try to upload the file other than simple text file (say for
e.g. pdf files) for checking at '/file_check/' all i get is "ValidationError
at /file_check/". The traceback of the error is
Environment:
Request Method: POST
Request URL: http://localhost:8000/file_check/
Django Version: 1.2.3
Python Version: 2.6.4
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'rocop_web.auth']
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.6/dist-packages/django/core/handlers/base.py" in get_response
100. response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/utils/decorators.py" in _wrapped_view
76. response = view_func(request, *args, **kwargs)
File "/home/kailash/workspace/rocop/rocop_web/../rocop_web/auth/views.py" in file_check
63. raise forms.ValidationError('File Type Not Supported!!!')
Exception Type: ValidationError at /file_check/
Exception Value:
I am a beginer in django and finding it hard to solve. Your help is warmly
appreciated.
Answer:
from django.forms import forms
from django.db.models.fields.files import FileField
class CustomFileField(FileField):
attr_class = CustomFieldFile
allowed_extensions = ('txt', 'pdf')
def clean(self, value, model_instance):
extension = str(value).lower().split('.').pop()
if extension not in self.allowed_extensions:
raise forms.ValidationError('Only %s are allowed!' % ', '.join(self.allowed_extensions))
return super(CustomFileField, self).clean(value, model_instance)
your view:
@csrf_protect
def file_check(request):
if request.method == 'POST':
form = UploadFileForm(data = request.POST, files = request.FILES)
if form.is_valid():
# do stuff!
else:
form = UploadFileForm()
And ... "do stuff!" should be handled by a CustomFieldFile that extends
FieldFile
@edit
* use the good import class
* Forgot to write or was lost in edit, that the check is made in the clean method ...
|
Libraries not imported when creating a Python executable with pyinstaller
Question: I am trying to build a Python .exe for Windows and am able to create it fine.
However, when I run the application, I notice that it cannot perform all of
its functions because not all the libraries were imported; PySNMP is not
getting imported in specific. When I look at the output of the build process,
I notice that PySNMP is not listed at all, even though several of modules in
my program import it. Anyone know what could be causing this issue? Thanks!
Here is the code that generates the installer:
FILES = <main program modules (.py)>
PyInstaller = C:/Python27/pyinstaller
CygPyInstaller = /cygdrive/c/Python27/pyinstaller run : python app.py makespec : $(FILES) @echo "***** PyInstaller: Makespec *****" python $(PyInstaller)/Makespec.py \
--onefile \
--windowed \
--icon=Icons/icon.ico \
--name=Application1045 \
app.py
Answer: if you are customising the module path in order to import these libraries (eg,
I have some non-standard libraries bundled in a `./lib/` folder in my source
code tree) then you should add them with `--paths=lib` on the pyinstaller
command line -- having sys.path.append("lib") in the middle of the code didn't
work (not sure how it managed to compile at all if it couldn't find them, but
it did, and this took a while to track down...)
|
how to use python xml.etree.ElementTree to parse eBay API response?
Question: I am trying to use xml.etree.ElementTree to parse responses from eBay finding
API, findItemsByProduct. After lengthy trial and error, I came up with this
code which prints some data:
import urllib
from xml.etree import ElementTree as ET
appID = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
isbn = '3868731342'
namespace = '{http://www.ebay.com/marketplace/search/v1/services}'
url = 'http://svcs.ebay.com/services/search/FindingService/v1?' \
+ 'OPERATION-NAME=findItemsByProduct' \
+ '&SERVICE-VERSION=1.0.0' \
+ '&GLOBAL-ID=EBAY-DE' \
+ '&SECURITY-APPNAME=' + appID \
+ '&RESPONSE-DATA-FORMAT=XML' \
+ '&REST-PAYLOAD' \
+ '&productId.@type=ISBN&productId=' + isbn
root = ET.parse(urllib.urlopen(url)).getroot()
for parts in root:
if parts.tag == (namespace + 'searchResult'):
for item in list(parts):
for a in list(item):
if a.tag == (namespace + 'itemId'):
print 'itemId: ' + a.text
if a.tag == (namespace + 'title'):
print 'title: ' + a.text
But that seems not very elegant, how can I get the 'itemId' and 'title'
without looping over all attributes and checking if it is the one I want? I
tried using things like `.get(namespace + 'itemId')` and `.find(namespace +
'itemId')` and `.attrib.get(namespace + 'itemId')` but nothing really worked.
Can someone maybe show me how to do this using some python wrapper for this
API? I saw [easyBay](http://pypi.python.org/pypi/easyBay), [ebay-sdk-
python](http://code.google.com/p/ebay-sdk-python/) and
[pyeBay](http://ebaydeveloper.typepad.com/pyebay.html) but I didn't manage to
get any of them to do what I want. Is there any eBay python API which is
worthwhile to use for this?
Answer: You can use `ElementTree`. If you want to get the items you can use findall
and the path to the items, then iterate over the list of items:
items = root.findall(namespace+'searchResult/'+namespace+'item')
for item in items:
item.find(namespace+'itemId').text
item.find(namespace+'title').text
To get directly to the first itemId from the root:
root.find(namespace+'searchResult/'+namespace+'item/'+namespace+'itemId')
Basically, the find method uses XPath to retrieve elements more than one level
below the subelements. See also [Effbot's explanation of XPath support in
ElementTree](http://effbot.org/zone/element-xpath.htm)
|
how to "reimport" module to python then code be changed after import
Question: I have a `foo.py`
def foo():
print "test"
In IPython I use:
In [6]: import foo
In [7]: foo.foo()
test
Then I changed the `foo()` to:
def foo():
print "test changed"
In IPython, the result for invoking is still `test`:
In [10]: import foo
In [11]: foo.foo()
test
Then I use:
In [15]: del foo
In [16]: import foo
In [17]: foo.foo()
test
I delete the `foo.pyc` in same folder `foo.py` exists, but still no luck.
May I know how to reimport the updated code in runtime?
Answer:
foo = reload(foo)
|
java: how to both read and write to & from process thru pipe (stdin/stdout)
Question: (i'm new to java) I need to start a process and receive 2 or 3 handles: for
STDIN, STDOUT, (and STDERR), so I can write input to the process and receive
its output, the same way command line pipes behave (e.g. "grep")
in Python this is acheived with the following code:
from subprocess import Popen, PIPE
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE)
(child_stdin, child_stdout) = (p.stdin, p.stdout)
child_stdin.write('Yoram Opposum\n')
child_stdin.flush()
child_stdout.readlines()
What's the Java equivalent??
I've tried so far
Process p = Runtime.getRuntime().exec(cmd);
BufferedReader inp = new BufferedReader( new InputStreamReader(p.getInputStream()) );
BufferedWriter out = new BufferedWriter( new OutputStreamWriter(p.getOutputStream()) );
out.write( "Some Text!\n\n" );
out.flush();
line = inp.readLine();
print("response1: " + line ); // that's ok
out.write( "Second Line...\n" );
out.flush();
line = inp.readLine();
print("response2: " + line ); // returns an empty string, if it returns,,,
inp.close();
out.close();
BTW the first try works only with \n\n, but doesn't work with single \n (why?)
the following code works, but all input is given in advance, not the behavior
i'm looking for:
out.write( "Aaaaa\nBbbbbb\nCcccc\n" );
out.flush();
line = inp.readLine();
print("response1: " + line );
line = inp.readLine();
print("response2: " + line );
line = inp.readLine();
print("response3: " + line );
line = inp.readLine();
print("response4: " + line );
output:
response1: AAAAA
response2:
response3: bbbbbb
response4:
the process being run looks like that:
s = sys.stdin.readline()
print s.upper()
s = sys.stdin.readline()
print s.lower()
Answer: ok, it was also my python's code fault, but opposite to @Jon's answer, there
was an EXTRA newline (0xA0 to be exact, which isn't Windows' standard).
once i'm strip()ing the extra 0xA0 from the line i get from Java, python adds
a single "normal" \n to Java on the way back, and things run smoothly.
for the completeness of the question and answer, here's a working Java code:
import java.io.*;
import java.util.*;
public class Main {
public static BufferedReader inp;
public static BufferedWriter out;
public static void print(String s) {
System.out.println(s);
}
public static String pipe(String msg) {
String ret;
try {
out.write( msg + "\n" );
out.flush();
ret = inp.readLine();
return ret;
}
catch (Exception err) {
}
return "";
}
public static void main(String[] args) {
String s;
String cmd = "c:\\programs\\python\\python.exe d:\\a.py";
try {
print(cmd);
print(System.getProperty("user.dir"));
Process p = Runtime.getRuntime().exec(cmd);
inp = new BufferedReader( new InputStreamReader(p.getInputStream()) );
out = new BufferedWriter( new OutputStreamWriter(p.getOutputStream()) );
print( pipe("AAAaaa") );
print( pipe("RoteM") );
pipe("quit")
inp.close();
out.close();
}
catch (Exception err) {
err.printStackTrace();
}
}
}
and this is the python code
import sys
s = sys.stdin.readline().strip()
while s not in ['break', 'quit']:
sys.stdout.write(s.upper() + '\n')
sys.stdout.flush()
s = sys.stdin.readline().strip()
|
negative pow in python
Question: I have this problem
>>> import math
>>> math.pow(-1.07,1.3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: math domain error
any suggestion ?
Answer: (-1.07)1.3 will not be a real number, thus the Math domain error.
If you need a complex number, ab must be rewritten into eb ln a, e.g.
>>> import cmath
>>> cmath.exp(1.3 * cmath.log(-1.07))
(-0.6418264288034731-0.8833982926856789j)
If you just want to return NaN, catch that exception.
>>> import math
>>> def pow_with_nan(x, y):
... try:
... return math.pow(x, y)
... except ValueError:
... return float('nan')
...
>>> pow_with_nan(1.3, -1.07) # 1.3 ** -1.07
0.755232399659047
>>> pow_with_nan(-1.07, 1.3) # (-1.07) ** 1.3
nan
BTW, in Python usually the built-in `a ** b` is used for raising power, not
`math.pow(a, b)`.
>>> 1.3 ** -1.07
0.755232399659047
>>> (-1.07) ** 1.3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: negative number cannot be raised to a fractional power
>>> (-1.07+0j) ** 1.3
(-0.6418264288034731-0.8833982926856789j)
|
Converting UTC datetime to user's local date and time
Question: I'm using python on Django and Google App Engine. I'm also using the
DateTimeProperty in one of my models. Occasionally I would like to display
that date and time to the user.
What is the best to convert the datetime stored in DateTimeProperty into the
user's datetime?
Or a more precise way of framing the question: What is the best way to get a
client's timezone and convert a python datetime object into their own local
time?
Answer: This is more a Python question, than a GAE one, unless GAE has some
infrastructure to facilitate this (I've made a quick scan but haven't found
any reference).
Basically, you want to store date/times in UTC timezone (e.g. use
datetime.datetime.utcnow) along with user timezones, which you can either try
to extract from user IPs (using GeoDjango, if avaiable on GAE, or pygeoip; you
need some geolocation db like: <http://www.maxmind.com/app/geolitecity>), or
to explicitly ask users about it - which has the advantage that you can ask
for a descriptive timezone name, like "Europe/Warsaw". If you ask for just
UTC+2, then you loose any indication of DST shifts.
Then, you can shift from utc to the desired timezone using e.g.
[pytz](http://pytz.sourceforge.net/):
import pytz
local_tz = pytz.timezone(timezone_name)
return timestamp_utc.replace(tzinfo=pytz.utc).astimezone(local_tz).replace(tzinfo=None)
\-- where `timestamp_utc` is utc datetime that you want to convert, and
timezone_name is the mentioned "Europe/Warsaw".
(Note that I don't know which of these works in GAE, but at least you will
know what to look for)
|
sys.argv[1] meaning in script
Question: I'm currently teaching myself Python and was just wondering (In reference to
my example below) in simplified terms what the sys.argv[1] represents. Is it
simply asking for an input?
#!/usr/bin/python3.1
# import modules used here -- sys is a very standard one
import sys
# Gather our code in a main() function
def main():
print ('Hello there', sys.argv[1])
# Command line args are in sys.argv[1], sys.argv[2] ..
# sys.argv[0] is the script name itself and can be ignored
# Standard boilerplate to call the main() function to begin
# the program.
if __name__ == '__main__':
main()
Answer: _I would like to note that previous answers made many assumptions about the
user's knowledge. This answer attempts to answer the question at a more
tutorial level._
For every invocation of Python, `sys.argv` is automatically a list of strings
representing the arguments (as separated by spaces) on the command-line. The
name comes from the [C programming
convention](http://www.crasseux.com/books/ctutorial/argc-and-argv.html) in
which argv and argc represent the command line arguments.
You'll want to learn more about lists and strings as you're familiarizing
yourself with Python, but it the meantime, here are a few things to know.
You can simply create a script that prints the arguments as they're
represented. It also prints the number of arguments, using the `len` function
on the list.
from __future__ import print_function
import sys
print(sys.argv, len(sys.argv))
The script requires Python 2.6 or later. If you call this script
`print_args.py`, you can invoke it with different arguments to see what
happens.
> python print_args.py
['print_args.py'] 1
> python print_args.py foo and bar
['print_args.py', 'foo', 'and', 'bar'] 4
> python print_args.py "foo and bar"
['print_args.py', 'foo and bar'] 2
> python print_args.py "foo and bar" and baz
['print_args.py', 'foo and bar', 'and', 'baz'] 4
As you can see, the command-line arguments include the script name but not the
interpreter name. In this sense, Python treats the script _as_ the executable.
If you need to know the name of the executable (python in this case), you can
use `sys.executable`.
You can see from the examples that it is possible to receive arguments that do
contain spaces if the user invoked the script with arguments encapsulated in
quotes, so what you get is the list of arguments as supplied by the user.
Now in your Python code, you can use this list of strings as input to your
program. Since lists are indexed by zero-based integers, you can get the
individual items using the list[0] syntax. For example, to get the script
name:
script_name = sys.argv[0] # this will always work.
Although that's interesting to know, you rarely need to know your script name.
To get the first argument after the script for a filename, you could do the
following:
filename = sys.argv[1]
This is a very common usage, but note that it will fail with an IndexError if
no argument was supplied.
Also, Python lets you reference a slice of a list, so to get _another list_ of
just the user-supplied arguments (but without the script name), you can do
user_args = sys.argv[1:] # get everything after the script name
Additionally, Python allows you to assign a sequence of items (including
lists) to variable names. So if you expect the user to always supply two
arguments, you can assign those arguments (as strings) to two variables:
user_args = sys.argv[1:]
fun, games = user_args # len(user_args) had better be 2
So, in final answer to your specific question, `sys.argv[1]` represents the
first command-line argument (as a `string`) supplied to the script in
question. It will not prompt for input, but it will fail with an IndexError if
no arguments are supplied on the command-line following the script name.
|
Prevent OpenCV function CreateVideoWriter from printing to console in Python
Question: I'm using the Python bindings for OpenCV and have run into a little annoyance
using CreateVideoWriter where when I call the function, it prints something
similar to the below to the console and I can't seem to surpress it or ideally
redirect it into a variable.
Output #0, avi, to 'temp/Temp.0433.avi':
Stream #0.0: Video: mjpeg, yuvj420p, 320x240, q=2-31, 9830 kb/s, 90k tbn, 25
tbc
The command I'm using for testing is this:
self.file = cvCreateVideoWriter(nf,CV_FOURCC('M','J','P','G'),self.fps,cvSize(320,240),1)
Although in the long run this app will have a control GUI its currently
console based, the function is called every minute so this means its difficult
to present even a simple menu or more useful status information without this
call filling up the console.
Just wondering if anyone has experienced the same and/or has any ideas how I
might be able to prevent this happening or can offer pointers as to what I'm
doing wrong?
Answer: I think the easiest way for you to do this is temporarily to redirect
`sys.stdout` while calling the messy function -- anything else will force you
to change the Python bindings.
Fortunately, this is easy: just use a `contextmanager`:
>>> import contextlib
>>> @contextlib.contextmanager
... def stdout_as(stream):
... import sys
... sys.stdout = stream
... yield
... sys.stdout = sys.__stdout__
...
>>> print("hi")
hi
>>> import io
>>> stream = io.StringIO()
>>> with stdout_as(stream):
... print("hi")
...
>>> stream.seek(0)
0
>>> stream.read()
'hi\n'
>>> print("hi")
hi
|
app engine python setup
Question: << Big update below implies it's simply a logging issue >>
I'm trying to get app engine setup with python and having some problem that I
suspect is some simple step I've missed. My app.yaml says this:
application: something #name here is the one I used to register i.e. something.appspot.com
version: 1
runtime: python
api_version: 1
handlers:
- url: .*
script: myapp.py
and my myapp.py says this:
import cgi
import Utils
import Sample
import logging
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
class MainPage(webapp.RequestHandler):
def get(self):
self.response.out.write('<html><body>')
self.response.out.write('Welcome to my server! Why is this not working?')
self.response.out.write('</body></html>')
def main():
application = webapp.WSGIApplication([('/', MainPage),
('/Sample', Sample.HttpRequestHandler)],
debug=True)
run_wsgi_app(application)
if __name__ == "__main__":
main()
When I run this on localhost, I get my html "Welcome" message when passing in
/ but when I pass in /Sample I don't get any where. Also, I can't seem to log
messages. I call logging.debug() and nothing shows on the log console. Any
ideas? Here is my Sample.py. Sorry about the strange tabbing. Copy paste
didn't line them up and editing it by hand didn't seem to correct it.
class HttpRequestHandler(webapp.RequestHandler):
def get(self):
Utils.log("Sample handler called")
try:
if HttpRequestHandler.requestIsValid(self):
intParam = int(self.request.get('param1'))
floatParam = float(self.request.get('param1'))
stringParam = self.request.get('param1')
Utils.log("params: " + str(intParam) + " " + str(floatParam) + " " + stringParam)
if intParam == 1:
self.response.set_status(200, message="Success")
else:
self.response.set_status(400, message="Error processing sample command")
else:
raise StandardError
except Exception, e:
logging.debug("Exception: %s" % (e))
self.response.set_status(400, message="Error processing sample command")
def requestIsValid(self):
if self.request.get('param1') != "" and \
self.request.get('param2') != "" and \
self.request.get('param3') != "":
return True
else:
return False
So I know this is totally lame, but since I couldn't see any log messages, I
threw in a bunch of "raise StandardError" calls just to see what would throw
exception output to my browser window when I try to invoke my Sample message.
What I found was that the server is calling into the Sample handler just fine
it seems, even checking the int param is right.
I think the problem is that I just can't see my log messages! Any idea why
they aren't showing up? I call logging.debug() through those Util.log() calls.
Is there some flag or something suppressing my output from showing in the log
console?
Answer: You don't have `RequestHandler` subclass for the `"/Sample"` path, like you do
for the `"/"` path (i.e., `MainPage`).
To get logs, either start your SDK app server with `dev_appserver.py` and look
at the logs it spits out, or click the Logs button in the Google App Engine
Launcher GUI.
|
Stack performance in programming languages
Question: Just for fun, I tried to compare the stack performance of a couple of
programming languages calculating the Fibonacci series using the naive
recursive algorithm. The code is mainly the same in all languages, i'll post a
java version:
public class Fib {
public static int fib(int n) {
if (n < 2) return 1;
return fib(n-1) + fib(n-2);
}
public static void main(String[] args) {
System.out.println(fib(Integer.valueOf(args[0])));
}
}
Ok so the point is that using this algorithm with input 40 I got these
timings:
C: 2.796s
Ocaml: 2.372s
Python: 106.407s
Java: 1.336s
C#(mono): 2.956s
They are taken in a Ubuntu 10.04 box using the versions of each language
available in the official repositories, on a dual core intel machine.
I know that functional languages like ocaml have the slowdown that comes from
treating functions as first order citizens and have no problem to explain
CPython's running time because of the fact that it's the only interpreted
language in this test, but I was impressed by the java running time which is
half of the c for the same algorithm! Would you attribute this to the JIT
compilation?
How would you explain these results?
EDIT: thank you for the interesting replies! I recognize that this is not a
proper benchmark (never said it was :P) and maybe I can make a better one and
post it to you next time, in the light of what we've discussed :)
EDIT 2: I updated the runtime of the ocaml implementation, using the
optimizing compiler ocamlopt. Also I published the testbed at
<https://github.com/hoheinzollern/fib-test>. Feel free to make additions to it
if you want :)
Answer: You might want to crank up the optimisation level of your C compiler. With
`gcc -O3`, that makes a big difference, a drop from 2.015 seconds to 0.766
seconds, a reduction of about 62%.
Beyond that, you need to ensure you've tested correctly. You should run each
program ten times, remove the outliers (fastest and slowest), then average the
other eight.
In addition, make sure you're measuring CPU time rather than clock time.
Anything less than that, I would not consider a decent statistical analysis
and it may well be subject to noise, rendering your results useless.
For what it's worth, those C timings above were for seven runs with the
outliers taken out before averaging.
* * *
In fact, this question shows how important algorithm selection is when aiming
for high performance. Although recursive solutions are usually elegant, this
one suffers from the fault that you duplicate a _lot_ of calculations. The
iterative version:
int fib(unsigned int n) {
int t, a, b;
if (n < 2) return 1;
a = b = 1;
while (n-- >= 2) {
t = a + b;
a = b;
b = t;
}
return b;
}
further drops the time taken, from 0.766 seconds to 0.078 seconds, a further
reduction of 89% and a _whopping_ reduction of 96% from the original code.
* * *
And, as a final attempt, you should try out the following, which combines a
lookup table with calculations beyond a certain point:
static int fib(unsigned int n) {
static int lookup[] = {
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377,
610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657,
46368, 75025, 121393, 196418, 317811, 514229, 832040,
1346269, 2178309, 3524578, 5702887, 9227465, 14930352,
24157817, 39088169, 63245986, 102334155, 165580141 };
int t, a, b;
if (n < sizeof(lookup)/sizeof(*lookup))
return lookup[n];
a = lookup[sizeof(lookup)/sizeof(*lookup)-2];
b = lookup[sizeof(lookup)/sizeof(*lookup)-1];
while (n-- >= sizeof(lookup)/sizeof(*lookup)) {
t = a + b;
a = b;
b = t;
}
return b;
}
That reduces the time yet again but I suspect we're hitting the point of
diminishing returns here.
|
Getting the root (head) of a DiGraph in networkx (Python)
Question: I'm trying to use `networkx` to do some graph representation in a project, and
I'm not sure how to do a few things that should be simple. I created a
directed graph with a bunch of nodes and edges, such that there is only one
root element in this graph. Now, what I'd like to do is start at the root, and
then iterate through the children of each element and extract some information
from them. How do I get the root element of this DiGraph?
So it would be something like this:
#This is NOT real code, just pseudopython to convey the general intent of what I'd like to do
root = myDiGraph.root()
for child in root.children():
iterateThroughChildren(child)
def iterateThroughChildren(parent):
if parent.hasNoChildren(): return
for child in parent.children():
//do something
//
iterateThroughChildren(child)
I didn't see anything in the documentation that suggested an easy way to
retrieve the root of a DiGraph -- am I supposed to infer this manually? :O I
tried getting `iter(myDiGraph)` with the hope that it would iterate starting
at the root, but the order seems to be random... :\
Help will be appreciated, thanks!
Answer: If by having "one root element" you mean your directed graph is a rooted tree,
(http://en.wikipedia.org/wiki/Tree_%28graph_theory) then the root will be the
only node with zero in-degree.
You can find that node in linear time (in the number of nodes) with:
In [1]: import networkx as nx
In [2]: G=nx.balanced_tree(2,3,create_using=nx.DiGraph()) # tree rooted at 0
In [3]: [n for n,d in G.in_degree().items() if d==0]
Out[3]: [0]
Or you could use a topological sort (root is first item):
In [4]: nx.topological_sort(G)
Out[4]: [0, 1, 3, 8, 7, 4, 9, 10, 2, 5, 11, 12, 6, 13, 14]
Alternatively it might be faster to start with a given (random) node and
follow the predecessors until you find a node with no predecessors.
|
How can i access the file-selection in Path Finder via py-appscript?
Question: Using the filemanager Path Finder on mac os x, i wanna retrieve the selected
files/folders with python by using [py-
appscript](http://appscript.sourceforge.net). py-appscript is a high-level
event bridge that allows you to control scriptable Mac OS X applications from
Python.
In applescript it would be something like
tell application "Path Finder"
set selection_list to selection -- list of fsItems (fsFiles and fsFolders)
set _path to posix path of first item of selection_list
do shell script "python " & quoted form of _path
end tell
In python it would instead something like
from appscript import *
selectection_list = app('Path Finder').selection.get() # returns reference, not string
So, how can i convert the references in selection_list to python-strings?
Answer: I'm not familiar with Pathfinder, but if it has its own file URL type (or
maybe it's a POSIX path?), then there is presumably a delimiter of some kind
that separates the levels of file hierarchy in the path. To convert between
one and the other, you need to work with `Applescript's text item delimiters`.
Something along these lines should work
set thePathFinderPath to "/pathfinder/path/to/finder"
set pathFinderPathDelimiter to "/" -- whatever it may be here
set finderPathDelimiter to ":"
set AppleScript's text item delimiters to {pathFinderPathDelimiter}
set thePathComponents to (get every text item in thePathFinderPath) as list
set AppleScript's text item delimiters to {finderPathDelimiter}
set theFinderPath to thePathComponents as text
set AppleScript's text item delimiters to "" -- very important you clear the TIDs.
Add salt to taste. But, if you can provide an example of the PathFinder URL,
then I can provide a better answer.
|
Why aren't anonymous (C)Python objects deallocated immediately?
Question: I noticed something about CPython's object deallocation which piqued my
curiosity. Let's say I define a type that prints a message from its
`tp_dealloc` function:
static void pyfoo_Bar_dealloc(pyfoo_Bar* self)
{
PySys_WriteStdout("Bar freed\n");
self->ob_type->tp_free((PyObject*)self);
}
I've also done the right thing with the allocator:
PyMODINIT_FUNC initpyfoo(void)
{
PyObject* m;
pyfoo_BarType.tp_new = PyType_GenericNew;
/* ... */
}
I compile it and run a Python 2.6 interpreter in the directory with
`pyfoo.so`:
>>> import pyfoo
>>> a = pyfoo.Bar()
>>> a = None
Bar freed
>>> quit()
This is what I'd expect... the reference count drops to zero and the `Bar`
object is collected. But now if I do:
>>> import pyfoo
>>> pyfoo.Bar()
<pyfoo.Bar object at 0x7f7c6d8f2080>
>>> quit()
Bar freed
... the `Bar` object is not collected until the interpreter exits. But surely
the reference count on the `Bar` object created anonymously is zero, just like
the one explicitly assigned. So why is it not deallocated immediately after
creation?
(I'm doing this on Debian Squeeze with Python 2.6.6 compiled with GCC 4.4.5. I
know it's not a "bug", I know Python-the-language doesn't place any particular
constraints on Python interpreters this... I just want to know what is going
on under the hood that makes it ignore anonymous objects like this.)
Answer: Because after you called `pyfoo.Bar()` the object is still accessible using
the special object `_`
This works with pure Python, by the way:
class X:
def __del__(self):
print 'deleted'
And later:
>>>a = X()
>>>a = None
deleted
>>>X()
<__main__.X instance at 0x7f391bb066c8>
>>> _
<__main__.X instance at 0x7f391bb066c8>
>>> 3 # causes _ to be reassigned
deleted
3
Notice how reassigning `_` implicitly deleted the `X` object?
|
Simple Python server
Question: How can I start a simple python server that will allow me to connect to
sockets from some outer source ?
I've tried :
import SocketServer
class MyUDPHandler(SocketServer.BaseRequestHandler):
def handle(self):
data = self.request[0].strip()
socket = self.request[1]
print "%s wrote:" % self.client_address[0]
print data
socket.sendto(data.upper(), self.client_address)
if __name__ == "__main__":
HOST, PORT = "localhost", 80
try:
server = SocketServer.UDPServer((HOST, PORT), MyUDPHandler)
print("works")
server.serve_forever()
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind((socket.gethostname(), 80))
serversocket.listen(5)
except:
print("nope")
while True:
(clientsocket, address) = serversocket.accept()
ct = client_thread(clientsocket)
ct.run()
But when I'm sending something to the server I don't get any info. How can I
change this code to see if someone is sending some data ?
* * *
EDIT
Now I've found this code :
class mysocket:
"""demonstration class only
- coded for clarity, not efficiency
"""
def __init__(self, sock=None):
if sock is None:
self.sock = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
else:
self.sock = sock
def connect(self, host, port):
self.sock.connect((host, port))
def mysend(self, msg):
totalsent = 0
while totalsent < MSGLEN:
sent = self.sock.send(msg[totalsent:])
if sent == 0:
raise RuntimeError("socket connection broken")
totalsent = totalsent + sent
def myreceive(self):
msg = ''
while len(msg) < MSGLEN:
chunk = self.sock.recv(MSGLEN-len(msg))
if chunk == '':
raise RuntimeError("socket connection broken")
msg = msg + chunk
return msg
but how to use this stuff to just listen to sockets and receive data sent ?
Answer: The simplest solution is
[SocketServer](http://docs.python.org/library/socketserver.html), which is
part of the Python standard library.
|
Having trouble importing C# interface into Python
Question: I've been doing a bunch of searching and reading today, and haven't figured
out the right way to implement something, or even determining if it's
possible.
Here's the gist of what I'm attempting right now. I have an application that
loads plugins via MEF. Plugins can implement a variety of interfaces, and
let's say I have one called `IDevice`. I had this wacky idea that maybe a user
would want to write his own Device plugin in IronPython, and his IronPython
would just have to inherit from `IDevice` and implement the requisite methods.
Now I know it's possible to implement the interface in IronPython by defining
a class like this:
class MyDevice(IDevice):
pass
But I can't get past the first problem -- what's the correct way to import the
interface?
The IDevice interface is defined in a separate assembly called
MyInterfaces.dll like this:
namespace Company.Shared.MyInterfaces
{
public interface IDevice
{
string GetName();
}
}
I've tried `import MyInterfaces` since that's the most logical thing, but that
didn't work. I also tried many less logical combinations of `import`s and
`from`s. I always get the following error:
ImportException occurred
No module named MyInterfaces
I loaded Process Monitor to see what my app was trying to load when I executed
my script, and it was trying to load a file called MyInterfaces, and then
would try to load MyInterfaces.py. Well, the file is called
MyInterfaces*_.dll_ *, so I changed my import statement to read `import
MyInterfaces.dll`, but that had no effect -- my code would still just try to
load a file called MyInterfaces. I have confirmed that all of my dependencies
are in the right folder.
I feel super lame for not being able to figure this out, so I'm hoping that
someone can point me in the right direction. Thank you!
Answer: I believe the correct approach would be:
import clr
clr.AddReference('MyInterfaces')
from Company.Shared.MyInterfaces import IDevice
|
Can't connect to org.freedesktop.UDisks via DBus-Python
Question: It's the first time I'm using DBus so please bear with me. This is my code:
import gobject
import pprint
gobject.threads_init()
from dbus import glib
glib.init_threads()
import dbus
bus = dbus.SessionBus()
remote_object = bus.get_object("org.freedesktop.UDisks", # Connection name
"/org/freedesktop/UDisks" # Object's path
)
print ("Introspection data:\n")
print remote_object.Introspect()
print remote_object.get_dbus_method("ListNames",dbus_interface="org.freedesktop.DBus")
for item in remote_object.ListNames():
print item
The error I'm getting is:
dbus.exceptions.DBusException: org.freedesktop.DBus.Error.ServiceUnknown: The name org.freedesktop.UDisks was not provided by any .service files
From the [udisk-demon
manpage](http://manpages.ubuntu.com/manpages/maverick/man8/udisks-
daemon.8.html)
_udisks-daemon provides the org.freedesktop.UDisks service on the system
message bus.**Users or administrators should never need to start this daemon
as it will be automatically started by dbus-daemon(1) whenever an application
calls into the org.freedesktop.UDisks service.** See the udisks(7) man page
for information on how to customize how udisks-daemon works._
**EDIT:** So it was `SystemSession()` and not `SessionBus()`
Answer: You can try using [DFeet](http://live.gnome.org/DFeet/) to check if this dbus
object really exists.
|
Python + QT, Windows Forms or Swing for a cross-platform application?
Question: I'd like to develop a small/medium-size cross-platform application (including
GUI).
My background: mostly web applications with MVC architectures, both Python
(Pylons + SqlAlchemy) and Java (know the language well, but don't like it that
much). I also know some C#. So far, I have no GUI programming experience
(neither Windows Forms, Swing nor QT).
I plan to use SQLite for data storage: It seems to be a nice cross-platform
solution and has some powerful features (e.g. full text search, which SQL
Server Compact lacks).
I have done some research and these are my favorite options:
**1) QT, Python (PyQT or PySide), and SQLAlchemy**
pros:
* Python the language
* open source is strong in the Python world (lots of libraries and users)
* SQLAlchemy: A fantastic way to interact with a DB and incredibly well documented!
cons:
* compilation, distribution and deployment more difficult?
* no QT experience
* QT Designer not as nice as the Visual Studio Winforms designer
**2) .NET/Mono, Windows Forms, C#, (Fluent) NHibernate, System.Data.SQLite**
pros:
* C# (I like it, especially compared to Java and would like to get more experience in it)
* The Winforms GUI designer in Visual Studio seems really slick
* IntelliSense
* ClickOnce Deployment(?)
* Windows Forms look and feel good on Windows
cons:
* (Fluent) NHibernate far less documented than SQLAlchemy; also annoying: Fluent docs refer to NHibernate docs which refer to Hibernate (aargh!). But plain NHibernate + XML does not look very comfortable.
* Windows Forms will not look + behave native on Linux/Mac OS (correct?)
* fewer open source libraries in the .NET world, fewer OSS users, less documentation in general
* no WinForms and NHibernate experience
**3) JVM, Java + Jython, Swing, SQLAlchemy**
(I'm emotionally biased against this one, but listed for completeness sake)
pros:
* JVM/Swing work well as cross-platform basis
* Jython
* SQLAlchemy
* lots of open source libraries
cons:
* Swing seems ugly and difficult to layout
* lacks a good GUI designer
* Guessing that I won't be able to avoid Java for UI stuff
* Not sure how stable the Jython/Java integration is
(Options that I have ruled out... just to avoid discussion on these):
\- wxWidgets/wxPython (now that QT is LGPLed)
\- GTK/PyGTK
The look and feel of the final application is very important to me. The above
technology stacks are very different (PyQT, .NET WinForms, JVM Swing) and
require some time to get proficient, so:
Which alternative would you recommend and why?
Answer: I'm a Python guy and use PyQt myself, and I can wholly recommend it.
Concerning your cons:
> compilation, distribution and deployment more difficult?
No, not really. For many projects, a full `setup.py` for e.g. cx_Freeze can be
less than 30 lines that rarely need to change (most `import` dependencies are
detected automatically, only need to specify the few modules that are not
recognized), and then `python setup.py` will build a standalone executable.
Then you can distribute it just like e.g. a C++ .exe.
> no QT experience
I didn't have notable GUI experience either when I started out with Qt (only a
bit of fiddling with Tkinter), but I grew to love Qt. Most of the time, all
widgets work seamlessly and do what they're supposed to do - and there's a
_lot_ of them for many purposes. You name it, there's probably a widget that
does it, and doesn't annoy the user by being half-assed. All the nice things
we've been spoiled with are there.
Qt _is_ huge, but the PyQt documentation answer most question with reasonable
search effort. And if all else fails and you know a bit of C++, you can also
look at Qt resources.
> QT Designer not as nice as the Visual Studio Winforms designer
I don't know the VS Winforms designer, but I must admit that the Qt Designer
is lacking. I ended up making a sketch of the UI in the designer, generating
the code, cleaning that up and taking care all remaining details by hand. It
works out okay so far, but my projects are rather small.
* * *
PS:
> (now that QT is LGPLed)
PyQt is still GPL only. PySide is LGPL, yes, but it's not that mature, if
that's a concern. The project website states that "starting development on
PySide should be pretty safe now" though.
|
Uniqueness of global Python objects void in sub-interpreters?
Question: I have a question about inner-workings of Python sub-interpreter
initialization (from Python/C API) and Python `id()` function. More precisely,
about handling of global module objects in a WSGI Python containers (like
uWSGI used with nginx and mod_wsgi on Apache).
The following code works as expected (isolated) in both of the mentioned
environments, but I can not explain to my self **why the`id()` function always
returns the same value** per variable, regardless of the process/sub-
interpreter in which it is executed.
from __future__ import print_function
import os, sys
def log(*msg):
print(">>>", *msg, file=sys.stderr)
class A:
def __init__(self, x):
self.x = x
def __str__(self):
return self.x
def set(self, x):
self.x = x
a = A("one")
log("class instantiated.")
def application(environ, start_response):
output = "pid = %d\n" % os.getpid()
output += "id(A) = %d\n" % id(A)
output += "id(a) = %d\n" % id(a)
output += "str(a) = %s\n\n" % a
a.set("two")
status = "200 OK"
response_headers = [
('Content-type', 'text/plain'), ('Content-Length', str(len(output)))
]
start_response(status, response_headers)
return [output]
I have tested this code in uWSGI with one master process and 2 workers; and in
mod_wsgi using a deamon mode with two processes and one thread per process.
The typical output is:
> pid = 15278
> id(A) = 139748093678128
> id(a) = 139748093962360
> str(a) = one
on first load, then:
> pid = 15282
> id(A) = 139748093678128
> id(a) = 139748093962360
> str(a) = one
on second, and then
> pid = 15278 | pid = 15282
> id(A) = 139748093678128
> id(a) = 139748093962360
> str(a) = two
on every other. As you can see, `id()` (memory location) of both the class and
the class instance remains the same in **both** processes (first/second load
above), while at the same time class instances live in a separate context
(otherwise the second request would show "two" instead of "one")!
I suspect the answer might be hinted by Python docs:
> **`id(object)`** :
>
> Return the “identity” of an object. This is an integer (or long integer)
> which is guaranteed to be unique and constant for this object during its
> lifetime. Two objects with non-overlapping lifetimes may have the same
> `id()` value.
But if that indeed is the reason, I'm troubled by the next statement that
claims the `id()` value is object's address!
While I appreciate the fact this could very well be just a Python/C API
"clever" feature that solves (or rather _fixes_) a [problem of caching object
references (pointers) in 3rd party extension
modules](http://code.google.com/p/modwsgi/wiki/ApplicationIssues#Multiple_Python_Sub_Interpreters),
I still find this behavior to be inconsistent with... well, common sense.
Could someone please explain this?
I've also noticed mod_wsgi imports the module in each process (i.e.
**twice**), while uWSGI is importing the module only **once** for both
processes. Since the uWSGI master process does the importing, I suppose it
seeds the children with copies of that context. Both workers work
independently afterwards (deep copy?), while at the same time using the same
object addresses, seemingly. (Also, a worker gets reinitialized to the
original context upon reload.)
I apologize for such a long post, but I wanted to give enough details. Thank
you!
Answer: It's not entirely clear what you're asking; I'd give a more concise answer if
the question was more specific.
First, the id of an object is, in fact--at least in CPython--its address in
memory. That's perfectly normal: two objects in the same process at the same
time can't share an address, and an object's address never changes in CPython,
so the address works neatly as an id. I don't know how this violates common
sense.
Next, note that a backend process may be spawned in two very distinct ways:
* A generic WSGI backend handler will fork processes, and then each of the processes will start a backend. This is simple and language-agnostic, but wastes a lot of memory and wastes time loading the backend code repeatedly.
* A more advanced backend will load the Python code once, and then fork copies of the server after it's loaded. This causes the code to be loaded only once, which is much faster and reduces memory waste significantly. This is how production-quality WSGI servers work.
However, the end result in both of these cases is identical: separate, forked
processes.
So, why are you ending up with the same IDs? That depends on which of the
above methods is in use.
* With a generic WSGI handler, it's happening simply because each process is doing essentially the same thing. So long as processes are doing the same thing, they'll tend to end up with the same IDs; at some point they'll diverge and this will no longer happen.
* With a pre-loading backend, it's happening because this initial code happens only once, before the server forks, so it's guaranteed to have the same ID.
However, _either way_ , once the fork happens they're separate objects, in
separate contexts. There's no significance to objects in separate processes
having the same ID.
|
Lazy logger message string evaluation
Question: I'm using standard python logging module in my python application:
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("log")
while True:
logger.debug('Stupid log message " + ' '.join([str(i) for i in range(20)]) )
# Do something
The issue is that although debug level is not enable, that stupid log message
is evaluated on each loop iteration, which harms performance badly.
**Is there any solution for this?**
In C++ we have `log4cxx` package that provides macros like this:
`LOG4CXX_DEBUG(logger, messasage)`
That effectively evaluates to
if (log4cxx::debugEnabled(logger)) {
log4cxx.log(logger,log4cxx::LOG4CXX_DEBUG, message)
}
But since there are no macros in Python (AFAIK), if there a efficient way to
do logging?
Answer: The logging module already has partial support for what you want to do. Do
this:
log.debug("Some message: a=%s b=%s", a, b)
... instead of this:
log.debug("Some message: a=%s b=%s" % (a, b))
The logging module is smart enough to not produce the complete log message
unless the message actually gets logged somewhere.
To apply this feature to your specific request, you could create a lazyjoin
class.
class lazyjoin:
def __init__(self, s, items):
self.s = s
self.items = items
def __str__(self):
return self.s.join(self.items)
Use it like this (note the use of a generator expression, adding to the
laziness):
logger.info('Stupid log message %s', lazyjoin(' ', (str(i) for i in range(20))))
Here is a demo that shows this works.
>>> import logging
>>> logging.basicConfig(level=logging.INFO)
>>> logger = logging.getLogger("log")
>>> class DoNotStr:
... def __str__(self):
... raise AssertionError("the code should not have called this")
...
>>> logger.info('Message %s', DoNotStr())
Traceback (most recent call last):
...
AssertionError: the code should not have called this
>>> logger.debug('Message %s', DoNotStr())
>>>
In the demo, The logger.info() call hit the assertion error, while
logger.debug() did not get that far.
|
efficient circular buffer?
Question: I want to create an efficient [circular
buffer](http://en.wikipedia.org/wiki/Circular_buffer) in python (with the goal
of taking averages of the integer values in the buffer).
Is this an efficient way to use a list to collect values?
def add_to_buffer( self, num ):
self.mylist.pop( 0 )
self.mylist.append( num )
What would be more efficient (and why)?
Answer: I would use
[`collections.deque`](http://docs.python.org/library/collections.html#collections.deque)
with a `maxlen` arg
>>> import collections
>>> d = collections.deque(maxlen=10)
>>> d
deque([], maxlen=10)
>>> for i in xrange(20):
... d.append(i)
...
>>> d
deque([10, 11, 12, 13, 14, 15, 16, 17, 18, 19], maxlen=10)
There is a [recipe](http://docs.python.org/library/collections.html#deque-
recipes) in the docs for `deque` that is similar to what you want. My
assertion that it's the most efficient rests entirely on the fact that it's
implemented in C by an incredibly skilled crew that is in the habit of
cranking out top notch code.
|