Reputation: 145
I am working on a small IRC bot to do a few simple things, and I find it annoying that every time I want to test any changes I have to find the process, kill it, start the bot again and wait for it to connect. I tried to make a command for it that reloaded the Python file so any changes would be saved and I could edit it more easily that way, but when using this code to try and reload:
def reload(self, *args):
reload(pybot)
return "Reloaded!"
I get this error:
TypeError: reload() argument must be module
The only files this bot uses is its own, pybot.py
, the iblib module and a few other python libraries.
What my question is, that is there any way to make Python reload the file it is currently using, and not a module?
Upvotes: 3
Views: 3313
Reputation: 50190
Instead of reloading the module, you can start a new process (replacing the old) with os.execl or os.execv:
os.execl("/path/to/pybot.py", "pybot.py")
But I think you'd be better off leaving this out of pybot. Just have your program save its PID (available via os.getpid()) into a file; then write a separate script to read the PID, kill and relaunch your program whenever you want. On a unix system it could be as simple as this:
#!/bin/sh
kill -9 `cat pybot.pid`
python pybot.py &
Upvotes: 2
Reputation: 385920
According to the error, "pybot" doesn't refer to a module. If the name of the module you want to reload is in fact "pybot", your code will work if at some point prior you successfully did "import pybot".
In the following example, assume "pybot.py" is a module that defines the variable version
:
>>> import pybot
>>> print pybot.version
1.0
>>> # edit pybot.py to change version to 1.1
...
>>> reload(pybot)
<module 'pybot' from 'pybot.py'>
>>> print pybot.version
1.1
Upvotes: 4
Reputation: 1138
Builtin function reload(module) reloads a MODULE that must have been successfully imported before
So what I can suggest:
Upvotes: 0