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()
这有效。我很困惑为什么相同的代码行不能在该函数中工作。
I have the following code which is executed from the command line:
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()
The rest of the functions worked fine except for upload_json_report()
. The string Uploading JSON report
shows but the line after doesn't execute. My server which is listening for the request does not receive anything. Is there anything wrong with the code here? If yes, what is the problem and how do I solve it? Many thanks in advance.
EDIT:
I have created a seperate client with the following lines from the method:
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()
This worked. I'm confused as to why the same lines of codes could not work in the function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
BaseHTTPRequestHandler
维护一个单线程(和单进程)服务器。这意味着每个请求必须先完成执行,然后才能执行另一个请求。upload_json_report
函数是从do_POST
方法中调用的。当它运行时,您的服务器无法处理其他任何事情。但接下来:您实际上正在尝试将 .zip 文件上传到同一个端口 8080。因此,upload_json_report 正在等待 do_POST > 完成,而
do_POST
正在等待upload_json_report
完成,所以他们当然永远不会停止等待。顺便说一句,这解释了为什么它在您的服务器上工作(我假设它是多线程的,尽管您需要提供更多详细信息),以及为什么当您使用单独的客户端执行它时它可以工作(它是不等待自身完成)。
BaseHTTPRequestHandler
maintains a single-threaded (and single-process) server. This means that each request has to finish executing before another request can be executed.The
upload_json_report
function is called from within thedo_POST
method. While it is running, your server can't handle anything else. But then at the line:You are actually trying to upload the .zip file to the same port, 8080. Thus,
upload_json_report
is waiting fordo_POST
to finish, anddo_POST
is waiting forupload_json_report
to finish, so of course they will never stop waiting.Incidentally, this explains why it was working on your server (I assume it was multithreaded, though you'd need to provide more details), and why it works when you perform it using a separate client (it's not waiting for itself to finish).
我建议调试代码。为此,我将删除
print
语句,在urllib2.urlopen
方法调用之前添加pdb.set_trace
并运行脚本。一旦调试器接管,我会检查 url 是否是您期望的,尝试执行下一行并检查 urllib2.urlopen 返回的值是什么(响应代码、文本、 ETC)。这应该可以为您提供有关正在发生的情况的足够信息,并希望让您知道如何解决问题。I'd recommend to debug the code. To do that, I'd remove the
print
statements, addpdb.set_trace
just before theurllib2.urlopen
method call and run the script. Once the debugger takes over, I'd check that the url is the one that you expect, try to execute the next line and check that what's the value returned byurllib2.urlopen
(response code, text, etc). That should provide you enough information about what's going on and hopefully let you know how to fix the problem.urllib2.urlopen(...) 返回一个文件描述符对象,您必须读取该对象才能打印出响应。本质上,为了查看从服务器获得的响应,您需要执行
print urllib2.urlopen(request).read()
urllib2.urlopen(...)
returns a file descriptor object which which you must read to print out the response. Essentially in order to see what response its getting from the server you need to doprint urllib2.urlopen(request).read()
我的建议是在“urllib2.urlopen”行周围添加“try”“ except”,以查看是否引发任何异常。
通过打印的异常信息,您可能会找到一些线索。
My suggestion is to add "try" "except" around the "urllib2.urlopen" line, to see if any exception was raised.
with the printed exception information, you might have some clues.