Re: howto handle nested for

2012-09-28 Thread Wojtek

W dniu 2012-09-28 16:42, Alister pisze:

On Fri, 28 Sep 2012 10:39:32 -0400, Neal Becker wrote:


I know this should be a fairly basic question, but I'm drawing a blank.

I have code that looks like:

   for s0 in xrange (n_syms):
 for s1 in xrange (n_syms):
 for s2 in xrange (n_syms):
 for s3 in xrange (n_syms):
 for s4 in range (n_syms):
 for s5 in range (n_syms):

Now I need the level of nesting to vary dynamically.  (e.g., maybe I
need to add for  s6 in range (n_syms))

Smells like a candidate for recursion.  Also sounds like a use for
yield.  Any suggestions?


It definitely looks like for is the wrong way to go for this
without more information on the reason why it is difficult to say what
the correct approach would be





it's well described in head first: python book ;)
check this sources from this book 
http://www.headfirstlabs.com/books/hfpython/code/chapter1.zip


hope it helps,

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


Re: Portable general timestamp format, not 2038-limited

2007-07-05 Thread Wojtek
James Harris wrote :
> I have a requirement to store timestamps in a database. Simple enough
> you might think but finding a suitably general format is not easy. The
> specifics are
>
> 2) not bounded by Unix timestamp 2038 limit

I use the Java Calendar class for storing dates, which as I understand 
it, uses a long to store the date/time/milliseconds.

In my application I use the date .12.31 23:59:59.000 to store a 
blank date. Calendar has no problem storing that date, and returning 
the correct year, month, day, hour, minute, and second.

Note: Since I am using the year  as a "magic number", some of you 
may think that I am repeating the Y2K problem. Hey, if my application 
is still being used in the year 9998 I am not being paid nearly 
enough...

-- 
Wojtek :-)


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


Re: what's so difficult about namespace?

2008-11-26 Thread Wojtek

Xah Lee wrote :

i cannot fathom what could possibly be difficult of
introducing or implementing a namespace mechanism into a language. I
do not understand, why so many languages that lacks so much needed
namespace for so long? If it is a social problem, i don't imagine they
would last so long. It must be some technical issue?


Simply put:
- it was not in the original language specification
- some hundreds of millions of distributed browsers interpret 
Javascript without namespaces
- to introduce namespaces into the language would require every browser 
to be replaced (at least if the user comes across a site which uses it)


The IT community has enough trouble getting a few ISPs to upgrade their 
DNS software. How are you going to get millions of general users to 
upgrade?


Web stats show that people are still using IE 5...

--
Wojtek :-)


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


Re: what's so difficult about namespace?

2008-11-26 Thread Wojtek

Kaz Kylheku wrote :

Javascript programs are scanned at the character level by the browser as part
of loading a page.  So there are severe practical limitations on how large
Javascript programs can be.



Namespaces are useful only in very large programs.


But even more useful where you are getting libraries from several 
sources.


Without a generally acknowledged name space scheme different developers 
will tend to walk all over each others variable/function names. 
Especially as Javascript has global variables.


--
Wojtek :-)


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


Embedding Python's library as zip file

2011-05-04 Thread Wojtek Mamrak
Hello,

I spent a lot of time googling for a solution of this problem, with no
result.

I have a C++ application, in which I would like to embed Python interpreter.
I don't want to rely on an interpreter being installed on user machine,
instead I would like to distribute all the necessary files with my app.

As far as I understand, beside of my executable and Python.dll (I am using
Python27), I need to provide two folders:
 - DLLs,
 - Lib

If I place the Lib folder and the contents of the DLLs folder in a directory
of my executable, then everything seems to work.
However I would like to use a zipped Lib folder. Hence I made an archive
(which contains contents of Lib folder) called Python27.zip. Unfortunately
the app crashes during execution.
I assume the reason might be lack of zlib.pyd. Is that assumption correct?
If so, how to obtain it? If not, what am I doing wrong?

Thanks in advance
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Embedding Python's library as zip file

2011-05-05 Thread Wojtek Mamrak
Thanks for the reply!

> Can you import from zip files when running the Python.exe interpreter?
When I zip the folder "Lib" into Python27.zip and later rename it and
try to run the python.exe, I receive an error:
"Import error: no module named site"

> Is the zip file included in sys.path?  You might need to add this
> yourself after callying Py_Initialize().
Before renaming the "Lib" folder, the path to the python27.zip exists
in sys.path.

> Is there a top-level directory in the zip file that may be throwing
> the importer off?
I am testing all the cases so this is not the issue.

> Are you getting any sort of error message?
When I run my app, it crashes while calling Py_Initialize(). The
console closes suddenly.

Is it necessary to create zip archive using zipfile.PyZipFile?

regards


2011/5/5 Ian Kelly 
>
> On Wed, May 4, 2011 at 3:09 PM, Wojtek Mamrak  wrote:
> > Hello,
> >
> > I spent a lot of time googling for a solution of this problem, with no
> > result.
> >
> > I have a C++ application, in which I would like to embed Python interpreter.
> > I don't want to rely on an interpreter being installed on user machine,
> > instead I would like to distribute all the necessary files with my app.
> >
> > As far as I understand, beside of my executable and Python.dll (I am using
> > Python27), I need to provide two folders:
> >  - DLLs,
> >  - Lib
> >
> > If I place the Lib folder and the contents of the DLLs folder in a directory
> > of my executable, then everything seems to work.
> > However I would like to use a zipped Lib folder. Hence I made an archive
> > (which contains contents of Lib folder) called Python27.zip. Unfortunately
> > the app crashes during execution.
> > I assume the reason might be lack of zlib.pyd. Is that assumption correct?
> > If so, how to obtain it? If not, what am I doing wrong?
>
> I believe zlib.pyd is statically linked into python27.dll nowadays.
> Some things to check:
>
> Can you import from zip files when running the Python.exe interpreter?
> Is the zip file included in sys.path?  You might need to add this
> yourself after callying Py_Initialize().
> Is there a top-level directory in the zip file that may be throwing
> the importer off?
> Are you getting any sort of error message?
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Embedding Python's library as zip file

2011-05-05 Thread Wojtek Mamrak
> That means it's not finding it.  After startup, try adding the zip
> file to your sys.path and then do "import site" at the command line,
> and it should work.

Maybe I am missing the point, but I think I am not able to do this.
When I remove the "Lib" folder and try to run Python.exe, the python
console window closes rapidly, so that it is hard to read any message
displayed in it and obvioulsy I can't run any python command. Could
you clarify this please?


> What if you put the zip file in your
> PYTHONPATH environment variable?

