I've been tinkering with Twisted for the past few days, having picked up python less than a month ago. My first inclination was to play with something I know and use every day, IRC. I've gotten a basic IRC connection up and running thanks to the ircLogBot.py example.
I want to have some arbitrary code that runs whenever an IRC event (PRIVMSG/CTCP/JOIN/PART) is received, and for purposes of debugging I'd like to be able to make changes to that piece of code and then reload it without shutting down the whole script and reconnecting to the IRC server.
It doesn't have to be a solution that incorporates Twisted, as I do not fully understand it yet. Though I assume this is the sort of thing that twisted, being an event-driven framework, is likely designed to do well.
You could use a simple while loop: line = "Y" while line[0] not in ("n", "N"): """ game here """ line = input("Play again (Y/N)?")
The reload() method is used to reload a module. The argument passed to the reload() must be a module object which is successfully imported before.
Try to learn about Python data serialization. You would basically be storing the large file as a python specific, serialized binary object using python's marshal function. This would drastically speed up IO of the file. See these benchmarks for performance variations.
To stop code execution in Python you first need to import the sys object. After this you can then call the exit() method to stop the program from running. It is the most reliable, cross-platform way of stopping code execution. Here is a simple example.
Twisted has some built-in functionality in twisted.python.rebuild
which provides a more comprehensive implementation of Python's built-in reload
function. There are still some limitations, but its chief difference from Python's built-in reload is that it will find old instances of objects and replace their classes with the new version. (The main limitation is that you have to be aware that your instances may have old state that doesn't match with your current version of __init__
, if you've changed it, which is what rebuild.Sensitive
is for.)
If you want to make something really fancy and automatic, you can set up a file-system monitor that detects when files change, and re-load the associated modules with rebuild when it changes. On Linux, you can use Twisted's inotify
support for the change notifications, and on OS X, you can use cfreactor
along with the FSEvents
API via PyObjC. (I don't know which file alteration monitoring schemes work on win32 but it may be possible there as well.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With