繁体   English   中英

如果被杀死,则重新启动 Python 脚本

[英]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")

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM