Ammad
Ammad

Reputation: 4235

/tmp directory clean up after python script execution

I am using python and invoking external utility "send-data" in my .py file as shown below,

cmd=['send-data', '-f', file_name]
res = subprocess.run(cmd,stdout=subprocess.PIPE, input=b'a')

I have no control over send-data utility and it creates file under /tmp directory with random name as shown below in the response string.

'a)bort, e)dit or s)end? send-data: the file remains in /tmp/pbadLWX .'

Wondering how can i delete the file "pbadLWX" under /tmp folder after each execution? Considering every time file name could be different?

Upvotes: 0

Views: 743

Answers (1)

a_guest
a_guest

Reputation: 36339

You can parse the output via re module and then delete the file via os.remove:

import os
import re

f_name = re.search(r'\s(/tmp/[a-zA-Z]+)\s', res.stdout.decode('ascii')).group(1)
os.remove(f_name)

Upvotes: 1

Related Questions