如何解决 Python 应用程序未连接到 Internet 时无法在 www.googleapis.com 找到服务器

How to solve Unable to find the server at www.googleapis.com when not connected to the internet with a Python Application

我有一个桌面应用程序,由 python 制作,可作为独立应用程序运行,无需依赖互联网即可正常运行。仅连接到 Google Drive 应用程序需要互联网连接。

问题是,在 运行 应用程序上,当未连接到互联网时,应用程序会崩溃,因为它包含与互联网连接相关的导入语句。

什么有效: 在注释掉与互联网连接相关的导入语句时,应用程序在离线环境中正常执行。

什么不起作用: 当导入语句包含在代码中并且没有互联网连接时,应用程序就会崩溃。下面是一些伪代码。

main.py

from kivy.app import App
'''More import statements'''
....
....
from helper import Hi

class Hello(Hi):
'''Rest of the Code goes here'''
...
...
...

helper.py

'''If the device is not connected to the internet, the following internet import statements throw an error. These imports are needed to connect Google Drive.'''

from __future__ import print_function
import httplib2
import os, io

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
from apiclient.http import MediaFileUpload, MediaIoBaseDownload
try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None
import auth

class Hi:
pass
'''Rest of the Code goes here'''
...
...
...

期望: 需要一种方法使应用程序即使在没有互联网连接的情况下也能正常运行。如果没有互联网连接,警告用户连接到互联网以访问 Google 驱动器而不是简单地崩溃。

错误: httplib2.ServerNotFoundError: 无法在 www.googleapis.com

找到服务器

我了解 python 代码是从上到下读取的,应用程序崩溃是因为导入语句验证它没有连接到互联网。有没有办法让应用程序离线工作,而在线活动要求用户连接到互联网?

感谢你在这件事上的帮助。

reference 的帮助下解决了这个问题。问题不在于引用这些语句的函数是否存在导入语句。

解决方法如下:

helper.py

from __future__ import print_function
import httplib2
import os, io

from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
from apiclient.http import MediaFileUpload, MediaIoBaseDownload
try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None
import auth

import socket

class Hi:

    def is_connected():
        try:
        # connect to the host -- tells us if the host is actually reachable
            socket.create_connection(("www.google.com", 80))
            print("Connected to the internet, execute code.")
            self.fileUpload() #----- function is called, if host is reachable.
        except OSError:
            print("No internet, code not executed.")
        
   def fileUpload():
       # This is the function that requires the import statements
       ...
       ...