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: 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: 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: 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: 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: 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: urllib.urlopen fails in Emacs

2008-09-26 Thread Wojtek Walczak
On Fri, 26 Sep 2008 02:23:18 -0600, Iain Dalton wrote:
> In Emacs, using run-python,
>
> import urllib
> urllib.urlopen('http://www.google.com/')
>
> results in this traceback:
...
> IOError: [Errno socket error] (111, 'Connection refused')
>
> It works fine from the command line.  Why is this happening?

I can't answer your question, since I don't use emacs,
but it looks like emacs has some kind of built in firewall.

;-)

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


Re: how to replace and string in a "SELECT ... IN ()"

2008-09-26 Thread Wojtek Walczak
On Fri, 26 Sep 2008 02:32:50 -0700 (PDT), bcurtu wrote:

> I have a BIG problem with the next query:
>
> cursor.execute("""
> SELECT titem.object_id, titem.tag_id
> FROM tagging_taggeditem titem
> WHERE titem.object_id IN (%s)
> """,( eid_list))
 ^
It should rather be '%'.
HTH.

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


Re: setattr in class

2008-09-12 Thread Wojtek Walczak
On Fri, 12 Sep 2008 08:08:18 -0700 (PDT), Bojan Mihelac wrote:
> Hi all - when trying to set some dynamic attributes in class, for
> example:
>
> class A:
> for lang in ['1', '2']:
> exec('title_%s = lang' % lang) #this work but is ugly
> # setattr(A, "title_%s" % lang, lang) # this wont work

> I guess A class not yet exists in line 4. Is it possible to achive
> adding dynamic attributes without using exec?

Yes, it is:

-
class A:
   for i in (1, 2):
  locals()['xxx%d' % (i)] = i

print A.xxx1
print A.xxx2
a = A()
print a.xxx1
print a.xxx2
-

And the output is:

-
1
2
1
2
-

But I definitely don't consider this one as a good programming
practice.

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


Re: Better error message on recursive import

2008-09-12 Thread Wojtek Walczak
On Thu, 11 Sep 2008 12:43:34 +0200, Thomas Guettler wrote:

Hello,

> why does Python only raise ImportError if it fails caused by a recursive 
> import?
>
> I know what's wrong. But I guess many beginner don't know what's wrong.

I don't think that you're right here. I can't remember any beginner
asking such a question on p.c.py. I think they would come and ask
if it really was problematic.

And, anyway, I don't know how to answer your question :-)

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


Re: how dump a program which is running in memory

2008-09-11 Thread Wojtek Walczak
On Thu, 11 Sep 2008 02:31:23 -0700 (PDT), ruqiang826 wrote:

> I have written a service running backgroud to do something in linux.
> unfortunately$B!$(BI deleted the source code by mistake, and I can still
> see the process running background using "ps aux" :
>
> username   13820  0.0  0.0 60368 2964 ?SAug20   0:33
> python ./UpdateJobStatus.py
>
>
> I wonder if there is some way to dump the programme
> "UpdateJobStatus.py" and get the source code back?

The best way to do it would be to undelete the file,
just as Gerhard suggested.

If you remember any line (or piece) of code from the UpdateJobStatus.py
file you can try to dump the /dev/mem to the hard disk, and then grep
through it (remember that you need root priviledges to access /dev/mem).

I tried it with this code:

http://www.mail-archive.com/[EMAIL PROTECTED]/msg03696.html

with a small modification of this line:
nvram = (strtol(argv[1], 0, 0)) << 16;
changed to:
nvram = (strtol(argv[1], 0, 0));

After compilation I just did:
./a.out 0x0 0x > memdump
to get the memory dump.

I am not a memory expert, but 0x should be enough
for <= 4GB of RAM. If you got more, increase it.

And to make it clear: I do not recommend this way of sorting
things out :)

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


Re: removing text string

2008-09-10 Thread Wojtek Walczak
On Wed, 10 Sep 2008 11:22:16 -0400, Ahmed, Shakir wrote:
> I need to remove text string from the list of the numbers mentioned
> below:
>
> 080829-7_A
> 070529-5_c
> 080824-7_O
> 070405_6_p
>
> The output will be : 080829-7
>  070529-5
>080824-7
>  070405-6

You need to read about slice indices. An example:

>>> a=('080829-7_A', '070529-5_c', '080824-7_O')
>>> [i[:-2] for i in a]
['080829-7', '070529-5', '080824-7']


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


Re: Reading binary data

2008-09-10 Thread Wojtek Walczak
On Wed, 10 Sep 2008 10:43:31 -0700 (PDT), Aaron Scott wrote:
>> signature, version, attr_count = struct.unpack('3cII',
>> yourfile.read(11))
>>
>
> This line is giving me an error:
>
> Traceback (most recent call last):
>   File "test.py", line 19, in 
> signature, version, attr_count = struct.unpack('3cII',
> file.read(12))
> ValueError: too many values to unpack