I don't have it defined. Maybe it is because I have 2 different Python
interpreters installed.
After adding the PYTHONPATH, the Python.exe seems to run normally.
Unfortunately I am not able to import Image module (I am using it),
which is installed in site-packages/PIL.
This happens, because for some reason the site-packages directory is
not present in sys.path. After reading the site module description I
checked the sys.prefix and sys.exec_prefix, which are both empty, when
the Lib folder is loaded from the zip archive. Thats why site-packages
is not added to sys.path.
Of course I can add site-packages directory to the sys.path by myself
(yet I don't know why sys.prefix and sys.exec_prefix are empty),
however how to deal with the PYTHONPATH, which is required to load
site.py and hence has to be defined at the very beginning?


thanks for your help


2011/5/5 Ian Kelly :
> On Thu, May 5, 2011 at 4:55 AM, Wojtek Mamrak  wrote:
>> Thanks for the reply!
>>
>>> Can you import from zip files when running the Python.exe interpreter?
>> When I zip the folder "Lib" into Python27.zip and later rename it and
>> try to run the python.exe, I receive an error:
>> "Import error: no module named site"
>
> That means it's not finding it.  After startup, try adding the zip
> file to your sys.path and then do "import site" at the command line,
> and it should work.
>
>>> Are you getting any sort of error message?
>> When I run my app, it crashes while calling Py_Initialize(). The
>> console closes suddenly.
>
> Hm, that definitely seems odd.  What if you put the zip file in your
> PYTHONPATH environment variable?
>
>> Is it necessary to create zip archive using zipfile.PyZipFile?
>
> It shouldn't be.  It works for me (at least with Python.exe) creating
> the zip archive using 7-Zip.
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Embedding Python's library as zip file

2011-05-06 Thread Wojtek Mamrak
> Are you calling Py_SetProgramName?  That may help to set sys.prefix
> and sys.exec_prefix.  However, looking at site.py, it appears that
> it's only looking for proper directories.  I don't think it will be
> able to add a site-packages inside a zip archive at all; you will just
> have to add that yourself.

Yes, I have tried Py_SetProgramName, but I am even not sure what
argument (name, path?) should be passed to it and how it will affect
the application.


Some good news.
After simplifying my application I realized, that importing of modules
from the zip archive works well, I only have to add site-packages to
sys.path (it looks like "python27.zip/site-packages").

Unfortunately even though I can import Image package, something still
causes applications' sudden death. I will try to figure out what is
the reason of that. As I said, the only non-standard package I am
using is PIL.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PIL: The _imaging C module is not installed

2011-05-06 Thread Wojtek Mamrak
@Michel
use PIL downloaded from here: http://www.lfd.uci.edu/~gohlke/pythonlibs/

regards

2011/5/6 Christian Heimes :
> Am 06.05.2011 01:48, schrieb Michel Claveau - MVP:
>> Re!
>>
>> And why the problem no exist with PIL 1.1.6?  (only 1.1.7)
>> Is that the version 1.1.6 does not use these libraries?
>
> PIL 1.1.6 also uses its internal C library to speed things up.
>
> For Windows you should use the precompiled packages.
> http://www.pythonware.com/products/pil/ offers X86 Windows binaries for
> 1.1.7. You might run into a problem with 1.1.7 Windows binaries. The
> freetype C library references a debug CRT that is not available on all
> machines. You can easily patch the _imagingft.pyd file with a hex editor.
>
> Christian
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Embedding Python's library as zip file

2011-05-06 Thread Wojtek Mamrak
> I used py2exe in the past for that, see 
> http://www.py2exe.org/index.cgi/ShippingEmbedded

Thanks for the advice, py2exe seems to be a great tool.
Unfortunately the application stops executing at the same place. It
might be the case of PIL library, I found some entries about it on
py2exe site.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: NewBie Doubt in Python Thread Programming

2011-05-11 Thread Wojtek Mamrak
Is there any special reason you don't want to use QThread?
http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qthread.html#details

regards

2011/5/11 Chris Angelico :
> On Wed, May 11, 2011 at 7:08 PM, vijay swaminathan  wrote:
>> Sorry. My intention was not to send out a private message. when I chose
>> reply to all, I was confused if this would start as a new thread. so just
>> did a reply..
>
> No probs. If you just send your response to the list
> python-list@python.org. it'll get to everyone.
>
>> I have developed a GUI based on pyQT4 which has a run button. when I click
>> on run, it invokes a command prompt and runs a .bat file.
>>
>> Till the execution of .bat file is over, I want the run button on the GUI to
>> be disabled. so i thought of invoking the command prompt and running the
>> .bat file on a thread so that I could monitor the status of the thread
>> (assuming that the thread would be active till command prompt is active -
>> correct me if I'm wrong).
>
> Yes, but only if you use os.system().
>
>> Any flaw  in the logic? any other better ways of achieving this?
>>
>
> You'll find it easier to get an event at the end of it; simply have
> another line of code after the os.system() which will reenable the
> button.
>
> Chris Angelico
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: NewBie Doubt in Python Thread Programming

2011-05-11 Thread Wojtek Mamrak
2011/5/11 Chris Angelico :
> On Thu, May 12, 2011 at 1:16 AM, Wojtek Mamrak  wrote:
>> Is there any special reason you don't want to use QThread?
>> http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qthread.html#details
>
> Other than that QThread is part of QT and threading isn't, what are
> the advantages of QThread? Is it possible (safe) to manipulate QT
> objects - in this case, the button - from a thread other than the one
> that created them? (If not, that would be a good reason for using
> QThread, which will fire an event upon termination.)
>


QThread provides mechanism of signals and slots ("from" and "to" the
thread), which are used across all pyQt. Unfortunately it is not
possible to use any widget classes in the thread (direct quote from
the docs). On the other hand signals can fire methods from the main
thread (running the app'a main loop), so this is not a big deal.
The signals are:
- finished
- started
- terminated
It is possible to block the thread, make it sleep, check whether the
thread is running, and few others.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python drawing library?

2011-05-15 Thread Wojtek Mamrak
Yes, it is possible with use of PyQt.

2011/5/15 Rafael Durán Castañeda :
> On 15/05/11 01:01, OKB (not okblacke) wrote:
>>
>>        Is there any Python library for interactive drawing?  I've done
>> some googling but most searches for "drawing" lead me to libraries for
>> programmatic creation of shapes on some GUI canvas.  I'm looking for GUI
>> widgets that allow the user to draw with the mouse, like a paint
>> program, and let me get info about the drawing as its made (get color at
>> mouse location, etc.).  I'd prefer a wxPython solution, although any
>> Python solution would be better than none.
>>
>> Thanks,
>
> I'm not suere, but I think you should be able to do that using PyQt
> QPaintDevice.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Compile Python 3 interpreter to force 2-byte unicode

2017-11-25 Thread wojtek . mula
Hi, my goal is to obtain an interpreter that internally
uses UCS-2. Such a simple code should print 65535:

  import sys
  print sys.maxunicode

This is enabled in Windows, but I want the same in Linux.
What options have I pass to the configure script?

w.
-- 
https://mail.python.org/mailman/listinfo/python-list


Compile Python 3 interpreter to force 2-byte unicode

2017-11-26 Thread wojtek mula
Hi, my goal is to obtain an interpreter that internally uses UCS-2. Such a
simple code should print 65535:

  import sys
  print sys.maxunicode

This is enabled in Windows, but I want the same in Linux. What options have I
pass to the configure script?

w.

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


Re: Compile Python 3 interpreter to force 2-byte unicode

2017-11-26 Thread wojtek . mula
On Sunday, November 26, 2017 at 1:00:19 AM UTC+1, Terry Reedy wrote:
> You must be trying to compile 2.7.  There may be Linux distributions 
> that compile this way.

You're right, I need 2.7. Any hint which distro has got these settings?

> If you want to seriously work with unicode, many recommend using modern 
> Python.

I have to fix a bug in my C extension that appears only in UCS-2 python
(i.e. Windows). I can reboot to Windows and debug there, but it's pain
in a neck for various reasons.

w.
-- 
https://mail.python.org/mailman/listinfo/python-list


Compile Python 3 interpreter to force 2-byte unicode

2017-11-26 Thread wojtek mula
Hi, my goal is to obtain an interpreter that internally uses UCS-2. Such a
simple code should print 65535:

  import sys
  print sys.maxunicode

This is enabled in Windows, but I want the same in Linux. What options have I
pass to the configure script?

w.

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


Re: Compile Python 3 interpreter to force 2-byte unicode

2017-11-27 Thread wojtek mula
On Sunday, November 26, 2017 at 1:00:19 AM UTC+1, Terry Reedy wrote:
> You must be trying to compile 2.7.  There may be Linux distributions
> that compile this way.

You're right, I need 2.7. Any hint which distro has got these settings?

> If you want to seriously work with unicode, many recommend using modern
> Python.

I have to fix a bug in my C extension that appears only in UCS-2 python (i.e.
Windows). I can reboot to Windows and debug there, but it's pain in a neck for
various reasons.

w.

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


Execute python script from VB6 to display Outlook Window

2019-12-22 Thread wojtek . dominicana
I have to prepare e-mail in python (e-mail address, body html, attachments 
etc.) and show Outlook window for user who will check everything and correct if 
necessary and will be able to send it.
My script work well :


o = win32com.client.Dispatch("Outlook.Application")
Msg = o.CreateItem(0)
Msg.To = "a...@gmail.com"
Msg.CC = ""
Msg.Subject = "The random subject"
Msg.HtmlBody = "content of e-mail"
Msg.Attachments.Add(attachment1)
Msg.Display()

This script work well but I have some problem with my Outlook 2019 or Command 
window (Win 10, 64). When Outlook is closed i can call my script using Shell() 
or ShellExecute() and everything is ok but when MS Outlook is open my script 
doesnt work. I use the same  Shell() or ShellExecute() function and still does 
not work although windows executing this script. It stops in the loine 
"win32com.client.Dispatch("Outlook.Application")". I tried many tricks and I 
gave up. The most important is that when I use windows command line and run my 
script manyally (python sendoutlookmail.py) everything works well regardless of 
state of Outlook (open or closed).
I think there is a different between calling script via Shell() function and 
run it directly from command line.
I tried of course solution as follows:

Set obj = CreateObject("WScript.Shell")
obj.Run sPythonFile 

but its the same situation. I createt bat file and I execute this bat file 
which has inside commant to execute my python script.

I have no idea how to run python script on my system that works the same as I 
call it directly from windows command line.

regards
Wojtek
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: urlparse import Faillure

2008-10-10 Thread Wojtek Walczak
On Thu, 9 Oct 2008 22:47:58 -0700 (PDT), Robert Hancock wrote:

>>>> import CGIHTTPServer
...
> ImportError: cannot import name urlparse
>>>>
...
> It points to the third line of the comment.  Any ideas on how to
> proceed with the debugging?

Have you tried getting rid of this comment? I doubt that
the comment is a reason of this error, but it seems that
it shadows the real problem. Moreover, try to import urlparse
itself and check if you got the pyc file for urlparse.py
in your */lib/python2.5/ directory.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: HTTPError... read the response body?

2009-03-02 Thread Wojtek Walczak
On Mon, 2 Mar 2009 14:29:12 -0800 (PST), Stuart Davenport wrote:

Hi,

> I am trying to connect to a web service but I am getting HTTP 400, I
> am not too concerned about the HTTP error - but what I'd like to know
> if there is anyway I can read the response body in the HTTP 400 or 500
> case? Does the HTTPError allow this? or the urllib2 in anyway?

HTTP error 400 means 'bad request', so it's almost certainly
your mistake.


> #url, body, headers
> rq = urllib2.Request(args[1], args[3], headers)

Is args[1] a valid URL? And are you sure that you want to send
something to the web serwer? By specifying the second argument
(args[3]) you're asking python to send HTTP "POST" request,
not "GET".

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Equivalent to C bitmasks and enumerations

2009-04-15 Thread Wojtek Walczak
On Wed, 15 Apr 2009 12:51:31 +0200, Ulrich Eckhardt wrote:

Hi,

> I'm currently using Python to implement a set of tests for code that is
> otherwise written in C. This code was wrapped using Boost.Python and is
> then loaded into Python as module.
...
> What I'm looking for is a suggestion how to handle this in Python. Note that
> technically, this works without problem, I'm rather looking for stylistic
> advise. What I currently have is these (note: I'm retyping this, so ignore
> any syntax errors, please):
...
> Any other suggestions how to structure this or rewrite this?

It's not exactly what you're searching for, but with a bit of work
it should fit your needs:

-
class Colors(object):
   def __init__(self):
  self.colors_reg = {}
  self.colors_set = 0

   def register_color(self, name):
  self.colors_reg.setdefault(name, 1 << len(self.colors_reg))

   def set_color(self, name):
  self.colors_set |= self.colors_reg[name]

   def has_color(self, color):
  return bool(self.colors_reg[color]&self.colors_set)

   def status_as_string(self, st):
  tmp = []
  for k in self.colors_reg:
 if st & self.colors_reg[k]:
tmp.append(k)
  return '|'.join(tmp)


c = Colors()
# register your colors
c.register_color('RED')
c.register_color('BLUE')
c.register_color('YELLOW')

# set colors 'on'
c.set_color('RED')
c.set_color('YELLOW')

print c.has_color('RED')
print c.has_color('BLUE')
print c.status_as_string(5)


HTH,
-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: I'm sort of mystified by the print hex to char conversion

2009-04-18 Thread Wojtek Walczak
On Sat, 18 Apr 2009 11:45:09 -0700 (PDT), grocery_stocker wrote:
> I'm just really not seeing how something like x63 and/or x61 gets
> converted by 'print' to the corresponding chars in the following
> output...
...
>>>> print "\x63h\x61d"
> chad
>>>>
>
> Does print just do this magically?

Not only print does that:

>>> a='\x63h\x61d'
>>> a
'chad'
>>> print a
chad
>>> import sys
>>> sys.stdout.write(a)
chad>>> eval(a)
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 1, in 
NameError: name 'chad' is not defined

The policy is described here:

http://www.python.org/doc/2.4.4/ref/strings.html

Unlike Standard C, all unrecognized escape sequences are left in the
string unchanged, i.e., the backslash is left in the string. (This
behavior is useful when debugging: if an escape sequence is mistyped,
the resulting output is more easily recognized as broken.)

So, as long as the escape sequence is recognized it is changed
accordingly.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: python alternatives to C structs??

2009-04-18 Thread Wojtek Walczak
On Sat, 18 Apr 2009 12:25:29 -0700 (PDT), KoolD wrote:

Hi,

> I need to convert a C code to python please help me figure out how to
> do
> it.
> Suppose the C program's like:
...
> Is there a way to code it in python.

You need struct module:
http://docs.python.org/library/struct.html
http://www.doughellmann.com/PyMOTW/struct/index.html
http://code.activestate.com/recipes/498149/

HTH,
-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: HTTP Authentication using urllib2

2009-04-24 Thread Wojtek Walczak
On Fri, 24 Apr 2009 04:25:20 -0700 (PDT), Lakshman wrote:
> I am trying to authenticate using urllib2. The basic authentication
> works if I hard code authheaders.
...
> except IOError, e:
> print "Something wrong. This shouldnt happen"

First of all, don't shoot yourself in the foot and check what
the exceptions are, i.e.:

  except:
 import traceback
 print traceback.format_exc()

Second, better use mechanize:

http://wwwsearch.sourceforge.net/mechanize/

HTH,
-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Check if module is installed

2008-08-04 Thread Wojtek Walczak
Dnia Mon, 4 Aug 2008 05:25:08 -0700 (PDT), Kless napisa�(a):
> How to check is a library/module is installed on the system? I use the
> next code but it's possivle that there is a best way.

You may also be interested in techniques to keep your software
compatible with older versions of python. Take a look at this
example: http://aima.cs.berkeley.edu/python/utils.html

-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list

Re: URLs and ampersands

2008-08-05 Thread Wojtek Walczak
Dnia 05 Aug 2008 09:59:20 GMT, Steven D'Aprano napisa�(a):

> I didn't say it urlretrieve was escaping the URL. I actually think the 
> URLs are pre-escaped when I scrape them from a HTML file. I have searched 
> for, but been unable to find, standard library functions that escapes or 
> unescapes URLs. Are there any such functions?

$ cd /usr/lib/python2.5/
$ grep "\&\;" *.py
BaseHTTPServer.py:return html.replace("&", "&").replace("<",
"<").replace(">", ">")
cgi.py:s = s.replace("&", "&") # Must be done first!
cgitb.py:doc = doc.replace('&', '&').replace('<',
'<')
difflib.py:
text=text.replace("&","&").replace(">",">").replace("<","<")
HTMLParser.py:s = s.replace("&", "&") # Must be last
pydoc.py:return replace(text, '&', '&', '<', '<', '>',
'>')
xmlrpclib.py:s = replace(s, "&", "&")

So it could be BaseHTTPServer, cgi, cgitb, difflib, HTMLParser,
pydoc or xmlrpclib. Do you use any of these? Or maybe some other
external module?

-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list

Re: Help with mechanize

2008-08-06 Thread Wojtek Walczak
Dnia Wed, 06 Aug 2008 07:16:37 -0400, Neal Becker napisa�(a):
> I'm trying to use mechanize to read for a M$ mail server.  I can get past the 
> login page OK using:
...
> Now it seems if I read b.links() I can see links to my mail.  My question is, 
> how do I now actually get the contents of this page?


Have you tried follow_link() method?
In your case it should be something like:

response = b.follow_link(b.links()[0]) # I suppose links()
   # returns a list or tuple
print response.info() # headers
print response.read() # body

IIRC, it's described in the documentation.

-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list

Re: mktime overflow in March 2008?

2008-08-07 Thread Wojtek Walczak
Dnia 7 Aug 2008 18:40:10 GMT, Robert Latest napisa�(a):
>>>> t = time.strptime("Mar 30, 2008 2:43:32 am", "%b %d, %Y %I:%M:%S
>>>> %p")
>>>> time.mktime(t)
> Traceback (most recent call last):
>   File "", line 1, in 
> OverflowError: mktime argument out of range
>>>> 

time module is written in C. time.mktime() function is actually
only a wrapper for mktime(3) and it also has its limits. Better
use datetime module instead.

-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list

Re: HTTP basic authentication with form-based authentication

2008-08-07 Thread Wojtek Walczak
Dnia Thu, 7 Aug 2008 11:14:05 -0700 (PDT), Max napisa�(a):
> Following the tutorial at http://personalpages.tds.net/~kent37/kk/00010.html,
> I understand how to access HTTP basic authenticated pages or form-
> based authenticated pages. How would I access a page protected by both
> form-based authentication (using cookies) *and* HTTP basic
> authentication?

Use ClientCookie or even better - mechanize:
http://pypi.python.org/pypi/mechanize/
The docs aren't perfect, but you should easily
find what you are searching for.

-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list

Re: Books to begin learning Python

2008-08-07 Thread Wojtek Walczak
Dnia Thu, 7 Aug 2008 12:37:55 -0700 (PDT), Samir napisa�(a):

> Some good online tutorials that I found really helpful include:

You might find it useful:
http://linkmingle.com/list/List-of-Free-Online-Python-Books-freebooksandarticles


-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list

Re: Books to begin learning Python

2008-08-07 Thread Wojtek Walczak
Dnia Thu, 7 Aug 2008 11:12:03 -0700 (PDT), Beliavsky napisa�(a):
> I have the 2nd edition. Has the 3rd edition been rewritten so that all
> of its code will be valid in Python 3? I'd prefer not to buy Python
> books that will become obsolete.

I guess it's for Python 2.x, but I wouldn't worry about this.
Pythons 2.x will be around for quite some time (just as python
1.5.x is).

-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list

Re: how to find out if an object is a class?

2008-08-07 Thread Wojtek Walczak
Dnia Thu, 7 Aug 2008 14:36:37 -0700 (PDT), szczepiq napisa�(a):
> Pardon me for most likely a dummy question but how do I find out if an
> object is a class?


Use types.ClassType:

>>> class Q:
...pass
...
>>> import types
>>> isinstance(Q, types.ClassType)
>>> True

-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list

Re: My very first python program, need help

2008-08-10 Thread Wojtek Walczak
Dnia Sun, 10 Aug 2008 15:52:37 +0200, WP napisa�(a):

Hi,

> import re
>
> def calculate_sum_1(str):
  ^^^
   this word is reserved, better use some other name

>  for c in str:
>  if c.isdigit() == False and c != ' ':
>  # That we assign to the variable we're looping over worries 
> me...
>  str = str.replace(c, ' ')

It's good that it worries you. AFAIR python behavior when assigning to
a variable that is used in for loop is undefined, so you can't count
on it. Better introduce second variable.

>
>  mylist = str.split()
>
>  print "(for loop version) mylist after replace() and split() = ", 
> mylist
>
>  sum = 0
>
>  for item in mylist:
> sum += long(item)

You could use list comprehensions and sum function in here.



> def calculate_sum_2(str):
>  #print "In replace_nondigits_2(), str = ", str
>  p = re.compile('[^0-9]')

or: p = re.compile('\d+')
'\d+' is for one or more digits

>  mylist = p.split(str)

You don't have to split this string. Just search through it.
Findall method seems appropriate.

A bit more pythonic approaches to both of your functions:

===
import re

a="123xx,22! p1"

# Note that 'string' isn't the best name too. It may be shadowed by
# or shadow 'string' module if it's imported.
def calculate_sum_1(string):
   result = ''

   for i in string:
  if i.isdigit():
 result += i
  else:
 result += ' '

   return sum([int(i) for i in result.split()])


def calculate_sum_2(string):
   pat = re.compile('\d+')
   digits = [int(i) for i in re.findall(pat, string)]
   return sum(digits)


print calculate_sum_1(a)
print calculate_sum_2(a)
===


-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list

Re: Second python program: classes, sorting

2008-08-10 Thread Wojtek Walczak
Dnia Sun, 10 Aug 2008 20:26:51 +0200, WP napisa�(a):

Hi,

> Hello, here are some new things I've problems with. I've made a program 
...

>  def __cmp__(self, other):
>  print "in __cmp__"
>  return self.score >= other.score

Check this out: http://docs.python.org/ref/customization.html

Definition of this method should rather look like this:
==
  def __cmp__(self, other):
  print "in __cmp__"
  if self.score == other.score:
 return 0
  elif self.score > other.score:
 return 1
  return -1
==

Should work fine now.

-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list

Re: Looking out a module for Subversion

2008-08-12 Thread Wojtek Walczak
Dnia Tue, 12 Aug 2008 04:25:50 -0400, Dudeja, Rajat napisa�(a):
> Hi,
>
> I'm new to Python. I only have read "Byte of Python" by Swaroop C H just
> to be familiar with sytax of python. I've installed Python 2.5 from
> Active State and using its PythonWin Editor / interpreter. This,
> unfortunaltely, does not help in debugging.
>
> I'm looking for an open source IDE / editor that has source level
> debugging. Please suggest some tool.
>
> I'm intending to write a testing tool that uses Subversion. Is there
> some module available for subversion, out of the box, that I can import
> in my script?

There is no such module in standard library, but you can try
an external one. Check: http://pysvn.tigris.org/


-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list

Re: very rare python expression

2008-08-12 Thread Wojtek Walczak
Dnia Tue, 12 Aug 2008 16:39:27 +0800, =?GB2312?B?zPC5zw==?= napisa�(a):
> Howdy everyone,
>
> I saw a strange python code in pygame project. What does "while
> not(x&528or x in l):" mean? Below code works in python2.5, so "x&528"
> is not HTML strings.

It looks like a check if 528 flag is set. In this way you can set
more than one flag in signle variable:

>>> flag1 = 1
>>> flag2 = 2
>>> flag3 = 4
>>> flag4 = 8
>>> flag5 = 10
>>> flags_set = flag2 | flag4
>>> flags_set & flag1
0
>>> flags_set & flag2
2
>>> flags_set & flag3
0
>>> flags_set & flag4
8
>>> flags_set & flag5
0


-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list

Re: trying to use SOCK_RAW yields error "

2008-08-12 Thread Wojtek Walczak
Dnia Tue, 12 Aug 2008 05:40:36 -0700 (PDT), Tzury Bar Yochay napisa�(a):

Hi,

> server = socket.socket(socket.AF_INET, socket.SOCK_RAW,
> socket.getprotobyname('ip'))
...
> Does anybody have used socket.SOCK_RAW in the past?

When using SOCK_RAW, the family should be AF_PACKET,
not AF_INET. Note that you need root privileges to do so.

-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list

Re: trying to use SOCK_RAW yields error "

2008-08-12 Thread Wojtek Walczak
Dnia Tue, 12 Aug 2008 07:21:15 -0700 (PDT), Tzury Bar Yochay napisa�(a):

> I changed as instructed:
> server = socket.socket(socket.AF_PACKET, socket.SOCK_RAW,
> socket.getprotobyname('ip'))
>
> now I am getting:
>
> Traceback (most recent call last):
>   File "tcpsrv.py", line 15, in 
> server.bind((host,port))
>   File "", line 1, in bind
> socket.error: (19, 'No such device')

What's the value of host variable? AFAIR it should be the name
of the interface you want to bind to ('eth0', 'ppp0', whatever).


-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list

Re: python interpreter

2008-08-12 Thread Wojtek Walczak
Dnia Tue, 12 Aug 2008 07:58:52 -0700 (PDT), [EMAIL PROTECTED] napisa�(a):
>> I'm using python's interpreter's to run various commands (like a
>> normal shell). However if sources are modified changes are not
>> reflected so I have to restart interpreter. Is there any way to avoid
>> restarting this?
>>
>> example:
>>
>> import blah
>>
>> blah.Blah()
>> # ... blah.Blah() changed
>>
>> blah.Blah()
>> # ... new behavior
>
> blah = reload(blah)

...but don't forget to read point 7.5 of the Programming FAQ:
http://www.python.org/doc/faq/programming/

And keep in mind that reload() is removed in Py3k. Hope this helps.

-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list

Re: os.system question

2008-08-12 Thread Wojtek Walczak
Dnia 12 Aug 2008 22:58:22 GMT, Steven D'Aprano napisa�(a):

>> but if I was in a hurry to find out who I was I would be tempted still
>> to use the deprecated "os.popen('whoami').read()".
>
> Is it really deprecated? Since when? I'm using Python 2.5 and it doesn't 
> raise any warnings or mention anything in the doc string.

I think that the deprecation warnings were added in Python 2.6.

-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list

Re: os.system question

2008-08-13 Thread Wojtek Walczak
Dnia Tue, 12 Aug 2008 23:38:56 -0700 (PDT), Asun Friere napisa�(a):

> I note 3.0 runs os.popen without complaint (and had thought to mention
> that in my previous).  Right now I'm wondering whether I should
> install the beta 2.6 to see whether Wotjek is pulling our leg or
> not. :)

:) Checked it to make sure.

Python 2.6b2 (r26b2:65082, Aug 13 2008, 01:12:28)
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import popen2
__main__:1: DeprecationWarning: The popen2 module is deprecated. Use the 
subprocess module.
>>> import os
>>> print os.popen('whoami').read()
gminick

>>> print os.popen2('whoami')[1].read()
gminick

>>> print os.popen2('whoami')[0].read()
__main__:1: DeprecationWarning: os.popen2 is deprecated. Use the subprocess 
module.
Traceback (most recent call last):
  File "", line 1, in 
IOError: [Errno 9] Bad file descriptor
>>>

The strange thing is that os.popen2 prints the deprecation warning
only when it's called inappropriately. Got to investigate it further.

os.popen won't return any deprecation warning in Py2.6beta2 probably
because it is defined in Lib/platform.py and not in Lib/os.py and
I guess that somebody has forgotten to add the warnings in there.

-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list

Re: Replace Several Items

2008-08-13 Thread Wojtek Walczak
Dnia Wed, 13 Aug 2008 09:39:53 -0700 (PDT), gjhames napisa�(a):
> I wish to replace several characters in my string to only one.
> Example, "-", "." and "/" to nothing ""
> I did like that:
> my_string = my_string.replace("-", "").replace(".", "").replace("/",
> "").replace(")", "").replace("(", "")
>
> But I think it's a ugly way.
>
> What's the better way to do it?

The regular expression is probably the best way to do it,
but if you really want to use replace, you can also use
the replace method in loop:

>>> somestr = "Qwe.Asd/Zxc()Poi-Lkj"
>>> for i in '-./()':
...somestr = somestr.replace(i, '')
...
>>> somestr
'QweAsdZxcPoiLkj'
>>>


Next step would be to define your own replacing function:

def my_replace(mystr, mychars, myrepl):
   """Replace every character from 'mychars' string with 'myrepl' string
   in 'mystr' string.

   Example:

   my_replace('Qwe.Asd/Zxc(', './(', 'XY') -> 'QweXYAsdXYZxcXY'"""

   for i in mychars:
  mystr = mystr.replace(i, myrepl)

   return mystr


-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list

Re: os.system question

2008-08-13 Thread Wojtek Walczak
Dnia Wed, 13 Aug 2008 22:03:49 +0200, Fredrik Lundh napisa�(a):

> not talking for the 3.X developers here, but os.popen is a binding to 
> the POSIX popen function, so I'm not sure it makes that much sense to 
> actually deprecate it.
>
> the os.popen[234], popen2, and commands stuff are different -- they're a 
> a series of attempts to provide more functionality by building on 
> lower-level primitives, something that the subprocess module does a lot 
> better.

This makes sense. My idea that some developer had forgotten to add
the deprecation warning for os.popen() goes to the bin.


-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list

Re: Suggestion for improved ImportError message

2008-08-13 Thread Wojtek Walczak
Dnia Wed, 13 Aug 2008 20:55:38 + (UTC), Kent Tenney napisa�(a):

> from image import annotate
>
> ImportError: cannot import name annotate
>
> I found the problem via 
>
> import image
> print image.__file__
>
> which made it clear that the wrong image module had been found.
>
> It would be nice if ImportError announced this up front.

Then go for it :-) You can prepare a patch and ask on python-dev
if the developers are interested.

