1

Hi I am using subprocess.call("sudo bash /home/pi/Desktop/switchtest.sh", shell=True) to start a python script. The content of switchtest.sh is sudo python /home/pi/Desktop/switch1.py. Now, using the same subprocess call how can I stop the python script from running? Or is there any other way of stopping this?

Etan Reisner
  • 77,877
  • 8
  • 106
  • 148
bobdxcool
  • 91
  • 1
  • 1
  • 10

1 Answers1

0

subprocess.call is synchronous, so it will not return until your script is finished. you can use popen to do it async:

p = subprocess.Popen("sudo bash /home/pi/Desktop/switchtest.sh", shell=True)
# do something else, polling or waiting perhaps
# now kill it
p.terminate()
Andrew Luo
  • 919
  • 1
  • 5
  • 6
  • i wanted to start the other program from my main program. So, I call subprocess to start the program from one function, and stop it in another function in my main program. – bobdxcool Oct 22 '14 at 04:10
  • @bobdxcool: In general, `p.terminate()` might kill only the immediate child process, leaving grandchildren running. See [How to terminate a python subprocess launched with shell=True](http://stackoverflow.com/q/4789837/4279) in that case. – jfs Oct 22 '14 at 06:34
  • As an additional improvement, you should omit the unnecessary and wasteful `shell=True`. – tripleee Oct 22 '14 at 08:02