我不确定如何使用错误检查,并且还要返回页面内容。有什么想法吗?
我正在尝试获取最旧的文件,然后获取其内容并将其发送到标题中,然后阅读网页响应。
Python 2.7。
#!/usr/bin/env python
import os, shutil, time
import urllib, urllib2, cookielib
import serial
fromdir = '/home/pi/scripts/data'
todir = '/home/pi/scripts/dataProcessed'
watch_path = "/home/pi/scripts/data/"
url='http://localhost/data'
fetch_timeout = 10
wait_time = 60
while not sum((len(f) for _, _, f in os.walk(watch_path))):
print 'No Files present in "' + (watch_path) + '". Checking again in %s' % (wait_time) + ' seconds...'
time.sleep(wait_time)
else:
print 'Files present'
oldest = ''
oldestAge = 0
for file in os.listdir(watch_path):
age = os.stat(watch_path + file).st_mtime
if age > oldestAge:
oldestAge = age
oldest = file
print oldest
with open(fromdir + "/" + oldest,'r') as f:
output = f.read()
print output
headers ={'data': output,
'User-Agent': 'Mozilla/5.0'}
from urllib2 import Request, urlopen, URLError, HTTPError
#data = urllib.urlencode(values)
#req = urllib2.Request(url, data, headers)
req = Request(url, "Data", headers)
try:
response = urlopen(req)
except HTTPError as e:
print 'The server couldn\'t fulfill the request.'
print 'Error code: ', e.code
except URLError as e:
print 'We failed to reach a server.'
print 'Reason: ', e.reason
else:
print "all ok"
print response
#shutil.move(fromdir + '/' + oldest, todir)