diff --git a/readMe.md b/readMe.md index d04e6d7..bc47b12 100644 --- a/readMe.md +++ b/readMe.md @@ -9,13 +9,36 @@ Python DeMo ### venv2 +#### 1. venv2 for mac + ``` virtualenv -p /usr/local/bin/python2 --no-site-packages venv2 ``` -## venv3 +#### 2. venv2 for windows + +``` +python2 -m virtualenv -p C:\Python\Python27\python2.exe venv2 + +或 + +python2 -m virtualenv -p C:\Python\Python27\python2.exe venv2 > venv2.log +``` + +### venv3 + +#### 1. venv3 for mac ``` virtualenv -p /usr/local/bin/python3 --no-site-packages venv ``` +#### 2. venv3 for windows + +``` +python3 -m virtualenv -p C:\Python\Python38\python3.exe venv + +或 + +python3 -m virtualenv -p C:\Python\Python38\python3.exe venv > venv.log +``` diff --git a/src/argparse/test_argparse.py b/src/argparse/test_argparse.py new file mode 100644 index 0000000..09382e9 --- /dev/null +++ b/src/argparse/test_argparse.py @@ -0,0 +1,34 @@ +# -*- coding:utf-8 -*- + +import argparse + +# +# python -m test_argparse.py --help +parser = argparse.ArgumentParser(description='Command-line example.') + +# Add optional switches +parser.add_argument('-v', + action='store_true', + dest='is_verbose', + help='produce verbose output') +parser.add_argument('-o', + action='store', + dest='output', + metavar='FILE', + help='direct output to FILE instead of stdout') +parser.add_argument('-C', + action='store', + type=int, + dest='context', + metavar='NUM', + default=0, + help='display NUM lines of added context') + +# Allow any number of additional arguments. +parser.add_argument(nargs='*', + action='store', + dest='inputs', + help='input filenames (default is stdin)') + +args = parser.parse_args() +print args.__dict__ diff --git a/src/class/test_class_2.7.py b/src/class/test_class_2.7.py new file mode 100644 index 0000000..21cdad6 --- /dev/null +++ b/src/class/test_class_2.7.py @@ -0,0 +1,26 @@ +# -- coding:utf-8 -- +# python 2.7.16 version + + +class A: + def foo(self): + print('深度优先 -> called A.foo()') + + +class B(A): + pass + + +class C(A): + def foo(self): + print('广度优先 -> called C.foo()') + + +class D(B, C): + pass + + +if __name__ == '__main__': + ''' 深度优先: D -> B -> A ''' + d = D() + d.foo() diff --git a/src/class/test_class_2.x.py b/src/class/test_class_2.x.py new file mode 100644 index 0000000..bc0fad4 --- /dev/null +++ b/src/class/test_class_2.x.py @@ -0,0 +1,26 @@ +# -- coding:utf-8 -- +# python 2.7.16 version + + +class A(object): + def foo(self): + print('深度优先 -> called A.foo()') + + +class B(A, object): + pass + + +class C(A, object): + def foo(self): + print('广度优先 -> called C.foo()') + + +class D(B, C, object): + pass + + +if __name__ == '__main__': + ''' 广度优先: D -> C -> A ''' + d = D() + d.foo() diff --git a/src/class/test_class_3.7.py b/src/class/test_class_3.7.py new file mode 100644 index 0000000..37f8dde --- /dev/null +++ b/src/class/test_class_3.7.py @@ -0,0 +1,31 @@ +# -- coding:utf-8 -- +# python 3.7.4 version + + +class A: + def foo(self): + print('深度优先 -> called A.foo()') + + +class B(A): + pass + + +class C(A): + def foo(self): + print('广度优先 -> called C.foo()') + + +class D(B, C): + pass + + +if __name__ == '__main__': + ''' 3.x 广度优先: D -> C -> A ''' + # 此处有点反直觉, 3.x 的应该是做了兼容为新式类型, + # D -> C -> A + # 我在我得机器上是: + # D -> B -> A + # 深度优先 -> called A.foo() + d = D() + d.foo() diff --git a/src/class/test_class_3.x.py b/src/class/test_class_3.x.py new file mode 100644 index 0000000..6608618 --- /dev/null +++ b/src/class/test_class_3.x.py @@ -0,0 +1,26 @@ +# -- coding:utf-8 -- +# python 3.7.4 version + + +class A(object): + def foo(self): + print('深度优先 -> called A.foo()') + + +class B(A, object): + pass + + +class C(A, object): + def foo(self): + print('广度优先 -> called C.foo()') + + +class D(B, C, object): + pass + + +if __name__ == '__main__': + ''' 3.x 广度优先: D -> C -> A ''' + d = D() + d.foo() diff --git a/src/file/test_file.py b/src/file/test_file.py new file mode 100644 index 0000000..466acef --- /dev/null +++ b/src/file/test_file.py @@ -0,0 +1,29 @@ +# -*- coding:utf-8 -*- + +import os + +# the define global cwd variable +cwd = os.getcwd() + + +def test_os_path(): + ''' the test os path ''' + absPath = os.path.abspath(cwd) + print('the current abs path is %s' % absPath) + baseName = os.path.basename(cwd) + print('the current base name is %s' % baseName) + # os.path.commonprefix(cwd) + dirName = os.path.dirname(cwd) + print('the current dir name is %s' % dirName) + exists = os.path.exists(cwd) + print('the current directory or file is exists that is %s ' % exists) + userProfile = os.path.expanduser("~") + print('the current user profile that is %s ' % userProfile) + supportUnicodeFileNames = os.path.supports_unicode_filenames + print('the current weather support unicode file names that is %s ' % + supportUnicodeFileNames) + + +if __name__ == "__main__": + '''主函数入口''' + test_os_path() diff --git a/src/logging/test_loggins.py b/src/logging/test_loggins.py new file mode 100644 index 0000000..eab9271 --- /dev/null +++ b/src/logging/test_loggins.py @@ -0,0 +1,48 @@ +# -*- coding:utf-8 -*- + +import logging + + +def loggingConfig(): + ''' the default logging config + + ### Python 日志格式 + + %(name)s Logger的名字 + %(levelno)s 数字形式的日志级别 + %(levelname)s 文本形式的日志级别 + %(pathname)s 调用日志输出函数的模块的完整路径名,可能没有 + %(filename)s 调用日志输出函数的模块的文件名 + %(module)s 调用日志输出函数的模块名 + %(funcName)s 调用日志输出函数的函数名 + %(lineno)d 调用日志输出函数的语句所在的代码行 + %(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示 + %(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数 + %(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒 + %(thread)d 线程ID。可能没有 + %(threadName)s 线程名。可能没有 + %(process)d 进程ID。可能没有 + %(message)s 用户输出的消息 + ''' + logging.basicConfig( + filename='./out/test_logging_recorder.log', + # format='%(asctime)s %(levelname)s:%(lineno)d:%(message)s', + format='%(asctime)s %(levelname)s:%(message)s', + # datefmt='%Y-%m-%d %H:%M:%S', + filemode='a', + level=logging.DEBUG) + + +def testLogging(): + ''' the test logging ''' + logging.debug('this is debug message.') + logging.info('this is info message.') + logging.warning('this is warning message.') + logging.error('this is error message.') + logging.critical('this is critical message.') + + +if __name__ == "__main__": + '''主函数入口''' + loggingConfig() + testLogging() diff --git a/src/logging/test_thread_loggins.py b/src/logging/test_thread_loggins.py new file mode 100644 index 0000000..8607144 --- /dev/null +++ b/src/logging/test_thread_loggins.py @@ -0,0 +1,33 @@ +# -*- coding:utf-8 -*- + +import logging +import threading +import time + + +def worker(arg): + while not arg['stop']: + logging.debug('我来自于工作线程...') + time.sleep(5) + + +def main(): + logging.basicConfig( + level=logging.DEBUG, + format='%(relativeCreated)6d %(threadName)s %(message)s') + info = {'stop': False} + thread = threading.Thread(target=worker, args=(info, )) + thread.start() + while True: + try: + logging.debug('我来自于主线程...') + time.sleep(5) + except KeyboardInterrupt: + info['stop'] = True + break + thread.join() + + +if __name__ == "__main__": + '''主函数入口''' + main() diff --git a/src/standard_library/test_argv.py b/src/standard_library/test_argv.py new file mode 100644 index 0000000..8e33ed8 --- /dev/null +++ b/src/standard_library/test_argv.py @@ -0,0 +1,21 @@ +# -- coding:utf-8 -- + + +import sys + + +def test_argv(): + argv = sys.argv[1:] + # 输出格式: + # ['start_date=2019', 'end_date=2020'] + # argv = sys.argv[:] + # 输出格式: + # ['test_argv.py', 'start_date=2019', 'end_date=2020'] + print(argv) + + +if __name__ == "__main__": + '''主函数入口''' + # the python command + # python test_argv.py start_date=2019 end_date=2020 + test_argv() diff --git a/src/standard_library/test_dict.py b/src/standard_library/test_dict.py new file mode 100644 index 0000000..d0acb98 --- /dev/null +++ b/src/standard_library/test_dict.py @@ -0,0 +1,13 @@ +# -*- coding: UTF-8 -*- + +import json + + +def test_dict(): + dict1 = {} + print json.dumps(dict1) + + +if __name__ == "__main__": + '''主函数入口''' + test_dict() diff --git a/src/standard_library/test_getopts.py b/src/standard_library/test_getopts.py new file mode 100644 index 0000000..bae4668 --- /dev/null +++ b/src/standard_library/test_getopts.py @@ -0,0 +1,49 @@ +# -- coding:utf-8 -- + +import getopt +import sys +# reload(sys) +# sys.setdefaultencoding('utf8') + + +def test_getopts(): + ''' + getopt函数的格式是getopt.getopt ( [命令行参数列表], "短选项", [长选项列表] ) + 短选项名后的冒号(:)表示该选项必须有附加的参数。 + 长选项名后的等号(=)表示该选项必须有附加的参数。 + ''' + short_opt = 'c:d' # 短链选项 + long_args = ['info', 'debug', 'time='] # 长链选项 + print + sys_argv = sys.argv[1:] + print 'the current sys_argv: %s' % sys_argv + print + opts, args = getopt.getopt(sys_argv, short_opt, long_args) + print('the current opts type: %s' % type(opts)) + print('the current opts = %s' % opts) + print ('the current opts[0] type: %s' % type(opts[0])) + print + print('the current args type: %s' % type(args)) + print ('the current args = %s' % args) + print + + +def debug_print_command(): + ''' + 命令输入,测试数据: + 1. python test_getopts.py -c c_args:c -d d start_date=2019 end_date=2020 + 2. python test_getopts.py -c c_args:c -d start_date=2019 end_date=2020 + 3. python test_getopts.py -c c_args:c -d --info start_date=2019 end_date=2020 + 4. python test_getopts.py -c c_args:c -d --debug --time=the_current_system_time start_date=2019 end_date=2020 + ''' + argv = [ + 'python', 'test_getopts.py', '-c', 'c_args:c', '-d', 'd', 'start_date=2019', + 'end_date=2020' + ] + print " ".join(argv) + + +if __name__ == "__main__": + '''主函数入口''' + test_getopts() + # debug_print_command() diff --git a/src/standard_library/test_lock.py b/src/standard_library/test_lock.py new file mode 100644 index 0000000..ca49005 --- /dev/null +++ b/src/standard_library/test_lock.py @@ -0,0 +1,54 @@ +# -*- coding: UTF-8 -*- + +import threading +import time + + +class myThread(threading.Thread): + def __init__(self, threadID, name, counter): + threading.Thread.__init__(self) + self.threadID = threadID + self.name = name + self.counter = counter + + def run(self): + print + print "Starting " + self.name + + # 获得锁,成功获得锁定后返回True + # 可选的timeout参数不填时将一直阻塞直到获得锁定 + # 否则超时后将返回False + threadLock.acquire() + print_time(self.name, self.counter, 3) + # 释放锁 + threadLock.release() + + +def print_time(threadName, delay, counter): + while counter: + time.sleep(delay) + print "%s: %s" % (threadName, time.ctime(time.time())) + counter -= 1 + + +threadLock = threading.Lock() +threads = [] + +if __name__ == "__main__": + '''主函数入口''' + # 创建新线程 + thread1 = myThread(1, "Thread-1", 1) + thread2 = myThread(2, "Thread-2", 2) + + # 开启新线程 + thread1.start() + thread2.start() + + # 添加线程到线程列表 + threads.append(thread1) + threads.append(thread2) + + # 等待所有线程完成 + for t in threads: + t.join() + print "Exiting Main Thread" diff --git a/src/standard_library/test_os_fork.py b/src/standard_library/test_os_fork.py new file mode 100644 index 0000000..faf0da3 --- /dev/null +++ b/src/standard_library/test_os_fork.py @@ -0,0 +1,14 @@ +# -*- coding: UTF-8 -*- + +import os + +if __name__ == "__main__": + '''主函数入口''' + print('Process (%s) start...' % os.getpid()) + # Only works on Unix/Linux/Mac: + pid = os.fork() + if pid == 0: + print('I am child process (%s) and my parent is %s.' % + (os.getpid(), os.getppid())) + else: + print('I (%s) just created a child process (%s).' % (os.getpid(), pid)) diff --git a/src/standard_library/test_popen.py b/src/standard_library/test_popen.py new file mode 100644 index 0000000..2819e97 --- /dev/null +++ b/src/standard_library/test_popen.py @@ -0,0 +1,48 @@ +# -- coding:utf-8 -- + +import os +import subprocess + + +def test_popen(cmds): + p = subprocess.Popen(cmds[0], stdout=subprocess.PIPE, shell=True) + print 'the current sub process pid(cwd: %s, ppid: %s, id: %s%d).' % ( + p.pid, os.getppid(), type(p), id(p)) + processes = [p] + for x in cmds[1:]: + p = subprocess.Popen(x, + stdin=p.stdout, + stdout=subprocess.PIPE, + shell=True) + print 'the current sub process pid(cwd: %s, ppid: %s, id: %s%d).' % ( + p.pid, os.getppid(), type(p), id(p)) + # print type(p), id(p) + processes.append(p) + print 'the current run process pid(cwd: %s, ppid: %s, id: %s%d).' % ( + p.pid, os.getppid(), type(p), id(p)) + print type(p), id(p) + output = p.communicate()[0] + # for p in processes: + # print 'the current wait pid(%s).' % p.pid + # p.wait() + + # print 'the current run process pid(cwd: %s, ppid: %s).' % (p.pid, + # os.getppid()) + content = output.rstrip('\n') + print 'the current run process pid(cwd: %s, ppid: %s, id: %s%d).' % ( + p.pid, os.getppid(), type(p), id(p)) + return content + + +if __name__ == "__main__": + '''主函数入口''' + print + print 'the current run main process is (cwd: %s, ppid: %s).' % ( + os.getpid(), os.getppid()) + # git config --local --list | grep "user" + # cmds = ["git config --local --list", "grep \"user\""] + cmds = ["git config --local --list", "grep \"user\"", "grep \"@\""] + result = test_popen(cmds) + print 'the current run main process is (cwd: %s, ppid: %s).' % ( + os.getpid(), os.getppid()) + print 'the content is %s' % result diff --git a/src/standard_library/test_popen_question.py b/src/standard_library/test_popen_question.py new file mode 100644 index 0000000..26b26d6 --- /dev/null +++ b/src/standard_library/test_popen_question.py @@ -0,0 +1,49 @@ +# -- coding:utf-8 -- + +import os +import subprocess + + +def test_popen(cmds): + pin = subprocess.Popen(cmds[0], stdout=subprocess.PIPE, shell=True) + print 'the current sub process pid(cwd: %s, ppid: %s, id: %s%d).' % ( + pin.pid, os.getppid(), type(pin), id(pin)) + processes = [pin] + for x in cmds[1:]: + # 管道流的输入应该是上个管道流的输出 + pout = subprocess.Popen(x, + stdin=pin.stdout, + stdout=subprocess.PIPE, + shell=True) + print 'the current sub process pid(cwd: %s, ppid: %s, id: %s%d).' % ( + pout.pid, os.getppid(), type(pout), id(pout)) + # print type(pout), id(pout) + processes.append(pout) + print 'the current run process pid(cwd: %s, ppid: %s, id: %s%d).' % ( + pout.pid, os.getppid(), type(pout), id(pout)) + print type(pout), id(pout) + output = pout.communicate()[0] + # for p in processes: + # print 'the current wait pid(%s).' % p.pid + # p.wait() + + # print 'the current run process pid(cwd: %s, ppid: %s).' % (pout.pid, + # os.getppid()) + content = output.rstrip('\n') + print 'the current run process pid(cwd: %s, ppid: %s, id: %s%d).' % ( + pout.pid, os.getppid(), type(pout), id(pout)) + return content + + +if __name__ == "__main__": + '''主函数入口''' + print + print 'the current run main process is (cwd: %s, ppid: %s).' % ( + os.getpid(), os.getppid()) + # git config --local --list | grep "user" + # cmds = ["git config --local --list", "grep \"user\""] + cmds = ["git config --local --list", "grep \"user\"", "grep \"@\""] + result = test_popen(cmds) + print 'the current run main process is (cwd: %s, ppid: %s).' % ( + os.getpid(), os.getppid()) + print result diff --git a/src/standard_library/test_queue.py b/src/standard_library/test_queue.py new file mode 100644 index 0000000..90c8e07 --- /dev/null +++ b/src/standard_library/test_queue.py @@ -0,0 +1,69 @@ +# -*- coding: UTF-8 -*- + +import Queue +import threading +import time + +exitFlag = 0 + + +class myThread(threading.Thread): + def __init__(self, threadID, name, q): + threading.Thread.__init__(self) + self.threadID = threadID + self.name = name + self.q = q + + def run(self): + print + print "Starting " + self.name + print + process_data(self.name, self.q) + print "Exiting " + self.name + + +def process_data(threadName, q): + while not exitFlag: + queueLock.acquire() + if not workQueue.empty(): + data = q.get() + queueLock.release() + print "%s processing %s" % (threadName, data) + else: + queueLock.release() + time.sleep(1) + + +threadList = ["Thread-1", "Thread-2", "Thread-3"] +nameList = ["One", "Two", "Three", "Four", "Five"] +queueLock = threading.Lock() +workQueue = Queue.Queue(10) +threads = [] +threadID = 1 + +if __name__ == "__main__": + '''主函数入口''' + # 创建新线程 + for tName in threadList: + thread = myThread(threadID, tName, workQueue) + thread.start() + threads.append(thread) + threadID += 1 + + # 填充队列 + queueLock.acquire() + for word in nameList: + workQueue.put(word) + queueLock.release() + + # 等待队列清空 + while not workQueue.empty(): + pass + + # 通知线程是时候退出 + exitFlag = 1 + + # 等待所有线程完成 + for t in threads: + t.join() + print "Exiting Main Thread" diff --git a/src/standard_library/test_send_smtp.py b/src/standard_library/test_send_smtp.py new file mode 100644 index 0000000..56b1b6a --- /dev/null +++ b/src/standard_library/test_send_smtp.py @@ -0,0 +1,55 @@ +# -*- coding: UTF-8 -*- + +import smtplib +from email.mime.text import MIMEText +from email.header import Header + +# 第三方 SMTP 服务 +mail_host = "smtp.qq.com" # 设置服务器 +mail_user = "xxx" # 用户名 +mail_pass = "xxx" # 口令 + +sender = 'xxx' # 发送人 +receiver = ['xxx'] # 接收人 + + +def obtainMailMessage(): + '''邮件配置信息''' + # 三个参数: + # 第一个为文本内容; + # 第二个 plain 设置文本格式; + # 第三个 utf-8 设置编码; + message = MIMEText('Python 邮件发送测试...', 'plain', 'utf-8') + sender_alias = "资深好男人<%s>" % sender + # print sender_alias + message['From'] = Header(sender_alias, 'utf-8') + receiver_alias = "我可姿势江山美如画<%s>" % receiver[0] + # print receiver_alias + message['To'] = Header(receiver_alias, 'utf-8') + message['Subject'] = Header('Python SMTP 邮件测试', 'utf-8') + return message + + +if __name__ == "__main__": + '''主函数入口''' + try: + smtpObj = smtplib.SMTP() + smtpObj.connect(mail_host, 25) # 25 为 SMTP 端口号 + smtpObj.login(mail_user, mail_pass) + content = obtainMailMessage().as_string() + print + print content + ''' + Content-Type: text/plain; charset="utf-8" + MIME-Version: 1.0 + Content-Transfer-Encoding: base64 + From: =?utf-8?b?6LWE5rex5aW955S35Lq6IEZyb20=?= + To: =?utf-8?b?5oiR5Y+v5ae/5Yq/5rGf5bGx576O5aaC55S7IFRv?= + Subject: =?utf-8?b?UHl0aG9uIFNNVFAg6YKu5Lu25rWL6K+V?= + + UHl0aG9uIOmCruS7tuWPkemAgea1i+ivlS4uLg== + ''' + smtpObj.sendmail(sender, receiver, content) + print "邮件发送成功" + except smtplib.SMTPException: + print "Error: 无法发送邮件" diff --git a/src/standard_library/test_send_smtp_ssl.py b/src/standard_library/test_send_smtp_ssl.py new file mode 100644 index 0000000..d15a718 --- /dev/null +++ b/src/standard_library/test_send_smtp_ssl.py @@ -0,0 +1,57 @@ +# -*- coding: UTF-8 -*- + +import thread +import time +import smtplib +from email.mime.text import MIMEText +from email.utils import formataddr + +# 第三方 SMTP 服务 +mail_host = "smtp.qq.com" # 设置服务器 +mail_port = 465 # 服务器SSL 默认端口 + +mail_user = "xxx" # 用户名 +mail_pass = "xxx" # 口令 + +sender = 'xxx' # 发送人 +receiver = 'xxx' # 接收人 + + +def obtainMailMessage(): + ''' 邮件配置信息 ''' + # 三个参数: + # 第一个为文本内容; + # 第二个 plain 设置文本格式; + # 第三个 utf-8 设置编码; + message = MIMEText('Python 邮件发送测试...', 'plain', 'utf-8') + # 括号里的对应发件人邮箱昵称、发件人邮箱账号 + message['From'] = formataddr(['资深好男人', sender]) + # 括号里的对应收件人邮箱昵称、收件人邮箱账号 + message['To'] = formataddr(['我可姿势江山美如画', receiver]) + # 邮件的主题,也可以说是标题 + message['Subject'] = 'Python SMTP SSL 邮件测试' + return message + + +def sendMail(): + ''' 发送邮件 ''' + smtpObj = smtplib.SMTP_SSL(mail_host, mail_port) + smtpObj.login(mail_user, mail_pass) + content = obtainMailMessage().as_string() + print + print content + smtpObj.sendmail(sender, [ + receiver, + ], content) + smtpObj.quit() + + +if __name__ == "__main__": + '''主函数入口''' + try: + thread.start_new_thread(sendMail, ()) + time.sleep(5) + print "邮件发送成功" + except Exception as e: + # print e.message + print "Error: 无法发送邮件" diff --git a/src/standard_library/test_sendmail.py b/src/standard_library/test_sendmail.py new file mode 100644 index 0000000..d27ee55 --- /dev/null +++ b/src/standard_library/test_sendmail.py @@ -0,0 +1,49 @@ +# -*- coding: UTF-8 -*- + +import smtplib +from email.mime.text import MIMEText +from email.header import Header + +sender = 'dovsnier@qq.com' # 发送人 +receiver = ['zhenwei-li@qq.com'] # 接收人 + + +def obtainMailMessage(): + '''邮件配置信息''' + # 三个参数: + # 第一个为文本内容; + # 第二个 plain 设置文本格式; + # 第三个 utf-8 设置编码; + message = MIMEText('Python 邮件发送测试...', 'plain', 'utf-8') + message['From'] = Header("资深好男人 From", 'utf-8') + message['To'] = Header("我可姿势江山美如画 To", 'utf-8') + message['Subject'] = Header('Python SMTP 邮件测试', 'utf-8') + return message + + +if __name__ == "__main__": + ''' + 通过本地设备sendmail 库进行发送邮件 + + 启动命令: + python -m smtpd -n -c DebuggingServer localhost:1025 + ''' + try: + smtpObj = smtplib.SMTP('localhost', 1025) + content = obtainMailMessage().as_string() + print + print content + ''' + Content-Type: text/plain; charset="utf-8" + MIME-Version: 1.0 + Content-Transfer-Encoding: base64 + From: =?utf-8?b?6LWE5rex5aW955S35Lq6IEZyb20=?= + To: =?utf-8?b?5oiR5Y+v5ae/5Yq/5rGf5bGx576O5aaC55S7IFRv?= + Subject: =?utf-8?b?UHl0aG9uIFNNVFAg6YKu5Lu25rWL6K+V?= + + UHl0aG9uIOmCruS7tuWPkemAgea1i+ivlS4uLg== + ''' + smtpObj.sendmail(sender, receiver, content) + print "邮件发送成功" + except smtplib.SMTPException: + print "Error: 无法发送邮件" diff --git a/src/standard_library/test_thread.py b/src/standard_library/test_thread.py new file mode 100644 index 0000000..e9b3d14 --- /dev/null +++ b/src/standard_library/test_thread.py @@ -0,0 +1,33 @@ +# -*- coding: UTF-8 -*- + +import thread +import time + + +# 为线程定义一个函数 +def print_time(threadName, delay): + count = 0 + while count < 5: + time.sleep(delay) + count += 1 + print "%s: %s" % (threadName, time.ctime(time.time())) + + +if __name__ == "__main__": + '''主函数入口''' + # 创建两个线程 + try: + thread.start_new_thread(print_time, ( + "Thread-1", + 2, + )) + thread.start_new_thread(print_time, ( + "Thread-2", + 4, + )) + except Exception as e: + print "Error: unable to start thread" + else: + print "主程序-正常执行." + + time.sleep(27) diff --git a/src/standard_library/test_threading.py b/src/standard_library/test_threading.py new file mode 100644 index 0000000..838ed9b --- /dev/null +++ b/src/standard_library/test_threading.py @@ -0,0 +1,47 @@ +# -*- coding: UTF-8 -*- + +import threading +import time + + +exitFlag = 0 + + +class myThread (threading.Thread): # 继承父类threading.Thread + def __init__(self, threadID, name, counter): + threading.Thread.__init__(self) + self.threadID = threadID + self.name = name + self.counter = counter + + def run(self): # 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数 + print "Starting " + self.name + print_time(self.name, self.counter, 5) + print "Exiting " + self.name + + +def print_time(threadName, delay, counter): + while counter: + if exitFlag: + (threading.Thread).exit() + time.sleep(delay) + print "%s: %s" % (threadName, time.ctime(time.time())) + counter -= 1 + + +if __name__ == "__main__": + '''主函数入口''' + # 创建新线程 + thread1 = myThread(1, "Thread-1", 1) + thread2 = myThread(2, "Thread-2", 2) + + # 开启线程 + thread1.start() + thread2.start() + + print + print "主程序-正常执行." + print + print "Exiting Main Thread" + + time.sleep(15) diff --git a/template/template.py b/template/template.py index 700cf39..3735452 100644 --- a/template/template.py +++ b/template/template.py @@ -1,4 +1,4 @@ -# -- coding:utf-8 -- +# -*- coding:utf-8 -*- if __name__ == "__main__": '''主函数入口''' diff --git a/template/template_case.py b/template/template_case.py new file mode 100644 index 0000000..b1cbbd6 --- /dev/null +++ b/template/template_case.py @@ -0,0 +1,34 @@ +# -*- coding:utf-8 -*- + +import unittest + + +class Test_Demo(unittest.TestCase): + ''' the test demo ''' + @classmethod + def setUpClass(cls): + print("...the set up...") + print + + def setUp(self): + return super(Test_Demo, self).setUp() + + def _xxx(self): + print "the test xxx is succeed." + pass + + def test_xxx(self): + print "the test xxx is succeed." + pass + + def tearDown(self): + return super(Test_Demo, self).tearDown() + + @classmethod + def tearDownClass(cls): + print + print("...the tear down...") + + +if __name__ == '__main__': + unittest.main() diff --git a/template/template_test.py b/template/template_test.py new file mode 100644 index 0000000..ff98375 --- /dev/null +++ b/template/template_test.py @@ -0,0 +1,30 @@ +# -*- coding:utf-8 -*- + +import unittest + + +class Test_XXX(unittest.TestCase): + ''' the test xxx ''' + @classmethod + def setUpClass(cls): + print("...the set up...") + print + + def setUp(self): + return super(Test_XXX, self).setUp() + + def test_xxx(self): + print "the test xxx is succeed." + pass + + def tearDown(self): + return super(Test_XXX, self).tearDown() + + @classmethod + def tearDownClass(cls): + print + print("...the tear down...") + + +if __name__ == '__main__': + unittest.main() diff --git a/test/case/case_1.py b/test/case/case_1.py new file mode 100644 index 0000000..9ba046e --- /dev/null +++ b/test/case/case_1.py @@ -0,0 +1,45 @@ +# -*- coding:utf-8 -*- + +import unittest +import os + + +class Test_Demo(unittest.TestCase): + ''' the test demo ''' + @classmethod + def setUpClass(cls): + print("...the set up...") + print + + def setUp(self): + return super(Test_Demo, self).setUp() + + def _xxx(self): + print "the test xxx is succeed." + pass + + def test_xxx(self): + # cwd == ./ + # cwd = os.getcwd() + + file = os.path.abspath("./readMe.md") + # file_1 = os.path.abspath(".") + # file_2 = os.path.abspath("./../") + # file_3 = os.path.abspath("./../readMe.md") + if os.path.exists(file): + if os.path.isfile(file): + print "the current is file(%s)" % file + print "the test xxx is succeed." + pass + + def tearDown(self): + return super(Test_Demo, self).tearDown() + + @classmethod + def tearDownClass(cls): + print + print("...the tear down...") + + +if __name__ == '__main__': + unittest.main() diff --git a/test/demo_test.py b/test/demo_test.py new file mode 100644 index 0000000..2d1b03c --- /dev/null +++ b/test/demo_test.py @@ -0,0 +1,40 @@ +# -*- coding:utf-8 -*- + +import unittest + + +class Test_Demo(unittest.TestCase): + ''' the test demo ''' + @classmethod + def setUpClass(cls): + print("...the set up...") + print + + def setUp(self): + return super(Test_Demo, self).setUp() + + def _xxx(self): + print "the test xxx is succeed." + pass + + def test_demo(self): + cmd_str = "the total time spent executing the current command({command}) is {cmd} s.\n" + content_str = "the execution result is ['{content}']." + msg = (cmd_str + content_str).format(command="命令", + cmd="cmds", + content="content") + print msg + print "the test demo is succeed." + pass + + def tearDown(self): + return super(Test_Demo, self).tearDown() + + @classmethod + def tearDownClass(cls): + print + print("...the tear down...") + + +if __name__ == '__main__': + unittest.main()