473,553 Members | 2,934 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why does this code crash python?

I am trying to make a program that will basically simulate a chess
clock in python. To do this I have two threads running, one that
updates the currently running clock, and one that watches for a
keypress. I am using the effbot Console module, and that is where I get
the events for the keypresses. But when I press space it crashes
shortly after. The program stops, the Console closes, and windows says
that the program pythonw.exe has had an unexpected reason to shut down.
I am using python2.5.

If there is a simpler way to do this ( I tried without threads but had
some problems with the Console module giving me input right and still
letting the timer display count down ) I would like to know about it. I
am not a very good programmer, and don't have much experience with
python

note: A chess clock is two timers that count down from a set time, and
when you start one of the timer the other stops.

Code below:

import time
import Console
from threading import Thread

c = Console.getcons ole()

turn = 0

class timer (Thread):
def run ( self ):
global turn
oldTime = [time.time(), time.time()]
timeLeft = [260, 260]

go = True
while go:
newTime = time.time()
timeLeft[turn] -= newTime - oldTime[turn]
oldTime[turn] = newTime
minutes = [str(int(timeLef t[0]//60)),
str(int(timeLef t[1]//60))]
seconds = [str(timeLeft[0]%60)[0:5],
str(timeLeft[1]%60)[0:5]]

if float(seconds[0]) < 10: seconds[0] = '0' +
seconds[0][:-1]
if float(seconds[1]) < 10: seconds[1] = '0' +
seconds[1][:-1]

c.text(3,3,minu tes[0] + ':' + seconds[0])
c.text(12,3,min utes[1] + ':' + seconds[1])

time.sleep(.1)

class eventMonitor (Thread):
def run ( self ):
global turn
go = True
while go:
event = c.peek()
if event != None:
c.get()
if event.type == 'KeyPress':
if event.keycode == 32:
if turn == 1: turn = 0
if turn == 0: turn = 1
c.text(10,20,'1 ')

timer().start()
eventMonitor(). start()

Nov 11 '06 #1
10 2462
My*****@gmail.c om wrote:
I am trying to make a program that will basically simulate a chess
clock in python. To do this I have two threads running, one that
updates the currently running clock, and one that watches for a
keypress. I am using the effbot Console module, and that is where I get
the events for the keypresses. But when I press space it crashes
shortly after. The program stops, the Console closes, and windows says
that the program pythonw.exe has had an unexpected reason to shut down.
I am using python2.5.
Try not (re)using an object created in a certain thread in another thread.
You're creating a console object "c" and use it in both threads.

Try creating the console object for each thread by itself,
i.e. remove the global "c = Console.getcons ole()" and replace
it by a getconsole() inside each thread class.

I don't have the Console module so I don't know if it fixes things
for you, but give it a try :)

--Irmen
Nov 11 '06 #2
On Nov 11, 11:28 am, Irmen de Jong <irmen.NOS...@x s4all.nlwrote:
You're creating a console object "c" and use it in both threads.

Try creating the console object for each thread by itself,
i.e. remove the global "c = Console.getcons ole()" and replace
it by a getconsole() inside each thread class.

I don't have the Console module so I don't know if it fixes things
for you, but give it a try :)
Well, I tried that, and it did something. It made it so the space bar
switched the clock once, but not a second time. And it still crashed,
but not always at the same time, sometimes it would do it the second
time I hit the space bar, sometimes before I hit it the first time, but
always when i did something that would generate a Console event (moving
the mouse or something). So, I thought it had something to do with
Console not working well with threads, so I took it completely out of
threads and had just the event checking loop run by itself, and it
still crashed. So apparently I am using the Console events wrong. I am
going to try and find some examples online on how to watch for events
with it, but if worse comes to worse I can try and use keyboard hooks,
I've looked at those before, and they might work better.

--Mythmon

Nov 11 '06 #3
In article <11************ **********@h54g 2000cwb.googleg roups.com>,
My*****@gmail.c om wrote
>Well, I tried that, and it did something. It made it so the space bar
switched the clock once, but not a second time. And it still crashed,
but not always at the same time, sometimes it would do it the second
time I hit the space bar, sometimes before I hit it the first time, but
always when i did something that would generate a Console event (moving
the mouse or something). So, I thought it had something to do with
Console not working well with threads, so I took it completely out of
threads and had just the event checking loop run by itself, and it
still crashed. So apparently I am using the Console events wrong. I am
going to try and find some examples online on how to watch for events
with it, but if worse comes to worse I can try and use keyboard hooks,
I've looked at those before, and they might work better.
Dear Pythonauts,

I usually lurk on the comp.lang.pytho n newsgroup. I'm not an expert
in the slightest, but I have had a growing feeling that there's
something definitely lacking in the concurrency aspects of Python. It
is the same problem with Java. Forgive me if I don't know the right
vocabulary, but Python concurrency seems to be exposed at too "low a
level". It's like assembler: it's all _possible_ to implement, but in
practise it's very complicated and fragile, glitchy, and really
difficult to extend. Like programming in Dartmouth BASIC with just
conditionals and "goto" instructions, before structured programming.

A higher-level system of concurrency, not based on monitors and
locks and great programmer discipline, will ultimately require making
"Python 3000" a reality.

In the meantime, is there anywhere, or any thing, that discusses the
various concurrency options related to Python? There's Stackless Python
(which I can't make head or tail of; I have been unable to find any
lucid overview, or genuine explanation of the purpose of the design.) I
know that there's a package for an Erlang system for Python, somewhere
("Parnassus" probably). There's probably a Py-CSP somewhere too. Lots
of trees, but where's the Wood?

Where are concurrency/distributed models compared and discussed?

With kind regards,

Sandy
--
Alexander Anderson <ju**********@a lma-services.abel.c o.uk>
(Yorkshire, England)

Where there is no vision, the people perish.
Nov 11 '06 #4
Sandy wrote:
I usually lurk on the comp.lang.pytho n newsgroup. I'm not an expert
in the slightest, but I have had a growing feeling that there's
something definitely lacking in the concurrency aspects of Python.
the culprit in this case appears to be Microsoft's console library,
though. I'm pretty sure that's not written in Python.

</F>

Nov 11 '06 #5


On Nov 11, 3:23 pm, Dennis Lee Bieber <wlfr...@ix.net com.comwrote:
I have no knowledge of Console, but under Windows I was able to hack
this (see bottom of post) together using only one non-portable library
-- msvcrt. Oh, and an ActiveState 2.4 build. I'm not touching 2.5 until
a lot of 3rd party stuff is rebuilt and installers are available.
And here I am thinking this was going to be an easy project. I haven't
had a chance to work on this since my last message, but that example
should be a good thing, since now i have an example of how threads
/should/ be done. I was pretty much just guessing so far.
>
newTime = time.time()
timeLeft[turn] -= newTime - oldTime[turn] I'd duplicated this form, but it is wrong... when the clock swaps it
will immediately decrement the current clock by the difference since it
was last updated!
if float(seconds[0]) < 10: seconds[0] = '0' +
seconds[0][:-1]
if float(seconds[1]) < 10: seconds[1] = '0' +
seconds[1][:-1] I've not handled leading 0s on the seconds field (I tried, but can't
figure out how to specify zero-filled field width for floats -- works
for integers)
I ran into the same problem, thats why I did it the way I did, instead
of continuing to wrestle with python's string formatting.
go = True
while go: Why define "go" when it never changes
Whenever I make infinite loops, I put in a control variable so I could
stop it if I want, which I was planning on doing, when the time runs
out or something like that.

>
Note that I lock access to timeLeft and side to ensure they don't
change in the middle of access; may not have been critical, but why risk
it (and if the code gets expanded so the changes take more time -- or
multiple look-ups using side).

getch() doesn't seem to return a value for <ctrl-c>, so I used
<ctrl-z>

Uh, it also updates the time with an invalid negative before it
exits <G>
Now to see if I can get this to work for my self with an example. This
is more a learning project than something that has to be done.

Nov 12 '06 #6
<My*****@gmail. comschrieb
I am trying to make a program that will basically simulate
a chess clock in python. ...
... it crashes shortly after.
Can't help you on why it crashes, but
>
class eventMonitor (Thread):
def run ( self ):
[snipped]
if event.keycode == 32:
if turn == 1: turn = 0
if turn == 0: turn = 1
looks wrong to me. This is supposed to switch between the
players (0 and 1), but the first if changes turn to 0, the
second changes it immediately back to 1.

I'd do:
if turn == 1: turn = 0
else: turn = 1

HTH
Martin
Nov 12 '06 #7
Sandy wrote:
>
A higher-level system of concurrency, not based on monitors and
locks and great programmer discipline, will ultimately require making
"Python 3000" a reality.
It would surprise me if Python 3000 introduced anything substantially
more than what Python 2.x provides in the area of concurrency.
In the meantime, is there anywhere, or any thing, that discusses the
various concurrency options related to Python? There's Stackless Python
(which I can't make head or tail of; I have been unable to find any
lucid overview, or genuine explanation of the purpose of the design.)
What about this introduction... ?

http://members.verizon.net/olsongt/s...stackless.html
I know that there's a package for an Erlang system for Python, somewhere
("Parnassus" probably). There's probably a Py-CSP somewhere too. Lots
of trees, but where's the Wood?
Here are some fairly similar projects in Python:

http://kamaelia.sourceforge.net/
- a way of making general concurrency easy to work with, and fun

http://candygram.sourceforge.net/
- a Python implementation of Erlang concurrency primitives

http://www.python.org/pypi/parallel
- process forking and channel-based communication (using pickles)
Where are concurrency/distributed models compared and discussed?
In the following article and comments there are some opinions expressed
on Python concurrency (along with the usual dose of Ruby vapourware
promotion):

http://www.oreillynet.com/onlamp/blo...ncurrency.html

Meanwhile, the topic has been discussed on python-dev:

http://mail.python.org/pipermail/pyt...er/056801.html

That discussion led to a description of something which isn't so far
from parallel/pprocess, at least:

http://mail.python.org/pipermail/pyt...er/056829.html

Other searching yielded this interesting paper about PyPy and "hardware
transactional memory":

http://portal.acm.org/citation.cfm?i...FTOKEN=6184618

Paul

Nov 12 '06 #8
My*****@gmail.c om wrote:
>...
>> if float(seconds[0]) < 10: seconds[0] = '0' +
seconds[0][:-1]
if float(seconds[1]) < 10: seconds[1] = '0' +
seconds[1][:-1] I've not handled leading 0s on the seconds field (I tried, but can't
figure out how to specify zero-filled field width for floats -- works
for integers)

I ran into the same problem, thats why I did it the way I did, instead
of continuing to wrestle with python's string formatting.
For this portion, you could quite simply:

totalsecs = int(whatever)
print '%02d:%02d' % divmod(totalsec s, 60)

Or, depending on your leading zero requirements:

totalsecs = int(whatever)
print '%2d:%02d' % divmod(totalsec s, 60)

--Scott David Daniels
sc***********@a cm.org
Nov 13 '06 #9
Sandy wrote:
....
Lots of trees, but where's the Wood?

Where are concurrency/distributed models compared and discussed?

I don't know about wood, but you can find a shrubbery[*] called Kamaelia
sitting here:

* http://kamaelia.sourceforge.net/Home

A basic (albeit now aging) tutorial as to how to take some existing code and
create components which can be used is here:
*
http://kamaelia.sourceforge.net/cgi-...eid=1113495151

Perhaps usefully, there's an overview of Kamaelia in this whitepaper:
* http://www.bbc.co.uk/rd/pubs/whp/whp113.shtml

It does miss out work from the past 18 months work since it was written
though.

Also, every single example you see here:
* http://kamaelia.sourceforge.net/Cookbook.html

Is rather heavily parallel, except we just call our units of execution
components, components then talk in a CSP style fashion. The problem
you've *REALLY* got is making things accessible to the average developer.

That's the target audience for Kamaelia. ( If it doesn't work for that kind
of person, it's a conceptual bug in the system. )

As a result we normally refer to components being really simple,
communicating with the outside world via inboxes and outboxes (think
a person at a desk with some in-trays and out-trays).

Why? Because this is directly analogous to the ideas in both CSP *and* Unix
pipelines - the latter has been long understood by unix people as a way of
making it easier to build systems, the former understood largely by people
interested in parallelism as a good mechanism.

It also provices a nice route for development of new components - you
simply solve the core of the problem you wanted to solve, and then
remove the inputs back to inboxes and remove outputs back to outboxes.
It doesn't work for every class of problem, but does for a suprising
number.

We're in the process of revamping the website at the moment (it's November).
But for the moment, a simple tutorial on how the core concurrency tools in
Kamaelia fundamentally work is here:
* http://kamaelia.sourceforge.net/MiniAxon/

