New Python Runtime

2009-03-26 Thread Adonis
Came across this article on Ars on a new LLVM (Low Level Virtual 
Machine) JIT compiler for Python being built by Google:


http://arstechnica.com/open-source/news/2009/03/google-launches-project-to-boost-python-performance-by-5x.ars

Now the question is will this make Vista run faster?

Thought I'd share (If its old news, its new to me)

Adonis
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python regex

2008-03-13 Thread Adonis Vargas
Andrew Rekdal  wrote:
 I hope posting is ok here for this question...
 
 I am attempting to extract the text from a CSS comment using 're' such as...
 
 string = /* CSS comment /*
 exp = [^(/*)].*[^(*/)] 
 
 p = re.compile(exp)
 q = p.search(string)
 r = q.group()
 
 print r
 
 CSS comment
 
 although this works to a degree... I know the within the brackets everything 
 is taken literally so the pattern
 I am to negating is (/*). ie. includes the parenthesis.
 
 So my question is...
 
 Is there a way to negate a pattern that is more than on character long? eg. 
 where rather than saying if forward slash OR astrisk appear..negate.
 
 I would be saying if parenthesis AND asterisk appear in this order... negate
 
 
 -- Andrew
 
 

Have you looked into this library:

http://cthedot.de/cssutils/

May help you, if you are trying to achieve something. If your doing it 
as an exercise then I can not help you, I avoid regex like the plague 
(but thats just me).

Hope this helps.

Adonis Vargas
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why no string return?

2008-03-11 Thread Adonis Vargas
gargonx wrote:
 Say i have the two methods:
 
 def ReturnMethod(request, x):
 if request is True:
 return x
 else: print No String for you...False!
 
 def SendMethod(request):
 xstring = Some text
 ReturnMethod(request, xstring)
 
 SendMethod(True)
 
 Why does ReturnMethod not return the string x? I do believe it is
 returning with a NoneType.
 Any help would be greatly obliged
 
 Thanks, Josh

That is because request is bound a string (str) object. You are probably 
testing for null so it should look like:

 if request:
 return x
 else:
 print No String for you...False!

Hope this helps.

Adonis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: loading dictionary from a file

2008-02-06 Thread Adonis Vargas
Amit Gupta wrote:
 Need a python trick, if it exists:
 
 I have a file that stores key, value in following format
 --
 v1 : k1,
 v2 : k2
 --
 
 Is there a way to directly load this file as dictionary in python. I
 could do (foreach line in file, split by : and then do dictionary
 insert). Wondering, if some python built-in function can just read a
 valid dictionary-file and load it?
 
 Thanks

If you could change the input data you can pickle the dict object then 
save and reopen as needed.

import cPickle

data = {'k1': 'v1', 'k2': 'v2'}
output = open('output.dat', 'wb')
cPickle.dump(data, output)
output.close()
data1 = cPickle.load(open('output.dat', 'rb'))
print type(data1)
print data1

Hope this helps.

Adonis Vargas
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: converting JSON to string

2008-01-11 Thread Adonis Vargas
Gowri wrote:
 Hello,
 
 I actually have two questions:
 1. Are there any libraries which convert XML to JSON?
 2. I am currently doing the above using the DOM parser and creating a
 JSON array
 
 snippet
 for node in doc.getElementsByTagName(book):
 isbn = node.getAttribute(isbn)
 titleNode = (node.getElementsByTagName(title)
 [0]).childNodes[0]
 title = titleNode.data
 primarykeys.append({'isbn': isbn, 'title': title})
 return primarykeys
 
 I want to send primarykeys as a response to my client. i use
 mod_python and apache. The problem is, I have not been able to figure
 out how to convert my JSON output to a string.
 
 Could someone please help me?
 
 Thanks in advance

do:

return str(primarykeys)

Also there are Python modules for just this. Here is the very first link 
from Google:

http://pypi.python.org/pypi/python-json

I have used this one personally and have been very satisfied with it. 
There is another one (CJSON?) which is similar, but written in C, for 
when performance may be an issue.

Hope this helps.

Adonis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pygame w/ GUI

2008-01-09 Thread Adonis Vargas
PatrickMinnesota wrote:
 I know this isn't strictly a Python question, but I'm betting some
 here might be able to give me a hint.
 
 I have a few graphical programs doing some 2D data visualization using
 simple Pygame code for pseudo real-time animation.   It's running
 under windows XP right now, but eventually it'll need to be cross-
 platform.  As it is right now, it probably is, I just haven't tried it
 anywhere but XP.
 
 Now I want to wrap some simple GUI functions around it.  I'm looking
 for some buttons, a text field or two and file system selection of
 data files.  I figure many have done this and there is a better
 solution than to use Pygame constructs to implement such things.
 
 My question:  I'm not seeing much support in Pygame for that stuff.
 It seems I should build buttons and file browsing in some other
 toolkit.  Is that true?  Or am I just to early on in the Pygame docs
 to see solutions?
 
 If I should use something else, am I going to be able to use Tkinter
 or WxPython in conjunction with my Pygame code?  Or is there something
 else I should be looking at?
 
 Oh, and I'm running Python 2.5.1
 
 Thanks for any thoughts.

I do not have experience using pygame, but you can look at:

http://pyui.sourceforge.net/

Creates an user interface with pygame as a possible back end.

Hope this helps.

Adonis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python from any command line?

2007-12-09 Thread Adonis Vargas
waltbrad wrote:
 Hi folks. I'm learning Python from the Mark Lutz Book, Programming
 Python 3rd edition.
 
 He seems to be able to invoke the Python interpreter from any command
 line prompt.
 
 C:\temppython
 
 C:\PP3rdEd\examplespython
 
 C:\PP3rdEd\Examples\PP3E\Systemcd
 
 Whereas I am only able to invoke it when the command line is pointing
 to the directory where the executable resides. Currently:
 
 C:\Python25
 
 Is there a way to set this so I can also invoke it from any command
 line prompt?
 
 Thankyou very much.

The Python executable must be found in your system path, that is why you 
are unable to just simply type python at anytime at a command prompt. 
Simple fix:

click Start  Control Panel  System  Advanced  Environment Variables 
(bottom right)

Then you will have two list boxes one for user environment variables 
another for system variables. I prefer placing the path in the System 
environment variables section that way it is available for all accounts 
on the system (provided you have more than 1 user on it).

In the System list locate the Path variables, select edit variable and 
append ;C:\Python25 to it. And thats it reopen a new command prompt the 
type python and it should just fire up.

Hope this helps.

Adonis Vargas
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: searching a value of a dict (each value is a list)

2007-12-09 Thread Adonis Vargas
Seongsu Lee wrote:
 Hi,
 
 I have a dictionary with million keys. Each value in the
 dictionary has a list with up to thousand integers.
 Follow is a simple example with 5 keys.
 
 dict = {1: [1, 2, 3, 4, 5],
2: [10, 11, 12],
90: [100, 101, 102, 103, 104, 105],
91: [20, 21, 22],
99: [15, 16, 17, 18, 19]}
 
 I want to find out the key value which has a specific
 integer in the list of its value. For example, if I search
 104 in the list, 90 must be returned.
 
 How can I do this with Python? Ideas?

You can try this:

items = {1: [1, 2, 3, 4, 5],
  2: [10, 11, 12],
  90: [100, 101, 102, 103, 104, 105],
  91: [20, 21, 22],
  99: [15, 16, 17, 18, 19]}

def findItem(item, dictionary):
 for key, value in dictionary.iteritems():
 if item in value:
 print key, value

findItem(104, items)

This will allow you to work with the existing dataset without needing to 
duplicate it. It will print all occurrances.

Also, you should never use reserved words like 'dict' this creates 
confusion and can cause Python to misbehave since you are rebinding the 
name.

Hope this helps.

Adonis Vargas

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can i find a file size on the web ?

2007-12-02 Thread Adonis Vargas
Abandoned wrote:
 Hi..
 Can i find a file size witdhout download?
 For example: www.roche.com/rochea_z_sp.pdf
 How can i find its size with python ?
 I'm sorry for my bad english.

Typically you would just do an HTTP HEAD request in order to get 
information about the file without downloading it, but I tested the 
given site and it does not seem to support the HEAD request. Instead I 
used the GET request and read the headers in which contains information 
regarding the file as well, but opted no to read the data to avoid 
downloading it.

import httplib
connection = httplib.HTTPConnection(www.roche.com)
connection.request(GET, /rochea_z_sp.pdf)
response = connection.getresponse()
print response.status, response.reason
print File sie: %s % response.getheader('content-length')

Also you can do:

import urllib
response = urllib.urlopen(http://www.roche.com/rochea_z_sp.pdf;)
print response.info()

Hope this helps.

Adonis Vargas
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Determine whether program was started by clicking icon or command line

2007-11-29 Thread Adonis Vargas
Roger Miller wrote:
 On Nov 28, 10:51 pm, Benjamin Hell [EMAIL PROTECTED] wrote:
 Hi!

 I wonder whether there might be a way to find out how a Python
 program was started (in my case in Windows): By double clicking the
 file or by calling it on the DOS command line prompt.

 Background: I would like to have the program run in an interactive
 mode if double clicked, and silently in a batch mode when started
 otherwise.
 
 I'm not sure whether this applies to your situation, but often
 programs
 started by clicking an icon are run by pythonw, but when started from
 the command line are run by python. If this is the case
 sys.stdin.fileno()
 will return -1 in the former case and 0 in the latter.
 

No, when it gets executed by pythonw the application has an extension of 
.pyw and .py files are run by the regular python executable. This the 
default behavior, unless for some odd reason you modified this through 
the registry or through explorer to do otherwise.

Adonis Vargas
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Async XMLRPC and job processing

2007-10-17 Thread Adonis Vargas
Sean Davis wrote:
 I would like to set up a server that takes XMLRPC requests and
 processes them asynchronously.  The XMLRPC server part is trivial in
 python.  The job processing part is the part that I am having trouble
 with.  I have been looking at how to use threadpool, but I can't see
 how to get that working.  I would like to have the XMLRPC part of
 things do something like:
 
 def method1(a,b,c):
 jobid=workRequest(long_method1,[a,b,c])
 return(jobid)
 
 def method2(a,b,c):
 jobid=workRequest(long_method2,[a,b,c])
 return(jobid)
 
 def long_method1(a,b,c)
 do lots of heavy computation, etc.
 store results in files in a given directory, etc
 return result
 
  for any number of methods
 
 Again, pretty straightforward.  However, I run into problems with the
 threadpool and xmlrpc server both waiting.  In particular, if I do
 something like:
 
 server = SimpleXMLRPCServer.SimpleXMLRPCServer(.)
 server.serve_forever()
 
 Where can tell the threadpool that I have set up to wait
 indefinitely?  Both are blocking.
 
 Thanks,
 Sean
 

This site shows how to make it multi-threaded:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/425043

But now you have to contend with the integrity of your data, provided 
your going be storing data through these processes. You may want to look 
into the Queue module to create a sort of message queue so your data can 
be properly synchronized.

Hope this helps.

Adonis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is there some module update(install tools)?

2007-09-24 Thread Adonis Vargas
hyena wrote:
 Hi,
 
   I am quite new to python and am looking for some tools that can 
 install and update modules a bit more intelligent then python setup.py 
 install. Is there some thing like yum in fedora which can search and 
 install/update packages automatically?
 
 thanks in advance!

setuptools is for you
http://peak.telecommunity.com/DevCenter/setuptools

Once installed, its easy as easy_install module name

Hope this helps.

Adonis Vargas
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to do python and RESTful

2007-09-05 Thread Adonis Vargas
MarkyMarc wrote:
 Hi all,
 
 I want to make a web service application in python and keywords are
 RESTful, python and nice urls(urls mapped to python objects).
 
 I don't want a big framework but a nice small one, that can just do
 the things I want.
 
 I have be looking at quixote, but is this uptodate? plain
 mod_python, can this make url to http put,get,delete and post?
 
 Can some one here point me some where I can read about python and
 RESTful or have some experiences with other?
 
 Any help is apricieted.
 
 Regards Marc
 

Here is a crude version, if you check out CherryPy there exists a 
RESTful module for it floating around. Plus you will get the power or 
CherryPy for your apps. I do not have the urls offhand but google should 
yeild exactly what you need.

import BaseHTTPServer

class REST(BaseHTTPServer.BaseHTTPRequestHandler):

 
 You can implement and do_* method you want
 

 def do_GET(self):
 self.wfile.write(get)

 def do_POST(self):
 self.wfile.write(post)

 def do_PUT(self):
 self.wfile.write(put)

 def do_DELETE(self):
 self.wfile.write(delete)

def main(server_class=BaseHTTPServer.HTTPServer, handler_class=REST):
 server_address = ('', 8000)
 httpd = server_class(server_address, handler_class)
 httpd.serve_forever()

if __name__ == '__main__':
 main()

Not fully tested but should get on your feet.

Hope this helps.

Adonis Vargas
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Correct abstraction for TK

2007-07-02 Thread Adonis Vargas
[EMAIL PROTECTED] wrote:
 I'm looking for a good example of how to correctly abstract TK code
 from the rest of my program. I want to just get some user info and
 then get 4 values from the GUI. Right now I've written it OOP per the
 examples on python.org but it doesn't seem to be meshing very well
 with the rest of my project.
 
 Can anyone suggest some examples so that I can get more ideas?
 
 Thanks,
 Luke
 

I would not consider this to be 'correct' as many have different 
philosophies on how to tackle certain projects. My way of doing 
programming with GUI is writing it in 'tiers' (using this word loosely).

i.e.

import Tkinter as tk

class UsersInfo:

 pass

class Events(UserInfo):

 pass

class GUI(Events):

 pass

This way your GUI class sends events to the Events class to act upon the 
UserInfo class. For the GUI class here all you do is code the actual 
display and the callbacks only. Then in the Events class you code the 
actions you want to happen when you interact the the GUI. Since the GUI 
class inherits the Events class, in the GUI class you would simply call 
a method found in the Events class when an event is triggered. Now the 
Events class which inherits the UserInfo class, you can start using the 
class to store/modify the user data you desire. Now your code is 
separated into more comprehensible, and easier to manage sections. In 
this example I am using inheritance, but if you prefer delegation, then 
that too can be done here. Also, by doing this it will simplify the 
moving to more robust graphic toolkits with little modification.

Hope this helps.

Adonis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to FTP a ASCII file

2007-07-02 Thread Adonis Vargas
[EMAIL PROTECTED] wrote:
 Hi,
 
 My program has the following code to transfer a binary file
 
 f = open(pathanme+filename,'rb')
 print start transfer
 self.fthHandle.storbinary('STOR '+filename, f)
 
 How can I do an ASCII file transfer??
 -Ted
 

Taken from online documentation:

http://docs.python.org/lib/ftp-objects.html

storlines(command, file)

Store a file in ASCII transfer mode. command should be an appropriate 
STOR command (see storbinary()). Lines are read until EOF from the 
open file object file using its readline() method to provide the data to 
be stored.

Hope this helps.

Adonis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ten small Python programs

2007-05-27 Thread Adonis Vargas
Steve Howell wrote:
 I've always thought that the best way to introduce new
 programmers to Python is to show them small code
 examples.  

snip

You could try this wiki page:

http://rosettacode.org/wiki/Main_Page

It has a fair amount of Python examples as well as many more other 
languages (doing the same algorithm).

Hope this helps.

Adonis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: bitwise shift?

2007-05-02 Thread Adonis Vargas
Tobiah wrote:
snip
 Wow, thunderbird displayed this to me as a true exponent, even
 though it is an ascii message.  anyone else get this?
 
 
Yeah I can confirm Thunderbird 1.5.10 on Linux.

Adonis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Minimal Linux system to run Python

2007-04-14 Thread Adonis Vargas
Chaz Ginger wrote:
 I have a need for the minimal Linux system to run Python. Basically I
 want the system to boot up and instead of starting up Init/etc. I would
 love it to run python (and a python script I have written).
 
 Before embarking on doing it myself I was wondering if anyone knew of
 just such a system?
 
 Peace,
 Chaz

You can also look into Linux From Scratch (LFS)
http://www.linuxfromscratch.org/ in which walks you through how to build 
  a Linux OS by picking what you need, as well as it may give you more 
insight on the inner workings of a Linux system.

Hope this helps.

Adonis
-- 
http://mail.python.org/mailman/listinfo/python-list


Writing files

2007-03-19 Thread Adonis Vargas
I am writing a program that walks a directory full of mp3s reads their 
ID3 data (using Mutagen), this part works perfectly. The problem is I 
write these tags to a CSV file through the CSV module. But when I read 
the file the file seems to be incomplete. Further inspecting it has 
seemed to have stopped writing to the file at a certain point. Something 
in my code? a bug?

System: Linux 2.4.31 (Slackware), Python 2.5c1

Any help is greatly appreciated.

Adonis

-- code --

 def _scan(self):
 outFile = file(mp3.dat, wb)
 outCSV = csv.writer(outFile)
 output = list()
 for root, dirs, files in os.walk(self.directory):
 files = [x for x in files if x.endswith(.mp3)]
 for aFile in sorted(files):
 mp3Data = MP3(os.path.join(root, aFile))
 title = mp3Data.get(TIT2)
 output.append([root, aFile, title])
 outCSV.writerows(output)
 output = list()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing files

2007-03-19 Thread Adonis Vargas
[EMAIL PROTECTED] wrote:
snip

 -- code --

  def _scan(self):
  outFile = file(mp3.dat, wb)
  outCSV = csv.writer(outFile)
  output = list()
  for root, dirs, files in os.walk(self.directory):
  files = [x for x in files if x.endswith(.mp3)]
  for aFile in sorted(files):
  mp3Data = MP3(os.path.join(root, aFile))
  title = mp3Data.get(TIT2)
  output.append([root, aFile, title])
  outCSV.writerows(output)
  output = list()
 
 Are you closing the file before you try to read it? Other than that,
 I'm drawing a blank with just this sample to work with. Maybe someone
 else will know...or you could post more code?
 
 Mike
 


Actually, I re-ran this in a terminal and it worked perfectly. I was 
using IDLE to write this code, kinda peculiar. Maybe something to do 
with IDLE and CSV (or writing to files) with lines  ~1000. A socket 
timing out maybe?

Thanks anyways.

Adonis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New to Tkinter GUI building

2007-03-01 Thread Adonis Vargas
Adam wrote:
 On Feb 28, 9:13 pm, Adonis Vargas [EMAIL PROTECTED]
 wrote:
 Adam wrote:

 snip

 I think my main questions are:
 1. How can I get the Window to be sized the way I want it?
 2. How can I get the Scrollbars to fill the side of the text box
 instead of being small? (like .pack(fill= tk.Y)
 snip

 I have only posted the code relevant to the GUI.
 TIA
 Adam
 To size the window use Tk's geometry method

  self.top.geometry(%dx%d%+d%+d % (800, 600, 0, 0)) # (width,
 height, x, y)

 For the scrollbar to fill vertically, use the sticky grid option.

  self.scrlr1.grid(row=0, column=1, sticky=tk.N + tk.S)

 Hope this helps.

 Adonis
 
 Can't test now as its late in th UK and I'm going to bed. Looks good
 though.
 So remove the size from the frames etc and use the geometry method
 instead? Then use grid to pack them for want of a better word?
 

No, the geometry method is used to set the size of your main application 
window. This is what I understood from your first question, and please 
correct me if I am wrong. The grid method (or the pack method) are used 
to layout the widgets.

In other words, after line 8 of the code you provided you would add this 
line:

 self.top.geometry(%dx%d%+d%+d % (800, 600, 0, 0))

Hope this helps.

Adonis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: New to Tkinter GUI building

2007-02-28 Thread Adonis Vargas
Adam wrote:
snip
 I think my main questions are:
 1. How can I get the Window to be sized the way I want it?
 2. How can I get the Scrollbars to fill the side of the text box
 instead of being small? (like .pack(fill= tk.Y)
 
snip
 
 I have only posted the code relevant to the GUI.
 
 TIA
 Adam
 

To size the window use Tk's geometry method

 self.top.geometry(%dx%d%+d%+d % (800, 600, 0, 0)) # (width, 
height, x, y)

For the scrollbar to fill vertically, use the sticky grid option.

 self.scrlr1.grid(row=0, column=1, sticky=tk.N + tk.S)

Hope this helps.

Adonis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Reg Google Web Toolkit and Python

2007-02-16 Thread Adonis Vargas
Shadab Sayani wrote:
 Hi ,
 We have a project where I need to read files store
 them in database in the backend.We have done this in
 python.Now we decided to use Ajax technique for user
 interface.For that we found that GWT is one of the
 best toolkits.Now I got a doubt can I interface GWT
 with python.
 Thanks ,
 Shadab.
 
 Send instant messages to your online friends http://uk.messenger.yahoo.com 

I have not gone into much detail with GWT (you can look into the Python 
rendition of GWT called PyJamas), but it should be talking to a web 
server with the use of XMLHTTPRequest. So this should the case, then you 
can simply access your resources dynamically.

e.g.

web server: http://example.com/
resource: http://example.com/someJSONFormattedData

An AJAX application with its XMLHTTPRequest it will perform an HTTP GET 
on /someJSONFormattedData, which depending on your web application 
server could either be static or dynamic data. Then upon reception of 
the data, simply parse it and update a section or sections of your AJAX 
application (unless GWT has mechanisms to handle such things for you).

Hope this helps.

Adonis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ip address

2007-01-28 Thread Adonis Vargas
Scripter47 wrote:
 How do i get my ip address?
 
 in cmd.exe i just type ipconfig then it prints:
  ...
  IP-address . . . . . . . . . . . . . . . . . : 192.168.1.10
  ...
 how can i do that in python??
 

If you want to get your external IP you can do:

import urllib

checkIP = urllib.urlopen(http://checkip.dyndns.org;).read()
externalIP = checkIP.split()[-1].strip(/body/html)
print externalIP

Hope this helps.

Adonis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert from unicode chars to HTML entities

2007-01-28 Thread Adonis Vargas
Steven D'Aprano wrote:
 I have a string containing Latin-1 characters:
 
 s = u© and many more...
 
 I want to convert it to HTML entities:
 
 result =
 copy; and many more...
 
 Decimal/hex escapes would be acceptable:
 #169; and many more...
 #xA9; and many more...
 
 I can look up tables of HTML entities on the web (they're a dime a
 dozen), turn them into a dict mapping character to entity, then convert
 the string by hand. Is there a batteries included solution that doesn't
 involve reinventing the wheel?
 
 

Its *very* ugly, but im pretty sure you can make it look prettier.

import htmlentitydefs as entity

s = u© and many more...
t = 
for i in s:
 if ord(i) in entity.codepoint2name:
 name = entity.codepoint2name.get(ord(i))
 entityCode = entity.name2codepoint.get(name)
 t +=# + str(entityCode)
 else:
 t += i
print t

Hope this helps.

Adonis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Convert from unicode chars to HTML entities

2007-01-28 Thread Adonis Vargas
Adonis Vargas wrote:
[...]
 
 Its *very* ugly, but im pretty sure you can make it look prettier.
 
 import htmlentitydefs as entity
 
 s = u© and many more...
 t = 
 for i in s:
 if ord(i) in entity.codepoint2name:
 name = entity.codepoint2name.get(ord(i))
 entityCode = entity.name2codepoint.get(name)
 t +=# + str(entityCode)
 else:
 t += i
 print t
 
 Hope this helps.
 
 Adonis

or

import htmlentitydefs as entity

s = u© and many more...
t = u
for i in s:
 if ord(i) in entity.codepoint2name:
 name = entity.codepoint2name.get(ord(i))
 t +=  + name + ;
 else:
 t += i
print t

Which I think is what you were looking for.

Adonis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to document Python code...

2007-01-22 Thread Adonis Vargas
Scott Huey wrote:
 I am working on a Python module and I would like to prepare some API
 documentaiton. I managed to find epydoc after some searching online.
 
 Is there a standard way to document the API for Python modules? Is
 epydoc the best way to go if there is no standard? Are there other ways
 to document a Python API?
 
 Thanks,
 
 Scott Huey
 

The standard is to use docstrings

i.e.,

class MyModule:
 
 This module does something
 

 def someMethod(self):
 
 This method does something, accepts args/returns value etc.
 

Then one way to view the docstrings is to start a python shell, import 
your module, and do help(MyModule)

i.e.,

module: mymodule.py
class: MyModule

do in the shell:

import mymodule
help(mymodule.MyModule)

Then Python will generate a quick help interface for your module. I 
suspect epydoc uses docstrings but I *may* be wrong, since I have never 
used epydoc. But a quick look at pydoc (not to be confused with epydoc) 
which is part of the standard library allows you to generate 
documentation in HTML format, and/or serve it over web with its built-in 
HTTP server.

pydoc: http://docs.python.org/lib/module-pydoc.html

Hope this helps.

Adonis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Starting a child process and getting its stdout?

2006-12-28 Thread Adonis Vargas
cypher543 wrote:
 This has been driving me insane for the last hour or so. I have search
 everywhere, and nothing works. I am trying to use the subprocess module
 to run a program and get its output line by line. But, it always waits
 for the process to terminate and then return the output all at once.
 
 Can someone please show me some code that actually works for this sort
 of thing? It doesn't even have to use the subprocess module. Don't
 worry if the code isn't compatible with Windows. My program is targeted
 at Linux/UNIX users.
 
 Thanks!
 

try:

Python 2.5c1 (r25c1:51305, Aug 17 2006, 17:07:04)
[GCC 3.3.6] on linux2
Type help, copyright, credits or license for more information.
  import subprocess
  cmd = ls
  process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
  print process.stdout.read()

For more info on how to do stdin and other things check out:
http://docs.python.org/lib/module-subprocess.html

Hope this helps.

Adonis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Confusion with calling function of a subclass

2006-12-21 Thread Adonis Vargas
Pyenos wrote:
 class TREE:
 def gettree(self):print self
 TREE.gettree() # I get an error saying 
# TypeError: unbound method gettree() must be called
# with TREE instance as first argument (got nothing instead
 
 
 I still don't understand how to solve this simple code. 

You first need to create an instance of the class:

tree = TREE()
tree.gettree()

or

TREE().gettree()

Hope this helps.

Adonis

P.S. You should look into the tutorial 
http://docs.python.org/tut/tut.html it will answer a lot of your questions.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simplest way to do Python/Ajax with server and client on same machine?

2006-12-19 Thread Adonis Vargas
Kenneth McDonald wrote:
 I'm doing some work with a Python program that works hand-in-hand with 
 the DOM on a local client (processing DOM events, issuing DOM 
 modification commands, etc.) I'm currently using cherrypy as the Python 
 server for this communication, and simple AJAX on the client browser 
 end. This works just fine, I'm simply wondering if there is a better 
 (even easier) way to do this, if there are libraries I'm not aware of 
 that I should be, etc.
 
 Thanks,
 Ken

You can try looking into PyJamas its a Python version of Google Web 
Toolkit, offers a way to create AJAX apps using Python code.

Hope this helps.

Adonis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to reverse tuples in a list?

2006-08-08 Thread Adonis
Noah wrote:
 I have a list of tuples
 [('a', 1.0), ('b', 2.0), ('c', 3.0)]
 I want to reverse the order of the elements inside the tuples.
 [(1.0,'a'), (2.0, 'b'), (3.0, 'c')]
 
 I know I could do this long-form:
 q = []
 y = [('a', 1.0), ('b', 2.0), ('c', 3.0)]
 for i in y:
 t=list(t)
 t.reverse()
 q.append(tuple(t))
 y = q
 
 But it seems like there should be a clever way to do this with
 a list comprehensions. Problem is I can't see how to apply
 reverse() to  each tuple  in the list because reverse() a
 list method (not a tuple method) and because it operates
 in-place (does not return a value). This kind of wrecks doing
 it in a list comprehension. What I'd like to say is something like
 this:
 y = [t.reverse() for t in y]
 Even if reverse worked on tuples, it wouldn't work inside a
 list comprehension.
 
 Yours,
 Noah
 

Provided the data remains the same [(a, b), ...]


Python 2.5a2 (r25a2:45740, May 24 2006, 19:50:20)
[GCC 3.3.6] on linux2
  x = [('a', 1.0), ('b', 2.0), ('c', 3.0)]
  y = [(b, a) for a, b in x]
  y
[(1.0, 'a'), (2.0, 'b'), (3.0, 'c')]


Hope this helps,
Adonis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Configuring IDLE on Linux

2006-07-13 Thread Adonis
Satya Kiran wrote:
 Hello,
 I have upgraded to Python2.4 on my Red Hat 9.0 Linux box.
 I want to work with IDLE and ran a search to check it's presence.
 Here is what I get.
 
 [EMAIL PROTECTED] bin]# find / -iname idlelib
 /usr/local/lib/python2.4/idlelib
 
 [EMAIL PROTECTED] bin]# cd /usr/local/lib/python2.4/idlelib
 [EMAIL PROTECTED] idlelib]# python PyShell.py
 ** IDLE can't import Tkinter.  Your Python may not be configured for Tk. **
 
 How do I resolve this and get IDLE working?
 
 thanks in advance,
 Kiran Satya

You must have the Tk libraries present in your system for Python to 
compile Tkinter. Go to your distribution's site and try to see if they 
offer a TCL/TK package and install it (being that it is Redhat they most 
definitely must have one). Then recompile Python.

Hope this helps.

Adonis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: os.isfile() error

2006-05-06 Thread Adonis
Gary Wessle wrote:
 Hi
 
 could someone help me to find out whats wrong with this code?
 
  code 
 import os, sys
 
 if len(sys.argv)  2:
 sys.exit(please enter a suitable directory.)
 
 dpath = sys.argv[1]
 for name in os.listdir(dpath):
 if os.isfile(dpath+name):
 infile = open(os.path.join(dpath,name), 'rb')
 print type(infile)
 
 
  error 
 Traceback (most recent call last):
   File python/useful/cat2all.py, line 13, in ?
 if os.isfile(dpath+name):
 AttributeError: 'module' object has no attribute 'isfile'
 
 
 thank you


Where 'if os.isfile()' it should be 'os.path.isfile()', the isfile 
method is not available in the os module, but in os.path. For more 
information look at the module index:

 http://docs.python.org/modindex.html

Hope this helps.

Adonis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Gettings subdirectories

2006-05-03 Thread Adonis
Florian Lindner wrote:
 Hello,
 how can I get all subdirectories of a given directories? os.listdir() gives
 me all entries and I've found no way to tell if an object is a file or a
 directory.
 
 Thanks,
 
 Florian


Here is a quick hack:

import os
import os.path

givenDir = /
listing = os.listdir(givenDir)
for item in listing:
 joinPath = os.path.join(givenDir, item)
 normPath = os.path.normpath(joinPath)
 if os.path.isdir(normPath):
 print normPath
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: --version?

2006-05-02 Thread Adonis
Paul Watson wrote:
 Is there any chance that Python would support the --version command line 
  parameter?  It seems that many open source programs use this switch to 
 report their version number.


try at a command prompt:
python -V

Hope this helps.

Adonis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Locate command in Python

2006-04-10 Thread Adonis
BartlebyScrivener wrote:
 How about one of these that works on Windows XP? I know there's no
 files.cache, but I wonder if your script could be combined with another
 function that would generate a list of paths on a Windows XP machine.
 
 Anyway, thanks for the script.
 

I wrote it on a Windows XP machine. The files.cache is generated when 
you use the -u option. For example if you saved the script as locate.py 
first at a command prompt: python locate.py -u this will create the 
files.cache, it simply walks through your entire hard drive writing all 
the directories and files it finds along the way. Then doing: python 
locate.py SomeFileOrDirName  will go through the files.cache matching 
whatever term your looking for if present. Although the rootPath 
variable is set to the POSIX style path of / Python converts it to a 
proper path. At least thats my assumption as it works fine on my system.

Adonis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Locate command in Python

2006-04-09 Thread Adonis
mwt wrote:
 Is there a function in python that does what locate does in a bash
 shell?
 
 I know I could do it by using os.popen('locate'), but I'm curious if
 there's a Python native way to go about it. Only needs to work in
 Unix, but would be interesting if it was cross-platform. 
 
 Thanks.
 

Here is a quick hack I just did, its very ugly, but does the job.

First do locate -u to create a cache then just locate [term], its not so 
fancy as to remind you when the cache is too old, but hey.

It requires Python 2.3+

Hope this helps.

Adonis


---

import os
import sys

rootPath = /

def search(term):
 if os.path.exists(files.cache):
 cache = file(files.cache, 'r')
 for line in cache:
 if term in line:
 print line.strip()
 cache.close()
 else:
 print Please update the cache

def cache():
 cache = file(files.cache, 'w')
 for root, dirs, files in os.walk(rootPath):
 for aDir in dirs:
 cache.write(%s\n % aDir)
 for aFile in files:
 filePath = os.path.join(root, aFile)
 filePath = os.path.normpath(filePath)
 cache.write(%s\n % filePath)
 cache.close()

if __name__ == __main__:
 try:
 if sys.argv[1] == -u:
 cache()
 else:
 search(sys.argv[1])
 except IndexError:
 print Usage: locate [-u] [term]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter, X-windows and ebay

2006-02-09 Thread Adonis
Bob Greschke wrote:
 When you post something on eBay (and other places) you can use a 'browse' 
 button on a web page to send a picture file from your hard drive to them for 
 inclusion in your listing.  Can the same kind of thing (not the same exact 
 thing, of course) be done with a Python/Tkinter program that is running on a 
 remote machine (that you logged into to start the program), but that's just 
 using your computer's display (with X11 on a Mac, X-whatever on Linux, 
 X-Win32 on Windows, etc.)?  I've got an inventory program that runs this way 
 and it would be nice if users could create a text file on their machine, but 
 then have the program read that file and, for example, update item 
 quantities according to information in that file.  Things like that.
 
 Thanks!
 
 Bob
 
 

This is not a full answer to your question, but an idea, just so happens 
last few days I have been playing with ssh clients (putty, ssh) X11 
Forwarding with success. Essentially the user would run their preferred 
X, ssh to the server with X11 forwarding enabled to their host address 
and they can run programs like Xterm or even Nautilus, most X programs 
and it will be forwarded to their X server over a secured connection. To 
address the users file system maybe try setting up a file server on the 
Linux system referring to the users home directory, the user then 
creates a reference to the file server, then now it may mimic a local 
feel but all on your Linux server. Now they can run the X app and be 
able to achieve what you want. I am in no way an expert and some of my 
ideas might not be 100% accurate, but at my university this is how we 
have it set and it works perfectly (a very mixed environment as well).

Just an idea, hope this helps.

Adonis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie ? -- SGML metadata extraction

2006-01-16 Thread Adonis
ProvoWallis wrote:

snip

 From what I gather here is a quickie, probably better solutions on the 
way but this accomplishes the idea I think.

Some helpful links:
http://docs.python.org/lib/module-sgmllib.html
http://docs.python.org/lib/module-HTMLParser.html
http://docs.python.org/lib/module-htmllib.html

---

from HTMLParser import HTMLParser

data = main-section no=1

form id=graphic_1.tif
form id=graphic_2.tif

main-section no=2

form id=graphic_3.tif

main-section no=3

form id=graphic_4.tif
form id=graphic_5.tif
form id=graphic_6.tif


class ParseForms(HTMLParser):

 def handle_starttag(self, tag, attrs):
 if tag == form:
 # attrs argument is a list of tuples [(attribute, value)]
 # converted it to a dictionary to access attribute easier
 print form id: %s % dict(attrs).get('id')

if __name__ == __main__:
 parser = ParseForms()
 parser.feed(data)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie ? -- SGML metadata extraction

2006-01-16 Thread Adonis
ProvoWallis wrote:
 Thanks. One more question, though.
 
 I'm not sure how to limit the scope of my search so that I'm just
 extracting the id attribute from the sections that I want. I.e., I want
 the id attributes from the forms in sections 1 and 3 but not from 2.
 
 Maybe I'm missing something.
 

If the data has closing tags this is easily achieved using a dom or sax 
parser, but here is a slightly modified version, very ugly but simple.

hope this helps.

Adonis

---

from HTMLParser import HTMLParser

data = main-section no=1

form id=graphic_1.tif
form id=graphic_2.tif

main-section no=2

form id=graphic_3.tif

main-section no=3

form id=graphic_4.tif
form id=graphic_5.tif
form id=graphic_6.tif


class ParseForms(HTMLParser):

 _section = None
 _secDict = dict()

 def getSection(self, key):
 return self._secDict.get(str(key))

 def handle_starttag(self, tag, attrs):
 if tag == form:
 if not self._secDict.has_key(self._section):
 self._secDict[self._section] = [dict(attrs).get('id')]
 else:
   self._secDict[self._section].append(dict(attrs).get('id'))

 if tag == main-section:
 self._section = dict(attrs).get('no')

if __name__ == __main__:
 parser = ParseForms()
 parser.feed(data)
 print parser.getSection(1)
 print parser.getSection(3)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Detect TKinter window being closed?

2005-12-02 Thread Adonis
Glen wrote:
 Is it possible to to detect a Tkinter top-level window being closed with the
 close icon/button (top right), for example to call a function before the
 window actually closes?
 
 Python 2.4 / Linux (2.6 kernel) if that makes any difference.
 Any info would be greatly appreciated.
 Thanks
 Glen

Here is an example code taken from:
http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm
(located at very end)

Example 7-2. Capturing destroy events

# File: protocol1.py

from Tkinter import *
import tkMessageBox

def callback():
 if tkMessageBox.askokcancel(Quit, Do you really wish to quit?):
 root.destroy()

root = Tk()
root.protocol(WM_DELETE_WINDOW, callback)

root.mainloop()

Hope this helps.

Adonis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: about list

2005-11-20 Thread Adonis
Shi Mu wrote:
 How to run a function to make [1,2,4] become [[1,2],1,4],[2,4]]?
 Thanks!

 From what I gather try:

a = [1,2,4]
n = list()
for i in a:
 index = a.index(i) + 1
 for x in a[index:]:
 n.append([i, x])
print n

more elegant ways to do this, but its a start.
hope this helps.

Adonis
-- 
http://mail.python.org/mailman/listinfo/python-list


Tkinter PhotoImage Question

2005-06-27 Thread Adonis
I have two classes one class inherits dict(), this class just takes in a 
path argument much like glob.glob() and loads the image using PhotoImage 
into itself, no biggie works fine. The other class inherits Frame and it 
implements an add(self, **kw) method passes all of its arguments to a 
Button. My question is that when I load the images with the first class 
and then use dict.get(name) as the image argument for the add method the 
image does not show up, mind you the variable holding the dict is seen 
by the whole class so its not a garbage collection issue, but if I put a 
command in the argument list it works just fine?

Any help is greatly appreciated.

Adonis
-- 
http://mail.python.org/mailman/listinfo/python-list


Python in the news, somewhat

2005-05-13 Thread Adonis
ZDNet has released this article that talks about open source scriptingg 
languages and mentions Python/Jython/IronPython, just wanted to share 
the info.

http://news.zdnet.com/2100-9593_22-5705448.html?tag=st.num

Adonis
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Web Application Client Module

2005-04-12 Thread Adonis
Raffi wrote:
Hi All,
I hope I'm posting this question to the correct newsgroups. We have a
web based database application that's accessed using IE. The
application opens a popup window to run in. With all the popup blockers
and compromised browsers out there, I'm looking into developing a web
based custom client side application to access the application with.
The application will be developed to only reach the web application
site using the https protocol. It also needs to javascript enabled. It
will be downloaded from the main web site and used to access the
database application.
Any suggestions/ideas on how to go about developing the client
application? What tools tools are out there for such a project.
Thanks,
Raffi
This is slightly what I am doing right now, you can use the JavaScript 
on the browser to (mainly the XMLHttpRequest object) to access servers 
asynchronously, when accessing the server's resource it returns an XML 
representation (document) of whatever you want using the browser's 
builtin DOM you can parse this and using the same DOM you can modify the 
predefined tags or whatever you want.  This approach reduces the traffic 
to the webserver by only accessing data you need. go to cherrypy.org and 
right on the start page there should be a link labeled AJAX which is the 
buzzword being used for this kind of implementation.

Hope this helps.
Adonis
--
http://mail.python.org/mailman/listinfo/python-list


Re: Lowest hassle Python web server?

2005-03-20 Thread Adonis
kanzen wrote:
I keep telling my friends that Python rocks. Now it's time to put my
money where my mouth is. I'm about to start writing a server for a
phone based game. It needs to handle simlpe requests from some Java
code running on the phone at a fairly low transaction rate. There will
also be a simple web site allowing users to edit preferences and so
forth. I have just enough Python experience to decide that I prefer it
over Java for this job. It'll be on a Linux box that I have full
control over.
I can see from FAQs that there are several possible ways of doing web
server work in Python, e.g. Twisted or mod_python in Apache, etc. So
I'm wondering:
- Could you recommend a solution you've found to be the most
convenient?
- Does threading cause any more of a hassle in Python than Java?
- Is there anything similar to JSP in Java?
Thanks,
KanZen
You can look into CherryPy http://www.cherrypy.org/
Hope this helps
Adonis
--
http://mail.python.org/mailman/listinfo/python-list


Re: xmlrpc.server.work() does not seem to handle multiple requests

2005-02-18 Thread Adonis
john14 wrote:
Hi,
I have an xmlrpc server. I using the python package
xmlrpc. Here is what I am doing:
s = xmlrpc.server()
s.addMethods(method_hash)
s.bindAndListen(PORT)
while 1:
try:
s.work()
except:
e = sys.exc_info()
The problem is that when I send multiple requests they are queued and
processed one after the other. Is there some other method that will allow
me to process multiple request at the same time?
Thank You
Check out this snippet look at the end for user comments to get a 
multi-threaded or forking version.

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81549
Hope this helps.
Adonis
--
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie: Pythonwin

2005-01-11 Thread Adonis
Brent W. Hughes wrote:
1)  I'm running a program within Pythonwin.  It's taking too long and I want 
to stop/kill it.  What do I do (other than ctrl-alt-del)?

2)  I'm running a long program and I want to minimize it to let it continue 
to run in the background while I do something else in the foreground.  I try 
clicking on Pythonwin's minimize box but it doesn't respond until the Python 
program finally quits  Then it minimizes!  Any way I can do what I want 
here?

Brent

Try running your script using (from command prompt):
\path\python.exe \path\script.py
Alternatively go to its folder in explorer and double click it to run.
pythonwin is just a developing enviroment, and the execution of scripts 
within it is just for debugging use.

Hope this helps.
Adonis
--
http://mail.python.org/mailman/listinfo/python-list