我正在编写一个程序,该程序将测试网络连接是否有效,如果有,请运行我们的软件下载器。如果下载器中有可供下载的更新,它将自动下载并安装该更新。
import urllib3
from subprocess import Popen
import subprocess
def run_downloader():
return subprocess.Popen(['C:\ProgramFiles\PrecisionOSTech\Education\POSTdownloader.exe'])
def internet_on():
if urllib3.urlopen('http://216.58.192.142', timeout=1):
return True
else:
urllib3.URLError
return False
if internet_on == True:
run_downloader()
期望对程序进行活动连接测试并返回true或false。如果为true,则应运行下载程序。
当前,该程序没有错误运行,但在完成时未运行下载程序。我只能想象internet_on():方法没有按我的意愿返回true。如果我在方法外部运行subprocess.Popen行,则下载程序将按计划启动。
感谢您的协助!
谢谢
答案 0 :(得分:1)
应该是这样的:
import urllib.request
from subprocess import Popen
import subprocess
def run_downloader():
return subprocess.Popen(['C:\ProgramFiles\PrecisionOSTech\Education\POSTdownloader.exe'])
def ispageresponding():
response_status_code = urllib.request.urlopen("http://www.stackoverflow.com").getcode()
return response_status_code == 200:
if __name__ == '__main__':
if ispageresponding() == True:
run_downloader()
请注意,Internet连接函数在if语句中调用,并且不在同一函数内。另外,如果您使用的是python3,则应使用urllib.request lib。