(The tutorial was originally written for a pre-university who'd learnt
python the previous week)

One interesting fact though - we have an application for collaborative
whiteboarding where each whiteboard is both a client & server, and they
can form a collaboration tree - whereby everything scribbled and said (each
whiteboard contains an audio mixer) is distributed to everyone connected in
a P2P like fashion. It's a classic example of a desktop application with a
small twist, and was written because we needed it.

The reason it's interesting is because it's highly parallel, with around
70 active components normally. *IF* the baseclass was changed to put
the generators in seperate threads, and ran under a Python VM that could
actually make the threads utilise seperate CPU's effectively (as allegedly
the IronPython VM does), then you'd be able to utilise a 60, 70 odd
multicore CPU with no change to the application code.

It's a nice example of a real world application written to solve a specific
need (we split the team multisite and needed an audio & scribbling based)
collaboration tool which is able to work effectively on existing hardware
systems, and *SHOULD* be trivially scalable to massively multicore systems
as VMs and CPUs become available, with no real change to the application
code. (Small change to Axon - our concurrency mechanism would be needed as
noted above. Obviously at the moment that change makes no sense to us)

It's also interesting because it was simpler to write due to the way we
make concurrency available (by thinking in terms of components that form
pipelines & graphlines), rather than despite using concurrency. (The initial
version took around 3 days)

