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

Jesse
  • 69
  • 1
  • 7

1 Answers1

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.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • 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? – Jesse Jul 05 '18 at 22:40
  • How are you setting the value of `p`? – chepner Jul 06 '18 at 13:03
  • I was actually successful using `os.execv` thanks to your help! **[See my other question](https://stackoverflow.com/questions/51201534/cannot-open-file-properly-in-vlc-with-pythons-os-execv-or-os-execl-on-windows)** on how I set the value of `p`. `p` stands for a _path to a video file_. – Jesse Jul 07 '18 at 19:08