Python代码未执行
作者:互联网
我有以下从命令行执行的代码:
import cgi,time,os,json,sys,zipfile,urllib2
from os import curdir, sep
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from time import strftime
from poster.encode import multipart_encode, MultipartParam
from poster.streaminghttp import register_openers
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
try:
if self.path.endswith("/"):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write("<HTML> GET OK.<BR>")
return
return
except IOError:
self.send_error(404,'File Not Found: %s' % self.path)
def do_POST(self):
global rootnode
ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
if ctype == 'multipart/form-data':
query=cgi.parse_multipart(self.rfile, pdict)
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
file = query.get('file')
zfile = "C:\Users\VM1\Desktop\data.zip"
extract_path = "C:\Users\VM1\Desktop\data\\"
f = open(zfile, "wb")
f.write(file[0])
f.close()
self.wfile.write("POST OK. File received from VM Host")
print("File received from VM Host.")
print("Unzipping zip file")
unzip = zipfile.ZipFile(zfile)
unzip.extractall(extract_path)
print "Files extracted to " + extract_path
scan_path = '"C:\Program Files (x86)\AVG\AVG2012\\avgscana.exe" /repok /report=C:\Users\VM1\Desktop\\avg_scan_results.txt /scan=' + extract_path
os.system('"%s"' % scan_path)
self.write_json_report()
self.upload_json_report()
return
def write_json_report(self):
scan_results = open("avg_scan_results.txt", "r")
saved = sys.stdout
f = file('avg_report.json', 'wb')
sys.stdout = f
dict2 = {}
for line in scan_results:
if ".jpg" in line:
result = line.split('\\')
result_split = result[5].split(' ')
filename = result_split[0]
raw_status = result_split[3]
if "OK" in raw_status:
status = "Okay"
status_code = "0"
elif "Virus identified" in raw_status:
status = raw_status
status_code = "1"
dict2[filename] = {'FileName': filename, 'DateTime': strftime("%Y-%m-%d %H:%M:%S"), 'statusCode': status_code, 'Description': status}
print json.dumps(dict2)
sys.stdout = saved
f.close()
print ""
print "JSON report written"
json_zip = zipfile.ZipFile("avg_report.zip", "w")
try:
json_zip.write('avg_report.json')
finally:
json_zip.close()
return
def upload_json_report(self):
av_name = "AVG Free 2012"
av_version = ""
scan_results = open("avg_scan_results.txt", "r")
for line in scan_results:
if "Program version" in line:
version_split = line.split(', ')
program_version_full = version_split[0]
program_version_split = program_version_full.split(' ')
av_version = program_version_split[2]
register_openers()
datagen, headers = multipart_encode({"av_name": av_name, "av_version": av_version, "filename": "avg_report.zip", "content": open("avg_report.zip", "rb")})
request = urllib2.Request("http://" + self.client_address[0] + ":8080/", datagen, headers)
print "Uploading JSON report"
print urllib2.urlopen(request).read()
return
def main():
try:
server = HTTPServer(('', 8080), MyHandler)
print 'Server started..'
server.serve_forever()
except KeyboardInterrupt:
print 'KeyboardInterrupt received, shutting down server'
server.socket.close()
if __name__ == '__main__':
main()
除upload_json_report()外,其余功能均正常运行.显示字符串Uploading JSON report,但是后面的行不执行.我正在监听请求的服务器未收到任何信息.这里的代码有什么问题吗?如果是,那是什么问题,我该如何解决?提前谢谢了.
编辑:
我从该方法的以下几行创建了一个单独的客户端:
register_openers()
datagen, headers = multipart_encode({"av_name": av_name, "av_version": av_version, "filename": "avg_report.zip", "content": open("avg_report.zip", "rb")})
request = urllib2.Request("http://" + self.client_address[0] + ":8080/", datagen, headers)
print "Uploading JSON report"
print urllib2.urlopen(request).read()
这工作了.我对为什么相同的代码行无法在函数中感到困惑.
解决方法:
BaseHTTPRequestHandler维护一个单线程(和单进程)服务器.这意味着每个请求必须先完成执行,然后才能执行另一个请求.
从do_POST方法中调用upload_json_report函数.在运行时,您的服务器无法处理其他任何事情.但是然后就行了:
print urllib2.urlopen(request).read()
您实际上是在尝试将.zip文件上传到相同的端口8080.因此,upload_json_report正在等待do_POST完成,而do_POST正在等待upload_json_report完成,因此,它们永远不会停止等待.
顺便说一句,这解释了为什么它在服务器上运行(我假设它是多线程的,尽管您需要提供更多详细信息),以及为什么在使用单独的客户端执行它时它可以工作(它不等待自身完成) .
标签:http-post,python 来源: https://codeday.me/bug/20191201/2082768.html