I was never hacking the import things on C level before,
but a hint: you have to modify import_from function from
Python/ceval.c

My quick attempt:
http://www.stud.umk.pl/~wojtekwa/patches/from-import-py2.5.1.patch


-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list

Re: Replace Several Items

2008-08-13 Thread Wojtek Walczak
Dnia Wed, 13 Aug 2008 23:31:42 +0200, Fredrik Lundh napisa�(a):
>>> I wish to replace several characters in my string to only one.
>>> Example, "-", "." and "/" to nothing ""
>>> I did like that:
>>> my_string = my_string.replace("-", "").replace(".", "").replace("/",
>>> "").replace(")", "").replace("(", "")
>>>
>>> But I think it's a ugly way.
>>>
>>> What's the better way to do it?
>> 
>> The regular expression is probably the best way to do it,
>> but if you really want to use replace, you can also use
>> the replace method in loop:
>
> suggested exercise: benchmark re.sub with literal replacement, re.sub 
> with callback (lambda m: ""), repeated replace, and repeated use of the form
>
>  if ch in my_string:
>   my_string = my_string.replace(ch, "")
>
> on representative data.

I don't have to, I can anticipate the results. I mentioned above
that using re is the best approach, but if one really wants to use
replace() multiple times (which will be slow, of course), it can
be done a bit cleaner than with str.replace().replace().replace()...

