0

I am trying to execute the bash script while :; do afplay beep.wav ; done command from a python script, but be able to kill it afterwards.

I tried:

process = subprocess.Popen("exec while :; do afplay %s ; done" % fileName, shell=True, executable='/bin/bash')

as this answer suggests, but the above doesn't work for me. (The script doesn't run.)

How can I run while :; do afplay beep.wav ; done from python and kill it at any point after it is started?


EDIT: just noticed that exec >(while :; do afplay %s; done) will launch the script, but now process.kill() won't kill it.

Community
  • 1
  • 1
theonlygusti
  • 11,032
  • 11
  • 64
  • 119
  • 2
    Type `help exec` instead of `man exec`, since `exec` is a builtin. Then you'll see that `exec` executes _commands._ If you think about it a little bit, it doesn't make sense to `exec` non-external commands `;)`. What are you trying to do? – gniourf_gniourf Dec 27 '16 at 13:38
  • @gniourf_gniourf I am trying to execute the `while :; do afplay beep.wav ; done` command from a python script, but be able to kill it afterwards. [This answer](http://stackoverflow.com/a/13143013/3310334) shows an easy way to kill a bash script from python, and I tried to copy it but it didn't work. – theonlygusti Dec 27 '16 at 13:40
  • Then make all this clear in your question! You need to heavily edit your question!!! – gniourf_gniourf Dec 27 '16 at 13:42
  • OP, be serious, `exec >(...)` is not what you want at all, it's not even semantically correct. – gniourf_gniourf Dec 27 '16 at 13:58
  • I tried it with the accepted answer in the question you linked, and it works well, without `exec` and other horrible hack. What's your OS? – gniourf_gniourf Dec 27 '16 at 14:07
  • @gniourf_gniourf macOS. without exec, the while loop is killed but the process inside it continues until it's finished – theonlygusti Dec 27 '16 at 14:34

1 Answers1

1
os.killpg(os.getpgid(process.pid), signal.SIGINT)

this seemed to do the trick. I am killing the process group (os.killpg) instead of the sole process.

theonlygusti
  • 11,032
  • 11
  • 64
  • 119