In my code I have a temporary file that I want to have removed either at the program end or if there is an abort via a click exception. I can't use tempfile.TemporaryFile
because the file could either be local or on a remote machine. Hence I thought registering a cleanup function via click.call_on_close
would be an elegant solution.
My problem now is: how do I get the filename into that cleanup callback?
This is what I got:
import click
import os
import tempfile
def remove_tmp_file(**kwargs):
# ??? somehow get the file name
if host == "localhost":
os.remove(tmp_file)
else:
delete_tmp_file_remote(tmp_file)
@click.command()
@click.pass_context
def main(...):
tmp_file = tempfile.mktemp(prefix="my_prefix_", dir="/tmp")
ctx.call_on_close(remove_tmp_file)
# do something with tmp_file
How can I pass information (stored in variables) from my main
function into this callback?