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?
            Asked
            
        
        
            Active
            
        
            Viewed 1,071 times
        
    1
            
            
         
    
    
        Etan Reisner
        
- 77,877
- 8
- 106
- 148
 
    
    
        bobdxcool
        
- 91
- 1
- 1
- 10
- 
                    How would you stop the script without python being involved? – Etan Reisner Oct 22 '14 at 02:57
- 
                    Why are you calling `sudo` twice? Once should suffice. – tripleee Oct 22 '14 at 03:12
- 
                    1And why are you using Python to run a shell to run Bash to run Python? – tripleee Oct 22 '14 at 03:13
- 
                    And which Python script do you want to stop? The parent or the grand-grandchild? – tripleee Oct 22 '14 at 03:21
1 Answers
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