-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list

Re: Suggestion for improved ImportError message

2008-08-13 Thread Wojtek Walczak
Dnia Wed, 13 Aug 2008 22:15:48 + (UTC), Wojtek Walczak napisa�(a):

> Then go for it :-) You can prepare a patch and ask on python-dev
> if the developers are interested.
>
> I was never hacking the import things on C level before,
> but a hint: you have to modify import_from function from
> Python/ceval.c
>
> My quick attempt:
> http://www.stud.umk.pl/~wojtekwa/patches/from-import-py2.5.1.patch

Uh, and an example:

Python 2.5.1 (r251:54863, Aug 14 2008, 00:04:00)
[GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from os import qweasd
Traceback (most recent call last):
  File "", line 1, in 
ImportError: cannot import name qweasd (/home/gminick/Python-2.5.1/Lib/os.pyc)
>>>

-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list

Re: Replace Several Items

2008-08-13 Thread Wojtek Walczak
Dnia Thu, 14 Aug 2008 00:31:00 +0200, Fredrik Lundh napisa�(a):

>>>  if ch in my_string:
>>>   my_string = my_string.replace(ch, "")
>>>
>>> on representative data.
>> 
>> I don't have to, I can anticipate the results.
>
> Chances are that you're wrong.

At the moment my average is about 0.75 of mistake per
post on comp.lang.python (please, bare with me ;-)).
I strongly believe that the statement I made above won't
make this number rise.

