Re: Weird local variables behaviors

2008-06-21 Thread Sebastjan Trepca
I see, intuitively one would think it would try to get it from global
context as it's not yet bound in the local.

Thanks for the explanation.

Sebastjan


On Sat, Jun 21, 2008 at 5:48 AM, Dan Bishop [EMAIL PROTECTED] wrote:
 On Jun 20, 7:32 pm, Matt Nordhoff [EMAIL PROTECTED] wrote:
 Sebastjan Trepca wrote:
  Hey,

  can someone please explain this behavior:

  The code:

  def test1(value=1):
  def inner():
  print value
  inner()

  def test2(value=2):
  def inner():
  value = value
  inner()

  test1()
  test2()

  [EMAIL PROTECTED] ~/dev/tests]$ python locals.py
  1
  Traceback (most recent call last):
File locals.py, line 13, in module
  test2()
File locals.py, line 10, in test2
  inner()
File locals.py, line 9, in inner
  value = value
  UnboundLocalError: local variable 'value' referenced before assignment

  Why can't he find the variable in the second case?

  Thanks, Sebastjan

 Python doesn't like when you read a variable that exists in an outer
 scope, then try to assign to it in this scope.

 (When you do a = b, b is processed first. In this case, Python
 doesn't find a value variable in this scope, so it checks the outer
 scope, and does find it. But then when it gets to the a =  part...
 well, I don't know, but it doesn't like it.)

 In a language like C++, the scope of a variable is determined by the
 declaration.

 int x; // A
 class Example
 {
   int x; // B
   void f()
   {
  int x; // C
  x = 42; // Which x?
   }
 };

 The x referred to in the statement x = 42; refers to local
 variable of Example::f.  If line C were removed, then it would refer
 to the member variable of class Example.  And if line B were removed,
 then it would refer to the global variable.

 In Python, however, there are no declarations.  Therefore, it requires
 another approach.  What it chose was:

 (1) Explicit self for object attributes.
 (2) A function's local variables are defined as those appearing on the
 left side of an assignment.  Whether the name happens to refer to a
 global is NOT considered.
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Weird local variables behaviors

2008-06-20 Thread Sebastjan Trepca
Hey,

can someone please explain this behavior:

The code:

def test1(value=1):
def inner():
print value
inner()


def test2(value=2):
def inner():
value = value
inner()

test1()
test2()

[EMAIL PROTECTED] ~/dev/tests]$ python locals.py
1
Traceback (most recent call last):
  File locals.py, line 13, in module
test2()
  File locals.py, line 10, in test2
inner()
  File locals.py, line 9, in inner
value = value
UnboundLocalError: local variable 'value' referenced before assignment

Why can't he find the variable in the second case?


Thanks, Sebastjan
--
http://mail.python.org/mailman/listinfo/python-list


Slovenian Python User Group

2006-05-13 Thread Sebastjan Trepca
Hi!

just wanted to send a notice about a new portal/group for Slovenian
Python fans here :)

http://soup.zen.si (btw, it's in slovene lang)

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


Egg with option to install extra packages

2006-04-19 Thread Sebastjan Trepca
Hi,

I'm trying to distribute my application which also support some extra
libraries but does not require them to run. I set the extra option
but I don't know how could I specify that I want to install my
application with any of that extra packages.

So now I have in my setup.py like this:

  extras_require={
'postgresql': ['psycopg2'],
'mysql': ['MySQLdb'],
'odbc': ['pyodbc'],
'mssql': ['pymssql'],
},

Could I now specify an extra package when installing?

ie. easy_install my_egg.egg --extra=postgresql,mysql,odbc


Thanks!

--
Sebastjan
http://www.trepca.si/blog
-- 
http://mail.python.org/mailman/listinfo/python-list


Distribution of Python apps

2006-04-05 Thread Sebastjan Trepca
Hi,I was wondering if there is anything similar to py2exe for OS X and Linux distributions so that I wouldn't have to pre-install Python and required modules for my application.Thanks.-- 
Sebastjanhttp://www.trepca.si/blog
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Very stupid question.

2006-03-30 Thread Sebastjan Trepca
Check os.stat() function here http://docs.python.org/lib/os-file-dir.html-- Sebastjanhttp://www.trepca.si/blog
On 30 Mar 2006 09:34:32 -0800, Sullivan WxPyQtKinter [EMAIL PROTECTED] wrote:
In addition, f=file('filename','r');len(f.read()) is quite expensive inmy point of view, If the file is serveral MB or larger.--http://mail.python.org/mailman/listinfo/python-list

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

Re: Very stupid question.

2006-03-30 Thread Sebastjan Trepca
On 3/30/06, Sullivan Zheng [EMAIL PROTECTED] wrote:
Wow, seems I am not that supid. Why python does not include this function in the file object. It is almost a tradition in other languages...

import os

os.stat(path).st_size

really not elegant or OO.True.-- Sebastjanhttp://www.trepca.si/blog
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: imap folder scanner

2006-03-25 Thread Sebastjan Trepca
senders is list, that is why that regex does not work. I don't like regexes that much so you can try this:parsed_senders = []sender = for item in senders: if isinstance(item,tuple):
 item= ''.join(item) if item==')': parsed_senders.append(sender[sender.find('From:')+5:].strip()) sender =  else: sender+=itemprint parsed_sendersSebastjan

On 3/25/06, Kun [EMAIL PROTECTED] wrote:

Marco Carvalho wrote: On 3/24/06, Sebastjan Trepca [EMAIL PROTECTED] wrote: 
m.select('myfolder') Some attention is required here to retrieve subfolders.
 Some imap servers like Cyrus and Courier uses INBOX.subfolder to access subfolders. -- Marco Carvalho (macs) | marcoacarvalho(a)gmail.com 

http://arrakis.no-ip.info| http://cdd.debian-br.org Maceio - Alagoas - Brazil Debian GNU/Linux unstable (Sid)
 GNU-PG ID:08D82127 - Linux Registered User #141545
 Notícias Semanais do Debian em Português: http://www.debian.org/News/weekly Alertas de Segurança Debian (DSA): 
http://www.debian.org/security
so i have used the following code and have successfully saved a list ofsenders as a string.however, the string has much more information thanjust the email address and i am wondering what is the best way to parse
the email address out of the entire string.sample string:  print status, sendersOK [('460 (BODY[HEADER.FIELDS (FROM)] {46}', 'From: Friend
[EMAIL PROTECTED]
\r\n\r\n'), ')', ('462 (BODY[HEADER.FIELDS (FROM)] {37}','From: Kun [EMAIL PROTECTED]\r\n\r\n'), ')']
how do i just get the two email addresses out of there?
my code is:from imaplib import *import getpassm = IMAP4()m.login('xx', 'xxx')m.select('Inbox')status, data = "" BIKES)')

assert status=='OK', Error. Message: %s%datadata = "" #you get your results in a list and search returns onlyone resultassert data,No results#cool, we have results, but IMAP's search command only returns IDs so we
have to fetch#msgs nowstatus,senders = m.fetch(data.replace(' ',','),'(BODY.PEEK[HEADER.FIELDS(FROM)])')assert status=='OK', Error. Message: %s%dataprint senders--

http://mail.python.org/mailman/listinfo/python-list-- Sebastjan
http://www.trepca.si/blog

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

Re: imap folder scanner

2006-03-24 Thread Sebastjan Trepca
A very simple example...

import imaplib
m = imap.IMAP4(myserver ip or host)
m.login(username,password)
m.select('myfolder')
status, data = m.search(None,'(SUBJECT BIKES)')
assert status=='OK', Error. Message: %s%data
data = data[0] #you get your results in a list and search returns only
one result
assert data,No results
#cool, we have results, but IMAP's search command only returns IDs so
we have to fetch
#msgs now
status,senders = m.fetch(data.replace('
',','),'(BODY.PEEK[HEADER.FIELDS (FROM)])')
assert status=='OK', Error. Message: %s%data

Now you just have to parse the senders data. There are many examples
about sending emails with python, like this one:

def send_notice():
import smtplib
msg = 'we got your mail, indeed'
from email.MIMEText import MIMEText
mail = MIMEText(msg, 'plain', 'utf-8')
mail['From'] =fro='[EMAIL PROTECTED]'
mail['Subject'] = Spam machine
mail['To'] = to = '[EMAIL PROTECTED]'
server = smtplib.SMTP('localhost')
errors = server.sendmail(fro, to, mail.as_string())
server.quit()

That other program should be very simple to make now.

Sebastjan

On 3/24/06, Kun [EMAIL PROTECTED] wrote:
 Hey guys, I would like to have a code in python (as simple as possible)
 to scan a specific folder in my mailbox and if the subject is equal to,
 say, 'BIKES', I would like to have the code automatically send the
 SENDER an email saying something like We have received your Email.
 Furthermore, I would also like to somehow save the sender's email into a
 list which would be compiled by another python program into an html file
 that would show a list of email addresses whose subject matched 'BIKE'

 I know i am asking for a lot but since i am new to python, can someone
 help me out with this? Whether its tips or code, i'll be very excited to
 hear your answer.  Thanks.
 --
 http://mail.python.org/mailman/listinfo/python-list

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


Re: What's The Best Editor for python

2006-03-24 Thread Sebastjan Trepca
http://www.pspad.com/en/It supports Python plugins! :)Sebastjanhttp://www.trepca.si/blog
On 24 Mar 2006 08:50:15 -0800, Fuzzyman [EMAIL PROTECTED] wrote:  PythonStudent wrote:  Hi,  Can one of you say to me what's the best editor for editing the python
  programs ( for linux or windows ), and if you can send it to me to the  adresse [EMAIL PROTECTED]   `SPE 
http://pythonide.stani.be`_  :-)  Fuzzyman http://www.voidspace.org.uk/python/index.shtml  
   Thanks  -- http://mail.python.org/mailman/listinfo/python-list
 
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Server applications - avoiding sleep

2006-03-15 Thread Sebastjan Trepca
You can create a Windows Service which will run as long as Windows are
up, well, except if you stop it.

You can find more info here: http://www.python.org/windows/win32/

Sebastjan

On 15 Mar 2006 05:26:45 -0800, rodmc [EMAIL PROTECTED] wrote:
 I have written a small server application (for Windows) which handles
 sending and receiving information from an instant messaging client and
 a database. This server needs to run 24/7, however it stops when the
 computer screen is locked.

 I assume there is a way to make it run in the background 24/7 but how
 do I go about doing this?

 At present the application runs from within a wxPython GUI, however
 this is only used to start and stop it. It could be entire faceless and
 the GUI only used to execute it.

 Best,

 rod

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

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


Re: File Permissions

2006-03-10 Thread Sebastjan Trepca
Those constants are in stat module so add import stat before the program.

On 10 Mar 2006 06:20:18 -0800, VJ [EMAIL PROTECTED] wrote:
 Hi All

 I need to get the user permission of a file using python. I was trying
 the following code which i found on google grups

  st = os.stat(myfile)
 mode = st[stat.ST_MODE]
 if mode  stat.ST_IREAD:
 print readable
 if mode  stat.ST_IWRITE:
 print writable
 if mode  stat.ST_IEXEC:
 print executable

 I am getting a error saying

  Traceback (most recent call last):
   File ./test.py, line 23, in ?
 if mode  stat.ST_IREAD:
 AttributeError: 'module' object has no attribute 'ST_IREAD' 

 any idea how to resolve this error ??

 Basically i want to write into a file .If the permissions are not there
 then print a error message.
 How do i achive this ???

 Thanks,
 VJ

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

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


Re: encoding problem

2006-03-03 Thread Sebastjan Trepca
I think you are trying to concatenate a unicode string with regular
one so when it tries to convert the regular string to unicode with
ASCII(default one) encoding it fails. First find out which of these
strings is regular and how it was encoded, then you can decode it like
this(if regular string is diff):

mailbody +=diff.decode('correct encoding')

Sebastjan

On 3/3/06, Yves Glodt [EMAIL PROTECTED] wrote:
 Hi list,


 Playing with the great pysvn I get this problem:


 Traceback (most recent call last):
File D:\avn\mail.py, line 80, in ?
  mailbody += diff
 UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position
 10710: ordinal not in range(128)



 It seems the pysvn.client.diff function returns bytes (as I read in
 the changelog of pysvn: http://svn.haxx.se/dev/archive-2005-10/0466.shtml)

 How can I convert this string so that I can contatenate it to my
 regular string?


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

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


Re: object's list index

2006-03-03 Thread Sebastjan Trepca
Um, what about:

for oindex in xrange(len(list)):
   object = list[oindex]
   print oindex

You can't create a generic function for this.

Sebastjan

On 3/3/06, William Meyer [EMAIL PROTECTED] wrote:
 hi,

 I need to get the index of an object in a list. I know that no two objects
 in the list are the same, but objects might evaluate as equal. for example

 list = [obj1, obj2, obj3, obj4, obj5]
 for object in list:
 objectIndex = list.index(object)
 print objectIndex

 prints 0, 1, 2, 3, 2 instead of 0, 1, 2, 3, 4 because obj3 == obj5. I could 
 loop
 through the list a second time comparing id()'s

 for object in list:
 objectIndex = 0
 for i in list:
 if id(object) == id(i):
 break
 objectIndex += 1
 print objectIndex

 but that seems like a real ugly pain. Somewhere, someplace python is keeping
 track of the current index in list, does anyone know how to access it? Or have
 any other suggestions?

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

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


Shared memory

2006-03-02 Thread Sebastjan Trepca
Hey!

Are there any live modules for working with shared memory in Python?
I found some but they are all dead(posh,shm)...

Thanks, Sebastjan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to create a unix shell account with Python?

2006-02-06 Thread Sebastjan Trepca
Ok, thanks :)


On 5 Feb 2006 13:01:23 -0800, [EMAIL PROTECTED]
[EMAIL PROTECTED] wrote:
 os.system(useradd ...)

 Its not pretty, but it gets it done.

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

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


How to create a unix shell account with Python?

2006-02-05 Thread Sebastjan Trepca
Hi!

I couldn't find anything on creating a new linux user account in
Python documentation.
Anyone has any experience with this? You just run useradd command in
shell or is there a more pythonic way?

Thanks, Sebastjan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dominant color PIL

2006-01-23 Thread Sebastjan Trepca
Hehe, interesting. I'll try it out.Thanks, SebastjanOn 1/23/06, Terry Hancock [EMAIL PROTECTED]
 wrote:On 23 Jan 2006 05:47:58 -0800Rinzwind 
[EMAIL PROTECTED] wrote: For example: getdata im.getdata() = sequence Returns the contents of an image as a sequence object containing pixel values. The sequence object is flattened,
 so that values for line one follow directly after the values of line zero, and so on. Note that the sequence object returned by this method is an internal PIL data type, which only supports certain
 sequence operations. To convert it to an ordinary sequence (e.g. for printing), use list(im.getdata()). So you could get them and count them in :) Don't know if you should do that on a 1600x1200 wallpaper
 tho :DI think he's thinking of how to get the values for themaster image. Terry Hancock wrote:  On Sun, 22 Jan 2006 21:07:45 +0100  Sebastjan Trepca 
