Re: Best way to compute length of arbitrary dimension vector?
> The dimension is arbitrary, though, so: > > length = reduce(math.hypot, self._coords, 0) > Thanks, I was going to ask Algis that same question. But still, is this solution really faster or better than the one using list comprehension and the expression 'x*x'? It seems to me that the above solution (using hypot) involves repeated square roots (with subsequent squaring). Best regards, Gabriel. -- http://mail.python.org/mailman/listinfo/python-list
Best way to compute length of arbitrary dimension vector?
Well, the subject says it almost all: I'd like to write a small Vector class for arbitrary-dimensional vectors. I am wondering what would be the most efficient and/or most elegant way to compute the length of such a Vector? Right now, I've got def length(self): # x.length() = || x || total = 0.0 for k in range(len(self._coords)): d = self._coords[k] total += d*d return sqrt(total) However, that seems a bit awkward to me (at least in Python ;-) ). I know there is the reduce() function, but I can't seem to find a way to apply that to the case here (at least, not without jumping through too many hoops). I have also googled a bit, but found nothing really elegant. Any ideas? Best regards, Gabriel. -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to compute length of arbitrary dimension vector?
Thanks a lot to both of you, Chris & Peter! (I knew the solution would be simple ... ;-) ) -- http://mail.python.org/mailman/listinfo/python-list
Event objects Threading on Serial Port on Win32
David: Tube el mismo problema que vos con el hilo del ejemplo de pyserial. Me paso que en Linux andaba bien, obvio, pero tenia un pequeño problemilla en Windows, también obvio. Lo solucione de la siguiente manera: Asi es el codigo original de la función ComPortThread def ComPortThread(self): """Thread that handles the incomming traffic. Does the basic input transformation (newlines) and generates an SerialRxEvent""" while self.alive.isSet(): #loop while alive event is true if self.ser.inWaiting() != 0: text = self.ser.read() event = SerialRxEvent(self.GetId(), text) self.GetEventHandler().AddPendingEvent(event) solo tiene que agregarle el siguiente bucle antes que nada: while not self.alive.isSet(): pass quedándote así dicha función... def ComPortThread(self): """Thread that handles the incomming traffic. Does the basic input transformation (newlines) and generates an SerialRxEvent""" while not self.alive.isSet(): pass while self.alive.isSet(): #loop while alive event is true if self.ser.inWaiting() != 0: text = self.ser.read() event = SerialRxEvent(self.GetId(), text) self.GetEventHandler().AddPendingEvent(event) y listo... Con eso debería andar Espero haber sido útil -- Gabriel -- http://mail.python.org/mailman/listinfo/python-list
USB
¿Alguien conoce algún módulo para python con el que se pueda tener acceso a los puertos USB y que sea multiplataforma? -- Gabriel -- http://mail.python.org/mailman/listinfo/python-list
Icono en wxpython
Hola: He echo un programa en wxpython. Se trata de un programa para desarrollos con microcontroladores como PIC's etc. en cuanto a transmisión RS232 se refiere. El programa es GNU y quiero publicarlo pronto pero no se como poner el ícono a la ventana y al archivo en si... ¿Alguien puede darme una mano con esto? Otra cosa ¿dónde puedo publicar el programa una vez que este terminado? Desde ya muchas gracias -- Gabriel -- http://mail.python.org/mailman/listinfo/python-list
Correr Programas Externos
Hola a todos: Necesitaría correr otros programas desde python. Es decir Cuando aprieto un boton que se abra el block de notas (por ejemplo) ¿Alguien sabe como hacerlo? Gracias -- Gabriel -- http://mail.python.org/mailman/listinfo/python-list
Re: Pythonic cats (and dogs?)
Yes ! Where are the dogs ? I preffer them .. :-) "Tim Churches" <[EMAIL PROTECTED]> escribió en el mensaje news:[EMAIL PROTECTED] > A challenge: an elegant, parsimonious and more general[1] implementation of this, in Python: > > http://lol.ianloic.com/feed/www.planetpython.org/rss20.xml > > Tim C > > [1] Dogs, ponies, babies, politicians... -- http://mail.python.org/mailman/listinfo/python-list
Graphics Module
Hi all ! I'm developing a math program that shows graphics of functions. I would hear suggestions about the way of drawing 2D . Thanks a lot for your answers. - Gabriel - -- http://mail.python.org/mailman/listinfo/python-list
Re: Graphics Module
On 11 ene, 22:51, Mike <[EMAIL PROTECTED]> wrote: > On Jan 11, 3:31 pm, "Gabriel" <[EMAIL PROTECTED]> wrote: > > > Hi all ! > > > I'm developing a math program that shows graphics of functions. > > I would hear suggestions about the way of drawing 2D . > > > Thanks a lot for your answers. > > > - Gabriel - > > That's not a very descriptive question, however most people talk about > matplotlib for graphing and 2D drawings. > > Here's a few links on graphing in Python: > > http://matplotlib.sourceforge.net/http://wiki.python.org/moin/PythonGraphApihttp://alpha-leonis.lids.mit.edu/nlp/pygraph/http://boost.org/libs/graph/doc/python.htmlhttp://www.python.org/doc/essays/graphs.html > > Some of these may have dependencies, such as numpy or scipy. Be sure > to read the docs for full details either way. > > Mike Thanks ! Yes. This is what I was looking for.. -- http://mail.python.org/mailman/listinfo/python-list
Web authentication urllib2
Hello,
I'm new in Python and i would like to write script which need to login
to a website. I'm experimenting with urllib2,
especially with something like this:
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
urllib2.install_opener(opener)
params = urllib.urlencode(dict(username='user', password='pass'))
f = opener.open('https://web.com', params)
data = f.read()
f.close()
And the problem is, that this code logs me in on some sites, but on
others doesn't, especially on the one I really
need to login. And i don't know why. So is there some way how to debug
this code and find out why that script cannot
login on that specific site?
Sorry if this question is too lame, but i am really beginner both in
python and web programming .)
--
http://mail.python.org/mailman/listinfo/python-list
Re: Web authentication urllib2
First, thank you both
I think this isn't basic auth, because this page has form login.
I read site's html source and used wireshark to analyze communication
between my browser and website and i really find out that a was ignoring
one field
I added it to the parameters but it didn't help..
Maybe i'm still missing something
Here's the post packet:
http://student.fiit.stuba.sk/~sevecek06/auth.txt
and here's the code again, with little change and real web location added:
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
urllib2.install_opener(opener)
params = urllib.urlencode(dict(login='login', pwd='pass', page=''))
f = opener.open('https://www.orangeportal.sk/', params)
data = f.read()
f.close()
Login and pass are fake ofc.
Thank you in advice for any help.
Steve Holden wrote:
Gabriel wrote:
Hello,
I'm new in Python and i would like to write script which need to login
to a website. I'm experimenting with urllib2,
especially with something like this:
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
urllib2.install_opener(opener)
params = urllib.urlencode(dict(username='user', password='pass'))
f = opener.open('https://web.com', params)
data = f.read()
f.close()
And the problem is, that this code logs me in on some sites, but on
others doesn't, especially on the one I really
need to login. And i don't know why. So is there some way how to debug
this code and find out why that script cannot
login on that specific site?
Sorry if this question is too lame, but i am really beginner both in
python and web programming .)
That's actually pretty good code for a newcomer! There are a couple of
issues you may be running into.
First, not all sites use "application-based" authentication - they may
use HTTP authentication of some kind instead. In that case you have to
pass the username and password as a part of the HTTP headers. Michael
Foord has done a fair write-up of the issues at
http://www.voidspace.org.uk/python/articles/authentication.shtml
and you will do well to read that if, indeed, you need to do basic
authentication.
Second, if it *is* the web application that's doing the authentication
in the sites that are failing (in other words if the credentials are
passed in a web form) then your code may need adjusting to use other
field names, or to include other data as required by the login form. You
can usually find out what's required by reading the HTML source of the
page that contains the login form.
Thirdly [nobody expects the Spanish Inquisition ...], it may be that
some sites are extraordinarily sensitive to programmed login attempts
(possible due to spam), typically using a check of the "Agent:" HTTP
header to "make sure" that the login attempt is coming from a browser
and not a program. For sites like these you may need to emulate a
browser response more fully.
You can use a program like Wireshark to analyze the network traffic,
though you can get add-ons for Firefox that will show you the HTTP
headers on request and response.
regards
Steve
--
http://mail.python.org/mailman/listinfo/python-list
Re: Web authentication urllib2
Oh, nevermind, it's working.
Thanks
Gabriel wrote:
First, thank you both
I think this isn't basic auth, because this page has form login.
I read site's html source and used wireshark to analyze communication
between my browser and website and i really find out that a was ignoring
one field
I added it to the parameters but it didn't help..
Maybe i'm still missing something
Here's the post packet:
http://student.fiit.stuba.sk/~sevecek06/auth.txt
and here's the code again, with little change and real web location added:
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
urllib2.install_opener(opener)
params = urllib.urlencode(dict(login='login', pwd='pass', page=''))
f = opener.open('https://www.orangeportal.sk/', params)
data = f.read()
f.close()
Login and pass are fake ofc.
Thank you in advice for any help.
Steve Holden wrote:
Gabriel wrote:
Hello,
I'm new in Python and i would like to write script which need to login
to a website. I'm experimenting with urllib2,
especially with something like this:
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
urllib2.install_opener(opener)
params = urllib.urlencode(dict(username='user', password='pass'))
f = opener.open('https://web.com', params)
data = f.read()
f.close()
And the problem is, that this code logs me in on some sites, but on
others doesn't, especially on the one I really
need to login. And i don't know why. So is there some way how to debug
this code and find out why that script cannot
login on that specific site?
Sorry if this question is too lame, but i am really beginner both in
python and web programming .)
That's actually pretty good code for a newcomer! There are a couple of
issues you may be running into.
First, not all sites use "application-based" authentication - they may
use HTTP authentication of some kind instead. In that case you have to
pass the username and password as a part of the HTTP headers. Michael
Foord has done a fair write-up of the issues at
http://www.voidspace.org.uk/python/articles/authentication.shtml
and you will do well to read that if, indeed, you need to do basic
authentication.
Second, if it *is* the web application that's doing the authentication
in the sites that are failing (in other words if the credentials are
passed in a web form) then your code may need adjusting to use other
field names, or to include other data as required by the login form. You
can usually find out what's required by reading the HTML source of the
page that contains the login form.
Thirdly [nobody expects the Spanish Inquisition ...], it may be that
some sites are extraordinarily sensitive to programmed login attempts
(possible due to spam), typically using a check of the "Agent:" HTTP
header to "make sure" that the login attempt is coming from a browser
and not a program. For sites like these you may need to emulate a
browser response more fully.
You can use a program like Wireshark to analyze the network traffic,
though you can get add-ons for Firefox that will show you the HTTP
headers on request and response.
regards
Steve
--
http://mail.python.org/mailman/listinfo/python-list
--
http://mail.python.org/mailman/listinfo/python-list
Re: Web authentication urllib2
Yep, i realize this a minute after posting, sorry.
And thank you again .)
Steve Holden wrote:
Gabriel wrote:
First, thank you both
I think this isn't basic auth, because this page has form login.
I read site's html source and used wireshark to analyze communication
between my browser and website and i really find out that a was ignoring
one field
I added it to the parameters but it didn't help..
Maybe i'm still missing something
Here's the post packet:
http://student.fiit.stuba.sk/~sevecek06/auth.txt
and here's the code again, with little change and real web location added:
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())
urllib2.install_opener(opener)
params = urllib.urlencode(dict(login='login', pwd='pass', page=''))
f = opener.open('https://www.orangeportal.sk/', params)
data = f.read()
f.close()
If you look at the login form on the home page of that portal you will see
This means that the form should be submitted to
https://www.orangeportal.sk/portal/do_login.dwp
Some forms submit to the same URL that contain them, but many don't.
This is one of the ones that requires submission to a different URL!
regards
Steve
--
http://mail.python.org/mailman/listinfo/python-list
python libpcap equivalent
Hello I need to write a software router [yes, software equivalent to a hardware box that is routing packets .)]. It's a school work.. Question is: is possible write this kind of application in python? and if it's, what module should i use? I tried search for some libpcap equivalent in python and found pylibpcap, but can't find documentation and tutorial. -- http://mail.python.org/mailman/listinfo/python-list
Re: python libpcap equivalent
Steve Holden wrote: Unknown wrote: On 2009-02-03, Gabriel wrote: I need to write a software router [yes, software equivalent to hardware box that is routing packets .)]. It's a school work.. Question is: is possible write this kind of application in python? Hmm. It's going to be rather difficult, but you might be able to. and if it's, what module should i use? I tried search for some libpcap equivalent in python and found pylibpcap, but can't find documentation and tutorial. You can use pylibpcap to capture packets, and then use a raw socket to send them out again on whatever interface you want. You'll have to make sure that the host's OS's network stack isn't going to process the packets at all. I'm not sure how you go about that. The documentation for pylibpcap is built into the module. See doc.i in the tarball. And note that this won't work on Vista, where the raw socket interface is no longer available to standard applications. regards Steve Thanks guys I don't care about Vista. What i will (i hope only) need is a linux system with two net devices running router, XP hosts connected (not only two.. hubs, switches) and these hosts have to ping via router. -- http://mail.python.org/mailman/listinfo/python-list
Re: python libpcap equivalent
Steve Holden wrote: Unknown wrote: On 2009-02-03, Gabriel wrote: I need to write a software router [yes, software equivalent to hardware box that is routing packets .)]. It's a school work.. Question is: is possible write this kind of application in python? Hmm. It's going to be rather difficult, but you might be able to. and if it's, what module should i use? I tried search for some libpcap equivalent in python and found pylibpcap, but can't find documentation and tutorial. You can use pylibpcap to capture packets, and then use a raw socket to send them out again on whatever interface you want. You'll have to make sure that the host's OS's network stack isn't going to process the packets at all. I'm not sure how you go about that. The documentation for pylibpcap is built into the module. See doc.i in the tarball. And note that this won't work on Vista, where the raw socket interface is no longer available to standard applications. regards Steve Thanks guys I don't care about Vista. What i will (i hope only) need is a linux system with two net devices running router, XP hosts connected (not only two.. hubs, switches) and these hosts have to ping via router. -- http://mail.python.org/mailman/listinfo/python-list
Low level hard drive reading
Hello, I have to write linux application that will analyze disk/partition (ext3 filesystem) on really low level. It has to find/analyze files on the disk by reading disk blocks to analyze file's headers to find out file type and then blocks related to file to get file content. The second part have to be searching deleted files by this blocks reading (is this even possible?) Can i do this in python? For example can i open disk image file and read it block by block? Or is there even better solution? .) I tried search web but I wasn't successful.. I will appreciate any help. Thank you in advice.. Gabriel -- http://mail.python.org/mailman/listinfo/python-list
Merging byte arrays
Hello
I'm using this function to read data in byte format from file
def readBytes(file, offset, size):
file.seek(offset)
return file.read(size)
file is opened with open function:
file = open(path, "rb")
then i'm using array.array('B', bytes) to parse read-out data, for
example in this function:
def getIntValOfBytes(bytes):
value = i = 0
for byte in array.array('B', bytes):
value |= byte << (8 * i)
i += 1
return value
when i read one portion of bytes everything works ok. but now i need
read from more locations in file, then somehow merge these data together
and then pass to getIntValOfBytes function..
i tried list
list = []
for offset in offsets
list.extend(readBytes(file, offset, size))
or string
string = ""
for offset in offsets
string += readBytes(file, offset, size)
but with list i get this error
for byte in array.array('B', bytes):
TypeError: an integer is required
in getIntValOfBytes (i passed the part of the list to the method, list[x:y])
and with string it just freeze
I will appreciate any help..
[I'm newbie so sorry if i'm missing something obvious]
--
http://mail.python.org/mailman/listinfo/python-list
GUI Programming
Hello, I'm python newbie and i need to write gui for my school work in python. I need to write it really quick, because i haven't much time .) So question is, which of gui toolkits should i pick and learn? I heard PyGTK and Glade are best for quick gui programming? Is it good for beginner? Or is there something better? I have some experience with java swing, btw.. -- http://mail.python.org/mailman/listinfo/python-list
Re: GUI Programming
r wrote: On Apr 12, 8:07 am, Gabriel wrote: Hello, I'm python newbie and i need to write gui for my school work in python. I need to write it really quick, [snip] Tkinter is built-in, why not start there? from Tkinter import * root = Tk() root.mainloop() -- http://mail.python.org/mailman/listinfo/python-list It seems ugly to me.. -- http://mail.python.org/mailman/listinfo/python-list
Re: GUI Programming
edexter wrote: On Apr 12, 8:07 am, Gabriel wrote: Hello, I'm python newbie and i need to write gui for my school work in python. I need to write it really quick, because i haven't much time .) So question is, which of gui toolkits should i pick and learn? I heard PyGTK and Glade are best for quick gui programming? Is it good for beginner? Or is there something better? I have some experience with java swing, btw.. pygame may work for you (sdl doesn't work on my compaq though so test the examples befour reading the manual)... most of the other ones are going to be "ugly".. If what you want is realy simple and pygame doesn't work for you may want pycap (a gaming system with python embeded) .. What do you need it to do?? just simple buttons??? -- http://mail.python.org/mailman/listinfo/python-list I definitely need some kind of treeview, text area to represents text (hexa strings .)), buttons, maybe some kind of menu.. -- http://mail.python.org/mailman/listinfo/python-list
Re: GUI Programming
Gabriel wrote: Hello, I'm python newbie and i need to write gui for my school work in python. I need to write it really quick, because i haven't much time .) So question is, which of gui toolkits should i pick and learn? I heard PyGTK and Glade are best for quick gui programming? Is it good for beginner? Or is there something better? I have some experience with java swing, btw.. -- http://mail.python.org/mailman/listinfo/python-list I'm going to try wxPython because i found some stuff i need on web and it seems easy to me .) But I checked everything you mentioned and i discovered that python is really great to write gui (not only of course ,)) Thank you all -- http://mail.python.org/mailman/listinfo/python-list
python-magic with python2.6
Is there any way to use python-magic(http://pypi.python.org/pypi/python-magic/0.1) with python2.6? Or do somebody know something similar to this what is running on 2.6? -- Gabriel -- http://mail.python.org/mailman/listinfo/python-list
Re: python-magic with python2.6
Gabriel wrote: Is there any way to use python-magic(http://pypi.python.org/pypi/python-magic/0.1) with python2.6? Or do somebody know something similar to this what is running on 2.6? If somebody care .. .) I have found sources of python-magic here: http://wiki.python.org/moin/HowTo/FileMagic?action=AttachFile&do=view&target=LARZ-python-magic-v0.1-c112ac064b7f.zip and it works fine with 2.6. -- Gabriel -- http://mail.python.org/mailman/listinfo/python-list
issue with twisted and reactor. Can't stop reactor
Hello all!,
I'm trying to implement a simple one way communication using twisted.
Sender:
> send message
> close connection
Receiver:
> receive
> do something
> wait for other message
I'm testing with this simple examples:
Sender:
[code]
class SenderClient(protocol.Protocol):
def __init__(self, data):
self.data = data
def connectionMade(self):
self.transport.write(self.data)
def dataReceived(self, data):
self.transport.loseConnection()
def connectionLost(self, reason):
pass
class SenderFactory(protocol.ClientFactory):
def __init__(self, data):
self.data = data
def buildProtocol(self, addr):
return SenderClient(self.data)
def clientConnectionFailed(self, connector, reason):
logger.error("Connection failed. Reason %s" % reason)
reactor.stop()
def clientConnectionLost(self, connector, reason):
reactor.stop()
class Sender(object):
def __init__(self, host='localhost', port=61610):
self.host = host
self.port = port
def send(self, data):
reactor.connectTCP(self.host, self.port, SenderFactory(data))
reactor.run()
[/code]
Receiver:
[code]
from twisted.internet import reactor, protocol
class Receiver(protocol.Protocol):
def dataReceived(self, data):
self.transport.write("success")
print data
def main():
factory = protocol.ServerFactory()
factory.protocol = Receiver
reactor.listenTCP(61610,factory)
reactor.run()
if __name__ == '__main__':
main()
[/code]
When I call send the first time it works fine, when I call send a
second time the sender hangs.
If I hit ctrl+c it throws:
[quote]
.../twisted/internet/base.py", line 527, in stop
"Can't stop reactor that isn't running.")
twisted.internet.error.ReactorNotRunning: Can't stop reactor that isn't running.
[/quote]
Any idea why this is happening?
King regards.
--
http://mail.python.org/mailman/listinfo/python-list
Re: issue with twisted and reactor. Can't stop reactor
Jean-Paul Calderone escribió: > None of the reactors in Twisted are restartable. You can run and stop them > once. After you've stopped a reactor, you cannot run it again. This is > the > cause of your problem. > > Jean-Paul I see. Is it possible to do what I want using twisted? or I should found another way? -- Kind regards. -- http://mail.python.org/mailman/listinfo/python-list
how to find the last decorator of a chain
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA256
Hi,
I have something like this:
@render(format="a")
@render(format="b")
@
def view(format, data):
return data
Each render will do something with 'data' if format match, and nothing
if not.
But if there is no more renders to eval, the last one is the default,
and must run even if the format doesn't match.
In my understanding this equivalent to:
render('a',
render('b',
view(***)))
Is there any way to know, in this case, that 'a' is the 'default' format?
PS: the number of renders could be 1 or more.
- --
Kind regards.
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.9 (GNU/Linux)
iEYEAREIAAYFAkohvjoACgkQNHr4BkRe3pJZQgCgqxL7Qq7/vqDQMLkGQs5emWgH
nbMAn2vzY0xGjG2xhOkxAf8hmERc8R5r
=wWbB
-END PGP SIGNATURE-
--
http://mail.python.org/mailman/listinfo/python-list
Re: List behaviour
Bruno Desthuilliers websiteburo.invalid> writes: > The problem here is that your first statement > > #>>> tasks = [[]]*6 > > creates a list (task) containing 6 references to the *same* (empty) list > object. You can check this easily using the identity test operator 'is': > > If you want 6 different list objects in tasks, you can use a list > comprehension instead: > > #>>> tasks = [[] for i in range(6)] > #>>> tasks > [[], [], [], [], [], []] > #>>> tasks[0].append(1) > #>>> tasks > [[1], [], [], [], [], []] > > HTH > -- > http://mail.python.org/mailman/listinfo/python-list Hi Bruno Thanks for clearing that up. Your example certainly works well, I will study list comprehension a little more. Many thanks Gabriel -- http://mail.python.org/mailman/listinfo/python-list
Re: List behaviour
Diez B. Roggisch nospam.web.de> writes: > So instead of creating a list of list by the *-operator that only multiplies > the references (which is fine immutable objects like strings or numbers), > you need to explicitly create new lists, e.g. with a list-comprehension: > > tasks = [[] for _ in xrange(6)] > > Try this and everything will work as expected. > Thanks, Diez. Thanks to all who replied to help me with this :) -- http://mail.python.org/mailman/listinfo/python-list
Re: List behaviour
virgilio.it> writes: > >>> tasks = [ [] for x in xrange(6) ] > >>> tasks[0].append(1) > >>> tasks > [[1], [], [], [], [], []] > >>> > Thanks, Bockman -- http://mail.python.org/mailman/listinfo/python-list
List behaviour
Hi all Just wondering if someone could clarify this behaviour for me, please? >>> tasks = [[]]*6 >>> tasks [[], [], [], [], [], []] >>> tasks[0].append(1) >>> tasks [[1], [1], [1], [1], [1], [1]] Well what I was expecting to end up with was something like: >>> tasks [[1], [], [], [], [], []] I got this example from page 38 of Beginning Python. Regards Gabriel -- http://mail.python.org/mailman/listinfo/python-list
Re: Calendar GUI
On Fri, Feb 5, 2010 at 9:08 PM, William Gaggioli wrote: > Hello Everyone, > > I'm working on setting up some software for a Peruvian non-profit to help > them organize their incoming volunteers. One of the features I'd like to add > is a calendar-like view of the different volunteers arrival dates and > staying time, with potentially some other info through some double-click > action. Rather than writing a calendar gui myself, is there some open-source > calendar program you guys could recommend that I could plug into? It has to > be run locally, as the internet isn't so reliable down here, but other than > that something simple and clean is ideal. > I wrote a gtk gui for google calendar. Maybe you can adapt it to your needs. http://code.google.com/p/googlecalendar-gtk/ -- Kind Regards -- http://mail.python.org/mailman/listinfo/python-list
Re: Timer
On Wed, Feb 17, 2010 at 3:14 PM, Victor Subervi wrote:
> Hi;
> I have the following css:
>
> .splash { position:absolute; left:0px; top:0px; z-index:2 }
> .page { position:absolute; left:0px; top:0px; z-index:1 }
> .text { font-family: Arial, Helvetica, sans-serif; font-size: 16px;
> text-decoration: none; text-align: justify}
>
> and the following python:
> if new is not None:
> print ''
> print ' codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0";
> WIDTH="%s" HEIGHT="%s" id="myMovieName">' % (str(wn*1008), str(wn*200))
> print '''
>
>
> '''
> print ' quality=high bgcolor=#FF WIDTH="%s" HEIGHT="%s" NAME="myMovieName"
> ALIGN="" TYPE="application/x-shockwave-flash"
> PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer";>' %
> (str(wn*1008), str(wn*200))
> print ''
> print ''
> Timer(5, removeCSS, ()).start()
> Obviously, the removeCSS isn't going to work in that last line. What can I
> put there to remove the splash page after 5 seconds?
> TIA,
> beno
I don't think this has anything to do with python.
--
Kind Regards
--
http://mail.python.org/mailman/listinfo/python-list
Re: Splitting on '^' ?
On Fri, Aug 14, 2009 at 5:23 PM, kj wrote:
>
import re
re.split('^', 'spam\nham\neggs\n')
> ['spam\nham\neggs\n']
re.split('(?m)^', 'spam\nham\neggs\n')
> ['spam\nham\neggs\n']
bol_re = re.compile('^', re.M)
bol_re.split('spam\nham\neggs\n')
> ['spam\nham\neggs\n']
>
> Am I doing something wrong?
>
Maybe this:
>>> import re
>>> te = 'spam\nham\neggs\n'
>>> pat = '\n'
>>> re.split(pat,te)
['spam', 'ham', 'eggs', '']
--
Kind Regards
--
http://mail.python.org/mailman/listinfo/python-list
Re: Python word to text
2009/9/1 BJörn Lindqvist : > Hello everybody, > > I'm looking for a pure Python solution for converting word documents > to text. App Engine doesn't allow external programs, which means that > external programs like catdoc and antiword can't be used. Anyone know > of any? > You could use the google docs api (http://code.google.com/apis/documents/docs/3.0/developers_guide_protocol.html#DownloadingDocsAndPresentations) -- Kind Regards -- http://mail.python.org/mailman/listinfo/python-list
Random List Loop?!
Hi I have tried now for ages to make a loop that does the following: Makes a new list with 9 random values, from 9 different lists, with 9 elements. And makes sure that none of the elements repeat! Is there anyone that can help, with a very simple solution?? Best Christian -- http://mail.python.org/mailman/listinfo/python-list
[ANN] Python/Cython/SDL 2D Game Engine
Hello list, I wanted to let you know about my pet project for the last few months, a multiplatform (Linux64/Win32/Android at the moment), Python/Cython/SDL open source 2D game engine called "Ignifuga". The source code mixes Python and Cython code, then uses Cython to convert everything to C, and compiles it all along with the Python interpreter and SDL into a static binary. It's still a long way of from being something serious, but you can already make nice Android Live wallpapers with it! You can check it out at www.ignifuga.org Thanks! -- Gabriel. -- http://mail.python.org/mailman/listinfo/python-list
Request META Help
I have a system that uses request.META ['HTTP_HOST'] to identify which will run APPLICATION. The domains testes1.xyz.com.br, tes.xyzk.com.br, xx.xyzk.com.br through a DNS redirect TYPE A link to the server IP. In most cases I get the request.META ['HTTP_HOST'] with the URL in the request header, but today I had a problem that a customer made an appointment for me, and I get the IP of the server that information. Actually I need to get tes.xyzk.com.br Does anyone know better how it works? How can I overcome this? -- http://mail.python.org/mailman/listinfo/python-list
Re: except KeyError, everywhere
En Fri, 03 Jun 2011 21:02:56 -0300, Nobody 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
En Sat, 28 May 2011 14:05:16 -0300, Steven D'Aprano 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 b>0: 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: Print Window on IDLE
En Mon, 06 Jun 2011 14:48:26 -0300, Steve Oldner
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?
En Fri, 27 May 2011 17:38:50 -0300, Thorsten Kampe 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?
En Tue, 07 Jun 2011 15:09:54 -0300, Dun Peal
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 ()
27 baz = foo+bar
28 spam.somenamethatdoesnotexist(foo+bar)
29 anotherglobal("thatdoesnotexisteither")
30
31 a(10, 20)
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 =
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 =
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
Re: Problems Compiling Python 2.6.7 for Win7
En Wed, 08 Jun 2011 12:28:56 -0300, Jay Osako 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: help on QUICKFIX
En Fri, 10 Jun 2011 04:13:05 -0300, prakash jp 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'
En Fri, 10 Jun 2011 07:30:28 -0300, Francesc Segura
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
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'
En Fri, 10 Jun 2011 07:30:28 -0300, Francesc Segura
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
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: Python 2.7.2 for Windows reports version as 2.7.0?
En Sun, 19 Jun 2011 12:35:38 -0300, 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: search through this list's email archives
En Thu, 23 Jun 2011 13:11:32 -0300, Cathy James 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
En Fri, 24 Jun 2011 11:33:23 -0300, Grant Edwards escribió: On 2011-06-24, Gabriel Genellina wrote: En Thu, 23 Jun 2011 13:11:32 -0300, Cathy James 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: from module import * using __import__?
En Sat, 02 Jul 2011 16:52:11 -0300, Dan Stromberg escribió: Is there a decent way of running "from 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: Execute a method in a file in an egg
En Tue, 23 Aug 2011 13:14:06 -0300, RVince 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: Calling Script from Command line not working
En Mon, 29 Aug 2011 07:40:06 -0300, Sathish S
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: [Python-ideas] allow line break at operators
So can be done with this syntax: > x = firstpart * secondpart + #line breaks here > anotherpart + #continue > stillanother #continue on. after a "+" operator the line is clearly not finished yet. Gabriel AHTUNE 2011/9/2 Matt Joiner > I guess the issue here is that you can't tell if an expression is > complete without checking the indent of the following line. This is > likely not desirable. > > On Thu, Sep 1, 2011 at 11:43 PM, Yingjie Lan wrote: > > Hi Matt, > > === > > From: Matt Joiner > > > > The "trailing \" workaround is nonobvious. Wrapping in () is noisy and > > already heavily used by other syntactical structures. > > === > > How about only require indentation > > to freely break lines? Here is an example: > > x = firstpart * secondpart #line breaks here > > + anotherpart #continue by indentation > > + stillanother #continue on. > > #until here, another line starts by dedentation > > y = some_expression - another_one > > All this would be completely compatible with former code, while > > having almost free line breaking! Plus, indentation makes it pretty. > > Really hope Python can have freedom in breaking lines. > > Yingjie > ___ > Python-ideas mailing list > [email protected] > http://mail.python.org/mailman/listinfo/python-ideas > -- http://mail.python.org/mailman/listinfo/python-list
Re: Handling 2.7 and 3.0 Versions of Dict
En Wed, 31 Aug 2011 22:28:09 -0300, Travis Parks escribió: On Aug 31, 7:37 pm, Gregory Ewing 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
En Wed, 31 Aug 2011 22:46:54 -0300, 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
En Thu, 01 Sep 2011 07:51:43 -0300, Yaşar Arabacı 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
En Fri, 02 Sep 2011 13:53:37 -0300, Travis Parks escribió: On Sep 2, 12:36 pm, "Gabriel Genellina" wrote: En Wed, 31 Aug 2011 22:28:09 -0300, Travis Parks escribi : > On Aug 31, 7:37 pm, Gregory Ewing 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: puzzle about file Object.readlines()
On 19 mar, 16:05, Dave Angel 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?
On 21 mar, 08:53, morphex 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
Help Amigos
Hello community My name is Gabriel. I'am from Brazil. 27. I finished last year Degree in Computer Engineering and I would go to the U.S.A to learn the local language. I wonder how is the market for developers, which city is best for this? I program for 5 years PHP (MVC) and for the past four months I working with Python and Django. Incidentally, I love it and work on it Working on a site in Brazil claims, moreover, the largest site latin america complaints. (ser for 'reclamação' in google.com.br). I would like to review and help the community. I am very interested in live in the USA. Even more. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help Amigos
On 11 abr, 09:01, Gabriel Novaes wrote: > Hello community > > My name is Gabriel. I'am from Brazil. 27. I finished last year > Degree in Computer Engineering and I would go to the U.S.A > to learn the local language. > I wonder how is the market for developers, which > city is best for this? > I program for 5 years PHP (MVC) and for the past four months I > working with Python and Django. Incidentally, I love it and work on it > > Working on a site in Brazil claims, moreover, the largest site > latin america complaints. (ser for 'reclamação' in google.com.br). > > I would like to review and help the community. I am very interested in > live in the USA. > > Even more. Visit my site and to know my job. www.igrow.com.br -- http://mail.python.org/mailman/listinfo/python-list
Re: PYTHONPATH
En Fri, 15 Apr 2011 05:33:18 -0300, Algis Kabaila 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: argparse parser stores lists instead of strings
En Thu, 28 Apr 2011 04:24:46 -0300, Andrew Berg
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
En Thu, 28 Apr 2011 03:35:48 -0300, yuan zheng
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
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
En Wed, 27 Apr 2011 11:14:54 -0300, Torsten Bronger 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: Testing tools classification
En Sat, 07 May 2011 02:21:02 -0300, rusi 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: 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.
En Tue, 10 May 2011 15:51:03 -0300, Jean Carlos Páez Ramírez 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: NewBie Doubt in Python Thread Programming
En Wed, 11 May 2011 03:57:13 -0300, vijay swaminathan 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: Peculiar Behaviour of __builtins__
En Thu, 12 May 2011 20:29:57 -0300, Aman Nijhawan 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__
En Thu, 12 May 2011 22:59:24 -0300, Gabriel Genellina escribió: En Thu, 12 May 2011 20:29:57 -0300, Aman Nijhawan 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: Import on case insensitive filesystem
En Fri, 13 May 2011 15:43:23 -0300, Mitchell Hashimoto 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
En Sat, 14 May 2011 03:08:44 -0300, Astan Chee 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: Datetime.timedelta
En Tue, 17 May 2011 07:44:08 -0300, Tsolmon Narantsogt 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 "", line 1, in 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
En Tue, 17 May 2011 06:43:51 -0300, hamed azarkeshb 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=fzUCGtyg0MMC&lpg=PA65&pg=PA65#v=onepage&f=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
En Tue, 17 May 2011 08:41:41 -0300, Neal Becker 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
En Tue, 17 May 2011 16:48:29 -0300, Albert Hopkins 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
En Tue, 17 May 2011 15:26:53 -0300, Neal Becker escribió: Gabriel Genellina wrote: En Tue, 17 May 2011 08:41:41 -0300, Neal Becker 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
En Tue, 17 May 2011 15:26:53 -0300, Neal Becker escribió: Gabriel Genellina wrote: En Tue, 17 May 2011 08:41:41 -0300, Neal Becker 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: Multiple file select with tkFileDialog passes back 'decorated' strings (sometimes)
En Mon, 23 May 2011 10:00:53 -0300, Alex van der Spek
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: Hotshoting recursive function
En Sun, 22 May 2011 10:42:08 -0300, Selvam 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
En Thu, 19 May 2011 08:29:21 -0300, Adrian Casey 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: Best way to compute length of arbitrary dimension vector?
En Mon, 30 May 2011 06:46:01 -0300, Peter Otten <[email protected]> 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: Alternatives to PythonPath
En Sun, 29 May 2011 18:49:28 -0300, ray 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
from packaging import version as pack_version ImportError: No module named packaging
Dears, I am running a python code that generates for me this error : from packaging import version as pack_version ImportError: No module named packaging I googled it and I have found so many suggestions regarding updating 'pip' and installing python-setuptools but all of these did not fix this issue. Do you have any idea how can I solve this problem. Thanks in advance. -- https://mail.python.org/mailman/listinfo/python-list
Re: from packaging import version as pack_version ImportError: No module named packaging
Thanks so Lutz much for your reply. I am using python2.7 and I am running this code in an Openstack instance. I will apply your recommandation and let you know about the result ... Kind regards. 2017-10-27 16:13 GMT+02:00 Lutz Horn : > On Fri, Oct 27, 2017 at 03:56:39PM +0200, David Gabriel wrote: > > from packaging import version as pack_version > > ImportError: No module named packaging > > > > I googled it and I have found so many suggestions regarding updating > > 'pip' and installing python-setuptools but all of these did not fix > > this issue. > > So many questions: > > * What is your Python version? > * Do you use virtualenv? > * How? > * Did you install packaging in this virtualenv? > > Just one example of making this work: > > $ mkdir /tmp/pack > $ cd /tmp/pack > $ virtualenv -p $(which python3.5) . > Running virtualenv with interpreter /usr/bin/python3.5 > Using base prefix '/usr' > New python executable in /tmp/pack/bin/python3.5 > Also creating executable in /tmp/pack/bin/python > Installing setuptools, pkg_resources, pip, wheel...done. > $ source bin/activate > $ pip3 install packaging > Collecting packaging > Using cached packaging-16.8-py2.py3-none-any.whl > Collecting six (from packaging) > Using cached six-1.11.0-py2.py3-none-any.whl > Collecting pyparsing (from packaging) > Using cached pyparsing-2.2.0-py2.py3-none-any.whl > Installing collected packages: six, pyparsing, packaging > Successfully installed packaging-16.8 pyparsing-2.2.0 six-1.11.0 > $ python3.5 > Python 3.5.2 (default, Sep 14 2017, 22:51:06) > [GCC 5.4.0 20160609] on linux > Type "help", "copyright", "credits" or "license" for more > information. > >>> from packaging import version as pack_version > >>> > -- > https://mail.python.org/mailman/listinfo/python-list > -- https://mail.python.org/mailman/listinfo/python-list
Re: from packaging import version as pack_version ImportError: No module named packaging
I forget to precise that I am using pycharm. And this issue is reproducible also using command line to run the code. Best regards 2017-10-28 14:31 GMT+02:00 David Gabriel : > Thanks so Lutz much for your reply. > I am using python2.7 and I am running this code in an Openstack instance. > I will apply your recommandation and let you know about the result ... > > Kind regards. > > 2017-10-27 16:13 GMT+02:00 Lutz Horn : > >> On Fri, Oct 27, 2017 at 03:56:39PM +0200, David Gabriel wrote: >> > from packaging import version as pack_version >> > ImportError: No module named packaging >> > >> > I googled it and I have found so many suggestions regarding updating >> > 'pip' and installing python-setuptools but all of these did not fix >> > this issue. >> >> So many questions: >> >> * What is your Python version? >> * Do you use virtualenv? >> * How? >> * Did you install packaging in this virtualenv? >> >> Just one example of making this work: >> >> $ mkdir /tmp/pack >> $ cd /tmp/pack >> $ virtualenv -p $(which python3.5) . >> Running virtualenv with interpreter /usr/bin/python3.5 >> Using base prefix '/usr' >> New python executable in /tmp/pack/bin/python3.5 >> Also creating executable in /tmp/pack/bin/python >> Installing setuptools, pkg_resources, pip, wheel...done. >> $ source bin/activate >> $ pip3 install packaging >> Collecting packaging >> Using cached packaging-16.8-py2.py3-none-any.whl >> Collecting six (from packaging) >> Using cached six-1.11.0-py2.py3-none-any.whl >> Collecting pyparsing (from packaging) >> Using cached pyparsing-2.2.0-py2.py3-none-any.whl >> Installing collected packages: six, pyparsing, packaging >> Successfully installed packaging-16.8 pyparsing-2.2.0 six-1.11.0 >> $ python3.5 >> Python 3.5.2 (default, Sep 14 2017, 22:51:06) >> [GCC 5.4.0 20160609] on linux >> Type "help", "copyright", "credits" or "license" for more >> information. >> >>> from packaging import version as pack_version >> >>> >> -- >> https://mail.python.org/mailman/listinfo/python-list >> > > -- https://mail.python.org/mailman/listinfo/python-list
Re: from packaging import version as pack_version ImportError: No module named packaging
Dears, When I run this command I got this error message: ubuntu@orchestrateur:/tmp/pack$ virtualenv -p $(which python3.5) . Running virtualenv with interpreter /usr/local/sbin/. Traceback (most recent call last): File "/usr/bin/virtualenv", line 3, in virtualenv.main() File "/usr/lib/python2.7/dist-packages/virtualenv.py", line 784, in main popen = subprocess.Popen([interpreter, file] + sys.argv[1:], env=env) File "/usr/lib/python2.7/subprocess.py", line 710, in __init__ errread, errwrite) File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child raise child_exception OSError: [Errno 13] Permission denied This error is also reproducible using sudo. Please advise how to fix it. Thanks in advance. Best regards 2017-10-28 14:33 GMT+02:00 David Gabriel : > I forget to precise that I am using pycharm. > And this issue is reproducible also using command line to run the code. > > Best regards > > 2017-10-28 14:31 GMT+02:00 David Gabriel : > >> Thanks so Lutz much for your reply. >> I am using python2.7 and I am running this code in an Openstack instance. >> I will apply your recommandation and let you know about the result ... >> >> Kind regards. >> >> 2017-10-27 16:13 GMT+02:00 Lutz Horn : >> >>> On Fri, Oct 27, 2017 at 03:56:39PM +0200, David Gabriel wrote: >>> > from packaging import version as pack_version >>> > ImportError: No module named packaging >>> > >>> > I googled it and I have found so many suggestions regarding updating >>> > 'pip' and installing python-setuptools but all of these did not fix >>> > this issue. >>> >>> So many questions: >>> >>> * What is your Python version? >>> * Do you use virtualenv? >>> * How? >>> * Did you install packaging in this virtualenv? >>> >>> Just one example of making this work: >>> >>> $ mkdir /tmp/pack >>> $ cd /tmp/pack >>> $ virtualenv -p $(which python3.5) . >>> Running virtualenv with interpreter /usr/bin/python3.5 >>> Using base prefix '/usr' >>> New python executable in /tmp/pack/bin/python3.5 >>> Also creating executable in /tmp/pack/bin/python >>> Installing setuptools, pkg_resources, pip, wheel...done. >>> $ source bin/activate >>> $ pip3 install packaging >>> Collecting packaging >>> Using cached packaging-16.8-py2.py3-none-any.whl >>> Collecting six (from packaging) >>> Using cached six-1.11.0-py2.py3-none-any.whl >>> Collecting pyparsing (from packaging) >>> Using cached pyparsing-2.2.0-py2.py3-none-any.whl >>> Installing collected packages: six, pyparsing, packaging >>> Successfully installed packaging-16.8 pyparsing-2.2.0 six-1.11.0 >>> $ python3.5 >>> Python 3.5.2 (default, Sep 14 2017, 22:51:06) >>> [GCC 5.4.0 20160609] on linux >>> Type "help", "copyright", "credits" or "license" for more >>> information. >>> >>> from packaging import version as pack_version >>> >>> >>> -- >>> https://mail.python.org/mailman/listinfo/python-list >>> >> >> > -- https://mail.python.org/mailman/listinfo/python-list
Pickle to source code
Hello I want to convert from pickle format to python source code. That is, given an existing pickle, I want to produce a textual representation which, when evaluated, yields the original object (as if I had unpickled the pickle). I know of some transformations pickle/xml (Zope comes with one such tool, gnosis xml is another) so I believe I could build something based on them. But I dont want to reinvent the wheel, I wonder if anyone knows of a library which could do what I want? Thanks, Gabriel Genellina Softlab SRL -- http://mail.python.org/mailman/listinfo/python-list
Re: Pickle to source code
Benjamin Niemann ha escrito: > Gabriel Genellina wrote: > > > I want to convert from pickle format to python source code. That is, > > given an existing pickle, I want to produce a textual representation > > which, when evaluated, yields the original object (as if I had > > If all objects correctly implement the __repr__ method (true for built-in > stuff like list, dict, set...): > Just unpickle it and call repr() on the resulting object. Unfortunately I need a more general approach... Gabriel Genellina Softlab SRL -- http://mail.python.org/mailman/listinfo/python-list
Re: Pickle to source code
Maksim Kasimov ha escrito: > As far i know, in pickle-file there are only attributes values of a pickled > object, but not an object itself. > > It is possible to unpickle object only if you have the sourse of the class > that object you have pickled. > So, if you have class code and attribute values of the class instance, there > is no problem to produce a textual representation of the object. Isn't it? Yes, but I need it for many different objects, some of them written by other people. Please see my next post for clarification. Gabriel Genellina Softlab SRL -- http://mail.python.org/mailman/listinfo/python-list
Re: Pickle to source code
> I want to convert from pickle format to python source code. That is,
> given an existing pickle, I want to produce a textual representation
> which, when evaluated, yields the original object (as if I had
> unpickled the pickle).
> I know of some transformations pickle/xml (Zope comes with one such
> tool, gnosis xml is another) so I believe I could build something based
> on them.
> But I dont want to reinvent the wheel, I wonder if anyone knows of a
> library which could do what I want?
An example to make things clear:
class MyClass:
def __init__(self,a,b):
self.a=a
self.b=b
def foo(self):
self.done=1
# construct an instance and work with it
obj = MyClass(1,2)
obj.foo()
# save into file
pickle.dump(obj,file('test.dat','wb'))
Then, later, another day, using another process, I read the file and
want to print a block of python code equivalent to the pickle saved in
the file.
That is, I want to *generate* a block of code like this:
xxx = new.instance(MyClass)
xxx.a = 1
xxx.b = 2
xxx.done = 1
Or perhaps:
xxx = new.instance(MyClass, {'a':1,'b':2,'done':1})
In other words, I need a *string* which, being sent to eval(), would
return the original object state saved in the pickle.
As has been pointed, repr() would do that for simple types. But I need
a more general solution.
The real case is a bit more complicated because there may be references
to other objects, involving the persistent_id mechanism of pickles, but
I think it should not be too difficult. In this example, if xxx.z
points to another external instance for which persistent_id returns
'1234', would suffice to output another line like:
xxx.z = external_reference('1234')
I hope its more clear now.
Thanks,
Gabriel Genellina
Softlab SRL
--
http://mail.python.org/mailman/listinfo/python-list
Re: Pickle to source code
Jean-Paul Calderone ha escrito: > >In other words, I need a *string* which, being sent to eval(), would > >return the original object state saved in the pickle. > > You may find twisted.persisted.aot of some use. Here is an example: > > AOT is unmaintained in Twisted, and may not support some newer features of > Python (eg, datetime or deque instances). If this seems useful, you may want > to contribute patches to bring it up to the full level of functionality you > need. Oh, thanks. I have some problems installing the package but I hope it will be useful. If any changes are needed I'll report them. Gabriel Genellina Softlab SRL -- http://mail.python.org/mailman/listinfo/python-list
Re: Pickle to source code
Olivier Dormond ha escrito:
> > xxx = new.instance(MyClass, {'a':1,'b':2,'done':1})
> >
> > In other words, I need a *string* which, being sent to eval(), would
> > return the original object state saved in the pickle.
>
> Doesn't pickle.loads just do what you need ? e.g.:
>
> >>> pickled = file('test.dat', 'rb').read()
> >>> obj = eval('pickle.loads(%r)'%pickled)
> >>> obj
> <__main__.MyClass instance at 0xb7bfb76c>
> >>> obj.a, obj.b, obj.done
> (1, 2, 1)
Er... Touché :)
- What year did World War II finish?
- Same year the Potsdam Conference was held.
- When was that?
- The year World War II finished.
I should have stated that I need an *explicit* string...
Gabriel Genellina
Softlab SRL
--
http://mail.python.org/mailman/listinfo/python-list
different binding behavior
It seems to me that the following behavior of python (2.4.1) is inconsistent: >>> a=1 >>> b=a >>> a+=1 >>> b 1 >>> a 2 >>> a=[1,2] >>> b=a >>> b+=[3] >>> a [1, 2, 3] >>> b [1, 2, 3] Why was it implemented like this?? Best regards, Gabriel. -- /---\ | Any intelligent fool can make things bigger, more complex,| | or more violent. It takes a touch of genius - and a lot of courage - | | to move in the opposite direction. (Einstein) | \---/ -- http://mail.python.org/mailman/listinfo/python-list
combine doxygen and doc-strings?
Is there a way to combine doxygen comments, like this one ## Documentation for a function. # @var a - variable # More details. def func( a ): pass with the doc strings, like this one def func( a ): """ Documentation for a function. More details. """ pass ? Obviously, one would like to write the documentaion only once. Best regards, Gabriel. -- /---\ | Any intelligent fool can make things bigger, more complex,| | or more violent. It takes a touch of genius - and a lot of courage - | | to move in the opposite direction. (Einstein) | \---/ -- http://mail.python.org/mailman/listinfo/python-list
Re: different binding behavior
> We've just had a HUGE thread arguing about this behaviour, just three or > five days ago. Let's not start it again. ok, could you please point me to it? > In a nutshell, the behaviour is because ints are immutable and can't be > changed in place, and lists are mutable and can be changed in place. > > Imagine that ints could be changed in place. Then you could do this: i don't see why there should be only one instance of Int with the value 0. But if all this has already been debated (and, apparently, my point didn't succeed), there is no need to discuss all this over again. In any case, thanks a lot for your response and summary. Best regards, Gabriel. -- /---\ | Any intelligent fool can make things bigger, more complex,| | or more violent. It takes a touch of genius - and a lot of courage - | | to move in the opposite direction. (Einstein) | \---/ -- http://mail.python.org/mailman/listinfo/python-list
ownership problem?
Is it correct to say that the typical ownership problem, which frequently arises in C++, does not occur normally in Python? Best regards, Gabriel. -- /---\ | Any intelligent fool can make things bigger, more complex,| | or more violent. It takes a touch of genius - and a lot of courage - | | to move in the opposite direction. (Einstein) | \---/ -- http://mail.python.org/mailman/listinfo/python-list
Re: ownership problem?
> the problem isn't determining who owns it, the problem is determining > who's supposed to release it. that's not a very common problem in a that's about what i meant. i think, in c++, the "ownership problem" means the problem to determine who and when is to delete an object, or to keep track thereof. The object could be something as simple as a list element. Best regards, Gabriel. -- /---\ | Any intelligent fool can make things bigger, more complex,| | or more violent. It takes a touch of genius - and a lot of courage - | | to move in the opposite direction. (Einstein) | \---/ -- http://mail.python.org/mailman/listinfo/python-list