:)
-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list

Re: Suggestion for improved ImportError message

2008-08-14 Thread Wojtek Walczak
On Thu, 14 Aug 2008 01:35:44 + (UTC), Kent Tenney wrote:
>> > Then go for it  You can prepare a patch and ask on python-dev
>> > if the developers are interested.
>
> hehe, I'll get a C level patch accepted right after I 
> out-swim Mike Phelps.

It's really not that hard. The only hard thing (harder than
writing the code) might be to win the acceptance of the core
developers that this change is really needed ;-) 


>> > I was never hacking the import things on C level before,
>> > but a hint: you have to modify import_from function from
>> > Python/ceval.c
>
> Am I correct in thinking that PyPy would mean low level
> stuff like this will be Python instead of C? 
> That would be nice.

I don't know PyPy, but I guess you're right here.


-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Replace Several Items

2008-08-14 Thread Wojtek Walczak
On 14 Aug 2008 01:54:55 GMT, Steven D'Aprano wrote:

>>>> I don't have to, I can anticipate the results.
>>>
>>> Chances are that you're wrong.
>> 
>> At the moment my average is about 0.75 of mistake per post on
>> comp.lang.python (please, bare with me ;-)). I strongly believe that the
>> statement I made above won't make this number rise.

> Okay, is this going to be one of those things where, no matter what the 
> benchmarks show, you say "I was right, I *did* anticipate the results. I 
> just anticipated them correctly/incorrectly."?

Don't count on it. I never really cared about being right or wrong
and I am not one of those guys who are trying to prove something
that actually makes no difference at all. Nice tests, though :)


-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list


Re: for y in range (0,iNumItems)--> not in order?

2008-08-14 Thread Wojtek Walczak
On Thu, 14 Aug 2008 08:35:15 -0700 (PDT), korean_dave wrote:
> Still the same output...
>
> Here's the actual code...
>
> for x in range(0,2):
> for y in range(0,27):
> for z in range(0,15):
> print(str(x) + " " + str(y) + " " + str(z))

This code won't produce the output you have shown in your
original post.

What's your supposed output for the code above (IOW, what
are you trying to achieve)?

And BTW, which version of python do you use? If it's not
Python 3.0 don't put parentheses around the print instruction,
it's not a function. You could also write:
   print "%d %d %d" % (x, y, z)

-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list


Re: negative numbers are not equal...

2008-08-14 Thread Wojtek Walczak
On Thu, 14 Aug 2008 18:23:21 -0300, ariel ledesma wrote:

> i see now, so i guess that's also why id() returns the same address for 
> them as well...

It just have to work like this.

a is b

is actually equal to:

id(a) == id(b)

so there is no other way for id() in such case.

Hope this helps.

-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list


Re: getattr nested attributes

2008-08-15 Thread Wojtek Walczak
On Fri, 15 Aug 2008 11:12:04 +0200, Gregor Horvath wrote:

> Thank's, but this does not work for this case:
>
> class A(object):
>  test = "test"
>
> class B(object):
>  a = [A(),]
>
> In [70]: reduce(getattr, "a[0].test".split("."), B)
> ---
>Traceback (most recent call last)
>
>/ in ()
>
>: type object 'B' has no attribute 'a[0]'
>
> Seems that I have to use eval ?

Nope. Always ask getattr for small things and it will like you:

>>> getattr(getattr(B, 'a')[0], 'test')
'test'
>>>

it works because:

>>> getattr(B, 'a') == B.a
True
>>> getattr(B, 'a')[0] == B.a[0]
True
>>>

-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do I control output buffering on Win32?

2008-08-15 Thread Wojtek Walczak
On Fri, 15 Aug 2008 09:47:34 -0500, Grant Edwards wrote:
> When I ssh in to my Windows XP box and run Python apps, output
> from "print" and and "sys.stdout.write()" is being buffered so
> that none of the output shows up until the program exits. 
>
> From within my program how do I set output buffering to either
> line-buffered or un-buffered?  [I'm looking for the equivalent
> of the C stdio "setbuf" call.]

That's not exactly what you want, but what about creating your
own printing function and flushing at its end?

import sys
def printf(mystr):
   print mystr
   sys.stdout.flush()

-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list


Re: QT, ctypes dll and SEG Faults

2008-08-17 Thread Wojtek Walczak
On Sat, 16 Aug 2008 21:17:25 -0700 (PDT), sapsi wrote:
>> Below is a small class using ctypes and libspectre to read a
>> postscript file.
>> My program is a PyQT 4.4 application �and when the user clicks on a
>> entry in a QTableWidget, i run
>>
>> PostScriptImage( filename_as_contained_in_clicked_tableWidgetItem )
>> However on i get a segfault while trying document_load.
>> Surprisingly, before i run sys.exit(app.exec_()) (i.e before the app
>> starts) if run PostScriptImage(command_line_specified_ps_file) it
>> works!

> To answer my own question, partially, i found out if i replace
> filename with a hard coded value it doesn't crash.
> Now why is that? Does python lose the reference? Should i store
> filename as attributed of the object?

Are you sure that the hardcoded value is _exactly_ the same
as the one passed to __init__? Try it in __init__ to make sure:

assert filename == 'your_hardcoded_value'

And why won't you try to store the filename as an attribute?
(even though I doubt it could help).

-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list

Re: how many nested for can we utilize?

2008-08-17 Thread Wojtek Walczak
On Sun, 17 Aug 2008 16:39:26 +0200, Fredrik Lundh wrote:

>> A good quote I read (I can't remember who it was from, though) is "If
>> you need more than three levels of indentation, then something is
>> seriously wrong with your code." Possibly Guido himself? Anyway. If
>> you've got 100 levels of for, you're probably making things way harder
>> than they need to be.
>
> assuming 100 levels of for and 2 items in each sequence, you'll end up 
> with 1267650600228229401496703205376 iterations through the inner loop. 
>   assuming each iteration takes a picosecond, it'll take approx 40 
> billion years to run the program.

I guess that's exactly why the OP asks the question. He just wants
to start as soon as possible ;-)

-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list


Re: how many nested for can we utilize?

2008-08-17 Thread Wojtek Walczak
On Sun, 17 Aug 2008 17:17:06 +0200, Fredrik Lundh wrote:
>>> it'll take approx 40 billion years to run the program.
>> 
>> I guess that's exactly why the OP asks the question. He just wants
>> to start as soon as possible ;-)
>
> required reading:
>
>"The Effects of Moore's Law and Slacking on Large Computations"
>http://arxiv.org/abs/astro-ph/9912202

Kinda buddhist approach. Anyway, it might work out, unless the number
of for loops is increasing in time and in 18 months it may be - let's
say - 20 nested for loops more ;) Got to ask the OP.

-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to call API Functions in python

2008-08-17 Thread Wojtek Walczak
On Sun, 17 Aug 2008 11:22:52 -0700 (PDT), raashid bhatt wrote:
>> > how to call API Functions in python
>>
>> The same way as you'd call any other function, of course. �What API are
>> you referring to?

> i am talking about WINAPI

I am not a Windows guy, but maybe ctypes module will be helpful
for you.

-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list

Re: like a "for loop" for a string

2008-08-17 Thread Wojtek Walczak
On Sun, 17 Aug 2008 11:22:37 -0700 (PDT), Alexnb wrote:

> funString = "string string string non-string non-string string"
> and
> for "string" in funString:
>   print something
>
> I know you can't do that; but, is there a way do do something similar that
> gets the same result?

What's "that"?

Do you mean _this_:

>>> somestr = "string1 string2 string3"
>>> for i in somestr.split():
...print i
...
string1
string2
string3
>>>

?

-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list


Re: like a "for loop" for a string

2008-08-17 Thread Wojtek Walczak
On Sun, 17 Aug 2008 12:07:45 -0700 (PDT), [EMAIL PROTECTED] wrote:

> I'm waiting for a str.xsplit still :-)
> If I write and submit a C implementation of xsplit how many chances do
> I have to see it included into Python? :-)

Got no idea, but it might be a nice try. It should be a quite good memory
saver for very large strings. While browsing the implementation of
split method I discovered something I didn't really realise before.
While calling split method without arguments it treats all four signs:
' ', '\n', '\r' and '\t' as a whitespace, so it's not the same as
str.split(' '). Moreover, specifying maxsplit argument whenever possible
seems to be a good practice. Anyway, go ahead with that xsplit thing :-)

-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list


Re: online tutorials?

2008-08-18 Thread Wojtek Walczak
On Sun, 17 Aug 2008 15:53:38 -0700 (PDT), Gits wrote:
> I want to learn how to program in python and would like to know if you
> guys know of any free online tutorials.  Or is it too complicated to
> learn from a site or books?

Try this:

http://linkmingle.com/list/List-of-Free-Online-Python-Books-freebooksandarticles

-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list


Re: searching through a string and pulling characters

2008-08-18 Thread Wojtek Walczak
On Mon, 18 Aug 2008 13:40:13 -0700 (PDT), Alexnb wrote:
> Now, I am talking 1000's of these. I need to do something like this. I will
> have a number, and what I want to do is go through this text file, just like
> the example. The trick is this, those "()'s" are what I need to match, so if
> the number is 245 I need to find the 245th () and then get the all the text
> from after it until the next (). If you have an idea about the best way to
> do this I would love your help. If you made it all the way through thanks!
> ;)

findall comes to mind:

>>> a="""(string1)
... (string2)
... (string3)
... (string4)
... (string5)
... (string6)"""
>>> import re
>>> pat = re.compile("(\(.*?\))")

and now let's say you want to get fourth element:

>>> pat.findall(a)[3]
'(string4)'

To save some memory use finditer (as long as you don't have to search
for too many of these):

>>> for i in enumerate(pat.finditer(a)):
...if i[0] == 2:
...   print i[1].group()
...
(string3)
>>>


-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list


Re: searching through a string and pulling characters

2008-08-18 Thread Wojtek Walczak
On Mon, 18 Aug 2008 21:43:43 + (UTC), Wojtek Walczak wrote:
> On Mon, 18 Aug 2008 13:40:13 -0700 (PDT), Alexnb wrote:
>> Now, I am talking 1000's of these. I need to do something like this. I will
>> have a number, and what I want to do is go through this text file, just like
>> the example. The trick is this, those "()'s" are what I need to match, so if
>> the number is 245 I need to find the 245th () and then get the all the text
>> from after it until the next (). If you have an idea about the best way to
>> do this I would love your help. If you made it all the way through thanks!
>> ;)
>
> findall comes to mind:

...forget it, I misread your post :)

-- 
Regards,
Wojtek Walczak,
http://www.stud.umk.pl/~wojtekwa/
--
http://mail.python.org/mailman/listinfo/python-list


Re: searching through a string and pulling characters

2008-08-19 Thread Wojtek Walczak
On Mon, 18 Aug 2008 15:34:12 -0700 (PDT), Alexnb wrote:

> Also, on a side-note, does anyone know a very simple dictionary site, that
> isn't dictionary.com or yourdictionary.com.

This one is my favourite: http://www.lingro.com/


-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: [tarfile] Difficultis catching an exception

2008-08-20 Thread Wojtek Walczak
On Wed, 20 Aug 2008 02:07:33 -0700 (PDT), [EMAIL PROTECTED] wrote:
> I'm trying to catch an "EOFError" exception that occurs when reading
> truncated tarfile. Here's my routine, and below that the callback
> trace. Note that although I'm trying to catch all TarFile exceptions,
> the tarfile.EOFError ecxeption, and the global EOFError exception, the
> program still falls through and fails.
...
> except tarfile.TarError, EOFError, tarfile.EOFError:
...

Multiple exceptions should be parenthesized. BTW, are you sure
your tarfile has EOFError attribute?
Try this:

...
except (tarfile.TarError, EOFError):
...

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Storing Passwords

2008-08-20 Thread Wojtek Walczak
On Tue, 19 Aug 2008 21:44:04 -0400, Eric Wertman wrote:
> I've a number of scripts set up that require a username/password
> combination to log in elsewhere.  It's gotten to the point where I
> need to keep them in a more secure location, instead of just in the
> scripts themselves.  I did a bit of searching, and haven't come up
> with a great way to store passwords using 2-way encryption (I have to
> send them as plain text).  Has anyone seen anything that fits this
> need?  I whipped up something using base64 and pickle, to keep them in
> a dictionary and at least prevent them from being plain text, but it
> seems a bit insecure all the same.   Any ideas, much appreciated.

Have you checked pyDes?

http://sourceforge.net/projects/pydes/

or

http://www.example-code.com/python/crypt2_3desTestVector.asp

there is a link to a library called chilkat and it looks like
this library provides some 3des functionality. 

HTH.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: TRying to read sercah results from googles web page

2008-08-20 Thread Wojtek Walczak
On Wed, 20 Aug 2008 05:42:34 -0700 (PDT), [EMAIL PROTECTED] wrote:

> the  web page.  When I try to load in a url with the search results,
> http://www.google.com/search?hl=en&q=ted', I get a web page that says
> I do not have permissions.  Is theree a way around this, or is Google
> just to smart

Try to imitate the web browser. Add 'User-Agent' (with add_header
method) to your http request. If it won't help, try to add more
browser-specific variables to your headers. Also, take a look at
mechanize and its Browser class:

http://wwwsearch.sourceforge.net/mechanize/

FYI and AFAIK, google doesn't allow to use their search engine
in this way. They even block certain IP addresses it it's constantly
abusing the search engine with too many requests.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess seems to "detach" / ignore wait()

2008-08-20 Thread Wojtek Walczak
On Wed, 20 Aug 2008 15:09:11 +0200, Mathieu Prevot wrote:

> flog = open(logfile, 'w')
> fpid = open(pidfile, 'w')
> try:
>   child = Popen(cmd.split(), stderr=flog)
>   print "Server running [PID %s]"%(child.pid)
>   fpid.write(child.pid)

What happens if you change:

fpid.write(child.pid)

into:

fpid.write('%d\n' % (child.pid))

I think that the problem here is that fpid.write() fails silently
(probably TypeError), because it takes string as its first argument,
not integer.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: 'While' question

2008-08-21 Thread Wojtek Walczak
On Thu, 21 Aug 2008 18:01:25 -0400, Ben Keshet wrote:
> somehow. I use 'while 'word' not in line' to recognize words in the 
> texts. Sometimes, the files are empty, so while doesn't find 'word' and 
> runs forever. I have two questions:
> 1) how do I overcome this, and make the script skip the empty files? 
> (should I use another command?)
> 2) how do I interrupt the code without closing Python? (I have ActivePython)

Try the docs first. You need to read about 'continue' and
'break' statements: http://docs.python.org/tut/node6.html

HTH.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: def X(l=[]): weirdness. Python bug ?

2008-08-22 Thread Wojtek Walczak
On Fri, 22 Aug 2008 11:13:52 +0200, Bart van Deenen wrote:

> I've stumbled onto a python behavior that I don't understand at all.
...
> Does anyone have any pointers to the language documentation where this 
> behavior is described?

Yes, it's documented in FAQ:
http://www.python.org/doc/faq/general/
Question 4.22.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: def X(l=[]): weirdness. Python bug ?

2008-08-22 Thread Wojtek Walczak
On Fri, 22 Aug 2008 11:41:18 +0200, Bart van Deenen wrote:

> Thanks all for your answers. I figured your solution already, but now I 
> understand where the behavior is from. One question remains: can I find my 
> parameter 'l' somewhere? I looked in a lot of objects, but couldn't find it.

YOURFUNCTION.func_globals['YOURFUNCTION'].func_defaults

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: def X(l=[]): weirdness. Python bug ?

2008-08-22 Thread Wojtek Walczak
On Fri, 22 Aug 2008 11:42:03 +0200, Diez B. Roggisch wrote:

> It's amazing. I didn't analyse this properly, but IMHO this issue is the 
> single most asked question (or rather the effects in produces) on this list.
>
> Maybe we should get *really* explicit in
>
> http://docs.python.org/tut/node6.html#SECTION00671
>
> and
>
> http://docs.python.org/ref/function.html
>
> Big, red warnings, or some such.

+1

Documenting this should also make it easier to understand
the difference between mutable/immutable objects before one
comes on c.l.py and asks about it.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: exception handling in complex Python programs

2008-08-22 Thread Wojtek Walczak
On Fri, 22 Aug 2008 06:43:58 -0700 (PDT), Lie wrote:

> I think we should change except: into expect:, it would confuse less,
> would it? It signifies that the program expects so and so kinds of
> exceptional situations. The try: should also be changed to... perhaps
> in:, block:, onthiscode:, etc (this paragraph is written with my taste
> buds on the part of my face below my eye and above my jaw)

IMO it's not even worth considering. Breaking all the python
software that exists and moreover breaking the habits of programmists
to gain *nothing* is a waste of time of so many people, that
we should just forget it.


-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: EOF

2008-08-22 Thread Wojtek Walczak
On Fri, 22 Aug 2008 22:18:37 +0530, Anjanesh Lekshminarayanan wrote:

> Im trying to download a file from a server. But how do I detect EOF ?

Whenever read() method returns empty string/list.


> while f1: # When to stop ?
 retval = f1.read()
 if not retval:
break
 f2.write(retval)

should do the job.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: 'While' question

2008-08-22 Thread Wojtek Walczak
On Fri, 22 Aug 2008 10:42:13 -0400, Ben Keshet wrote:
> Thanks.  I tried to use 'for' instead of 'while' as both of you 
> suggested.  It's running well as my previous version but breaks 
> completely instead of just skipping the empty file.  I suspect the 
> reason is that this part is inside another 'for' so it stops 
> everything.  I just want to it to break only one 'for', that is go back 
> to 5th line in the example code (directory C has one empty file):

>for line in f:
^^^
>line = line.rstrip()
>if "PRIMARY" not in line:
>j += 1
>if j == 20:
>break
>else:
>for line in f:
^^^
You're iterating through the same value in inner and outer loop.
Don't do that. It's hard to predict the behavior of such a code.

Regarding break statement, it breaks only the inner loop
and returns to the outer loop/block.

It would be great if you could reduce your code to a short piece
that illustrates your problem and that we could all run.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python one-liner??

2008-08-22 Thread Wojtek Walczak
-c?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Generate alphabet?

2008-08-22 Thread Wojtek Walczak
On Fri, 22 Aug 2008 15:02:19 -0700 (PDT), ssecorp wrote:
> In Haskell I can do [1..10] for range(1,11) and ['a'..'z'] for a list
> of the alphabet.
>
> Is there a way in Python to generate chars?

It's not actually about generating anything, but why should
one generate something if it's accessible anyway:

import string
print string.letters

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Generators can only yield ints?

2008-08-22 Thread Wojtek Walczak
On Fri, 22 Aug 2008 15:44:15 -0700 (PDT), defn noob wrote:
> def letters():
>   a = xrange(ord('a'), ord('z')+1)
>   B = xrange(ord('A'), ord('Z')+1)
>   while True:
>   yield chr(a)
>   yield chr(B)
>
>
>>>> l = letters()
>>>> l.next()
>
> Traceback (most recent call last):
>   File "", line 1, in 
> l.next()
>   File "", line 5, in letters
> yield chr(a)
> TypeError: an integer is required
>>>>

The error you're seeing is a result of passing
non-integer to chr() function, it has nothing to do
with generators:

>>> chr([])
Traceback (most recent call last):
  File "", line 1, in 
TypeError: an integer is required
>>>

I have simplified your code a bit:
-
import string
def letters():
a, B = (string.letters,) * 2
for i in zip(a, B):
yield i[0]
yield i[1]

l = letters()

print l.next()
print l.next()
print l.next()
--

and the output:

$ python genlet.py
a
a
b
$

Is that what you tried to achieve?

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to know a top directory?

2008-08-23 Thread Wojtek Walczak
On Sat, 23 Aug 2008 04:15:25 -0700 (PDT), Grigory Temchenko wrote:
> Help me please. How to know a top directory? I mean I have path "/this/
> is/path" and I wanna get "/this/is".
> Also I want to use it as platform independent. If I want to pass "c:
> \that\path" then I need to get "c:\that".
>
> Does anyone have ideas?

Read about os.path module. It's all in there:
http://docs.python.org/lib/module-os.path.html

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to check in CGI if client disconnected

2008-08-24 Thread Wojtek Walczak
On Sun, 24 Aug 2008 17:21:52 -0300, Gabriel Genellina wrote:
>>I am writing a CGI to serve files to the caller. I was wondering if
>> there is any way to tell in my CGI if the client browser is still
>> connected. If it is not, i want to execute some special code before
>> exiting.
>>
>>Is there any way to do this? Any help on this is appreciated :)
>
> I don't think so. A CGI script runs once per request, and exits. The server 
> may find that client disconnected, but that may happen after the script 
> finished.

I am not a web developer, but I think that the only way is to
set a timeout on server side. You can't be sure that the client
disconnected, but you can stop CGI script if there's no
action on client side for too long.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: passing arguments to exec

2008-08-25 Thread Wojtek Walczak
On Mon, 25 Aug 2008 06:31:53 -0700 (PDT), Alexandru Mosoi wrote:
> i want to execute a python script using exec open('script.py'). how do
> I pass arguments?

Take a look at subprocess module. It comes with a set of examples.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: class definition syntax

2008-08-29 Thread Wojtek Walczak
On Fri, 29 Aug 2008 02:50:57 -0700 (PDT), harryos wrote:

> class MyClass(object):
> def __init__(self):
>
>
> what does the object keyword inside the braces in MyClass() mean?
> Has it got any significance?

It's inheritance. MyClass class inherits from object class.
Check out point 9.5 in the tutorial.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Importing module with name given as a variable

2008-08-30 Thread Wojtek Walczak
On Sat, 30 Aug 2008 11:02:03 -0700 (PDT), Sean Davis wrote:
> What is the "best practice" for importing an arbitrary module given
> that the name is stored in a variable?  The context is a simple web
> application with URL dispatching to a module and function.  I know of
> __import__(), the imp module, and exec.  For each of these, is there a
> way to make them work "just like" the normal import call?

It all depends on your needs. If you have to deal with user
input to get the name of the module, better use __import__
than exec. __import__ works just like the normal import call:

import sys

is equal to:

sys = __import__('sys')

If you need, let's say, to search for a module that lies
outside sys.module paths, then use imp's functions.

HTH.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Relative imports and "import X as Y"

2008-08-31 Thread Wojtek Walczak
On Sun, 31 Aug 2008 06:40:35 GMT, OKB (not okblacke) wrote:

>> Download the latest beta for your system and give it a try.
>
>   Thanks for the advice, but I'd really rather not deal with 
> installing the entire thing alongside my existing version, possibly 
> causing conflicts in who knows what ways.

Then you can download tar.gz package, compile it, and try it
without installing :-)

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: How can we get to the end of a quote inside a string

2008-08-31 Thread Wojtek Walczak
On Sun, 31 Aug 2008 07:29:26 -0700 (PDT), [EMAIL PROTECTED] wrote:

> Suppose I have a string which contains quotes inside quotes -
> single and double quotes interchangeably -
>  s = "a1' b1 " c1' d1 ' c2" b2 'a2"

>>> s = "a1' b1 " c1' d1 ' c2" b2 'a2"
  File "", line 1
s = "a1' b1 " c1' d1 ' c2" b2 'a2"
   ^
SyntaxError: invalid syntax
>>>

Writing a small parser for your needs shouldn't be that hard.
To some extent you can use regular expressions:

>>> re.findall(re.compile("\".*?\""), s)
['" c1\' d1 \' c2"']
>>> re.findall(re.compile("\'.*?\'"), s)
['\' b1 " c1\'', '\' c2" b2 \'']
>>>

but it won't work in all cases. You can read more here:
http://www.gnosis.cx/TPiP/

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Processes in Linux from Python

2008-09-01 Thread Wojtek Walczak
On Sun, 31 Aug 2008 23:25:56 -0700 (PDT), Johny wrote:
> To get a number of  the http processes running on my Linux( Debia box)
> I use
> ps -ef | grep "[h]ttpd" | wc -l
...
> So my question is:
> Is it possible to get a number of the http processes running on Linux
> directly from Python ?

Yes, it is. There is a number of third party packages that provide
such functionality, including PSI: http://www.psychofx.com/psi/
I never actually liked them, because they are parsing /proc directory
by themselves. Thus I wrote my own tool that is a wrapper around
procps library (libproc* in your /lib, probably). Your system tools
like ps, w or top are using this library. My wrapping library is
available at: http://code.google.com/p/procpy/
In your case you could use it like this:

>>> import procpy
>>> pp = procpy.Proc()
>>> for pid in pp.pids:
...if pp.procs[pid]['cmd'] == 'apache2':
...   print pp.procs[pid]['tid']
...
5204
5205
5206
5208
>>>  

it prints the PIDs of all the apache2 processes on my system.
Procpy is fine for my own needs, but if I were about to write
a code that is intended to be portable, I'd use PSI. It also is
more mature.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: list + dictionary searching

2008-09-01 Thread Wojtek Walczak
On Mon, 1 Sep 2008 03:14:22 -0700 (PDT), Manoj wrote:

> I would like to :
>
> search dictionaries within this list
> create a new list with dictionaries which gives 1 dictionary for every
> user with month_year as a key and utilization for that month as a
> value
>
> Please give your thoughts

Reading about for loop seems like a good idea. You can easily
create a set of functions that gives you direct access to the
information you need.

http://docs.python.org/tut/node6.html#SECTION00620
http://docs.python.org/tut/node7.html#SECTION00750

Give it a try. Try to design some functions that let you
view and add new lists/dictionaries to your variables.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to find position of dictionary values

2008-09-01 Thread Wojtek Walczak
On Mon, 1 Sep 2008 03:51:13 -0700 (PDT), lee wrote:

> i am soory for that keystrokes. can anyone tell me how can i change
> the value of key.
> suppose i have a dictionary
>
> kev =  {'kabir': ['[EMAIL PROTECTED]', '1234', 'missuri'], 'shri':
> ['[EMAIL PROTECTED]', '23423', 'india'], 'marsa': ['[EMAIL PROTECTED]',
> '2345', 'brazil'], 'sandeep': ['[EMAIL PROTECTED]', '007',
> 'canada']}

> how can i change the key to something like 'sabir' and 

kev['sabir'] = kev['kabir']
del kev['kabir']

> how can i
> change the values of kabir?

kev['sabir'][0] = '[EMAIL PROTECTED]'

*untested*

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Eleganz way to get rid of \n

2008-09-01 Thread Wojtek Walczak
On Mon, 01 Sep 2008 15:25:03 +0200, Hans M�ller wrote:

> I'm quite often using this construct:
>
> for l in open("file", "r"):
>   do something

> Has someone a better solution ?

The most general would be to use rstrip() without
arguments:

>>> a="some string\r\n"
>>> a.rstrip()
'some string'
>>>

but be careful, because it will also cut whitespaces:

>>> a="some string\t \r\n"
>>> a.rstrip()
'some string'
>>> 

so maybe you could do this:

>>> a.rstrip('\n').rstrip('\r')
'some string\t '
>>>  

HTH.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list

Re: Getting an objetcs dict?

2008-09-01 Thread Wojtek Walczak
On Mon, 1 Sep 2008 11:31:42 -0700 (PDT), ssecorp wrote:
> I did nce(I think).
>
> class X
>
> X.__dict__() and ngot a dict of its variables.
>
> Now i get errors doing this. what am i doing wrong?

You're not asking smart questions:
http://www.catb.org/~esr/faqs/smart-questions.html

HINT: the attribute you're accessing is not a callable.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Algorithm used by difflib.get_close_match

2008-09-02 Thread Wojtek Walczak
On Tue, 2 Sep 2008 06:17:37 -0700 (PDT), Guillermo wrote:

> Does anyone know whether this function uses edit distance? If not,
> which algorithm is it using?

The following passage comes from difflib.py:

SequenceMatcher is a flexible class for comparing pairs of sequences of
any type, so long as the sequence elements are hashable.  The basic
algorithm predates, and is a little fancier than, an algorithm
published in the late 1980's by Ratcliff and Obershelp under the
hyperbolic name "gestalt pattern matching".  The basic idea is to find
the longest contiguous matching subsequence that contains no "junk"
elements (R-O doesn't address junk).  The same idea is then applied
recursively to the pieces of the sequences to the left and to the right
of the matching subsequence.  This does not yield minimal edit
sequences, but does tend to yield matches that "look right" to
people.

HTH.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Storing Subprocess Results

2008-09-02 Thread Wojtek Walczak
On Tue, 2 Sep 2008 07:16:21 -0700 (PDT), topazcode wrote:
> I am using the subprocess module to run some shell commands on a Linux
> system:
>
> import subprocess
> output = subprocess.call('''ssh server1 "uptime"''', shell=True)
>
> The above assigns the output variable with a return code, i.e. 0 in
> this case.  How can I actually capture the data returned from
> subprocess.call, rather than just the return code?

Use subprocess.Popen instead of call.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: What is module initialization?

2008-09-02 Thread Wojtek Walczak
On Tue, 2 Sep 2008 15:32:07 +0100, [EMAIL PROTECTED] wrote:

> But if I do :-
>#question.py
> from myglobals import *
> myglobals.answer = "WTF ?"
>
> will this work?

Why won't you try? In this case you should receive NameError.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: python - mechanize/browser/POST issue

2008-09-03 Thread Wojtek Walczak
On Tue, 2 Sep 2008 19:39:05 -0700, bruce wrote:

> using mechanize/Browser, i can easily do a url/get, and process submitting a
> form that uses a GET as the action. however, I'm not quite sure how to
> implement the submittal of a form, that uses the POST action.
>
> Anyone have a short chunk of code that I can observer, that uses the
> mechanize.Browser implentation?

Take a look at the bottom of this post:

http://mail.python.org/pipermail/python-list/2006-June/390037.html

It seems that submit does the job.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: properties setting each other

2008-09-03 Thread Wojtek Walczak
On Wed, 03 Sep 2008 15:57:50 +0200, mk wrote:

> I try to set two properties, "value" and "square" in the following code, 
> and arrange it in such way that setting one property also sets another 
> one and vice versa. But the code seems to get Python into infinite loop:

> Is there a way to achieve this goal of two mutually setting properties?

My attempt:
---
import math

class Square(object):
   def __init__(self, val):
  self._square = pow(val, 2)
  self._value = math.sqrt(self.square)

   def getsquare(self):
  return self._square

   def setsquare(self, square):
  self._square = square
  self._value = math.sqrt(self._square)

   square = property(getsquare, setsquare)

   def getvalue(self):
  return self._value

   def setvalue(self, value):
  self._value = value
  self._square = math.pow(value, 2)

   value = property(getvalue, setvalue)


a = Square(5)
print a.square
print a.value
a.value = 10
print a.square
print a.value
a.square = 64
print a.square
print a.value
---

and the result:

$ python sqval.py
25
5.0
100.0
10
64
8.0
$ 

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: properties setting each other

2008-09-03 Thread Wojtek Walczak
On Wed, 3 Sep 2008 14:31:17 + (UTC), Wojtek Walczak wrote:

> class Square(object):
>def __init__(self, val):
>   self._square = pow(val, 2)
>   self._value = math.sqrt(self.square)
  ^^
or just:
self._value = val

:-)


-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Looking for File comparison utility that produces actual differences

2008-09-03 Thread Wojtek Walczak
On Wed, 3 Sep 2008 19:40:40 +0100, [EMAIL PROTECTED] wrote:

> I looking for a file comparison utility in Python that works like
> 'diff' command in Unix and 'comp' in Windows.
> The present 'cmd'  in filecmp module only presents output in the form
> of 1 or 0 i.e whether the 2 files differ or not?

In python it's called difflib. Try to import it.

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: overwrite set behavior

2008-09-04 Thread Wojtek Walczak
On Thu, 04 Sep 2008 11:48:18 +0200, Michele Petrazzo wrote:
> Hi all, I want to modify the method that set use for see if there is
> already an object inside its obj-list. Something like this:
...
> It's possible?

As far as I understand you, you need descriptors:
http://users.rcn.com/python/download/Descriptor.htm


-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Issue warning if no "return" in function?

2008-09-04 Thread Wojtek Walczak
On Thu, 04 Sep 2008 12:05:45 +0200, Poster28 wrote:
> What would you suggest to check python programs for non-syntax error.
> One example I could think of that one might forget to "return" a value from
> a function.
>
> How could I check for these and maybe other mistakes?

Check pychecker or figleaf:
http://pychecker.sourceforge.net
http://darcs.idyll.org/~t/projects/figleaf/doc/

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: overwrite set behavior

2008-09-04 Thread Wojtek Walczak
On Thu, 4 Sep 2008 12:06:14 +0200, Marco Bizzarri wrote:

>> As far as I understand you, you need descriptors:
>> http://users.rcn.com/python/download/Descriptor.htm

> I know descriptors a litte, Wojtek, but didn't use them often; can you
> elaborate a little more on your idea?

Marco, I think that I misunderstood the OP, but I was thinking
about immutable (or set-once) attributes. Something like this:

---
class SetOnce(object):
   def __init__(self):
  self._attr1 = ""
  self._attr1flag = False

   def setatt(self, x):
  if self._attr1flag:
 raise ValueError("attribute already set")
  self._attr1flag = True
  self._attr1 = x

   def getatt(self):
  return self._attr1

   attr1 = property(getatt, setatt)

a = SetOnce()
a.attr1 = 1
print a.attr1
try:
   a.attr1 = 2
except ValueError:
   print a.attr1
---

$ python immutattr.py
1
1
$

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >