[issue18244] singledispatch: When virtual-inheriting ABCs at distinct points in MRO, composed MRO is dependent on haystack ordering

2013-06-30 Thread Gabriel Genellina

Changes by Gabriel Genellina ggenell...@gmail.com:


--
nosy: +ggenellina

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue18244
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue18318] Idle: stop depending on console output

2013-06-30 Thread Gabriel Genellina

Changes by Gabriel Genellina ggenell...@gmail.com:


--
nosy: +ggenellina

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue18318
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue13582] IDLE and pythonw.exe stderr problem

2013-06-30 Thread Gabriel Genellina

Changes by Gabriel Genellina ggenell...@gmail.com:


--
nosy: +ggenellina

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue13582
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: When I use Python under Windows. I found some file handles are not closed,

2011-11-01 Thread Gabriel Genellina
En Mon, 31 Oct 2011 12:57:15 -0300, 罗勇刚(Yonggang Luo)   
luoyonggang-re5jqeeqqe8avxtiumw...@public.gmane.org escribió:


How did detecting where those handlers are created to tracing it and  
close

it.
Mainly because I was using C binding library(subvertpy) and file is not
closed.


A better place to ask is python-list@python.org

Please include the Python version you're using. Also, a small, complete,  
runnable code example showing the problem would be very valuable. Usually,  
in building such example, you may well find out where your problem is.


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


Re: Fast recursive generators?

2011-10-28 Thread Gabriel Genellina
En Fri, 28 Oct 2011 15:10:14 -0300, Michael McGlothlin  
micha...@plumbersstock.com escribió:



I'm trying to generate a list of values where each value is dependent
on the previous value in the list and this bit of code needs to be
repeatedly so I'd like it to be fast. It doesn't seem that
comprehensions will work as each pass needs to take the result of the
previous pass as it's argument. map() doesn't seem likely. filter() or
reduce() seem workable but not very clean. Is there a good way to do
this? About the best I can get is this:

l = [ func ( start ) ]
f = lambda a: func ( l[-1] ) or a
filter ( f, range ( big_number, -1, -1 ) )


I guess I'm looking for something more like:

l = do ( lambda a: func ( a ), big_number, start )


What about a generator function?

def my_generator():
  prev = 1
  yield prev
  while True:
this = 2*prev
yield this
prev = this

print list(itertools.islice(my_generator(), 10))

--
Gabriel Genellina

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


Re: why msvcrt.printf show the first char only?

2011-10-15 Thread Gabriel Genellina
On 12 oct, 08:50, Nobody nob...@nowhere.com wrote:
 On Wed, 12 Oct 2011 04:18:25 -0700, install...@189.cn wrote:
  from ctypes import *
  msvcrt = cdll.msvcrt
  message_string = Hello world!\n
  print(msvcrt.printf(Testing: %s, message_string))

  when running in eclipse, the result is:
  1
  T

  when running in IDLE, then result is:
  1

  why is that?

 Odd. I get 22 when running from IDLE.

 Also, when using the console, it actually prints the text. I suspect that
 stdout gets block-buffered when using an IDE. I can't see any way to get a
 reference to stdout, so you can't fflush() it.

Launch IDLE from the command line and you'll see the text output.

To the OP: I bet your Eclipse runs Python 2.x and IDLE is 3.x.

In Python 3.x, Test... is a Unicode string, internally represented
using two bytes per character. (In contrast, in Python 2.x, Test...
is a byte string, and uTest... is unicode). All ASCII characters
have a 0 as their second byte in its internal representation. printf
expects a byte string, and stops as soon as it sees the '\0' following
the 'T' in 'Testing'. Either use wprintf(Testing...), or encode the
Unicode object into a byte string before calling:
printf(Testingencode(sys.stdout.encoding)), or tell ctypes about
the right parameter type:

printf = msvcrt.printf
printf.argtypes = [c_char_p]
printf(Testing\n)

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


Re: database connection

2011-10-07 Thread Gabriel Genellina
En Fri, 07 Oct 2011 02:18:04 -0300, masood shaik masood@gmail.com  
escribió:



 can u please tell me how we can connect to database without changing
the permission of db file using sqlite3


The OS user who executes the Python script must have read (and write,  
usually) access to the database file - *any* OS user who can read the  
database file can connect to it.


sqlite does not have internal users, and does not implement GRANT/REVOKE  
statements.


--
Gabriel Genellina

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


Re: How to inspect slot wrappers arguments in Python?

2011-10-07 Thread Gabriel Genellina
En Sat, 01 Oct 2011 12:13:45 -0300, julian bilcke  
julian.bil...@gmail.com escribió:


I would like to get the list of parameters I need to initialize an AST  
node.


I'm trying to use the `inspect` module, however it seems I can't use it  
on a

built-in (native?) class, or else I misunderstood. [...]

 import inspect
 import ast
 inspect.getargspec(ast.If.__init__)
Traceback (most recent call last):
  File stdin, line 1, in module
  File
/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py,
line 813, in getargspec
raise TypeError('{!r} is not a Python function'.format(func))
TypeError: slot wrapper '__init__' of '_ast.AST' objects is not a
Python function

I am wondering if there is another way to get these parameters
automatically? (ie. without compiling myself a dict)


I'm afraid there is no way; this kind of introspection does not work for  
functions written in C. The function itself usually has a generic  
signature resembling (*args, **kw), and its parameters are usually  
unpacked calling a suitable variant of PyArg_ParseXXX. The information  
about the number and type of expected arguments is encoded in its 'format'  
parameter, and is not stored anywhere.


--
Gabriel Genellina

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


Re: sending ftp file list to mail???

2011-10-07 Thread Gabriel Genellina
En Fri, 07 Oct 2011 03:23:57 -0300, selahattin ay selahattin...@msn.com  
escribió:


hi all. I want to get my ftp list and send the list to my mail adress...  
my codes are


And your problem is...?

--
Gabriel Genellina

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


Re: sending ftp file list to mail???

2011-10-07 Thread Gabriel Genellina
En Fri, 07 Oct 2011 03:23:57 -0300, selahattin ay selahattin...@msn.com  
escribió:


hi all. I want to get my ftp list and send the list to my mail adress...  
my codes are



baglanti = FTP(ftp.guncelyorum.org)
baglanti.login(**, ***)
print baglanti.dir()
posta = MIMEMultipart()
def posta_olustur():
posta['Subject']=konu
posta['From']=gmail_kullanici
posta['To']=kime
posta.attach(MIMEText(baglanti.retrlines(LIST)))  -- what  
can I do for here


Ah, I didn't notice that part.
MIMEText expects a string. retrlines, by default, outputs to stdout, isn't  
very useful. Try this:


def posta_olustur():
  ...
  lines = []
  baglanti.retrlines(LIST, lines.append)
  text = '\n'.join(lines)
  posta.attach(MIMEText(text))



--
Gabriel Genellina

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


Re: socket.getsockname is returning junk!!

2011-10-07 Thread Gabriel Genellina
En Wed, 05 Oct 2011 08:56:08 -0300, Wong Wah Meng-R32813  
r32...@freescale.com escribió:


I am migrating my application from python 1.5.2 to 2.7.1. One of the  
existing code breaks. The getsockname method from socket object somehow  
returns me with some number which I deem as junk, rather than the  
listening port as I would have expected in the older python. Has anyone  
seen the same thing or is it due to my python is built with some  
corrupted library or something?



$ python
Python 2.7.1 (r271:86832, Oct  5 2011, 18:34:15) [C] on hp-ux11
Type help, copyright, credits or license for more information.

import socket
sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
sock.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 )
sock.setsockopt( socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1 )
sock.setsockopt( socket.IPPROTO_TCP, 1, 1 )
server_address=('zmy02hp3', 1)
sock.bind(server_address)
sock.getsockname()

(0, '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')

In python 1.5.2

server_address=('zmy02aix04', 1)
sock.bind(server_address)
sock.getsockname()

('10.228.51.41', 1)


I'd say it's a problem with the _socket module; did the unit tests flag  
anything when you built Python?


On Windows, Python 2.7.1:


server_address=('lepton', 1)
sock.bind(server_address)
sock.getsockname()

('127.0.0.1', 1)

--
Gabriel Genellina

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


Re: Deleting files on a shared server

2011-10-07 Thread Gabriel Genellina
En Fri, 07 Oct 2011 04:45:32 -0300, Tim Golden m...@timgolden.me.uk  
escribió:

On 07/10/2011 02:14, Josh English wrote:



To delete the files, I am using os.unlink.

One lock file refuses to disappear, even though I have code at both
application startup and shutdown (on the OnInit and OnExit methods to
the wxPython Application object) that hunts down .lock files and
deletes them.


Assuming that your code paths succeed and that the unlink actually
happens, it is possible for files to continue to exist after they
have been successfully deleted. This happens if another process
has opened them with share-delete mode; typically this will be
a virus checker or a process like the TortoiseSVN cache (or its
counterparts for other VCS). The file won't actually disappear
until the last handle on it is released.


In such cases the openfiles command [1] is very useful for detecting who  
is holding the file open.


[1]  
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/openfiles.mspx


--
Gabriel Genellina

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


Re: BaseHTTPServer ThreadMixIn not working

2011-10-05 Thread Gabriel Genellina

En Mon, 03 Oct 2011 12:03:18 -0300, amit wilson.a...@gmail.com escribió:


I am really stuck in a very simple problem and wanted to know if you
could take some time to check it out -

My code is simple. Using BaseHTTPServer and ThreadInMix I want to run
a python script (Script1.py) for every request made simultaneously.
[...]

If I open multiple tabs/pages in Chrome/Firefox/IE and give URL:
http://localhost:8080, the pages wait for previous page? This does not
imply threading? Any help? Thanks


Your code is fine, and Python behaves correctly. The browser is queuing  
all similar requests when it sees they all refer to the same URI. Had the  
first response contained an Expires: header in the future, there would be  
no need to ask again for the same object; the ETag: and Last-Modified:  
headers may play a role too. So, only after the first response is  
completely read, Chrome/Firefox/IE sees it is invalid and knows she cannot  
re-use the received body and has to issue the second request and waits  
again and ...


Try with different URLs for each request:
http://localhost:8080/a
http://localhost:8080/b
http://localhost:8080/c
and you'll see they all are processed in parallel.


--
Gabriel Genellina

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


Re: Is exec() also not used in python 2.7.1 anymore?

2011-10-05 Thread Gabriel Genellina
En Tue, 04 Oct 2011 07:32:41 -0300, Wong Wah Meng-R32813  
r32...@freescale.com escribió:


Haha... yeah I reviewed the code, it is supposed to exposed some remote  
methods locally (RMI proxy usage). However, I am not sure why what it  
does is merely a pass.


I commented out this code and haven't seen any negative implication. I  
will look into this again if I am convinced the next error I see is due  
to I commented out this code.



  exec('def %s(self, *args, **kw): pass'%methodStrName)


In case you convince yourself that defining this dynamic but empty  
function is really needed, you can avoid exec this way:


  def some_function(...)

...
# instead of exec('def ...' % methodStrName)
def empty_function(self, *args, **kw): pass
empty_function.func_name = methodStrName
...
# presumably methodStrName is referred somehow in
# the remaining code block, or perhaps locals();
# modify accordingly


--
Gabriel Genellina

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


Re: Change import order with *.pth files

2011-10-03 Thread Gabriel Genellina
En Sun, 02 Oct 2011 18:29:24 -0300, Andrea Gavana  
andrea.gav...@gmail.com escribió:



Let's say I am using a package called blah, and this package is already
installed on site-packages (and I need it to be there) with a name
blah-1.2-win. In the site-packages folder, there is a pth file called
blah.pth which contains this line:

blah-1.2-win

To redirect Python to the correct folder when I type import blah.  
Anyway,

now I am developing another version of this package and it's called
blah-2.0-win, and it sits on my computer into a different folder (not  
on

site-packages, on an entire different drive in reality). How can I tell
Python *not* to use the version inside site-packages but to use the other
one in my development folder (without touching the pth file in
site-packages, of course)?


From Python 2.6 on, there is a per user site-packages directory, which is  
searched before the global one. See:


http://docs.python.org/whatsnew/2.6.html#pep-370-per-user-site-packages-directory

You could put your developing version on that directory.

In Python 2.5 and earlier, if you have to PREPEND a directory to sys.path,  
you may set the PYTHONPATH environment variable, or edit the site.py  
standard module. This may be fine in your development environment, but I  
would never do that in production.


--
Gabriel Genellina

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


Re: syntactic sugar for def?

2011-09-28 Thread Gabriel Genellina
En Wed, 28 Sep 2011 18:51:00 -0300, Chris Kaynor  
ckay...@zindagigames.com escribió:


On Wed, Sep 28, 2011 at 2:37 PM, Arnaud Delobelle arno...@gmail.com  
wrote:

On 28 September 2011 22:26, Ethan Furman et...@stoneleaf.us wrote:

I remember that 'class' is sugar for type().

I don't remember if 'def' is sugar for something besides lambda.

Any clues for me?  Heck, I'll even be grateful for outright answers!


It's not really sugar.  But I think you mean something like this:



class A: pass

...

type(A)

class 'type'

type is type(A)

True

So the closest you get for functions will be:


def f(): pass

...

type(f)

class 'function'

Try help(type(f)) to see how to use it to create a function object.
The problem is that you need to provide a code object, and the easiest
way to create a code object is to use a def statement :)


I would say compile isn't too much harder to use:

