1# encoding=utf-8
2
3import os
4import socket
5import subprocess
6import time
7
8from util.log_info import logger
9from aw.Common.Constant import *
10
11def copyFile(source_path, copy_path, size=1024 * 1024):
12    '''
13    #===================================================================================
14    #   @Method:        copyFile(self, source_path, copy_path, size=1024 * 1024)
15    #   @Precondition:  none
16    #   @Func:          拷贝文件
17    #   @PostStatus:    none
18    #   @Param:         source_path:资源文件路径
19    #                   copy_path:文件下载到本地的文件夹路径
20    #                   size:字节数的大小
21    #   @eg:            downloadByBitComet("xxxx", "D:\\local\\image")
22    #   @return:        True or Flase
23    #===================================================================================
24    '''
25    if not os.path.isfile(source_path):
26        raise Exception("%s is not file" % source_path)
27    if os.path.isdir(copy_path):
28        copy_path = os.path.join(copy_path, os.path.basename(source_path))
29    try:
30        with open(source_path, 'rb') as fr, open(copy_path, 'wb') as fw:
31            while(True):
32                data = fr.read(size)
33                if not data:
34                    break
35                fw.write(data)
36    except:
37        raise Exception("Copy %s to %s failed" % (source_path, copy_path))
38
39
40def copyDirectory(src_dir, dst_dir):
41    # copy everything under <src_dir> into <dst_dir>
42    if not os.path.isdir(src_dir):
43        return False
44
45    if not os.path.isdir(dst_dir):
46        try:
47            os.makedirs(dst_dir)
48        except Exception as e:
49            logger.error(e)
50
51    time.sleep(1)
52    if not os.path.isdir(dst_dir):
53        return False
54
55    logger.info("copy %s to %s" % (src_dir, dst_dir))
56    for item in os.listdir(src_dir):
57        file_path = os.path.join(src_dir, item)
58        child_path = os.path.join(dst_dir, item)
59        if os.path.isfile(file_path):
60            logger.info("copy %s to %s" % (file_path, child_path))
61            copyFile(file_path, child_path)
62            if not os.path.isfile(child_path):
63                logger.error("Copy %s to %s failed" % (file_path, child_path))
64                return False
65        else:
66            if os.path.isdir(file_path):
67                ret = copyDirectory(file_path, child_path)
68                if not ret:
69                    return False
70    return True
71
72def getHostIp():
73    """
74    #===================================================================================
75    #   @Method:        getHostIp()
76    #   @Precondition:  none
77    #   @Func:          返回机器ip
78    #   @PostStatus:    none
79    #   @eg:            getHostIp()
80    #   @return:        ip
81    #===================================================================================
82    """
83    ip = ""
84    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
85    try:
86        s.connect(('8.8.8.8', 80))
87        ip = s.getsockname()[0]
88    except OSError as e:
89        print(e)
90    finally:
91        s.close()
92        return ip
93
94def getFileName(path, suffix_name):
95    '''
96    #===================================================================================
97    #   @Method:        getFileName(path, suffix_name)
98    #   @Precondition:  none
99    #   @Func:          find the flash script in version path or root path
100    #   @PostStatus:
101    #   @Param:         path, version path or root path
102    #   @Example:       getFileName(path, suffix_name)
103    #   @Author:        zwx205888
104    #   @ModifyRecord:  none
105    #===================================================================================
106    '''
107    logger.info("get %s in %s" % (suffix_name, path))
108    import glob
109    script_files = glob.glob(os.path.join(path, "*" + suffix_name))
110    logger.info("real file is : %s " % script_files)
111    if len(script_files) != 1:
112        logger.error("more than one %s file or has No %s file" % (suffix_name, suffix_name))
113        return False
114
115    return script_files[0]
116
117def subProcessPopen(cmd, outlog_enable=True, errlog_enable=True):
118    """
119    @Method:          subProcessPopen()
120    @Precondition:    none
121    @Func:            excute the command
122    @PostStatus:      none
123    @Param:           cmd,the command that will be excuted
124    @Example:         subProcessPopen("RD /Q /F D:\test")
125    @ModifyRecord:    none
126    """
127
128    ret_dict = {}
129    number = 3
130
131    for i in range (number):
132        p1 = subprocess.Popen(cmd,
133                                 stdin=subprocess.PIPE,
134                                 stdout=subprocess.PIPE,
135                                 stderr=subprocess.PIPE,
136                                 shell=True)
137        out, err = p1.communicate()
138        if 0 != p1.returncode:
139            if True == outlog_enable:
140                logger.error(err)
141                logger.error("%s fail" % cmd)
142            ret = False
143        else:
144            ret = True
145        ret_dict["ret"] = ret
146        ret_dict["out"] = out.strip()
147        ret_dict["err"] = err.strip()
148        if outlog_enable:
149            logger.info("ret is %s" % ret)
150            logger.info(out.strip())
151        if errlog_enable:
152            logger.info(err.strip())
153        if ret_dict["out"] or ret_dict["err"]:
154            break
155    return ret_dict