Do:
print struct.unpack('3cII', yourfile.read(11))
instead of:
signature, version, attr_count = struct.unpack('3cII', yourfile.read(11))
to check what does struct.unpack return.

I guess it returns more than three elements. Just like below:

>>> a,b,c=(1,2,3,4)
Traceback (most recent call last):
  File "", line 1, in ?
ValueError: too many values to unpack

As you can see the fourth element from the tuple has no place to go.
Same thing happens in your code.

HTH.

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


Re: md5 differences

2008-09-10 Thread Wojtek Walczak
On Wed, 10 Sep 2008 12:39:24 -0500, Grant Edwards wrote:

>> The strange thing is that 
>>>>> md5.new("/Volumes/data/Arno/test.txt").hexdigest()
>> returns '8dd66a1592e2a8c3ab160822fb237f4d' on my machine.
>
> Same here.

I guess it will be the same for vast majority of us ;-)
The question is why is it '90364ed45b452d43378629c20543a81d'
for the OP? :-)

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


Re: md5 differences

2008-09-10 Thread Wojtek Walczak
On Wed, 10 Sep 2008 19:12:28 +0200, Python wrote:
> [EMAIL PROTECTED]:~% echo "test" > test.txt
>
> [EMAIL PROTECTED]:~% md5 test.txt
> MD5 (test.txt) = d8e8fca2dc0f896fd7cb4cb0031ba249

> >>> import md5
> >>> md5.new("/Volumes/data/Arno/test.txt").hexdigest()
> '90364ed45b452d43378629c20543a81d'


Works for me:

>>> import md5
>>> f = open('test.txt').read()
>>> md5.new(f).hexdigest()
'd8e8fca2dc0f896fd7cb4cb0031ba249'
>>>

IOW, don't pass the path to the file to md5.new, but the contents
of this file.

The strange thing is that 
>>> md5.new("/Volumes/data/Arno/test.txt").hexdigest()
returns '8dd66a1592e2a8c3ab160822fb237f4d' on my machine.

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


Re: dict slice in python (translating perl to python)

2008-09-10 Thread Wojtek Walczak
On Wed, 10 Sep 2008 08:28:43 -0700 (PDT), hofer wrote:
> Hi,
>
> Let's take following perl code snippet:
>
> %myhash=( one  => 1, two   => 2, three => 3 );
> ($v1,$v2,$v3) = @myhash{qw(one two two)}; # <-- line of interest
> print "$v1\n$v2\n$v2\n";

What about:

>>> myhash={'one':1, 'two':2, 'three':3}
>>> map(myhash.get, ['one', 'two', 'two'])
[1, 2, 2]
>>>

or, to make it more similar to perl's qw() thing:

>>> map(myhash.get, 'one two two'.split())
[1, 2, 2]
>>>

...but I think that using explicit list is more pythonic.
Isn't it? ;)

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


Re: Cathing several potential errors?

2008-09-06 Thread Wojtek Walczak
On Sat, 6 Sep 2008 15:13:45 -0700 (PDT), cnb wrote:
> if i do
> try:
> something
> except TypeError, IndexError:
> pass

Parenthesize them:

except (TypeError, IndexError):

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


Re: String/Number Conversion

2008-09-06 Thread Wojtek Walczak
On Sat, 06 Sep 2008 23:04:14 +0200, Andreas Hofmann wrote:

Hi,

> I've got a little problem here, which which really creeps me out at the 
> moment.
> I've got some strings, which only contain numbers plus eventually one 
> character as si-postfix (k for kilo, m for mega, g for giga). I'm trying 
> to convert those strings to integers, with this function:

>  if mult is 1:
   ^^
You're testing for identity, not for equality.
Change it to "if mult == 1". Is it alright now?


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


Re: max(), sum(), next()

2008-09-04 Thread Wojtek Walczak
On Thu, 4 Sep 2008 10:57:35 -0700 (PDT), Mensanator wrote:

> Why then, doesn't
>
>>>> sum([A for A in [None, None, None, None, None, None] if A != None])
> 0
>
> give me an error?

Because "[A for A in [None, None, None, None, None, None] if A != None]"
returns an empty list, and sum([]) doesn't return an error. What did you
expect?


-- 
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


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, 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: Python one-liner??

2008-08-22 Thread Wojtek Walczak
-c?
--
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: 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: 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: 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: 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: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: '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: 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: 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: 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: [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: 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: 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-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: 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: 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: 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: 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: 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 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: 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 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: 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: 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: 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: 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: 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-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-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 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 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: 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: 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 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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: 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