c = compile('a = 123', 'test', 'exec')
d = {}
f = types.FunctionType(c, d, 'test')
f()
print d

{'a': 123}

Although it appears you get all of the variables defined as global
apparently (try f = types.FunctionType(c, globals(), 'test')
instead).


I know no way of compiling a function body alone. Suppose you have this  
function:


def foo(x):
  print x
  y = 2*x
  return y

py compile(  print x\n  y = 2*x\n  return y, string, exec)
Traceback (most recent call last):
  File stdin, line 1, in module
  File string, line 1
print x
^
IndentationError: unexpected indent
py compile(print x\ny = 2*x\nreturn y, string, exec)
Traceback (most recent call last):
  File stdin, line 1, in module
  File string, line 3
SyntaxError: 'return' outside function

If you include the 'def' statement in the source string, the resulting  
code object does not represent the function itself, but a module  
defining it:


py f = FunctionType(compile(def foo(x):\n print x\n y = 2*x\n return  
y\n,

...   string, exec), globals(), foo)
py f(3)
Traceback (most recent call last):
  File stdin, line 1, in module
TypeError: module() takes no arguments (1 given)
py dis.dis(f)
  1   0 LOAD_CONST   0 (code object foo at 00C0FAD0,  
file string, line 1)

  3 MAKE_FUNCTION0
  6 STORE_NAME   0 (foo)
  9 LOAD_CONST   1 (None)
 12 RETURN_VALUE

To get at the actual function code, one should use  
f.func_code.co_consts[0]; this would be the 'code' parameter for  
types.FunctionType. Very complicated, really; nothing can beat the 'def'  
statement for defining a function ;)


--
Gabriel Genellina

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


Re: Installing Python 2.6.7 on Windows

2011-09-28 Thread Gabriel Genellina

En Wed, 28 Sep 2011 21:10:38 -0300, Nobody nob...@nowhere.com escribió:


On Wed, 28 Sep 2011 15:21:25 -0700, Ned Deily wrote:


No, it was a deliberate decision.  After a release is in security-fix
mode only, we don't build Windows or Mac OS X installers for them.


But you continue to offer the installers for the unfixed version.


As well as all the previous ones back to Python 1.x

I can think of several alternatives:

* Upgrade to Python 2.7, the current stable and maintained release.

* Compile Python 2.6.7 yourself. For the 32 bits version, you may use  
Microsoft Visual C++ 2008 Express Edition (free/gratis); see  
PCbuild\readme.txt for details. Obtain the required dependencies using  
Tools\buildbot\external.bat. It compiles cleanly out of the box.


* Obtain the compiled binary somewhere else. Considering that 2.6.7 is  
just a security patch, I'm not sure if running a precompiled binary from  
untrusted sources is any better than sticking with the official, previous  
version. I've built the binaries, in case you're interested.


* Compare both source trees and look at their differences. Most of them  
are in Python modules that you can just drop over an existing 2.6.6  
install. Only two C modules have changed, and require rebuilding  
python26.dll:


 timemodule.c r87648: Issue #8013: Fixed time.asctime segfault when OS's  
asctime fails

 unicodedata.c http://bugs.python.org/issue10254

If you think you're not affected by these, just ignore 2.6.7 (or apply  
only the .py changes)


--
Gabriel Genellina

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


Re: Error 'module' object has no attribute _extension_registry when cPickle is imported from an installed Python 2.7.1

2011-09-27 Thread Gabriel Genellina
En Tue, 27 Sep 2011 06:08:54 -0300, Wong Wah Meng-R32813  
r32...@freescale.com escribió:



Hello all,

I encounter this issue whereby I am not able to load cPickle module into  
the python I newly built. There is no issue when I load it right from  
the folder where the python executable and libpython2.7.so is built.  
However, it gives me this error when I load the same module using the  
installed files (python and all its modules, shared library from default  
/use/local folder that contains bin, lib, include sub-folders) from  
make install command.


Does anyone know why? Here is the error:-

$ python
Python 2.7.1 (r271:86832, Sep 27 2011, 15:19:26) [C] on hp-ux11
Type help, copyright, credits or license for more information.

import cPickle

Traceback (most recent call last):
  File stdin, line 1, in module
AttributeError: 'module' object has no attribute '_extension_registry'


Looking at cPickle.c, it imports the copy_reg module and then looks for  
its _extension_registry attribute. Maybe your copy_reg.py is broken, or  
you have another copy_reg.py hiding the standard one.


--
Gabriel Genellina

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


PyCon Argentina 2011

2011-09-03 Thread Gabriel Genellina
PyCon Argentina 2011 - Conectando la Comunidad Python

PyAr, el grupo de usuarios de Python Argentina, está
orgulloso de presentar la Conferencia del lenguaje Python
2011 (PyCon) en la ciudad de Junín (Provincia de Buenos
Aires, Argentina) los días Viernes 23 y Sábado 24 de
Septiembre de 2011 en la Universidad Nacional del Noroeste
de la Provincia de Buenos Aires (UNNOBA).

Invitados Internacionales confirmados de PyConAr 2011:

* Steve Holden - ( Python Software Foundation )
* Jim Fulton ( Zope Corp. )
* Alan Runyan ( Plone  Enfold Systems )
* Maciej Fijałkowski ( PyPy )
* Wesley Chun ( Google )

La entrada es libre y gratuita, pero se requiere
registración previa. El cupo es limitado, falta menos de
un mes, ¡a apurarse!

Más información: http://ar.pycon.org/2011




-- 
Gabriel Genellina
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations/


Re: Handling 2.7 and 3.0 Versions of Dict

2011-09-02 Thread Gabriel Genellina
En Wed, 31 Aug 2011 22:28:09 -0300, Travis Parks jehugalea...@gmail.com  
escribió:



On Aug 31, 7:37 pm, Gregory Ewing greg.ew...@canterbury.ac.nz wrote:

Ian Kelly wrote:
 if sys.version_info  (3,):
 getDictValues = dict.itervalues
 else:
 getDictValues = dict.values

 (which is basically what the OP was doing in the first place).


My problem was that I didn't understand the scoping rules. It is still
strange to me that the getValues variable is still in scope outside
the if/else branches.


Those if/else are at global scope. An 'if' statement does not introduce a  
new scope; so getDictValues, despite being indented, is defined at  
global scope, and may be used anywhere in the module.


--
Gabriel Genellina

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


Re: Help required accessing dictionary

2011-09-02 Thread Gabriel Genellina

En Wed, 31 Aug 2011 22:46:54 -0300, mrinal...@edss.co.in escribió:


 I need to access the dictionary of the script that I am running through
 my vc++ application by embedding python.
 I am linking to python dynamically. I want to obtain the dictionary of
 the script and access the variables declared in the script.
 However, with the PyObject * that I get from the dictionary, I am not
 able to find the type of the object. The reason being that
 GetProcAddress to PyInt_Check returns a NULL. The same thing with
 PyFloat_Check and so on. I think this is because they are macros and  
 not

 exported functions.

 What can be done to be able to perform these checks without statically
 linking to the pyhon lib ?


Just include python.h
PyInt_Check is completely implemented as a macro, it doesn't call any  
function.


/* from intobject.h */
#define PyInt_Check(op) \
 PyType_FastSubclass((op)-ob_type, Py_TPFLAGS_INT_SUBCLASS)

/* from object.h */
#define PyType_FastSubclass(t,f)  PyType_HasFeature(t,f)
#define PyType_HasFeature(t,f)  (((t)-tp_flags  (f)) != 0)

--
Gabriel Genellina

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


Re: Invoking profile from command line prevent my sys.path modification

2011-09-02 Thread Gabriel Genellina
En Thu, 01 Sep 2011 07:51:43 -0300, Yaşar Arabacı yasar11...@gmail.com  
escribió:



I am new to profile module, so I am sorry if this is an absolute beginner
question. In order to my code to run, I need to add a directory to  
sys.path.
When I invole python -m profile myfile.py, my code won't work, saying  
that

the thing that is supposed to be in path, isn't. Code works fine without
profiling. Profiling works if I write it into the file, but I don't  
prefer

doing that, if that is possible.


You may set the PYTHONPATH environment variable, just for the profiling  
session.


http://docs.python.org/install/index.html#modifying-python-s-search-path

--
Gabriel Genellina

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


Re: Handling 2.7 and 3.0 Versions of Dict

2011-09-02 Thread Gabriel Genellina
En Fri, 02 Sep 2011 13:53:37 -0300, Travis Parks jehugalea...@gmail.com  
escribió:



On Sep 2, 12:36 pm, Gabriel Genellina gagsl-...@yahoo.com.ar
wrote:
En Wed, 31 Aug 2011 22:28:09 -0300, Travis Parks  
jehugalea...@gmail.com escribi :


 On Aug 31, 7:37 pm, Gregory Ewing greg.ew...@canterbury.ac.nz wrote:
 Ian Kelly wrote:
  if sys.version_info  (3,):
  getDictValues = dict.itervalues
  else:
  getDictValues = dict.values

  (which is basically what the OP was doing in the first place).

 My problem was that I didn't understand the scoping rules. It is still
 strange to me that the getValues variable is still in scope outside
 the if/else branches.

Those if/else are at global scope. An 'if' statement does not introduce  
a new scope; so getDictValues, despite being indented, is defined at  
global scope, and may be used anywhere in the module.


Does that mean the rules would be different inside a function?


Yes: a function body *does* create a new scope, as well as the class  
statement. See

http://docs.python.org/reference/executionmodel.html

--
Gabriel Genellina

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


Re: Calling Script from Command line not working

2011-09-01 Thread Gabriel Genellina
En Mon, 29 Aug 2011 07:40:06 -0300, Sathish S sath...@solitontech.com  
escribió:


We created a DLL using cygwin and have written a class based python  
module

for the same. We have created a sample script for the class based python
module, that creates an object of the class and calls various methods in  
the
class. This Test script works fine while I run it from IDLE. However  
when I
run it from command prompt it either hangs or just returns without  
executing

the functions. When it returns I do not get a error trace.

When I tried to findout where exactly the issue is happening. the issue
occurs when I try to call the *cygwin_dll_init* method of the  
cygwin1.dll .

This cygwin1.dll is actualy a dependency to the DLL we have built. So we
have to load this DLL and call this *cygwin_dll_init* method before  
loading

my DLL.


cyg = cdll.LoadLibrary(cygwin1.dll)
cyg.cygwin_dll_init() #hangs or returns here
mydll=cdll.LoadLibrary(my.dll)
mydll.func1()
I'm trying to understand what exactly is the difference, when we call it
IDLE and when we call it from command prompt using the python command. I
will have to get the script working from command prompt as well.


A few comments:

* why do you initialize cygwin1.dll in Python? If it's a dependency of  
my.dll, it might be better to load and initialize it there.


* for this function prototype: void cygwin_dll_init(void);
you should declare it using:

cyg = cdll.LoadLibrary(cygwin1.dll)
cyg.restype = None
cyg.cygwin_dll_init() #hangs or returns here
...

Anyway, I don't see why a console application would fail but not inside  
IDLE.


--
Gabriel Genellina

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


Re: Execute a method in a file in an egg

2011-08-24 Thread Gabriel Genellina

En Tue, 23 Aug 2011 13:14:06 -0300, RVince rvinc...@gmail.com escribió:


Is there a way to do this from the command line? Thanks.


Something like this?

python -c import the.module;the.module.someclass().method(arguments)

--
Gabriel Genellina

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


Re: from module import * using __import__?

2011-07-04 Thread Gabriel Genellina
En Sat, 02 Jul 2011 16:52:11 -0300, Dan Stromberg drsali...@gmail.com  
escribió:


Is there a decent way of running from variable import *?  Perhaps  
using

__import__?

Does it mean using the copy module or adding an element to globals()
somehow?

Yes, I think I do have a good use for this: importing either pure python  
or

cython versions of a module into a single namespace that can provide the
same interface (transparent to the caller), whether C extension modules  
are

viable in the current interpreter or not.  So you have a stub module that
provides one or the other, depending on availability and suitability.


See pickle.py in Python 3 as an example: the slow (pure Python) code  
resides in pickle.py; the fast (C code) in _pickle.so (on Windows, a  
built-in module). Near the end of pickle.py, there is a line from _pickle  
import * which, if successful, overrides (replaces) any previous  
definitions; if not, the ImportError is trapped and the previously defined  
Python code remains valid.


Unlike the 2.x series, where you should decide to import cPickle or  
import pickle (or attempt both, cathcing the ImportError), here you only  
have to import pickle in your code; if the fast module is present, it is  
automatically loaded and used; else, the slow but compatible version is  
used. You don't even have to know that an alternative implementation  
exists.


--
Gabriel Genellina

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


Re: search through this list's email archives

2011-06-24 Thread Gabriel Genellina
En Thu, 23 Jun 2011 13:11:32 -0300, Cathy James nambo...@gmail.com  
escribió:



I looked through this forum's archives, but I can't find a way to
search for a topic through the archive. Am I missing something?



Gmane provides a search capability also:
http://blog.gmane.org/gmane.comp.python.general

--
Gabriel Genellina

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


Re: search through this list's email archives

2011-06-24 Thread Gabriel Genellina
En Fri, 24 Jun 2011 11:33:23 -0300, Grant Edwards  
invalid@invalid.invalid escribió:



On 2011-06-24, Gabriel Genellina gagsl-...@yahoo.com.ar wrote:

En Thu, 23 Jun 2011 13:11:32 -0300, Cathy James nambo...@gmail.com
escribi?:


I looked through this forum's archives, but I can't find a way to
search for a topic through the archive. Am I missing something?



Gmane provides a search capability also:
http://blog.gmane.org/gmane.comp.python.general


FWIW, I've found the Gmane search feature to be very unreliable.  It
often overlooks a lot of matching articles for no apparent reason.


It seems no single provider is perfect. Google searching capability is  
quite good, but for some reason, many posts are missing, often the initial  
post head of a thread. The Python-URL summaries usually include a Google  
Groups url, but sometimes I have to link to Gmane, velocityreviews.com or  
even to the list archives at python.org because of that problem.


--
Gabriel Genellina

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


Re: Python 2.7.2 for Windows reports version as 2.7.0?

2011-06-22 Thread Gabriel Genellina

En Sun, 19 Jun 2011 12:35:38 -0300, pyt...@bdurham.com escribió:

The version info comes from the DLL - I wonder if the DLL being found  
is somehow old?


Make sure:

 import sys
 win32api.GetModuleFileName(sys.dllhandle)

Is the DLL you expect.


After uninstalling and reinstalling for the current user only (vs. all
users), Python now reports the correct version number.

And running your code above confirms that the proper DLL is being loaded
(c:\Python27\Python27.dll).

My original version of Python 2.7.0 was installed for all users and when
I ran the 2.7.2 MSI I chose to install for all users as well.

After running the 2.7.2 MSI, my Python exe's had the correct timestamps,
but I failed to check the python27.dll timestamp to see if this file was
out-of-date.

I wonder if changing my install method to current user forced the
installation of the updated python27.dll? And perhaps the default 2.7.2
installation in all users mode (when one is updating an existing 2.7
installation) doesn't update the Python27.dll under some conditions?


In a for all users install, python27.dll goes into c:\windows\system32,  
not c:\python27


Maybe you installed 2.7.0 twice, for all users and also for current  
user only, and both in the same directory (c:\python27). That could  
explain the old .dll in the install directory; the new one goes into  
system32, but the old one takes precedence.


--
Gabriel Genellina

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


Re: help on QUICKFIX

2011-06-10 Thread Gabriel Genellina
En Fri, 10 Jun 2011 04:13:05 -0300, prakash jp prakash.st...@gmail.com  
escribió:



I am using quickfix, would like to start with that

..\quickfix-1.13.3\quickfix\examples\executor\python\executor.py asks  
for a

configuration file how should it look like.


This one? http://www.quickfixengine.org/
I see a forum and a mailing list - I think you'll get more help there.

--
Gabriel Genellina

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


Re: Unsupported operand type(s) for +: 'float' and 'tuple'

2011-06-10 Thread Gabriel Genellina

En Fri, 10 Jun 2011 07:30:28 -0300, Francesc Segura frseg...@gmail.com
escribió:


Hello all, I'm new to this and I'm having problems on summing two
values at python.

I get the following error:

Traceback (most recent call last):
  File C:\edge-bc (2).py, line 168, in module
if (costGG = cost + T0):
TypeError: unsupported operand type(s) for +: 'float' and 'tuple'


I see Tim Chase already told you about this error. Let me make a few
comments about the rest.


try:
import matplotlib.pyplot as plt
except:
raise


I guess the above try/except was left from some earlier debugging attempt
- such an except clause is useless, just omit it.


T0 = 0.5
RO = 0.99


Perhaps those names make sense in your problem at hand, but usually I try
to use more meaningful ones. 0 and O look very similar in some fonts.


for i in range(len(edges)):
total = 0
cost = 0
factor = 1
   liedges = list(edges[i])
linode1 = list(liedges[0])
linode2 = list(liedges[1])


list(something) creates a new list out of the elements from `something`.
You're just iterating here, so there is no need to duplicate those lists.
In addition, Python is not C: the `for` statement iterates over a
collection, you don't have to iterate over the indices and dereference
each item:

for liedges in edges:
linode1 = liedges[0]
linode2 = liedges[1]



distance = (((linode2[0]-linode1[0])%N)^2)+(((linode2[1]-
linode1[1])%N)^2)


That doesn't evaluate what you think it does. ^ is the bitwise xor
operator, and I bet you want **, the power operator.



total = total + cost
return(total)


return is not a function but a statement; those () are unnecesary and
confusing.
And I think you want to initialize total=0 *before* entering the loop;
also, initializing cost and factor is unnecesary.


def costGeasy(G):
bc = NX.edge_betweenness_centrality(G,normalized=True)
total = 0
for i in range(len(bc)):
total=total+bc.values()[i]

return (total)


bc = NX.edge_betweenness_centrality(G,normalized=True)
values = bc.values()
total = sum(values)
return total

==

return sum(bc.values())



pos={}
for i in range(NODES):
pos[nod[i]]=(nod[i][0]/(N*1.0),nod[i][1]/(N*1.0))


In Python version 2.x, 1/3 evals to 0, but that's a mistake; it is fixed
in the 3.x version. If you put this line at the top of your script:
  from __future__ import division
then 1/3 returns 0....
When you actually want integer division, use //, like 1//3

So we can rewrite the above as:

  from __future__ import division
...
for node in nod:
pos[node] = (node[0] / N, node[1] / N)

Another way, not relying on true division:

divisor = float(N)
for node in nod:
pos[node] = (node[0] / divisor, node[1] / divisor)

or even:

pos = dict((node, (node[0] / divisor, node[1] / divisor)) for node in nod)



for y in range(NK):
for x in range(ITERATIONS):
cost = costG(G)
if (cost  (best_cost)):
best_graph = G
best_cost = cost
GG = G


Again, I think this doesn't do what you think it does. GG = G means let's
use the name GG for the object currently known as G. GG is not a copy
of G, just a different name for the very same object. Later operations
like GG.remove_edge(...) modify the object - and you'll see the changes in
G, and in best_graph, because those names all refer to the same object.
I think you'll benefit from reading this:
http://effbot.org/zone/python-objects.htm


a = random.randint(0,NODES-1)
b = random.randint(0,NODES-1)
adj=G.adjacency_list()
while ((nod[b] in adj[a]) or (b == a)):
a = random.randint(0,NODES-1)
b = random.randint(0,NODES-1)
GG.add_edge(nod[a],nod[b])


As above, I'd avoid using indexes, take two random nodes using
random.sample instead, and avoid adjacency_list():

while True:
a, b = random.sample(nod, 2)
if b not in G[a]:
  break
GG.add_edge(a, b)

(mmm, I'm unsure of the adjacency test, I've used networkx some time ago
but I don't have it available right now)

--
Gabriel Genellina

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


Re: Unsupported operand type(s) for +: 'float' and 'tuple'

2011-06-10 Thread Gabriel Genellina

En Fri, 10 Jun 2011 07:30:28 -0300, Francesc Segura frseg...@gmail.com
escribió:


Hello all, I'm new to this and I'm having problems on summing two
values at python.

I get the following error:

Traceback (most recent call last):
  File C:\edge-bc (2).py, line 168, in module
if (costGG = cost + T0):
TypeError: unsupported operand type(s) for +: 'float' and 'tuple'


I see Tim Chase already told you about this error. Let me make a few
comments about the rest.


try:
import matplotlib.pyplot as plt
except:
raise


I guess the above try/except was left from some earlier debugging attempt
- such an except clause is useless, just omit it.


T0 = 0.5
RO = 0.99


Perhaps those names make sense in your problem at hand, but usually I try
to use more meaningful ones. 0 and O look very similar in some fonts.


for i in range(len(edges)):
total = 0
cost = 0
factor = 1
   liedges = list(edges[i])
linode1 = list(liedges[0])
linode2 = list(liedges[1])


list(something) creates a new list out of the elements from `something`.
You're just iterating here, so there is no need to duplicate those lists.
In addition, Python is not C: the `for` statement iterates over a
collection, you don't have to iterate over the indices and dereference
each item:

for liedges in edges:
linode1 = liedges[0]
linode2 = liedges[1]



distance = (((linode2[0]-linode1[0])%N)^2)+(((linode2[1]-
linode1[1])%N)^2)


That doesn't evaluate what you think it does. ^ is the bitwise xor
operator, and I bet you want **, the power operator.



total = total + cost
return(total)


return is not a function but a statement; those () are unnecesary and
confusing.
And I think you want to initialize total=0 *before* entering the loop;
also, initializing cost and factor is unnecesary.


def costGeasy(G):
bc = NX.edge_betweenness_centrality(G,normalized=True)
total = 0
for i in range(len(bc)):
total=total+bc.values()[i]

return (total)


bc = NX.edge_betweenness_centrality(G,normalized=True)
values = bc.values()
total = sum(values)
return total

==

return sum(bc.values())



pos={}
for i in range(NODES):
pos[nod[i]]=(nod[i][0]/(N*1.0),nod[i][1]/(N*1.0))


In Python version 2.x, 1/3 evals to 0, but that's a mistake; it is fixed
in the 3.x version. If you put this line at the top of your script:
  from __future__ import division
then 1/3 returns 0....
When you actually want integer division, use //, like 1//3

So we can rewrite the above as:

  from __future__ import division
...
for node in nod:
pos[node] = (node[0] / N, node[1] / N)

Another way, not relying on true division:

divisor = float(N)
for node in nod:
pos[node] = (node[0] / divisor, node[1] / divisor)

or even:

pos = dict((node, (node[0] / divisor, node[1] / divisor)) for node in nod)



for y in range(NK):
for x in range(ITERATIONS):
cost = costG(G)
if (cost  (best_cost)):
best_graph = G
best_cost = cost
GG = G


Again, I think this doesn't do what you think it does. GG = G means let's
use the name GG for the object currently known as G. GG is not a copy
of G, just a different name for the very same object. Later operations
like GG.remove_edge(...) modify the object - and you'll see the changes in
G, and in best_graph, because those names all refer to the same object.
I think you'll benefit from reading this:
http://effbot.org/zone/python-objects.htm


a = random.randint(0,NODES-1)
b = random.randint(0,NODES-1)
adj=G.adjacency_list()
while ((nod[b] in adj[a]) or (b == a)):
a = random.randint(0,NODES-1)
b = random.randint(0,NODES-1)
GG.add_edge(nod[a],nod[b])


As above, I'd avoid using indexes, take two random nodes using
random.sample instead, and avoid adjacency_list():

while True:
a, b = random.sample(nod, 2)
if b not in G[a]:
  break
GG.add_edge(a, b)

(mmm, I'm unsure of the adjacency test, I've used networkx some time ago
but I don't have it available right now)

--
Gabriel Genellina

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


Re: Problems Compiling Python 2.6.7 for Win7

2011-06-08 Thread Gabriel Genellina
En Wed, 08 Jun 2011 12:28:56 -0300, Jay Osako josephos...@gmail.com  
escribió:



I have been trying to get PyODBC to work with Python 2.6 (the latest
version it is known to be compatible with) and Django, but have run
into a problem which, according to the information I've got elsewhere,
probably stems from a DLL incompatibility - apparently, [...]

The first of these problems is, of course, tracking down a copy of VC+
+ 2008 Express. While one would think that this would be the simplest
solution, Microsfot themselves no longer provide the installer for
this, and I'm not sure I'd trust most of the other sources claiming to
provide it.


Doesn't http://www.microsoft.com/express/Downloads/#2008-Visual-CPP work  
for you?
I didn't try past the initial download prompt, but it seems to be the  
right version.


--
Gabriel Genellina

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


Re: Print Window on IDLE

2011-06-07 Thread Gabriel Genellina
En Mon, 06 Jun 2011 14:48:26 -0300, Steve Oldner steven.old...@la.gov  
escribió:


Seems to work using 2.7 but not 3.2.  On 3.2 it just closes all my  
python sessions.  Is this a bug?  Can someone point me to a How To on  
using a local printer in windows?


It's a bug. Starting IDLE from the command line, one can actually see the  
error:



Exception in Tkinter callback
Traceback (most recent call last):
  File D:\apps\python32\lib\tkinter\__init__.py, line 1399, in __call__
return self.func(*args)
  File D:\apps\python32\lib\idlelib\IOBinding.py, line 453, in  
print_window

command = idleConf.GetOption('main','General','print-command-win')
  File D:\apps\python32\lib\idlelib\configHandler.py, line 245, in  
GetOption

type=type, raw=raw)
  File D:\apps\python32\lib\idlelib\configHandler.py, line 54, in Get
return self.get(section, option, raw=raw)
  File D:\apps\python32\lib\configparser.py, line 789, in get
d)
  File D:\apps\python32\lib\configparser.py, line 391, in before_get
self._interpolate_some(parser, option, L, value, section, defaults, 1)
  File D:\apps\python32\lib\configparser.py, line 440, in  
_interpolate_some

found: %r % (rest,))
configparser.InterpolationSyntaxError: '%' must be followed by '%' or '(',  
found

: '%s'

IDLE is attempting to read an entry from its configuration file, but fails  
because of a syntax error in the file (it's an error for a ConfigParser  
entry, %s should be %%s). The same entry was fine for earlier IDLE  
versions. As a workaround, you may edit the offending lines in your  
configuration file.



Go to the idlelib directory; if you don't know where it is, just open idle  
or Python command line and execute:


py import idlelib
py idlelib.__file__
'D:\\apps\\python32\\lib\\idlelib\\__init__.py'

In the same directory you'll find config-main.def; open it, and replace  
these lines in the [General] section:


print-command-posix=lpr %%s
print-command-win=start /min notepad /p %%s

