0

I made a script which plays a video file by using subprocess.run().

import subprocess

DATA_DIR = 'path\\to\\video\\files'
MEDIA_PLAYER = 'path\\to\\my\\media-player'

# returns path of random video file
p = chooseOne(DATA_DIR)
print('playing {}'.format(p))

# runs chosen path
subprocess.run([MEDIA_PLAYER, p])

But I would like to kill the python script running this code immediately after opening the child subprocess.

Is this possible? And if not, is there an alternative means of opening an external process using Python which would allow the script to terminate?

Note: I am using Python v3.6

1 Answer 1

2

Don't use subprocess.run; use os.execl instead. That makes your media player replace your Python code in the current process, rather that starting a new process.

os.execl(MEDIA_PLAYER, p)

subprocess.run effectively does the same thing, but forks first so that there are temporarily two processes running your Python script; in one, subprocess.run returns without doing anything else to allow your script to continue. In the other, it immediately uses one of the os.exec* functions—there are 8 different varieties—to execute your media player. In your case, you just want the first process to exit anyway, so save the effort of forking and just use os.execl right away.

Sign up to request clarification or add additional context in comments.

3 Comments

Excellent! So that is effectively replacing my python code in the current process, but the path is not being run properly due to spaces in the path's name. It is taking the last part of the path string and adding it to my home directory as the file path. Any idea how to fix that?
How are you setting the value of p?
I was actually successful using os.execv thanks to your help! See my other question on how I set the value of p. p stands for a path to a video file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.