Reputation: 4085
I'm using Python 2.6 on linux.
I have a run.py script which starts up multiple services in the background and generates kill.py to kill those processes.
Inside kill.py, is it safe to unlink itself when it's done its job?
import os
# kill services
os.unlink(__file__)
# is it safe to do something here?
I'm new to Python. My concern was that since Python is a scripting language, the whole script might not be in memory. After it's unlinked, there will be no further code to interpret.
I tried this small test.
import os
import time
time.sleep(10) # sleep 1
os.unlink(__file__)
time.sleep(10) # sleep 2
I ran stat kill.py
when this file was being run and the number of links was always 1, so I guess the Python interpreter doesn't hold a link to the file.
As a higher level question, what's the usual way of creating a list of processes to be killed later easily?
Upvotes: 3
Views: 1122
Reputation: 67010
Don't have your scripts write new scripts if you can avoid it – just write out a list of the PIDs, and then through them. It's not very clear what you're trying to do, but creating and deleting scripts sounds like too much fragile magic.
To answer the question: Python compiles all of the source and closes the file before executing it, so this is safe.
In general, unlinking an opened file is safe on Linux. (But not everywhere: on Windows you can't delete a file that is in use.)
Note that when you import
a module, Python 2 compiles it into a .pyc
bytecode file and interprets that. If you remove the .py
file, Python will still use the .pyc
, and vice versa.
Upvotes: 2
Reputation: 61625
As a higher level question, what's the usual way of creating a list of processes to be killed later easily?
I would put the PIDs in a list
and iterate over that with os.kill
. I don't see why you're creating and executing a new script for this.
Upvotes: 1
Reputation: 22781
IIRC(!): When on *nix an unlink only removes the name in the filesystem, the inode is removed when the last file handle is closed. Therefore this should not induce any problems, except python tries to reopen the file.
Upvotes: 1
Reputation: 11255
Just don't call reload!
There's no need for Python to hold locks on the files since they are compiled and loaded at import time. Indeed, the ability to swap files out while a program is running is often very useful.
Upvotes: 1
Reputation: 86768
Python reads in a whole source file and compiles it before executing it, so you don't have to worry about deleting or changing your running script file.
Upvotes: 0