(%s should become %%s). Tested on Windows, but Linux should have the same  
problem and temporary solution. You may need to roll this change back when  
the code is corrected.


Reported as http://bugs.python.org/issue12274


--
Gabriel Genellina

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


Re: sys.tracebacklimit not working in Python 3.2?

2011-06-07 Thread Gabriel Genellina
En Fri, 27 May 2011 17:38:50 -0300, Thorsten Kampe  
thors...@thorstenkampe.de escribió:



sys.tracebacklimit = 0

The 3.2 documentation says When set to 0 or less, all traceback
information is suppressed and only the exception type and value are
printed. Bug?


Yes; reported at http://bugs.python.org/issue12276

--
Gabriel Genellina

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


Re: Function call arguments in stack trace?

2011-06-07 Thread Gabriel Genellina
En Tue, 07 Jun 2011 15:09:54 -0300, Dun Peal dunpea...@gmail.com  
escribió:



In a stack trace, is it possible to somehow get the arguments with
which each function was called?

So for example, if function `foo` in module `bar` was called with
arguments `(1, [2])` when it raised an exception, then instead of:

Traceback (most recent call last):
  File bar.py, line 123, in foo
build_rpms()

The stack trace would read:

Traceback (most recent call last):
  File bar.py, line 123, in foo(1, [2])
build_rpms()

This would save a lot of debugging time!


The cgitb module does exactly that; some third-party modules offer similar  
functionality, but I don't remember any names.

Despite its name, cgitb works with any script.

Given this test script:

# begin test_traceback.py
import cgitb
cgitb.enable(format=text)

spam = []

def a(x, y):
  This is function a
  z = x+y
  return b(z)


def b(z, n=3):
  This is function b.

  Its docstring is longer.

  if n!=3:
just(to_consume_space)

  w = c(foo=z*n)

  return w


def c(foo=0, bar=1):
  This is function c
  baz = foo+bar
  spam.somenamethatdoesnotexist(foo+bar)
  anotherglobal(thatdoesnotexisteither)

a(10, 20)
# end test_traceback.py

the output is:


AttributeError
Python 3.2: d:\apps\Python32\python.exe
Tue Jun  7 23:36:36 2011

A problem occurred in a Python script.  Here is the sequence of
function calls leading up to the error, in the order they occurred.

 D:\TEMP\test_traceback.py in module()
   27   baz = foo+bar
   28   spam.somenamethatdoesnotexist(foo+bar)
   29   anotherglobal(thatdoesnotexisteither)
   30
   31 a(10, 20)
a = function a

 D:\TEMP\test_traceback.py in a(x=10, y=20)
7   This is function a
8   z = x+y
9   return b(z)
   10
   11
global b = function b
z = 30

 D:\TEMP\test_traceback.py in b(z=30, n=3)
   18 just(to_consume_space)
   19
   20   w = c(foo=z*n)
   21
   22   return w
w undefined
global c = function c
foo undefined
z = 30
n = 3

 D:\TEMP\test_traceback.py in c(foo=90, bar=1)
   26   This is function c
   27   baz = foo+bar
   28   spam.somenamethatdoesnotexist(foo+bar)
   29   anotherglobal(thatdoesnotexisteither)
   30
global spam = []
spam.somenamethatdoesnotexist undefined
foo = 90
bar = 1
AttributeError: 'list' object has no attribute 'somenamethatdoesnotexist'
   [... exception attributes ...]
   [... original traceback ...]

--
Gabriel Genellina

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


[issue12274] Print window menu on IDLE aborts whole application

2011-06-07 Thread Gabriel Genellina

New submission from Gabriel Genellina gagsl-...@yahoo.com.ar:

On Windows, IDLE closes all open windows and exits completely, without any 
error message, when selecting the Print window menu command.

Starting IDLE from inside a console, one can see the error message:

Exception in Tkinter callback
Traceback (most recent call last):
  File D:\apps\python32\lib\tkinter\__init__.py, line 1399, in __call__
return self.func(*args)
  File D:\apps\python32\lib\idlelib\IOBinding.py, line 453, in print_window
command = idleConf.GetOption('main','General','print-command-win')
  File D:\apps\python32\lib\idlelib\configHandler.py, line 245, in GetOption
type=type, raw=raw)
  File D:\apps\python32\lib\idlelib\configHandler.py, line 54, in Get
return self.get(section, option, raw=raw)
  File D:\apps\python32\lib\configparser.py, line 789, in get
d)
  File D:\apps\python32\lib\configparser.py, line 391, in before_get
self._interpolate_some(parser, option, L, value, section, defaults, 1)
  File D:\apps\python32\lib\configparser.py, line 440, in _interpolate_some
found: %r % (rest,))
configparser.InterpolationSyntaxError: '%' must be followed by '%' or '(', found
: '%s'


It is trying to read this entry from the config-main.def file:

[General]
print-command-posix=lpr %s
print-command-win=start /min notepad /p %s

For a ConfigParser file, those %s should be %%s instead. Previous IDLE versions 
(2.7 and 3.1) read the same entry without problem; I suspect they were using a 
RawConfigParser or processing the entry in a different way.

As a workaround, replacing %s with %%s in config-main.def is enough, until the 
code gets fixed.

--
components: IDLE
messages: 137789
nosy: gagenellina
priority: normal
severity: normal
status: open
title: Print window menu on IDLE aborts whole application
type: behavior
versions: Python 3.2

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue12274
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue12274] Print window menu on IDLE aborts whole application

2011-06-07 Thread Gabriel Genellina

Gabriel Genellina gagsl-...@yahoo.com.ar added the comment:

Note: There is a much bigger problem here: IDLE should not abort abruptly in 
such cases, without any error indication.

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue12274
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue12276] 3.x ignores sys.tracebacklimit=0

2011-06-07 Thread Gabriel Genellina

New submission from Gabriel Genellina gagsl-...@yahoo.com.ar:

Python 3.x doesn't honor sys.tracebacklimit=0

According to 
http://docs.python.org/py3k/library/sys.html#sys.tracebacklimit
when set to 0, it should not print any stack trace, but it does.

Python 3.2 (r32:88445, Feb 20 2011, 21:29:02) [MSC v.1500 32 bit (Intel)] on win
32
Type help, copyright, credits or license for more information.
p3 import sys
p3 sys.tracebacklimit = 0
p3
p3 def f(x):
...   return f(x-1) if x else 0/0
...
p3 f(5)
Traceback (most recent call last):
  File stdin, line 1, in module
  File stdin, line 2, in f
  File stdin, line 2, in f
  File stdin, line 2, in f
  File stdin, line 2, in f
  File stdin, line 2, in f
  File stdin, line 2, in f
ZeroDivisionError: division by zero
p3

--
components: Interpreter Core
files: tracebacklimitbug.py
messages: 137792
nosy: gagenellina
priority: normal
severity: normal
status: open
title: 3.x ignores sys.tracebacklimit=0
versions: Python 3.1, Python 3.2
Added file: http://bugs.python.org/file22269/tracebacklimitbug.py

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue12276
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue12276] 3.x ignores sys.tracebacklimit=0

2011-06-07 Thread Gabriel Genellina

Gabriel Genellina gagsl-...@yahoo.com.ar added the comment:

Originally reported by Thorsten Kampe in comp.lang.python 2011-5-27
http://permalink.gmane.org/gmane.comp.python.general/691496

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue12276
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[issue12276] 3.x ignores sys.tracebacklimit=0

2011-06-07 Thread Gabriel Genellina

Gabriel Genellina gagsl-...@yahoo.com.ar added the comment:

Is this the intended behavior then? I don't get the rationale for that change.

There is no way to completely supress traceback information now; for 
sys.tracebacklimit to be of any significance, it must be = 1; 0 and negative 
values behave the same as it not being set (that is, a full traceback is 
printed).

--

___
Python tracker rep...@bugs.python.org
http://bugs.python.org/issue12276
___
___
Python-bugs-list mailing list
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



Re: except KeyError, everywhere

2011-06-06 Thread Gabriel Genellina

En Fri, 03 Jun 2011 21:02:56 -0300, Nobody nob...@nowhere.com escribió:


On Fri, 03 Jun 2011 22:08:16 +0200, Wilbert Berendsen wrote:

I find myself all over the place associating objects with each other  
using

dicts as caches:


The general concept is called memoization. There isn't an  
implementation

in the standard library


Yes, there is, in Python 3.2:
http://docs.python.org/py3k/library/functools.html#functools.lru_cache


--
Gabriel Genellina

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


Re: GIL in alternative implementations

2011-06-06 Thread Gabriel Genellina
En Sat, 28 May 2011 14:05:16 -0300, Steven D'Aprano  
steve+comp.lang.pyt...@pearwood.info escribió:



On Sat, 28 May 2011 09:39:08 -0700, John Nagle wrote:


Python allows patching code while the code is executing.


Can you give an example of what you mean by this?

If I have a function:


def f(a, b):
c = a + b
d = c*3
return hello world*d


how would I patch this function while it is executing?


I think John Nagle was thinking about rebinding names:


def f(self, a, b):
  while b0:
b = g(b)
c = a + b
d = self.h(c*3)
  return hello world*d

both g and self.h may change its meaning from one iteration to the next,  
so a complete name lookup is required at each iteration. This is very  
useful sometimes, but affects performance a lot.


--
Gabriel Genellina

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


Re: Alternatives to PythonPath

2011-05-31 Thread Gabriel Genellina

En Sun, 29 May 2011 18:49:28 -0300, ray r...@aarden.us escribió:


I am using Win7 on a tightly locked down desktop.

Is there an alternative to using PythonPath?

What are the trade-offs?


Usually there is no need to define the PYTHONPATH variable; I never use it.
There is a per-user site-packages directory (2.6 and up), on Windows it is  
located at %APPDATA%\Python\PythonXX\site-packages. Every user gets its  
own %APPDATA% directory, with read and write permissions.


--
Gabriel Genellina

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


Re: Best way to compute length of arbitrary dimension vector?

2011-05-30 Thread Gabriel Genellina

En Mon, 30 May 2011 06:46:01 -0300, Peter Otten __pete...@web.de
escribió:


Gabriel wrote:


Well, the subject says it almost all: I'd like to write a small Vector
class for arbitrary-dimensional vectors.




class Vector(object):

... def __init__(self, *coords):
... self._coords = coords
... def __abs__(self):
... return math.sqrt(sum(x*x for x in self._coords))
...

import math
abs(Vector(1,1))

1.4142135623730951

abs(Vector(3,4))

5.0


Using math.fsum instead of sum may improve accuracy, specially when  
len(coords)≫2


py import math
py
py def f1(*args):
...   return math.sqrt(sum(x*x for x in args))
...
py def f2(*args):
...   return math.sqrt(math.fsum(x*x for x in args))
...
py pi=math.pi
py args=[pi]*16
py abs(f1(*args)/4 - pi)
4.4408920985006262e-16
py abs(f2(*args)/4 - pi)
0.0


--
Gabriel Genellina

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


Re: Hotshoting recursive function

2011-05-25 Thread Gabriel Genellina
En Sun, 22 May 2011 10:42:08 -0300, Selvam s.selvams...@gmail.com  
escribió:



I am using  hotshot module to profile my python function.

I used the details from (
http://code.activestate.com/recipes/576656-quick-python-profiling-with-hotshot/
).

The function I profile is a recursive one and I am getting the following
error,

ProfilerError: profiler already active

I guess this is due to the recursive call to the profiling function.

I would like to get some suggestions.


The recursive call inside your function should call the undecorated  
function, not the decorated function again. Decorator syntax is not  
convenient anymore.


Using the same names as in the recipe example:


# a recursive function
def my_slow_function(n):
  ...
  return my_slow_function(n-1)


my_profiled_slow_function = hotshotit(my_slow_function)
my_profiled_slow_function(n)


This works, in the sense that it does not raise ProfileError anymore.  
Interpreting profile data is up to you...



--
Gabriel Genellina

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


Re: pexpect: TIMEOUT no longer clears child.before

2011-05-25 Thread Gabriel Genellina
En Thu, 19 May 2011 08:29:21 -0300, Adrian Casey m...@agcasey.com  
escribió:


The behaviour of pexpect has changed between version 2.1 and 2.3.  In  
version 2.1, the following code would result in child.before being  
cleared -:


 child.expect(pexpect.TIMEOUT,1)
 In version 2.3, this is no longer the case.  No matter how many times  
the above code is run, child.before continues to hold the output from  
previous commands.  It is important to be able to clear the contents of  
child.before between each command.  What is the correct way to do this  
in version 2.3?


Try contacting the author: www.noah.org

--
Gabriel Genellina

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


Re: Multiple file select with tkFileDialog passes back 'decorated' strings (sometimes)

2011-05-23 Thread Gabriel Genellina

En Mon, 23 May 2011 10:00:53 -0300, Alex van der Spek zd...@xs4all.nl
escribió:

I switched from Mark Hammonds pywin32 extensions for file choosers as  
the multiselect there seems to crash on me when selecting more than a  
few dozen. Using Tk now. Works well but the resulting string passed back  
seems to 'decorated' when the files are on local disk and not decorated  
when retrieved over a USB interface from an external disk?


I do this:


From local disk I get back:


'{file1.bin} {file2.bin}'


From external disk I get back:


'file1.bin file2.bin'

I can handle/parse both, not an issue but it raises the question: Are  
these the only two possibilities? Is it the same across platforms (I use  
Python 2.7 on Win Vista)?


An old bug. See http://bugs.python.org/issue5712 for a workaround.

