Ad
How Can I Execute And Terminate Another Python Script In Current Python Script
I'm writing a code in python which reads a status(that is 'on') from txt file and then executes a python script (a.py) and if it reads 'off' from txt file,
I want to terminate a.py and start another script b.py.
so far, I am able to run a.py when status is 'on' but unable to close this script when status is 'off'.
Where I am wrong?
I am using subprocess library in Raspberry pi.
import subprocess as sp
while True:
file = open("status.txt", "r")#open txt file
status = file.read()#read the status of file
print(status)#print the status
time.sleep(2)
if status =='on':
extProc = sp.Popen(['python','a.py'])
elif status == off:
print("stop")
sp.Popen.terminate(sp.Popen(['python','a.py']))
Ad
Answer
You can try this:
import subprocess as sp
import time
procA = None
procB = None
while True:
file = open("status.txt", "r") # open txt file
status = file.read() # read the status of file
file.close()
print(status) # print the status
time.sleep(2)
if status == 'on':
if procB:
procB.terminate()
procB = None
if not procA:
procA = sp.Popen(['python', 'a.py'])
else:
if procA:
procA.terminate()
procA = None
if not procB:
procB = sp.Popen(['python', 'b.py'])
Ad
source: stackoverflow.com
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module
Ad