The python method cannot be used in the process (python is attached to obtain network traffic), and python network traffic

Source: Internet
Author: User

The python method cannot be used in the process (python is attached to obtain network traffic), and python network traffic

In python, you can define a method and call it directly, but creating a thread for calling may cause failure. This phenomenon occurs most often when a com object is used for system operations and is called in the form of a thread.

The error message is syntax error. WMI returned a syntax error: you're probably running inside a thread without first calling pythoncom. CoInitialize [Ex] (no underlying exception)

After careful observation, the solution is provided in the exception prompt. Call the pythoncom. CoInitialize () method when running a thread. The monks used the WMI module in the program and tried to obtain some system information.

The cause of the exception (speculation) is the mechanism problem of com. Because the COM mechanism allows any two components to communicate with each other, you do not have to worry about the computer on which the operating system runs, or the language in which the component is compiled, this makes COM technology powerful. The purpose of initializing the COM environment is to make the APIs that call COM work normally, that is, to call CoInitialize or CoInitializeEX before the COM operation. Therefore, in the thread function, if you use a com object, you must call CoInitialize or CoInitializeEX, and use CoUninitialize to release the object when you exit.
Case:


c = wmi.WMI()interfaces = c.Win32_PerfRawData_Tcpip_NetworkInterface()print len(interfaces)rec = send = 0.0for t in interfaces:print t.Namerec += float(t.BytesReceivedPersec) / 1024 / 1024send += float(t.BytesSentPersec) / 1024 / 1024print rec, send

 

This code is used to obtain the upstream and downstream traffic (that is, the sent traffic and the received traffic) based on the computer's network adapter, and runs directly. However, when used in the get or post method of RequestHandler of tornado, an exception syntax error and related prompts will be thrown. In RequestHandler, post or get requests are considered as a background thread method. Therefore, you need to instantiate com before instantiating the com component WMI.

Why is a post or get request in RequestHandler considered as a background thread method? This problem can be seen from the code using tornado. The Code is as follows:

if __name__ == '__main__':    app = tornado.web.Application(        handlers=[(r"/test/(\w+)", testHandler),                  (r'/', MainHandler)]    )    server = tornado.httpserver.HTTPServer(app)    server = server.listen(8848)    tornado.ioloop.IOLoop.instance().start();

After configuring routing rules for tornado, we enable the httpserver service and create a process to run tornado. Each post or get request calls the corresponding Handler through a route, which is executed in the thread. In this case, if you use the com component WMI to retrieve system traffic and put it in the get method, an error is returned. The modification is as follows:

    def get(self):        res = {}        pythoncom.CoInitialize()        c = wmi.WMI()        interfaces = c.Win32_PerfRawData_Tcpip_NetworkInterface()        print len(interfaces)        rec = send = 0.0        for t in interfaces:            print t.Name            rec += float(t.BytesReceivedPersec) / 1024 / 1024            send += float(t.BytesSentPersec) / 1024 / 1024        print rec, send        res["receive"] = "%.2f" % rec        res["send"] = "%.2f" % send               self._write_json(res)

The use of WMI module can be referred to as below: http://wutils.com/wmi/root/cimv2/win32_perfrawdata_tcpip_networkinterface/ module has a lot of types (type also has a lot of attributes), in the specific use of the process of query is very painful. The traffic statistics in this case use Win32_PerfRawData_Tcpip_NetworkInterface, and some solutions use Win32_PerfRawData_Tcpip_TCPv4. The data collected by Win32_PerfRawData_Tcpip_TCPv4 varies greatly depending on the actual situation.

Reference for the com mechanism from: http://blog.csdn.net/chenglingsu6/article/details/5999134

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.