--
Gabriel Genellina

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


Re: Datetime.timedelta

2011-05-17 Thread Gabriel Genellina
En Tue, 17 May 2011 07:44:08 -0300, Tsolmon Narantsogt mnt...@gmail.com  
escribió:



I'm using datetime.timedelta and i have a problem

delta = 1 day, 2:30:00
hours = delta.days * 8

how to add 8 + 2:30:00


Just operate with it as it were a number. The timedelta class implements  
all sane mathematical operations.


py from datetime import *
py def timedelta_from_dhms(days=0, hours=0, mins=0, secs=0):
...   return timedelta(days, hours*3600 + mins*60 + secs)
...
py delta = timedelta_from_dhms(1, 2, 30)
py delta
datetime.timedelta(1, 9000)
py hours = delta.days * 8
py delta + hours
Traceback (most recent call last):
  File stdin, line 1, in module
TypeError: unsupported operand type(s) for +: 'datetime.timedelta' and  
'int'

py hours = timedelta_from_dhms(0, delta.days * 8)
py hours
datetime.timedelta(0, 28800)
py delta + hours
datetime.timedelta(1, 37800)
py def dhms_from_timedelta(td):
...   return td.days, td.seconds // 3600, (td.seconds % 3600) // 60,  
td.seconds % 60

...
py dhms_from_timedelta(delta + hours)
(1, 10, 30, 0)

--
Gabriel Genellina

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


Re: FW: help please

2011-05-17 Thread Gabriel Genellina
En Tue, 17 May 2011 06:43:51 -0300, hamed azarkeshb  
hamed3...@hotmail.com escribió:


hi dearinwant to useautomation with catiaby python,but i dont know,how  
do we can creat catsafearrayvariant in python?please help me.i need  
urhelp by one example.thank u forany thing 		 	   		


There are two sides when you want to use automation with Python:

* learn how to do automation by itself, how COM works, how to invoke a COM  
server from Python. This is mostly application-independent. A good  
resource is Python Programming in Win32 book by Mark Hammond. Chapter 5  
Introduction to COM is exactly what you need, and is available for  
preview in Google Books:  
http://books.google.com.ar/books?id=fzUCGtyg0MMClpg=PA65pg=PA65#v=onepagef=false


* learn how to use the actual objects exposed by the desired application.  
Usually, documentation is available for VBA or other languages, but can be  
easily translated into Python terms.


So I'd say you first read the book, then search the documentation about  
CATSafeArrayVariant and see how to create it, and then translate that into  
Python. Feel free to post any problem you encounter, a better place would  
be the python-win32 list:  
http://mail.python.org/mailman/listinfo/python-win32


Good luck!
--
Gabriel Genellina

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


Re: cPickle - invalid signature

2011-05-17 Thread Gabriel Genellina
En Tue, 17 May 2011 08:41:41 -0300, Neal Becker ndbeck...@gmail.com  
escribió:



What does it mean when cPickle.load says:
RuntimeError: invalid signature

Is binary format not portable?


Are you sure that's the actual error message?
I cannot find such message anywhere in the sources.
The pickle format is quite portable, even cross-version. As a generic  
answer, make sure you open the file in binary mode, both when writing and  
reading.


--
Gabriel Genellina

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


Re: FW: help please

2011-05-17 Thread Gabriel Genellina

En Tue, 17 May 2011 16:48:29 -0300, Albert Hopkins
mar...@letterboxes.org escribió:

On Tue, 2011-05-17 at 10:18 -0600, Littlefield, Tyler wrote:



Not to be pedantic or anything, and I may not be able to help
regardless, but it looks like your space key is fixed, and I don't
really care to pick through and try to play hangman with your message.


I actually, at first glance, thought it was spam, ignored it, and was
wondering why people were replying to it :|


I can't remember exactly in which release 'perfect English skills' were
added to Python runtime requirements, could you please refresh my memory?

--
Gabriel Genellina

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


Re: cPickle - invalid signature

2011-05-17 Thread Gabriel Genellina

En Tue, 17 May 2011 15:26:53 -0300, Neal Becker ndbeck...@gmail.com
escribió:


Gabriel Genellina wrote:


En Tue, 17 May 2011 08:41:41 -0300, Neal Becker ndbeck...@gmail.com
escribió:


What does it mean when cPickle.load says:
RuntimeError: invalid signature

Is binary format not portable?


Are you sure that's the actual error message?
I cannot find such message anywhere in the sources.
The pickle format is quite portable, even cross-version. As a generic
answer, make sure you open the file in binary mode, both when writing  
and

reading.



Yes, that's the message.

Part of what is pickled is a numpy array.  I am writing on a 32-bit  
linux system
and reading on a 64-bit system.  Reading on the 64-bit system is no  
problem.


Maybe the message comes from numpy's unpickling?


Maybe, at least 'invalid signature' makes sense in Numpy. In that case, a
better place to ask would be a numpy specific list, see
http://www.scipy.org/Mailing_Lists


--
Gabriel Genellina

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


Re: cPickle - invalid signature

2011-05-17 Thread Gabriel Genellina

En Tue, 17 May 2011 15:26:53 -0300, Neal Becker ndbeck...@gmail.com
escribió:


Gabriel Genellina wrote:


En Tue, 17 May 2011 08:41:41 -0300, Neal Becker ndbeck...@gmail.com
escribió:


What does it mean when cPickle.load says:
RuntimeError: invalid signature

Is binary format not portable?


Are you sure that's the actual error message?
I cannot find such message anywhere in the sources.
The pickle format is quite portable, even cross-version. As a generic
answer, make sure you open the file in binary mode, both when writing  
and

reading.



Yes, that's the message.

Part of what is pickled is a numpy array.  I am writing on a 32-bit  
linux system
and reading on a 64-bit system.  Reading on the 64-bit system is no  
problem.


Maybe the message comes from numpy's unpickling?


Maybe, at least 'invalid signature' makes sense in Numpy. In that case, a
better place to ask would be a numpy specific list, see
http://www.scipy.org/Mailing_Lists


--
Gabriel Genellina

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


Re: Import on case insensitive filesystem

2011-05-16 Thread Gabriel Genellina
En Fri, 13 May 2011 15:43:23 -0300, Mitchell Hashimoto  
mitchell.hashim...@gmail.com escribió:



I'm developing an app which runs Python on a filesystem which is not case
sensitive (Mac OS X), but is mounted as an NFS drive on a remote machine.
This causes errors because of the import being case sensitive but  
accessing
an FS which is case insensitive. Short of copying the entire directory  
tree
over to another filesystem, is there anything I can do to flag Python to  
act

as though it were on a case sensitive FS?


Try creating an environment variable PYTHONCASEOK with any value.
See http://www.python.org/dev/peps/pep-0235/ for details.

--
Gabriel Genellina

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


Re: turn monitor off and on

2011-05-16 Thread Gabriel Genellina
En Sat, 14 May 2011 03:08:44 -0300, Astan Chee astan.c...@gmail.com  
escribió:



I'm trying to turn off my monitor, pause and then turn it on again.
I'm doing this in python 2.6 and windows xp. Here is my script so far
(that doesn't work):

def turnOnMonitor():
  SC_MONITORPOWER = 0xF170
  win32gui.SendMessage(win32con.HWND_BROADCAST,
win32con.WM_SYSCOMMAND, SC_MONITORPOWER, -1)

For some reason, the script doesn't turn the monitor back on. What am
I doing wrong here or are there any other alternative?


Your script worked fine for me, 2.6 and XP also. Perhaps your monitor  
device driver is buggy or does not implement the required functionality.  
Mine is from Philips.


--
Gabriel Genellina

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


Re: Peculiar Behaviour of __builtins__

2011-05-12 Thread Gabriel Genellina
En Thu, 12 May 2011 20:29:57 -0300, Aman Nijhawan amannijha...@gmail.com  
escribió:



I was trying to call the builtin function min by using
getattr(__builtins__,'min')

This works at the interpretter prompt

However when I called it inside a module that was imported by another  
module

it fails and gives an attribute error


__builtins__ (note the final 's') is an implementation detail. You want  
the __builtin__ (no 's') module, renamed 'builtin' in Python 3.x


py import __builtin__
py builtin_min = __builtin__.min
py builtin_min([8,2,5])
2

See http://docs.python.org/library/__builtin__.html

Note: using getattr with a literal name is not so useful. Better to use  
dot notation.



--
Gabriel Genellina

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


Re: Peculiar Behaviour of __builtins__

2011-05-12 Thread Gabriel Genellina
En Thu, 12 May 2011 22:59:24 -0300, Gabriel Genellina  
gagsl-...@yahoo.com.ar escribió:


En Thu, 12 May 2011 20:29:57 -0300, Aman Nijhawan  
amannijha...@gmail.com escribió:



I was trying to call the builtin function min by using
getattr(__builtins__,'min')

This works at the interpretter prompt

However when I called it inside a module that was imported by another  
module

it fails and gives an attribute error


__builtins__ (note the final 's') is an implementation detail. You want  
the __builtin__ (no 's') module, renamed 'builtin' in Python 3.x


Should read ...renamed 'builtins' in Python 3.x, just to add to the  
confusion. :)



--
Gabriel Genellina

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


Re: NewBie Doubt in Python Thread Programming

2011-05-11 Thread Gabriel Genellina
En Wed, 11 May 2011 03:57:13 -0300, vijay swaminathan swavi...@gmail.com  
escribió:



Hi All,

I'm new bie to thread programming and I need some assistance in
understanding few concepts ...

I have a very simple program which runs a thread and prints a string.

import threading

class MyThread(threading.Thread):
def __init__(self, parent = None):
threading.Thread.__init__(self)

def run(self):
print 'Hello World'

def main():
for i in range(10):
MyThread_Object = MyThread()
print 'Object id is : ' , id(MyThread_Object)
print 'Staring thread -- ' , MyThread_Object.getName()
MyThread_Object.start()
count = threading.activeCount()
print 'The active thread count is: ' , count

if __name__ == '__main__':
main()

When I run this, I could see 10 thread being called. But when I print the
active thread count it is only 2.

Need some understanding on the following.

1. How the total active thread is 2?


Because most of them have already finished by then. Your run() method  
executes quite fast. Make it take more time (maybe by adding  
time.sleep(1)) and you'll see 10 active threads.


2. how do I stop a thread? does it get automatically stopped after  
execution

?


You don't; a trhread runs until the run() method exits. After that, the OS  
thread finishes. The Python object (a threading.Thread instance) is still  
alive (until the last reference to it disappears, as any other object).



3. Am I totally wrong in understanding the concepts.


I don't know...


4. what is the difference between active_count() and activeCount() since
both seem to give the same result.


Nothing. active_count is the preferred Python spelling per PEP8;  
activeCount is the original Java spelling.



5. is there a way to find out if the thread is still active or dead?



Yes, use is_alive()

--
Gabriel Genellina

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


Re: This it is the code of tmb_import.py (to matter of .tmb to blender) I need tmb_exporter.py (to export of blender to .tmb) Thanks.

2011-05-10 Thread Gabriel Genellina
En Tue, 10 May 2011 15:51:03 -0300, Jean Carlos Páez Ramírez  
jean_p...@hotmail.es escribió:



The attached file is script of blender fact in python that .tmb serves to
concern archives (secondly attached file), unloadings to blender and uses


Por lo que pude entender, tu problema es bastante específico de Blender,  
así que tal vez te convenga preguntar en un foro como:

http://www.g-blender.org/
(específicamente dedicado a Blender 3D en español)

También está la comunidad de Python Argentina: http://python.org.ar/pyar/  
(busca la lista de correo)


Suerte!

--
Gabriel Genellina

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


Re: Testing tools classification

2011-05-09 Thread Gabriel Genellina

En Sat, 07 May 2011 02:21:02 -0300, rusi rustompm...@gmail.com escribió:


There is this nice page of testing tools taxonomy:
http://pycheesecake.org/wiki/PythonTestingToolsTaxonomy

But it does not list staf: http://staf.sourceforge.net/index.php.


The good thing about wikis is, you can add it yourself.

--
Gabriel Genellina

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


Re: argparse parser stores lists instead of strings

2011-04-28 Thread Gabriel Genellina
En Thu, 28 Apr 2011 04:24:46 -0300, Andrew Berg  
bahamutzero8...@gmail.com escribió:



I've set up groups of arguments for a script I'm writing, and any time I
give an argument a value, it gets stored as a list instead of a string,
even if I explicitly tell it to store a string. Arguments declared with
other types (e.g. float, int) and default values are stored as expected.
For example:

