Russell Russell - 11 months ago 45
Linux Question

Is it safe to call os.unlink(__file__) in Python?

I'm using Python 2.6 on linux.

I have a script which starts up multiple services in the background and generates to kill those processes.

Inside, is it safe to unlink itself when it's done its job?

import os
# kill services
# 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
time.sleep(10) # sleep 2

I ran
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?


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.