[EMAIL PROTECTED] wrote:   I was wondering is it possible to find out which   colour is dominant in an image using PIL?   It would be very easy to create interesting mozaic
   images with that :)   Shrink it to one pixel, and get that pixel's value. ;-)   Seriously, that ought to do it.Bear in mind that you  need to use the right sampling mode (IIRC, you want
  ANTIALIAS).This is answering the OP's question which is how to getthe average color for a whole image:color = img.resize( (1,1), Image.ANTIALIAS).getpixel((0,0))You just shrink the image down. The ANTIALIAS filter
averages every pixel in the image (this occurs in the PILlibrary, so it's probably pretty fast), and then you fishthe single remaining pixel out into tuple format.--Terry Hancock (
[EMAIL PROTECTED])Anansi Spaceworks http://www.AnansiSpaceworks.com--http://mail.python.org/mailman/listinfo/python-list

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

Dominant color PIL

2006-01-22 Thread Sebastjan Trepca
Hi!I was wondering is it possible to find out which colour is dominant in an image using PIL? It would be very easy to create interesting mozaic images with that :)Thanks, Sebastjan
-- 
http://mail.python.org/mailman/listinfo/python-list

PIL and ImageMagick scalability

2005-12-26 Thread Sebastjan Trepca
Hi everyone!

I have a question about image processing. We have a website which will
process a lot of images a day.It will be running Apache(worker) with
mod_python. My question is what should we use for processing. If we
use PIL the processing will be done with the same process that handles
other requests and that will probably slow them down when there will
be a peak. If we use ImageMagick you create new process that does the
image processing which probably uses multiple CPUs better and is more
scalable, right?

Thanks, Sebastjan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python is incredible!

2005-12-12 Thread Sebastjan Trepca
Welcome to Python world :)


On 12 Dec 2005 03:44:13 -0800, Tolga [EMAIL PROTECTED] wrote:
 Hi everyone,

 I am using Common Lisp for a while and nowadays I've heard so much
 about Python that finally I've decided to give it a try becuase Python
 is not very far away from Lisp family.

 I cannot believe this! This snake is amazing, incredible and so
 beautiful! You, Pythonists, why didn't you tell me about this before?
 :-)

 Actually I loved Lisp and still don't want to throw it away beacuse of
 my interest of artificial intelligence, but using Python is not
 programming, it IS a fun! It is so friendly and soft and nice and
 blahblahblah

 I'll be here!!!

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

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


Dictionary string parser

2005-11-22 Thread Sebastjan Trepca
Hi,

is there any library or some way to parse dictionary string with list,
string and int objects into a real Python dictionary?

For example:

 my_dict = dict_parser({'test':'123','hehe':['hooray',1]})

I could use eval() but it's not very fast nor secure.

Thanks, Sebastjan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary string parser

2005-11-22 Thread Sebastjan Trepca
Wow, this helps a LOT! It's just what I needed, thank you very much! :)

Sebastjan

On 22/11/05, Fredrik Lundh [EMAIL PROTECTED] wrote:
 Sebastjan Trepca wrote:

  is there any library or some way to parse dictionary string with list,
  string and int objects into a real Python dictionary?
 
  For example:
 
   my_dict = dict_parser({'test':'123','hehe':['hooray',1]})
 
  I could use eval() but it's not very fast nor secure.

 it's definitely slower than eval (which is written in C, after all), but it's
 definitely more limited, and hopefully also more secure:

 import cStringIO
 import tokenize

 def _parse(token, src):
 if token[1] == {:
 out = {}
 token = src.next()
 while token[1] != }:
 key = _parse(token, src)
 token = src.next()
 if token[1] != ::
 raise SyntaxError(malformed dictionary)
 value = _parse(src.next(), src)
 out[key] = value
 token = src.next()
 if token[1] == ,:
 token = src.next()
 return out
 elif token[1] == [:
 out = []
 token = src.next()
 while token[1] != ]:
 out.append(_parse(token, src))
 token = src.next()
 if token[1] == ,:
 token = src.next()
 return out
 elif token[0] == tokenize.STRING:
 return token[1][1:-1].decode(string-escape)
 elif token[0] == tokenize.NUMBER:
 try:
 return int(token[1], 0)
 except ValueError:
 return float(token[1])
 else:
 raise SyntaxError(malformed expression)

 def myeval(source):
 src = cStringIO.StringIO(source).readline
 src = tokenize.generate_tokens(src)
 return _parse(src.next(), src)

 print myeval({'test':'123','hehe':['hooray',0x10]})
 {'test': '123', 'hehe': ['hooray', 16]}

 hope this helps!

 /F



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

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


Localized strftime()

2005-10-23 Thread Sebastjan Trepca
Hi!

I'm trying to get a localized date format from strftime() but it seems
that is doesn't have any parameters for that or any information about
this issue in Python docs.

For example I want to turn this:
19 Oct, 2005
to this(slovene language):
19 Okt, 2005

Thanks for help, Sebastjan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Localized strftime()

2005-10-23 Thread Sebastjan Trepca
Great, it works, thanks :)

On 23/10/05, Fredrik Lundh [EMAIL PROTECTED] wrote:
 Sebastjan Trepca wrote:

  I'm trying to get a localized date format from strftime() but it seems
  that is doesn't have any parameters for that or any information about
  this issue in Python docs.
 
  For example I want to turn this:
  19 Oct, 2005
  to this(slovene language):
  19 Okt, 2005

 you must call locale.setlocale first, to switch from the default C
 locale to a locale of your choice.

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

  import time
  print time.strftime(%a, %d %b %Y %H:%M:%S)
 Sun, 23 Oct 2005 20:38:56
  import locale
  locale.setlocale(locale.LC_TIME, sv_SE) # swedish
 'sv_SE'
  print time.strftime(%a, %d %b %Y %H:%M:%S)
 sön, 23 okt 2005 20:39:15
  locale.setlocale(locale.LC_TIME, sl_SI)
 'sl_SI'
  print time.strftime(%a, %d %b %Y %H:%M:%S)
 ned, 23 okt 2005 20:39:32

 /F





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


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