vidin_args=parser.add_argument_group('Video Input Options', 'Various
options that control how the video file is demuxed/decoded.')
vidin_args.add_argument('-m', dest='vmode', nargs=1, type=str,
metavar='video_mode', choices=['ntsc', 'pal', 'film', 'ivtc'],
default='ntsc', help='Valid values are ntsc, pal, film and  
ivtc.')

...more arguments...
opts=parser.parse_args()

If I assign a value on the command line (e.g. -m pal), opts.vmode is a
list, otherwise it's a string. This is pretty bad since I can't know
whether to get opts.vmode or opts.vmode[0] later in the script. I could
loop through all the options and convert each option to a string, but
that's not really something I want to do, especially if I start adding
more options.


That's because of nargs=1. From the argparse documentation: [1]

	Note that nargs=1 produces a list of one item. This is different from the  
default, in which the item is produced by itself.


So, just remove nargs=1 from add_argument()

[1] http://docs.python.org/py3k/library/argparse.html#nargs

--
Gabriel Genellina

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


Re: Access violation reading 0x00000010

2011-04-28 Thread Gabriel Genellina
En Thu, 28 Apr 2011 03:35:48 -0300, yuan zheng tsinghuayua...@gmail.com  
escribió:



Sorry , the path is just an example.

This is not the question I think. Because there is lots of api
in libcommon-0.dll, and there is no fault when invoking other
api, such as libcommon.SIM_start().. It's just fault when invoking
this api - SIM_init(). So I wanna which situation would lead to this  
error:

--
WindowsError: exception: access violation reading 0x0010
--


On Thu, Apr 28, 2011 at 4:01 PM, yuan zheng tsinghuayua...@gmail.com
wrote:

 libcommon = CDLL(c:\libcommon-0.dll, RTLD_GLOBAL)

 libcommon.SIM_init() - This is the invoking.


It's hard to guess, but if you get an access violation just from those two  
lines of code, I'd say the problem is inside SIM_init() itself.


It may be attempting to dereference a NULL pointer: accessing a field  
inside a struct, or calling a virtual function from a NULL object...


Also, make sure CDLL is the right choice; it implies a prototype like this:

int cdecl SIM_INIT(void);

--
Gabriel Genellina

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


Re: How to upload a file

2011-04-28 Thread Gabriel Genellina
En Wed, 27 Apr 2011 11:14:54 -0300, Torsten Bronger  
bron...@physik.rwth-aachen.de escribió:



Hallöchen!

I'm skimming through the various recipies for uploading a file via
HTTP.  Unfortunately, all of them are awkward but also rather old.
(See for example
http://stackoverflow.com/questions/68477/send-file-using-post-from-a-python-script)

In my module, I do my HTTP request like this:

opener =  
urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))

opener.open(url, urllib.urlencode(data, doseq=True))

Well, and now I'd also like to include a file upload to the POST
data.  The solution should use urllib2, otherwise I'd have to change
most of my existing code.

If you now say Torsten, unfortunately it *is* so complicated I'll
jump through the hoops, but I'd love to hear that with Python 2.6.5
there's an easier way.  ;-)


This particular battery isn't included (yet - see  
http://bugs.python.org/issue3244)

but this little library may help:
https://bitbucket.org/chrisatlee/poster

--
Gabriel Genellina

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


Re: PYTHONPATH

2011-04-15 Thread Gabriel Genellina
En Fri, 15 Apr 2011 05:33:18 -0300, Algis Kabaila akaba...@pcug.org.au  
escribió:



An elementary question that is bugging me, regarding sys.path
values.sys.path can be altered easily, but the changes last for
the current session only. I would like the changes to stay for
several sessions.  Is PYTHONPATH a system variable that sets the
path for several sessions and if so, where in the system is it?
Do I need to create one for setting python path for several
sessions?


PYTHONPATH is an environment variable, you set it the same way as any  
other, the details depend on the operating system/shell you're currently  
using.


But - why do you think you need to set PYTHONPATH? Don't do that. Use the  
standard places to put your library modules and packages, like  
site-packages (where third-party libraries are installed by default). From  
Python 2.6+ the search path includes per-user directories like  
~/.local/lib/python2.6/site-packages and  
%APPDATA%\Python\Python26\site-packages (see PEP370 [1] for details) so  
you don't even have to mess with the Python installation directories.



[1] http://www.python.org/dev/peps/pep-0370/

--
Gabriel Genellina

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


Re: puzzle about file Object.readlines()

2011-03-22 Thread Gabriel Genellina
On 19 mar, 16:05, Dave Angel da...@ieee.org wrote:
 On 01/-10/-28163 02:59 PM, MRAB wrote:
  On 19/03/2011 13:15, 林桦 wrote:
  i use python 2.5. os is window 7.
  the puzzle is :python don't read the leave text when meet character:
  chr(26)
  the code is:
  /fileObject=open('d:\\temp\\1.txt','w')
  fileObject.write('22\r\n')
  fileObject.write(chr(26)+'\r\n')
  fileObject.write('33')
  fileObject.close()
  fileObject=open('d:\\temp\\1.txt','r')
  i=0
  for line in fileObject:
  i+=1
  print str(i)+'**'+line
  fileObject.close()/

  the output only print:
  /
  1**22/

  but can't print next line text:/'33'' 。who tell me why?
  /

  chr(26) can sometimes be used in text files to indicate the end of the text.

  In Microsoft Windows it dates from MS-DOS, which borrowed from CP/M, an
  operating
  system which stored the file size as the number of 128-byte records.
  chr(26) was used to
  indicate where the text ended in the last record.

 On Win a ctrl-z is end of file.  So if you want to read beyond the end
 of a text file, you have to pretend it's binary.  Open it with  rb
 instead of r

Using mode rU may be more convenient, because it still translates \r
\n into \n but disregards chr(26) as a special marker.

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


Re: How to build and upload eggs to pypi?

2011-03-22 Thread Gabriel Genellina
On 21 mar, 08:53, morphex morp...@gmail.com wrote:
 Hi,

 I have a couple of project which are on PyPi, and now I'd like to
 update some of them.  Is there a good howto somewhere, showing how to
 add new versions (instead of updating one that's already there) etc?

There is a tutorial: http://wiki.python.org/moin/CheeseShopTutorial
To add a new version, simply increment the version number, and then
python setup.py upload should be enough.

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


Re: favicon.ico problem

2010-08-11 Thread Gabriel Genellina
En Tue, 10 Aug 2010 01:32:49 -0300, Navkirat Singh navkir...@gmail.com  
escribió:


I am having this strange problem. I have programmed a very basic  
multiprocessing webserver using low level sockets. Each time the server  
receives a request it spawns a new process to handle the request. Now  
when through a web browser I type http://localhost:8001/ it  
automatically creates two processes: One process to server the '/' path  
and another one to serve the '/favicon.ico' path. I have not programmed  
it to serve the latter. Infact I dont even know where that name  
'/favicon.ico' comes from. Any insight into this weird behavior would be  
greatly appreciated.


It't the browser attempting to get an icon for the page.
See http://en.wikipedia.org/wiki/Favicon

--
Gabriel Genellina

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


Re: easy question on parsing python: is not None

2010-08-09 Thread Gabriel Genellina
En Mon, 09 Aug 2010 08:41:23 -0300, saeed.gnu saeed@gmail.com  
escribió:



x is y  means   id(y) == id(y)
x is not y  means   id(x) != id(x)


No; consider this:


py id([])==id([])
True
py [] is []
False

Comparing id's is the same as using the is operator only if you can  
guarantee that both operands are alive at the same time.



--
Gabriel Genellina

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


Re: easy question on parsing python: is not None

2010-08-07 Thread Gabriel Genellina
En Sat, 07 Aug 2010 04:04:06 -0300, Stefan Schwarzer  
sschwar...@sschwarzer.net escribió:

On 2010-08-07 00:28, Steven D'Aprano wrote:



Actually, yes, equality is implemented with a short-cut

that checks for

identity first. That makes something like:
[...]


Oops, I didn't realize that the OP had mentioned the
identity check as an optimization in case the objects are
the same. I thought he was confusing the operator with `is`.


s = abc*1000*1000*10
s == s

nice and quick, as Python can immediately recognise that a string is
always equal to itself without having to walk the entire string  
comparing

each character with itself.


Yes, that definitely makes sense. I guess I would have
implemented it this way as well. :)


For strings and other internal types this optimization certainly makes  
sense. For user-defined types it gets in the way and prevents defining an  
object such x==x is False (like NANs).


--
Gabriel Genellina

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


Re: Byte Offsets of Tokens, Ngrams and Sentences?

2010-08-06 Thread Gabriel Genellina
En Fri, 06 Aug 2010 06:07:32 -0300, Muhammad Adeel nawabad...@gmail.com  
escribió:



Does any one know how to tokenize a string in python that returns the
byte offsets and tokens? Moreover, the sentence splitter that returns
the sentences and byte offsets? Finally n-grams returned with byte
offsets.

Input:
This is a string.

Output:
This  0
is  5
a   8
string.   10


Like this?

py import re
py s = This is a string.
py for g in re.finditer(\S+, s):
...   print g.group(), g.start()
...
This 0
is 5
a 8
string. 10

--
Gabriel Genellina

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


Re: How to read large amounts of output via popen

2010-08-06 Thread Gabriel Genellina

En Fri, 06 Aug 2010 06:06:29 -0300, loial jldunn2...@gmail.com escribió:


I need to read a large amount of data that is being returned in
standard output by a shell script I am calling.

(I think the script should really be writing to a file but I have no
control over that)

Currently I have the following code. It seeems to work, however I
suspect this may not work with large amounts of standard output.

What is the best way to read a large amount of data from standard
output and write to a file?

Here is my code.

process=subprocess.Popen(['myscript', 'param1'],
shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE)

cmdoutput=process.communicate()

myfile = open('/home/john/myoutputfile','w')

myfile.write(cmdoutput[0])

myfile.close()



If all you do with the process' output is to write it to the output file,  
you can avoid the intermediate step:



myfile = open('/home/john/myoutputfile','w')
myerror = open('/home/john/myerrorfile','w')
process=subprocess.Popen(['myscript', 'param1'],
shell=False,stdout=myfile,stderr=myerror)
process.wait()

(untested)

--
Gabriel Genellina

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


Re: abstract metaclass

2010-08-06 Thread Gabriel Genellina
En Thu, 05 Aug 2010 10:46:29 -0300, Roald de Vries downa...@gmail.com  
escribió:


I'm trying to create a metaclass that keeps track of its objects, and  
implement this as a collections.MutableMapping. That is, something like  
this:



class type2(type, MutableMapping):
 ...

/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/ 
python2.6/abc.pyc in __new__(mcls, name, bases, namespace)
  83  if getattr(value, __isabstractmethod__,  
False))

  84 for base in bases:
--- 85 for name in getattr(base, __abstractmethods__,  
set()):

  86 value = getattr(cls, name, None)
  87 if getattr(value, __isabstractmethod__,  
False):


TypeError: Error when calling the metaclass bases
 'getset_descriptor' object is not iterable


Anybody knows why? Every type is just an object, isn't it?


This may be an oversight in ABCMeta implementation - please file a bug  
report at http://bugs.python.org/


--
Gabriel Genellina

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


Re: Urrlib2 IncompleteRead error

2010-08-04 Thread Gabriel Genellina
On 27 jul, 11:00, dirknbr dirk...@gmail.com wrote:

 I am running urllib2.request and get this response when I do the read.
 Any ideas what causes this?

 return response.read()
   File C:\Python26\lib\socket.py, line 329, in read
     data = self._sock.recv(rbufsize)
   File C:\Python26\lib\httplib.py, line 518, in read
     return self._read_chunked(amt)
   File C:\Python26\lib\httplib.py, line 561, in _read_chunked
     raise IncompleteRead(''.join(value))
 IncompleteRead: IncompleteRead(3235 bytes read)

Looks like a server error; a chunked transfer encoding finished before
reaching the expected size.

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


Re: Using Unicode file names with ftplib and encodings.idna as a workaround?

2010-06-23 Thread Gabriel Genellina

En Tue, 22 Jun 2010 11:43:34 -0300, pyt...@bdurham.com escribió:


Python 2.6.5 (Win32): Is there a work around for ftplib's (and
ftputil's) apparent inability to support Unicode file names?

I'm thinking that I might be able to use the encodings.idna as a
work around for this?


According to RFC 2640, you should use UTF-8 instead.
http://www.faqs.org/rfcs/rfc2640.html


One downside is that processes on the server will also have to
wrap directory access with a similar transformation. This
wouldn't be too complicated for Python programs, but I'm not sure
how convenient this would be for our PHP and shell scripters.
(Just checked: There's a PEAR module for PHP4/5; oddly enough
nothing pops up for .NET IDNA libraries)


The server software must be able to convert from file system encoding to  
utf-8 and viceversa; check its configuration.


--
Gabriel Genellina

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


Re: adding new function

2010-06-23 Thread Gabriel Genellina
En Tue, 22 Jun 2010 14:18:59 -0300, Terry Reedy tjre...@udel.edu  
escribió:

On 6/22/2010 5:44 AM, Daniel Fetchinson wrote:

how can i simply add new functions to module after its initialization
(Py_InitModule())?  I'm missing something like
PyModule_AddCFunction().


in Python, for modules written in python

import mymod
mymod.fname = somefunc #or
setattr(mymod, namestring, funcobject)


I presume you use the C-API equivalent of setattr.


That one, or PyModule_AddObject (just for nicer error messages really).

--
Gabriel Genellina

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


Re: encodings.idna.ToASCII( unicodeStr ) != unicodeStr.encode( 'idna' )

2010-06-23 Thread Gabriel Genellina

En Tue, 22 Jun 2010 11:02:58 -0300, pyt...@bdurham.com escribió:


Python 2.6.4 (Win32): Anyone have any explanation for the
following

encodings.idna.ToASCII( unicodeStr ) != unicodeStr.encode( 'idna'
)

Given that other processes may have to use the output of these
methods, what is the recommended technique?

Demonstration:


import encodings.idna
name = u'junk\xfc\xfd.txt'
name

u'junk\xfc\xfd.txt'

encodings.idna.ToASCII( name )

'xn--junk.txt-95ak'

name.encode( 'idna' )

'xn--junk-3rag.txt'

encodings.idna.ToUnicode( encodings.idna.ToASCII( name ) )

u'junk\xfc\xfd.txt'

