How to run a process and quit after the script is

2019-08-13 08:19发布

问题:

I have asked a question how to run a clipboard clearing command from python, and I got a good answer for that:

subprocess.run("xclip",stdin=subprocess.DEVNULL)
subprocess.run(["xclip","-selection","clipboard"],input="")

This seem to work in python, but there is a problem, it leaves the process open. Actually it opens 2 processes, one xclip and one with xclip -selection clipboard parameters.

And it seems like they are zombie processes, they remain there indefinitely, until you copy-paste something again. After that both of them dissapear.

So I have run the script from an USB drive's directory, and it doesn't let you remove the USB drive, it says "USB drive busy", until the processes don't close.

So either I copy something new into the clipboard, otherwise the process remains there indefinitely, like a zombie.

Is it possible to just close the process after the python script ends? Since there is no reason for that process to remain open after the python script has ran.

回答1:

I'd have to read xclip's source to see if the parent (your direct child) waits until the selection has been claimed to exit. If not, you would race with the actual work if you killed anything. You can use xsel -c (as was suggested in the other question); to solve just the unmounting problem, you can simply change the current directory of the child:

subprocess.run("xclip",stdin=subprocess.DEVNULL,cwd="/")