Search code examples
pythoncmdrestart

Restart a Python script if killed


I write this post because I have not found solutions for my specific case. I refer to this article, which, however, did not work for me on Windows 10 version 1909.

I programmed a "python_code_a.py" script that has the task of uploading, one at a time, all the images contained in a local folder on a converter server and to download them, always one at a time, from the server to my PC in another folder. How the script works depends on the server, which is public and not owned by me, so it is possible, approximately every two and a half hours, that the script crashes due to an unexpected connection error. Obviously, it is not possible to consider the fact that he stays all day observing the Python shell and acting in case the script stops. As reported in the article above, I compiled a second file with the name "python_code_b.py", which had the task of acting in case "python_code_a.py" had stopped by restarting the latter. When I try to get it to run from the "python.exe" CMD, however, the latter responds to the input with "...", nothing else.

I attach a general example of "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(
)

How can I solve it?


Solution

  • you can use error capturing:

      while photosindex<"number of photos in folder":
        try:
          @Your code
        except:
          print("Something else went wrong")
    

    https://www.w3schools.com/python/python_try_except.asp