name.encode( 'idna' ).decode( 'idna' )

u'junk\xfc\xfd.txt'


IDNA is *specifically* designed to operate with domain names, not  
arbitrary text. (IDNA = Internationalizing Domain Names in Applications).  
Even the encoding/decoding part alone(punycode) is specifically tailored  
for use in domain names. Do not use it for any other purpose.


That said, it seems that encodings.idna.ToUnicode/ToAscii work on  
individual 'labels' only (a domain name is comprised of several labels  
separated by '.') -- and encode/decode('idna') takes the whole name,  
splits, and processes each label (following RFC 3490, I presume)


--
Gabriel Genellina

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


Re: question about multiprocessing

2010-06-22 Thread Gabriel Genellina

En Sun, 20 Jun 2010 09:43:09 -0300, hywhy hy...@live.com escribió:


from multiprocessing.managers import BaseManager
import Queue

class CrawlerManager(BaseManager):
pass

downloader_queue = Queue.Queue()
downloader_queue.put('hello')

CrawlerManager.register('get_downloader_queue', callable=lambda:
downloader_queue)

mgr = CrawlerManager()
mgr.start()

q = mgr.get_downloader_queue()



error:

pickle.PicklingError: Can't pickle function lambda at 0x00C02F70:  
it's

not found as __parents_main__.lambda


Multiprocessing uses pickle to transfer data between processes. You can't  
pickle a lambda expression - functions must have a name and be available  
at the outermost module level. (See Programming guidelines in the  
multiprocessing documentation, and the pickle module)
But you can't share a Queue object - use the multiprocessing one (see  
Exchanging data between processes).


--
Gabriel Genellina

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


Re: Serialization, save type information in file and restore them

2010-06-22 Thread Gabriel Genellina
En Fri, 18 Jun 2010 08:24:01 -0300, Timothy Wu 2hug...@gmail.com  
escribió:



I created a class that's able to manipulate tabulated data. I want to be
able to dump the bulk of the data and other attributes as a tab-delimited
text. I have trouble saving/restoring type information in the file. For
example, some attributes are int, others may be float, etc. So I want to
store the data type as well as the data value themselves in a file. And I
don't think I want to use Pickle because I want it to be readily opened  
in
vi and be readable as a tab-delimited file and be able to import into  
Excel

as well.

What's the best way to achieve this? I was able to write string like
attribute = int(value) into a file. But how do I get the value back? I
want the int(value) string to be loaded into the program and be  
executable

so I can actually create the instance variable in the class.


Use the csv module to write your data in the RDB file format.
The RDB format is fairly simple: first line contains the column names (tab  
separated), second line stores type information (tab separated), remaining  
lines contain actual data (also, tab separated).
(You may use any format you want, but why reinvent it, and you may even  
find an existing RDB parser/writer in Python)


--
Gabriel Genellina

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


Re: isinstance question

2010-06-22 Thread Gabriel Genellina
En Tue, 22 Jun 2010 23:45:07 -0300, John Nagle na...@animats.com  
escribió:



   I want to test whether an object is an instance of any user-defined
class.  isinstance is less helpful than one would expect.

  import types
  class foo() : # define dummy class
... pass
...
  x = foo()
 
  type(x)
type 'instance'
 
  isinstance(x, types.ClassType)
False
  isinstance(x, types.InstanceType)
True
  foo
class __main__.foo at 0x004A2BD0
  x
__main__.foo instance at 0x020080A8

So far, so good. x is an InstanceType.  But let's try a
class with a constructor:

  class bar(object) :
...def __init__(self, val) :
...  self.val = val
...
  b = bar(100)
  b
__main__.bar object at 0x01FF50D0
  isinstance(b, types.InstanceType)
False
  isinstance(b, types.ClassType)
False
  bar
class '__main__.bar'

Without a constructor, we get an instance.  With a constructor,
we get an object, one which is not an InstanceType.


That's not the relevant difference. In the first case, you don't inherit  
from object; in the second one, you do.


foo is a classic class (or old-style class); x is an instance of foo,  
its *type* is InstanceType, its *class* is foo. All instances of any other  
classic class have the same type (InstanceType).


bar is a new-style class, b is an instance of bar, its type is bar, its  
class is bar. class and type are equivalent for new style classes; things  
are a lot more regular and predictable. In Python 3.x classic classes are  
gone.


--
Gabriel Genellina

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


Re: Strange factory pattern

2010-06-22 Thread Gabriel Genellina

En Tue, 22 Jun 2010 23:33:55 -0300, Zac Burns zac...@gmail.com escribió:


In the threading module there are several code bits following this
convention:

###
def Class(*args, **kwargs):
return _Class(*args, **kwargs)

class _Class(...
###

This is true for Event, RLock, and others.

Why do this? It seems to violate the rule of least astonishment
(isinstance(Event(), Event) raises an exception). I assume there must be
some trade-off that the designer intended to achieve. So, what is that
trade-off and when should I follow this in my code?


Those classes are not meant to be subclassed (I don't know *why*). From  
original module documentation (1998):


http://svn.python.org/view/python/trunk/Lib/threading_api.py?view=markuppathrev=10430


Lock()
A factory function that returns a new primitive lock object...

RLock()
A factory function that returns...

Same for Condition, Semaphore, Event, but:

Thread
A class that represents a thread of control -- subclassable.

Note that the classes marked as ''do not subclass'' are actually  
implemented as factory functions; classes are

shown here as a way to structure the documentation only.

And those classes have a big *** DO NOT SUBCLASS THIS CLASS *** message.  
The message never made into the documentation.



--
Gabriel Genellina

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


Re: variable variables

2010-06-18 Thread Gabriel Genellina
En Fri, 18 Jun 2010 06:48:34 -0300, someone petshm...@googlemail.com  
escribió:



is it possible to make first attr variable?

some_object.attr.attr

so instead of attr I could use self.foo which has value attr


I think you're looking for getattr:
http://docs.python.org/library/functions.html#getattr

name = spam
getattr(some_object, name) == some_object.spam == getattr(some_object,  
spam)


--
Gabriel Genellina

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



Re: Overriding __setattr__ of a module - possible?

2010-06-17 Thread Gabriel Genellina
En Wed, 16 Jun 2010 19:56:39 -0300, Ian Kelly ian.g.ke...@gmail.com  
escribió:



On Wed, Jun 16, 2010 at 3:38 PM, John Nagle na...@animats.com wrote:

That just leaves things in a state where even sys and import
are undefined.


Say what?  It works fine for me.


import proxy_mod
proxy_mod.f()

1

proxy_mod.a = 2

setting a=2

proxy_mod.f()

2

proxy_mod.sys

module 'sys' (built-in)


It *mostly* works, but not always. Try this function:

def g(x):
global a
print 'global a - ', x
a = x

py import fake # ModuleProxy stuff
py fake.f()
1
py fake.a = 3
setting a=3
py fake.f()
3
py fake.g(8)
global a -  8
py fake.f()
8
py fake.a
8

Note the fake.g(8) call: __setattr__ wasn't called.
If the OP wants to trace assignments to global variables, this becomes a  
problem.


A function defined in a module holds a reference to the module's __dict__  
in its func_globals attribute. Getting and setting global variables goes  
directly to this dictionary, and does not use the module object at all.


Even worse, the LOAD_GLOBAL/STORE_GLOBAL opcodes (which implement getting  
and setting global variables) assume func_globals is a true dictionary and  
bypass any overriden __getitem__/__setitem__ methods (an optimization,  
surely). I'm afraid it will be hard to intercept global variable usage in  
these circumstances.


--
Gabriel Genellina

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


Re: basic doubt

2010-06-17 Thread Gabriel Genellina
En Thu, 17 Jun 2010 02:06:54 -0300, madhuri vio madhuri@gmail.com  
escribió:



def h(self,event):
handle = open(myco.fasta,r)
for seq_record in SeqIO.parse(handle, fasta):
 messenger_rna = coding_myco.fasta.transcribe()
 han1 = open(mycorna.fasta,wU)
 han1.close()
 return self.messenger_rna


the error is...

File /usr/lib/python2.6/lib-tk/Tkinter.py, line 1413, in __call__
return self.func(*args)
TypeError: h() takes exactly 2 arguments (0 given)

 ia m unable to debug...i am stuck


This is just a guess, but looks like your h function is a plain function,  
not a method, so it doesn't take a self parameter. Also, you are  
probably using it in some place where the callback doesn't receive any  
additional arguments (like a Button command).

Try with def f(): ...
If it doesn't work, show us the part where h is used.

--
Gabriel Genellina

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


Re: Overriding __setattr__ of a module - possible?

2010-06-17 Thread Gabriel Genellina
En Thu, 17 Jun 2010 04:52:48 -0300, Alf P. Steinbach al...@start.no  
escribió:



* Gabriel Genellina, on 17.06.2010 09:25:

En Wed, 16 Jun 2010 19:56:39 -0300, Ian Kelly ian.g.ke...@gmail.com
escribió:


On Wed, Jun 16, 2010 at 3:38 PM, John Nagle na...@animats.com wrote:

That just leaves things in a state where even sys and import
are undefined.


Say what? It works fine for me.


import proxy_mod
proxy_mod.f()

1

proxy_mod.a = 2

setting a=2

proxy_mod.f()

2

proxy_mod.sys

module 'sys' (built-in)


It *mostly* works, but not always. Try this function:

def g(x):
global a
print 'global a - ', x
a = x

py import fake # ModuleProxy stuff
py fake.f()
1
py fake.a = 3
setting a=3
py fake.f()
3
py fake.g(8)
global a - 8
py fake.f()
8
py fake.a
8

Note the fake.g(8) call: __setattr__ wasn't called.
If the OP wants to trace assignments to global variables, this becomes a
problem.

A function defined in a module holds a reference to the module's
__dict__ in its func_globals attribute. Getting and setting global
variables goes directly to this dictionary, and does not use the module
object at all.

Even worse, the LOAD_GLOBAL/STORE_GLOBAL opcodes (which implement
getting and setting global variables) assume func_globals is a true
dictionary and bypass any overriden __getitem__/__setitem__ methods (an
optimization, surely). I'm afraid it will be hard to intercept global
variable usage in these circumstances.


Great exposition.

But who would have thunk that Python *isn't dynamic enough*? :-)


Yep... There are other examples too (e.g. the print statement in 2.x  
bypasses sys.stdout.write; see also a recent thread Which objects are  
expanded by double-star ** operator?)


Most of them seem to be speed optimizations, some might be considered  
subtle bugs. But in this case (global variable references) speed is so  
critical than even the dict lookup is inlined; the code in ceval.c says:


/* Inline the PyDict_GetItem() calls.
WARNING: this is an extreme speed hack.
Do not try this at home. */

Python is dynamic but not so much as to make it crawl like a snail...

--
Gabriel Genellina

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


Re: Overriding __setattr__ of a module - possible?

2010-06-17 Thread Gabriel Genellina

En Thu, 17 Jun 2010 07:12:23 -0300, Fuzzyman fuzzy...@gmail.com escribió:

On Jun 17, 10:29 am, Gabriel Genellina gagsl-...@yahoo.com.ar
wrote:
En Thu, 17 Jun 2010 04:52:48 -0300, Alf P. Steinbach al...@start.no  
escribió:


 But who would have thunk that Python *isn't dynamic enough*? :-)

Yep... There are other examples too (e.g. the print statement in 2.x  
bypasses sys.stdout.write;


What do you mean by this? The print statement in 2.x does *not* bypass
sys.stdout. It may use other methods besides write (writeln perhaps)
but you can *definitely* override sys.stdout to capture the output
from print statements.


Suppose you want to implement a tee variant in Python: print output
should go to stdout and also to some file (with timestamp added, just to
be fancy). First attempt:

py import sys
py import time
py
py class tee(file):
...   def write(self, data):
... file.write(self, '%s: %r\n' % (time.ctime(), data))
... sys.__stdout__.write(data)
...
py sys.stdout = tee('test.txt', 'w')
py print Hello world
py print Bye
py ^Z

D:\TEMPtype test.txt
Hello world
Bye


Note:
- no output to stdout inside the interpreter
- no timestamp in the file

This modified version works fine:

py class tee():
...   def __init__(self, filename, mode):
... self.file = open(filename, mode)
...   def write(self, data):
... self.file.write('%s: %r\n' % (time.ctime(), data))
... sys.__stdout__.write(data)

What happened? When sys.stdout is an instance of some class inheriting
  from file (that is, isinstance(sys.stdout, file) is true) then the print
statement ignores sys.stdout.write() completely -- instead it calls
directly some C stdio functions (fwrite).
The only way to influence 'print' is *not* to inherit from file in the
first place.

It's an optimization, sure.  I guess it is there before inheriting from
builtin types was allowed (in such scenario, it's a perfectly valid
optimization).  Now, perhaps the test for 'file' should be more strict,
only taking the C shortcut when using an actual file instance, not a
subclass of it.  This would allow the example above to work correctly.

--
Gabriel Genellina

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


Re: Overriding __setattr__ of a module - possible?

2010-06-17 Thread Gabriel Genellina

En Thu, 17 Jun 2010 14:09:38 -0300, John Nagle na...@animats.com
escribió:


I'm trying out a proof of concept implementation for a new
approach to safe threading.  It's somewhat similar in concept
to Alan Olsen's scheme.  The basic difference is that once
the program goes multi-thread, code objects and some other
bindings are locked down and become unchangeable.  Olsen
was climbing the walls trying to get the locking right for
the awful cases like redefining a function while another thread
is inside it.  I'm trying to lock out some of those cases.
If you do that, removing the GIL requires less pain than
Olsen experienced.

The key idea is that the use cases for most of Python's
code dynamism are during setup and initialization.  You usually
don't change code once the program has gone into its heavy
parallel processing phase.  This suggests a practical compromise.


Seems interesting...!

--
Gabriel Genellina

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


Re: Capture the request/response log for local web server through python.

2010-06-15 Thread Gabriel Genellina
En Tue, 15 Jun 2010 00:41:08 -0300, shanti bhushan  
ershantibhus...@gmail.com escribió:



Dear all,
I have made local webserver up by the python script

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

class MyHandler(BaseHTTPRequestHandler):

def do_GET(self):
try:
if self.path.endswith(.html):
f = open(curdir + sep + self.path) #self.path has /
[...]

def main():
try:
server = HTTPServer(('', 80), MyHandler)
print 'started httpserver...'
server.serve_forever()
[...]


I have designed one html page also.
when i access the HTML page ,i want to capture following things
user_agents client-request ,server-response with the help of python
script.
please guide me to write such python script with which i can log all
server /client request and response.


HTTPServer already logs the request - using sys.stderr, but you may  
override log_message() if you want:

http://docs.python.org/library/basehttpserver.html#BaseHTTPServer.BaseHTTPRequestHandler.log_message

If you want to log the response, do that in the request handler, a good  
place would be at the end of your do_GET() method above.


--
Gabriel Genellina

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


Re: File descriptor to file object

2010-06-15 Thread Gabriel Genellina
En Mon, 14 Jun 2010 11:57:20 -0300, Nathan Huesken  
pyt...@lonely-star.org escribió:



tempfile.mkstemp returns a file name and a file descriptor (as returned
by os.open). Can I somehow convert this descriptor to a file object?


py import os
py help(os.fdopen)
Help on built-in function fdopen in module nt:

fdopen(...)
fdopen(fd [, mode='r' [, bufsize]]) - file_object

Return an open file object connected to a file descriptor.

--
Gabriel Genellina

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


Re: First program

2010-06-15 Thread Gabriel Genellina

En Sat, 12 Jun 2010 06:03:43 -0300, Phil H skilp...@gmail.co.za escribió:


Trying my hand with Python but have had a small hiccup.
Reading  'A byte of Python' and created helloworld.py as directed.

#!/usr/bin/python
# filename : helloworld.py
print 'Hello World'

At the terminal prompt cd to the file location and run from the prompt.

p...@grumpy:~/projects/python$ python helloworld.py
Hello World

All fine.

Then I tried the following as described in the tutorial and get the
following error

p...@grumpy:~/projects/python$ chmod a+x helloworld.py
p...@grumpy:~/projects/python$ ./helloworld.py
bash: ./helloworld.py: /usr/bin/python^M: bad interpreter: No such file
or directory

The permissions are: rwxr-xr-x.


Looks like you created helloworld.py on Windows, or using Windows-oriented  
tools (perhaps a samba drive? ftp from a Windows disk?)
Windows text files end each line with the \r\n sequence (CR LF, bytes 0x0D  
0x0A, ^M^J). Unix (and Linux) uses only a \n (LF, 0x0A). The \r will be  
read as part of the previous line then.


There are tools to convert back and forth those formats (dos2unix and  
unix2dos, or the crlf.py demo script in the Python source distribution).  
But to avoid problems, it's better to use the right tools for the OS  
you're working with (that is, don't use notepad to edit Linux files...)


--
Gabriel Genellina

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


Re: sir

2010-06-11 Thread Gabriel Genellina
En Wed, 09 Jun 2010 05:03:36 -0300, madhuri vio madhuri@gmail.com  
escribió:



url[, data[, timeout])

in this format of passing arguments i dint understand d syntax...d comma  
is

coming immediately after the bracket...dint get it..


Those square brackets are not real brackets, you're not supposed to  
actually include them. They indicate an optional section, e.g., given this  
description:


FTP.connect(host[, port[, timeout]])

you may invoke the method as:

connect(host)
connect(host, port)
connect(host, port, timeout)

--
Gabriel Genellina

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


Re: changing format of time duration.

2010-06-05 Thread Gabriel Genellina
On 4 jun, 06:14, Günther Dietrich gd.use...@spamfence.net wrote:
 GabrielGenellinagagsl-...@yahoo.com.ar wrote:

 Try the strptime method with a suitable format, like this (untested):
 delta = now2-now1
 delta.strftime('%H:%M:%S.%f')

 Throws an exception:

 |Traceback (most recent call last):
 |  File stdin, line 1, in module
 |AttributeError: 'datetime.timedelta' object has no attribute 'strftime'

 What seems logical, since the documentation doesn't mention an strftime
 method for timedelta.

You're right. Second try (still untested):

def nice_timedelta_str(d):
  result = str(d)
  if result[1] == ':':
result = '0' + result
  return result

delta = now2-now1
print nice_timedelta_str(delta)


--
Gabriel Genellina

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


Re: General questions - where how

2010-06-05 Thread Gabriel Genellina
On 4 jun, 14:54, Terry Reedy tjre...@udel.edu wrote:
 On 6/4/2010 1:35 PM, Philip Semanchuk wrote:
  On Jun 4, 2010, at 1:22 PM, Uriah Eisenstein wrote:

  I'm relatively new to Python and have a few questions. Frankly, it
  took me a
  while to find on python.org what seems like a suitable place to post my
  questions. However, I'd like to check the archives and see if they
  haven't
  been discussed already...

  I use Google's site keyword search. e.g. to search the archives for
  banana:
 http://www.google.com/search?q=site%3Amail.python.org%2Fpipermail%2Fp...

 One can also search mailing lists mirrored and archived by 
 gmanehttp://search.gmane.org/
 This is gmane.comp.python.general. There are about 200 other g.c.python
 lists/groups that are more specialized. I have no idea about comparitive
 performance.

In addition, Google Groups mirrors this list too as
http://groups.google.com/group/comp.lang.python/

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


Re: Missing DLL in win98

2010-06-05 Thread Gabriel Genellina
On 4 jun, 19:47, Spyder42 spyder1...@yahoo.com wrote:
 On Fri, 04 Jun 2010 14:03:48 -0400, Terry Reedy tjre...@udel.edu
 wrote:
 On 6/4/2010 9:08 AM, Spyder42 wrote:
  On Fri, 04 Jun 2010 14:50:28 +0200, Christian Heimes

  Python 2.6 is not supported on Windows 98 and earlier. You need at least
  Windows 2000 with a recent service pack.
  So your response is either, you don't know if there is a fix, or 'No
  way in h377.' You couldn't figure out by my post that I already knew
  that?

 It was not obvious, without closely reading your original post, and even
 then it is not clear, that you *knew* than 2.6 was not supported on
 Win98. You could have asked 'I know 2.6+ is not officially supported in
 win98. Does anyone know a workaround other than upgrading windows or
 sticking with 2.5?. *That* would have been clear.

 I had a specific question and I got a non-specific non-answer.
 If they didn't know, they should not have answered.

You didn't state your question as clearly as you appear to think.

 It was not obvious, without closely reading your original post...

 So it WAS obvious to anyone who was PAYING ATTENTION?

It is not obvious to me at least, even after closely reading your
post.
All I can deduce from it is that you assumed you would have a better
chance upgrading your OS, not that you *knew* your current OS was
officially unsupported.
Christian Heimes gave you the right answer, even if it was not the
answer you expected.

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


Re: reading help() - newbie question

2010-06-05 Thread Gabriel Genellina
On 31 mayo, 07:19, Payal payal-pyt...@scriptkitchen.com wrote:

 When I type help(something) e.g. help(list), I see many methods like,
 __methodname__(). Are these something special? How do I use them and why
 put __ around them?

You may want to install and use see, a human-friendly replacement of
dir()

So instead of this mess:

py dir(pencil_case)
['__add__', '__class__', '__contains__', '__delattr__',
'__delitem__', '
__delslice__', '__doc__', '__eq__', '__ge__', '__getattribute__',
'__get
item__', '__getslice__', '__gt__', '__hash__', '__iadd__',
'__imul__', '
__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__',
'__ne__
', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__reversed__',
 '__rmul__', '__setattr__', '__setitem__', '__setslice__',
'__str__', 'a
ppend', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
'reverse'
, 'sort']

you get this instead:

py see(pencil_case)
[]   in   ++=
**=
=   ==   !=
=
hash()   help()   iter()   len()repr()
reversed()
str().append().count() .extend().index()
.insert().pop()   .remove().reverse()   .sort()


For us mere mortals, it's a lot more readable.
see is available at http://github.com/inky/see


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


Re: Py_single_input and the side-effects...

2010-06-05 Thread Gabriel Genellina
On 31 mayo, 08:11, moerchendiser2k3 googler.
1.webmas...@spamgourmet.com wrote:

 you are right, Python still holds the last
 reference. I just set a dummy and thats it :)

 Can you tell me where did you get the information from?

Do you mean the _ variable?
It's in the tutorial:
http://docs.python.org/tutorial/introduction.html#using-python-as-a-calculator

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


Re: changing format of time duration.

2010-06-04 Thread Gabriel Genellina
On 3 jun, 17:24, dave davidrey...@gmail.com wrote:
 Quick question. I have to time stamps (now and now2).

 now = datetime.datetime.now();
 now2 = datetime.datetime.now();

 now2-now1 yields me a result in 0:00:00.11221 (H:MM:SS.)

 I wanted to know if there is a standard python method or a quick hack
 to add an extra zero in the beginning.

 So the result I am looking for would be 00:00:00.11221

Try the strptime method with a suitable format, like this (untested):
delta = now2-now1
delta.strftime('%H:%M:%S.%f')

http://docs.python.org/library/datetime.html#strftime-strptime-behavior

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


Re: open(False) in python3

2010-05-11 Thread Gabriel Genellina
En Tue, 11 May 2010 18:40:36 -0300, geremy condra debat...@gmail.com  
escribió:


I'm unsure if this qualifies as a bug (it is also clearly user error)  
but I just

ran into a situation where open() was inadvertantly called on a False,
and I was somewhat surprised to see that this didn't bail horribly, but
rather hung forever. Here's some example sessions for python3.x and
python2.x:

redacted@redacted:~$ python3
Python 3.1.2 (r312:79147, Apr 15 2010, 12:35:07)
[GCC 4.4.3] on linux2
Type help, copyright, credits or license for more information.

f = open(False)
f.read()

^CTraceback (most recent call last):
  File stdin, line 1, in module
KeyboardInterrupt


open() in Python 3 does a lot of things; it's like a mix of codecs.open()  
+ builtin open() + os.fdopen() from 2.x all merged together. It does  
different things depending on the type and quantity of its arguments, and  
even returns objects of different types.


In particular, open(some_integer) assumes some_integer is a file  
descriptor and return some variant of file object using the given file  
descriptor.


Now, False is an instance of bool, a subclass of int, and is numerically  
equal to 0:


p3 isinstance(False, int)
True
p3 False==0
True

so open(False) is the same as open(0), and 0 is the file descriptor  
associated to standard input. The program isn't hung, it's just waiting  
for you to type some text:


p3 f = open(False)
p3 f.read()
Type some text
^Z
^Z
'Type some text\n'
p3



Should I chalk this up to stupid coder syndrome or file a bug report?


Uhm, perhaps the bug is, bool should not inherit from int in Python 3, but  
it's way too late to change that.


--
Gabriel Genellina

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


Re: PEP 3119 ABC - And how I learned to love the Abstract Bomb

2010-05-11 Thread Gabriel Genellina
En Wed, 12 May 2010 01:38:47 -0300, Hatem Nassrat hnass...@gmail.com  
escribió:



1. To create a YajlContentHandler class that forces all sub-classers
to implement a certain set of methods. (Great, thats what ABC is for)

There is a certain set of mutually exclusive callbacks, i.e. if you
implement the first set you need not implement the second, and vice
versa, so my second requirement is:

2. Conditional Abstractness! if certain methods are not implemented
then be able to require some method to be implemented.


Mmm, can't you use two separate ABCs? Perhaps inheriting from a common  
base.


--
Gabriel Genellina

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


Re: Fast Efficient way to transfer an object to another list

2010-05-05 Thread Gabriel Genellina

En Fri, 30 Apr 2010 23:16:04 -0300, Jimbo nill...@yahoo.com escribió:


Hello I have a relatively simple thing to do; move an object from one
to list into another. But I think my solution maybe inefficient 
slow. Is there a faster better way to move my stock object from one
list to another? (IE, without having to use a dictionary instead of a
list or is that my only solution?)

[code]
class stock:

code = NULL
price = 0


stock_list1 = []
stock_list2 = []

def transfer_stock(stock_code, old_list, new_list):
 Transfer a stock from one list to another 
# is there a more efficient  faster way to

index = 0

for stock in old_list:

temp_stock = stock

if temp_stock.code == stock_code:
new_list.append(temp_stock)
del old_list[index]
index += 1

return new_list[/code]


I'd do that in two steps:

def transfer_stock(stock_code, old_list, new_list):
  # find the indexes to transfer
  indexes = [i for i,stock in enumerate(old_list)
 if stock.code==stock_code]
  # actually transfer them
  for index in reversed(indexes):
stock = old_list[index]
new_list.append(stock)
del old_list[index]
  # I would not return anything

--
Gabriel Genellina

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


  1   2   3   4   5   6   7   8   9   10   >