[英]Restart a Python script if killed
我寫這篇文章是因為我還沒有為我的具體案例找到解決方案。 我參考了這篇文章,但是,它不適用於 Windows 10 版本 1909。
我編寫了一個“python_code_a.py”腳本,該腳本的任務是一次上傳一個轉換服務器上本地文件夾中包含的所有圖像,然后將它們從服務器下載到我的 PC,每次一個在另一個文件夾中。 腳本的工作方式取決於服務器,該服務器是公共的,不歸我所有,因此大約每兩個半小時,腳本有可能由於意外的連接錯誤而崩潰。 顯然,不可能考慮他整天觀察 Python shell 並在腳本停止的情況下采取行動的事實。 正如上面文章中所報道的,我編譯了另一個名為“python_code_b.py”的文件,它的任務是在“python_code_a.py”通過重新啟動后者而停止的情況下采取行動。 然而,當我嘗試讓它從“python.exe”CMD 運行時,后者以“...”響應輸入,僅此而已。
我附上“python_code_a.py”的一般示例:
processnumber= 0
photosindex= 100000
photo = 0
path = 0
while photosindex<"number of photos in folder":
photo = str('your_path'+str(photoindex)+'.png')
path = str('your_path'+str(photoindex)+'.jpg')
print ('It\'s converting: '+ photo)
import requests
r = requests.post(
"converter_site",
files={
'image': open(photo , 'rb'),
},
headers={'api-key': 'your_api_key'}
)
file= r.json()
json_output = file['output_url']
import urllib.request
while photosindex<'number of photos in folder':
urllib.request.urlretrieve( json_output , path )
print('Finished process number: '+str(processnumber))
break
photosindex= photosindex +1
processnumber= processnumber +1
print(
)
print('---------------------------------------------------')
print('Every pending job has been completed.')
print(
)
我該如何解決?
您可以使用錯誤捕獲:
while photosindex<"number of photos in folder":
try:
@Your code
except:
print("Something else went wrong")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.