If you want more detail on the whiteboard, there's been a tutorial in the
past month's Linux Format (ie December issue).

If you're interested in discussing anything concurrency related, and need a
forum to do so, you're more than welcome to use the Kamaelia mailing list
for doing so.

Kamaelia's hardest core goal is to make concurrency actually USEFUL for the
average developer. (though we tend to target maintenance over initial
development - which doesn't always makes life easier initially) That said,
we seem to be getting somewhere.
There's Stackless Python (which I can't make head or tail of; I have been
unable to find any lucid overview,
Finally, if the descriptions you find on the Kamaelia website don't make
sense to you, PLEASE tell us. I consider that as much of a bug as anything
else. (and we can't know that without being told)

Regards,
Michael.
--
Kamaelia Project Lead/Dust Puppy
http://kamaelia.sourceforge.net/Home
http://yeoldeclue.com/blog
[*] (yes, it's a deliberate mispelling of Camellia, which is a shrubbery,
rather than a backronym)

Nov 17 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1355
by: Fabien SK | last post by:
Hi, I wrote a plugin for Visual C++ 6 that uses Python 2.2 (it worked perfectly for months). I just installed Python 2.3, and recompiled my plugin, and now it crashes. My plugin do the following things: Py_Initialize(); LoadLibrary("pythoncom23.dll"); typedef PyObject* (*CONVERT_PROC)(IUnknown *punk, REFIID riid, BOOL
6
3004
by: Juho Saarikko | last post by:
The program attached to this message makes the Python interpreter segfault randomly. I have tried both Python 2.2 which came with Debian Stable, and self-compiled Python 2.3.3 (newest I could find on www.python.org, compiled with default options (./configure && make). I'm using the pyPgSQL plugin to connect to a PostGreSQL database, and have...
1
1750
by: Daniele Varrazzo | last post by:
Hi everybody, i'm experiencing crashing of the apache process when a mod_python handler access the properties "boundary" and "allowed_xmethods" of the request argument. This prevents the use of some interactive remote debuggers (such ActiveState's) that try to read the contents of the variables in the namespace and graphically present them...
0
998
by: Stormbringer | last post by:
I am using latest python 2.4 under Windows. I have a file where I have a bunch of functions, but none with a special name and nothing outside the functions, no import etc In the main module all works fine if I don't import that file. The moment I import it nothing happens but I get a crash later on when I call a pyopengl function. If I...
1
1969
by: klaus.roedel | last post by:
Hi @all, I've implement a python application with boa constructor and wx.python. Now I wanted to add a help to my application. I found the helpviewer, where it is very easy to open a helpbook. So I've create an helpbook with boa constructor and then I open the book with the helpviewer. That's all no problem. It works fine, but when I open...
13
2918
by: python | last post by:
hello and thanks for reading this, i have been a dos/windows user using some form of the basic language for 30 years now. i own and run a small programming company and there is one feature that keeps me in the windows/basic world. while i will agree that it has not evolved well, it does have one awesome feature that i have yet to see...
34
4439
by: NewToCPP | last post by:
Hi, Why does a C/C++ programs crash? When there is access to a null pointer or some thing like that programs crash, but why do they crash? Thanks.
4
1623
by: Kevin Walzer | last post by:
I'm using a build of Python 2.5.1 on OS X 10.5.1 that links to Tk 8.5. Trying to test PIL with this new build, Python barfs when trying to display an image in a Tkinter Label. Here is my sample code: --- from Tkinter import * import Image, ImageTk root = Tk()
162
10110
by: Sh4wn | last post by:
Hi, first, python is one of my fav languages, and i'll definitely keep developing with it. But, there's 1 one thing what I -really- miss: data hiding. I know member vars are private when you prefix them with 2 underscores, but I hate prefixing my vars, I'd rather add a keyword before it. Python advertises himself as a full OOP language,...
0
7568
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7492
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7772
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7526
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
3537
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3525
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1990
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1106
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
808
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.