# python透過subprocess來重啟程式 為了避免辨識程式出錯後,整台機器人就不再動作了,於是決定使用重啟的方式來做簡單的救援,當程式碰到錯誤的時候,就將整個程式重新啟動。本文將說明使用subprocess重新啟動程式,並且解決主程式當機後無法釋放資源的問題(**使用os.kill殺死自己**)。 > **但是使用這種方式無法使用ctrl+C 等方式中止程式,必須透過htop 來kill程式。** subprocess.run()執行cmd,直到cmd內容整個完成後主程式才會往下跑 subprocess.Popen()執行cmd,主程式同時會接著往下跑,不等待subprocess完成 主程式: inference.py ```python= import os import signal import subprocess import time def main(): print("Start to sleep") time.sleep(15) print("Sleep end") test= 1/0 #強制製造錯誤 if __name__=='__main__': try: main() except: program_path= os.path.realpath(__file__) subprocess.Popen('python3 {}'.format(program_path), shell=True) os.kill(os.getpid(), signal.SIGKILL)#kill self to prevent which can't release resource ``` ### 參考資料: os.kill: https://blog.csdn.net/xueruixuan/article/details/81100198 subprocess: https://docs.python.org/zh-tw/3.9/library/subprocess.html
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up