How to modify a program while it's running?

Aaron Brady castironpi at gmail.com
Wed Dec 17 02:34:02 EST 2008


On Dec 16, 11:47 pm, Paul Rubin <http://phr...@NOSPAM.invalid> wrote:
> Joe Strout <j... at strout.net> writes:
> > So I'd like to restructure my app so that it can stay running and stay
> > logged in, yet I can still update and reload at least most of the
> > code.  But I'm not sure what's the best way to do this.  Should I move
> > the reloadable code into its own module, and then when I give my bot a
> > "reload" command, have it call reload on that module?  Will that work,
> > and is there a better way?
>
> If you are on Linux, an alternative might be to start a new version of
> your program in a separate process, then transfer the open connections
> from the old process to the new ones through Unix domain sockets.  The
> SCM_RIGHTS message lets you pass file descriptors around between
> processes.  I've never tried this myself but have always wanted to.  I
> think someone submitted a patch for Python's socket module a year or
> so ago to support that operation, but I don't know if it was accepted.
> You could always apply it yourself.
>
> Generally, trying to hot-patch code is messy and dangerous even in
> systems that were designed for it.

Sorry for the repeated posts, but sockets made me think of pickling.
(You can't pickle sockets.)

>>> class A: pass
...
>>> a= A()
>>> s= pickle.dumps( a )
>>> class A: pass
...
>>> pickle.loads( s )
<__main__.A instance at 0x00B53328>

So, 's' was unpickled to be an instance of a new class.  Probably not
the most elegant.  Just make sure the sockets are preserved in a
separate object.

For yet another option, exec the code, and assign it to a method in a
class.

>>> class A:
...     def f( self ): pass
...
>>> a= A()
>>> a.f()
>>> exec "def f( self ): print 'new f'"
>>> A.f= f
>>> a.f()
new f



More information about the Python-list mailing list