您的位置:首页 > 编程语言 > Python开发

python多线程

2016-07-25 15:59 579 查看
#两个线程一个发心跳,一个往打印机发数据#

#!/usr/local/bin/python2.7

# encoding: utf-8

import threading

import socket

import time

import logging

import sys

from logging.handlers import TimedRotatingFileHandler

import ConfigParser

'''

Created on 2016年07月7日

@author: wuxiaobing

Mail:2683904575@qq.com

history:

V1.0增加多线程机制,一个线程是和打印机做心跳连接、另一个线程发数据到打印机。(2016-07-15)

V1.1将所有配置文件用模块ConfigParser整理到一个配置文件,按配置文件读写方式处理。(2016-07-25)

'''

conf = ConfigParser.ConfigParser()

conf.read("D:\\test.conf")

HOST = conf.get("section1", "ip")

PORT = int(conf.get("section1", "port"))

time1 = conf.get("section2", "t1")

time2 = conf.get("section2", "t2")

def lan_send_data_printer():

    

    BUFFERSIZE = 1024

    ADDR = (HOST, PORT)

    count=0

    while(1):

        count=count+1

        TCPClient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        try:

            TCPClient.connect(ADDR)

        except socket.error, e:

            print "Connection error: %s" % e

            continue  

        looger.info(u"V1.1&正在运行第 %s 次" % str(count))

        TCPClient.close()

        print HOST+"--->"+"threading1"+"--->"+u"发心跳"+" "+str(count)+u"次"

        time.sleep(int(time1))      

        

def loop2(title,txt):

    BUFFERSIZE = 1024

    ADDR = (HOST, PORT)

    countt=0

    while (1):

        countt=countt+1

        TCPClient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        try:

            TCPClient.connect(ADDR)

        except socket.error, e:

            print "Connection error: %s" % e

            print u"亲,打印机IP是不被人占了或没开打印机?"

            continue

        

        looger.info(u"V1.1&正在运行第 %s 次" % str(countt))

        TCPClient.send(txt)

        TCPClient.close()

        print HOST+"--->"+"threading2"+"--->"+u"打印数据"+" "+str(countt)+u"次"

        time.sleep(int(time2))

        

        

if __name__ == '__main__':

    looger = logging.getLogger('threading2')

    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

    LogHandLer=TimedRotatingFileHandler(r'E:\countLAN.log',when="midnight")

    LogHandLer.suffix="%Y%m%d-%H%M.log"

    LogHandLer.setFormatter(formatter)

    looger.addHandler(LogHandLer)

    looger.setLevel(logging.INFO)

    f2 = open(r"D:\Users\Out123.spc",'rb')

    lines2 = f2.read()

    f2.close()

    t = threading.Thread(target=lan_send_data_printer)

    t2=threading.Thread(target=loop2,args=("lines2",lines2))

    t.start()

    t2.start()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: