前置

  • 容器类可以存储任意类型的数据
  • 方法属于类;函数可以直接调用
  • break语句强行退出循环体,不再执行循环体中剩余的语句
  • 短路设计
    • 与 一False全False
    • 或 一True全True
    • 会不计算后面的表达式
  • set 集合
    • add(elem)
    • remove(elem)
    • clear()

字符串

  • string 字符串
    • 普通字符串
    • 原始字符串 r
    • 长字符串(还是需要转义)
  • 转义符
    • \t 水平制表符
    • \n 换行
    • \r 回车
  • 默认下,int()函数将字符串参数当作十进制数字进行转换
  • format() 格式化字符串
    • s 字符串
    • d 十进制整数
    • f 十进制浮点数
    • g 十进制整数或浮点数
    • o 八进制整数
    • x 十六进制整数
  • 字符串查找 find() 返回索引
  • 字符串替换 replace(old, new[, count])

函数

  • 函数的可变参数

    • *可变参数在函数中被组装成一个元组

      python
      1
      2
      3
      4
      5
      6
      7
      def sum(*numbers):
      total = 0.0
      for number in numbers:
      total += number
      return total
      print(sum(100.0, 20.0, 30.0)) # 150.0
      print(sum(30.0, 80.0)) # 110.0
    • **可变参数在函数中被组装成一个字典

      python
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      def show_info(**info):
      for key, value in info.items():
      print(f"{key} -- {value}")

      show_info(name= "Ben", age = 18, sex = True)
      show_info(student_name = "Ben", student_no = 1)
      # name -- Ben
      # age -- 18
      # sex -- True
      # student_name -- Ben
      # student_no -- 1
  • global x 修改成全局变量

  • 过滤函数
    • filter(function, iterable)
    • 返回值不是列表,需要用list()
    • 条件判断
  • 映射函数
    • map(function, iterable)
    • 返回值不是列表,需要用list()
    • 操作变换
  • 匿名函数

    • lambda 参数列表: lambda体

      python
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      '''
      lamdba函数
      '''
      def calc(opr):
      if opr == "+":
      return lambda a, b: (a + b)
      else:
      return lambda a, b: (a - b)

      f1 = calc('+')
      f2 = calc('-')
      print(f"10 + 5 = {f1(10, 5)}")
      print(f"10 - 5 = {f2(10, 5)}")

      data1 = [66, 15, 91, 28, 98, 50, 7, 80, 99]

      filtered = filter(lambda x: (x > 50), data1)
      data2 = list(filtered)
      print(data2)

      mapped = map(lambda x: (x * 2), data1)
      data3 = list(mapped)
      print(data3)

类与对象

    • 成员变量

      • 实例变量

        python
        1
        def __init__(self···):
      • 类变量 理解为通用数据即可

    • 成员方法

      • 实例方法

        python
        1
        def function(self···):
      • 类方法

        • @修饰函数、方法和类
        • def function(cls,···):
    • 构造方法 __init__()
    • 属性
  • 私有变量
    • 前面加上 __ 双下划线
    • 默认类的变量是公有的,可以在类的外部访问
  • 私有方法 前面加上 __ 双下划线
  • get(取值)和set(赋值)函数来访问私有变量
python
1
2
3
4
5
6
7
8
9
# get(取值)和set(赋值)函数来访问私有变量
@property
def property(self)
# get() property

@属性.setter()
def property(self, property):
self.__property= property
# set() property
  • 继承 父类 只有公有的成员变量和方法才可以被继承
  • super().__init__() 初始化父类成员变量
  • 多继承 继承多个父类
  • 方法重写 子类的方法会重写Override父类的同名方法
  • 封装 继承 多态

    异常处理

  • try-except try代码块发生异常执行except代码块

python
1
2
3
4
5
6
7
8
try:
pass
except Error as e:
print(f"异常是{e}")
# 多重异常捕获
except (Error1, Error) as e:
print(f"异常是{e}")

  • 无论try代码块执不执行,finally代码块都会执行
  • raise 引发异常

内置函数

  • datetime库
    • datetime类
      • datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None) 构造datetime类
      • datetime.today() 返回当前的本地日期和时间
      • datetime.now(tz=None) 返回指定时区的当前日期和时间(tz设置时区)
      • datetime.fromtimestamp(timestamp, tz=None) 返回与UNIX时间戳对应的本地日期和时间(单位是秒)
    • date类
      • datetime.date(year, month, day) 构造date类
      • date.today() 返回当前的本地日期
      • date.fromtimestamp(timestamp) 返回与UNIX时间戳对应的本地日期
    • time类
      • datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None) 构造time类
    • timedelta
      • 计算时间跨度
      • datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) 构造timedelta类
    • strftime(format) 日期时间对象转字符串
      • %m 两位月份表示
      • %y 两位年份表示
      • %Y 四位年份表示
      • %d 两位表示月中的一天
      • %H 两位小时表示(24小时制)
      • %I 两位小时表示(12小时制)
      • %p AM或PM区域性设置
      • %M 两位分钟表示
      • %S 两位秒表示
      • %f 以六位数表示微秒
      • %z +HHMM或-HHMM形式的UTC偏移
      • %Z 时区名称
    • strptime(format) 字符串转日期时间对象
  • re正则表达式
    • re.match(p, text) 返回一个·Match匹配对象,否则返回None
    • re.search(p, text) 返回第一个匹配对象,否则返回None
    • re.findall(p, text) 返回所有匹配字符串列表,,否则返回None
    • re.sub(pattern, repl, string, count=0) 字符串替换
      • pattern 正则表达式
      • repl 替换的新字符串
      • string 被替换的旧字符串
      • count 替换的最大数量,默认为零
    • re.split(pattern, string, maxsplit=0) 字符串分割
      • pattern 正则表达式
      • string 分割的字符串
      • maxsplit最大分割次数,默认为零
  • open(file, mode=‘r’, encoding=None, errors=None) 打开文件
    • file 要打开的文件
    • mode 文件打开模式
      • t 文本文件模式
      • b 二进制文件模式
      • r 只读模式
      • w 只写模式
      • x 独占创建模式(文件不存在则创建;文件存在则FileExistsError异常)
      • a 追加模式(文件不存在则创建,文件存在则末尾追加)
        • 更新读写模式(必须与r、w或a组合使用)
    • encoding 打开文件的文件编码,默认是UTF编码
    • errors 指定文本文件发生编码错误时如何处理
  • close() 关闭文件
  • with open(filename) as file: 自动释放资源(关闭文件)
    • filename 文件名
    • file 打开的文件对象
  • 读写文本文件(或二进制文件)
    • read(size=-1) size限制读取的字符数,size=-1对读取的字符数没有限制
    • readline(size=-1) 返回单行字符串,size限制读取的字符数
    • readlines() 读取文件到一个字符串列表,每一行数据都是列表的一个元素
    • write(s) 将字符串s写入文件并返回写入的字符数
    • writelines(lines) 向文件中写入一个字符串列表(每一行末尾都提供分隔符)
    • flush() 刷新写缓冲区,在文件没关闭的情况下将数据写入文件

⭐⭐图形用户界面

  • 应用程序
  • 窗口
  • 面板
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
'''
the first wxPython program
'''

import wx

# create a app object
app = wx.App()

# create window object(pos=position)
frm = wx.Frame(None, title='the first wxPython program', size=(400, 300), pos=(100, 100))
# show window(hide by default)
frm.Show()

# get into the main event loop
app.MainLoop()
  • 事件循环是一种事件或消息分发处理机制,大部分GUI在界面的现实及相应用户事件的处理都是通过主事件循环实现的
  • 自定义窗口类
python
1
2
3
4
5
6
7
8
9
10
11
12
13
import wx

# user-defined windows MyFrame
class MyFrame(wx.Frame):
def __init__(self):
super().__init__(None, title='the first wxPython program', size=(400, 300), pos=(100, 100))
# your own code

app = wx.App()

frm = MyFrame()
frm.Show()
app.MainLoop()
  • 在窗口中添加控件(面板Panel和静态文本StaticText)
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import wx

# user-defined windows MyFrame
class MyFrame(wx.Frame):
def __init__(self):
super().__init__(None, title='the first wxPython program', size=(400, 300), pos=(100, 100))
# create panel object
panel = wx.Panel(parent=self)
# create statictext object
statictext = wx.StaticText(parent=panel, label="Hello World", pos=(10,10))

app = wx.App()

frm = MyFrame()
frm.Show()
app.MainLoop()
  • 事件处理
    • 事件源(控件)
    • 事件
    • 事件处理程序
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import wx

# user-defined windows MyFrame
class MyFrame(wx.Frame):
def __init__(self):
super().__init__(None, title='event handing', size=(400, 300), pos=(100, 100))
# create panel object
panel = wx.Panel(parent=self)
# create statictext object
self.statictext = wx.StaticText(parent=panel, label="please click ok button", pos=(110,20))
b = wx.Button(parent=panel, label='OK', pos=(100, 50))
# bind event,wx.EVT_BUTTON is the kind of event(按钮单击事件), on_click is event handing
self.Bind(wx.EVT_BUTTON, self.on_click, b)

def on_click(self, event):
self.statictext.SetLableText("Hello, World.")

app = wx.App()

frm = MyFrame()
frm.Show()
app.MainLoop()
  • 布局管理

    • 创建对象
      • wx.BoxSizer(wx.HORIZONTAL) 创建水平方向盒子对象
      • wx.BoxSizer(wx.VERTICAL) 创建垂直方向盒子对象
      • 默认是水平方向
    • 添加到父窗口

      • Add(window, proportion=0, flag=0, border=0) 添加到父窗口
      • proportion 设置当前占父窗口的空间比例
      • flag 布局标志(对齐、边框、调整尺寸)

        image.png

        image.png

        image.png

      • border 边框宽度

python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import wx

# user-defined windows MyFrame
class MyFrame(wx.Frame):
def __init__(self):
super().__init__(None, title='event handing', size=(400, 300), pos=(100, 100))
# create panel object
panel = wx.Panel(parent=self)
# create statictext object
self.statictext = wx.StaticText(parent=panel, label="please click ok button", pos=(110,20))
b = wx.Button(parent=panel, label='OK', pos=(100, 50))
# bind event,wx.EVT_BUTTON is the kind of event(按钮单击事件), on_click is event handing
self.Bind(wx.EVT_BUTTON, self.on_click, b)

# create a layout manager box vbox
vbox = wx.BoxSizer(wx.VERTICAL)
# add statictext into vbox
vbox.Add(self.statictext, proportion=1, flag=wx.ALIGN_CENTER_HORIZONTAL|wx.FIXED_MINSIZE|wx.TOP, border=30)
# add button b into vbox
vbox.Add(b, proportion=1, flag=wx.EXPAND|wx.BOTTOM, border=10)
panel.SetSizer(vbox)

def on_click(self, event):
self.statictext.SetLabelText("Hello, World.")

app = wx.App()

frm = MyFrame()
frm.Show()
app.MainLoop()

image.png

  • 控件
    • wx.TextCtrl() 文本输入控件
    • wx.TextCtrl(panel)
    • wx.TextCtrl(panel, style=wx.TE_PASSWORD)
    • wx.TextCtrl(panel, style=wx.TE_MULTILINE)
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import wx

# user-defined windows MyFrame
class MyFrame(wx.Frame):
def __init__(self):
super().__init__(None, title='文本输入控件', size=(400, 300), pos=(100, 100))
panel = wx.Panel(parent=self)
tc1 = wx.TextCtrl(panel)
tc2 = wx.TextCtrl(panel, style=wx.TE_PASSWORD)
tc3 = wx.TextCtrl(panel, style=wx.TE_MULTILINE)

userid = wx.StaticText(panel, label="用户ID:")
pwd = wx.StaticText(panel, label="密码:")
content = wx.StaticText(panel, label="多行文本:")

vbox = wx.BoxSizer(wx.VERTICAL)
vbox.Add(userid, flag=wx.EXPAND|wx.LEFT, border=10)
vbox.Add(tc1, flag=wx.EXPAND|wx.ALL, border=10)
vbox.Add(pwd, flag=wx.EXPAND|wx.LEFT, border=10)
vbox.Add(tc2, flag=wx.EXPAND|wx.ALL, border=10)
vbox.Add(content, flag=wx.EXPAND|wx.LEFT, border=10)
vbox.Add(tc3, flag=wx.EXPAND|wx.ALL, border=10)

# set panel
panel.SetSizer(vbox)

def on_click(self, event):
self.statictext.SetLabelText("Hello, World.")

app = wx.App()

frm = MyFrame()
frm.Show()
app.MainLoop()

image.png

  • 复选框和单选按钮
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import wx

# user-defined windows MyFrame
class MyFrame(wx.Frame):
def __init__(self):
super().__init__(None, title='复选框和单选按钮', size=(400, 300), pos=(100, 100))
panel = wx.Panel(parent=self)

st1 = wx.StaticText(panel, label="select one your favorite language")
cb1 = wx.CheckBox(panel, id=1, label="Python")
cb2 = wx.CheckBox(panel, id=2, label="Java")
cb2.SetValue(True) # 设置cb2初始状态为选中
cb3 = wx.CheckBox(panel, id=3, label="C++")
self.Bind(wx.EVT_CHECKBOX, self.on_checkbox_click, id=1, id2=3)

st2 = wx.StaticText(panel, label="选择性别:")
radio1 = wx.RadioButton(panel, id=4, label="男", style=wx.RB_GROUP)
radio2 = wx.RadioButton(panel, id=5, label="女")
self.Bind(wx.EVT_CHECKBOX, self.on_radio1_click, id=4, id2=5)

hbox1 = wx.BoxSizer()
hbox1.Add(st1, flag=wx.Left|wx.Right, border=5)
hbox1.Add(cb1)
hbox1.Add(cb2)
hbox1.Add(cb3)

hbox2 = wx.BoxSizer()
hbox2.Add(st2, flag=wx.Left|wx.Right, border=5)
hbox2.Add(radio1)
hbox2.Add(radio2)

vbox = wx.BoxSizer(wx.VERTICAL)
vbox.Add(hbox1, flag=wx.ALL, border=10)
vbox.Add(hbox2, flag=wx.ALL, border=10)

# set panel
panel.SetSizer(vbox)

def on_checkbox_click(self, event):
cb = event.GetEventObject()
print(f"选择{cb.GetLabel()},状态{event.IsChecked()}")

def on_radio1_click(self, event):
rb = event.GetEventObject()
print(f"第一组{rb.GetLabel()}被选中")


app = wx.App()

frm = MyFrame()
frm.Show()
app.MainLoop()

image.png

  • 列表
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import wx

class MyFrame(wx.Frame):
def __init__(self):
super().__init__(None, title="列表", size=(350, 175))
panel = wx.Panel(parent=self)

st1 = wx.StaticText(panel, label="选择你喜欢的编程语言:")
list1 = ['Python', "C++", "Java"]
lb1 = wx.ListBox(panel, choices=list1, style=wx.LB_SINGLE)
self.Bind(wx.EVT_LISTBOX, self.on_listbox1, lb1)

st2 = wx.StaticText(panel, label="选择你喜欢吃的水果:")
list2 = ["苹果", "橘子", "香蕉"]
lb2 = wx.ListBox(panel, choices=list2, style=wx.LB_EXTENDED)
self.Bind(wx.EVT_LISTBOX, self.on_listbox2, lb2)

hbox1 = wx.BoxSizer()
hbox1.Add(st1, proportion=1, flag=wx.LEFT|wx.RIGHT, border=5)
hbox1.Add(lb1, proportion=1)

hbox2 = wx.BoxSizer()
hbox2.Add(st2, proportion=1, flag=wx.LEFT|wx.RIGHT, border=5)
hbox2.Add(lb2, proportion=1)

vbox = wx.BoxSizer(wx.VERTICAL)
vbox.Add(hbox1, flag=wx.ALL|wx.EXPAND, border=5)
vbox.Add(hbox2, flag=wx.ALL|wx.EXPAND, border=5)

panel.SetSizer(vbox)

def on_listbox1(self, event):
listbox = event.GetEventObject()
print("选择(0)".format(listbox.GetSelection()))

def on_listbox2(self, event):
listbox = event.GetEventObject()
print("选择(0)".format(listbox.GetSelections()))

app = wx.App()

frm = MyFrame()
frm.Show()
app.MainLoop()

image.png

python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import wx

class MyFrame(wx.Frame):
def __init__(self):
super().__init__(None, title='静态图片控件', size=(1000, 1000))
self.panel = wx.Panel(parent=self)

self.bmps = [
wx.Bitmap('T:/MY WORLD/chasing stars/一起走花路吧.png', wx.BITMAP_TYPE_ANY),
wx.Bitmap('T:/MY WORLD/chasing stars/海源1.png', wx.BITMAP_TYPE_ANY),
wx.Bitmap('T:/MY WORLD/chasing stars/一起走花路吧.png', wx.BITMAP_TYPE_ANY)
]

b1 = wx.Button(self.panel, id=1, label='Button1')
b2 = wx.Button(self.panel, id=2, label='Button2')
self.Bind(wx.EVT_BUTTON, self.on_click, id=1, id2=2)

self.image = wx.StaticBitmap(self.panel, bitmap=self.bmps[0])

vbox = wx.BoxSizer(wx.VERTICAL)
vbox.Add(b1, proportion=1, flag=wx.EXPAND)
vbox.Add(b2, proportion=1, flag=wx.EXPAND)
vbox.Add(self.image, proportion=3, flag=wx.EXPAND)

self.panel.SetSizer(vbox)

def on_click(self, event):
event_id = event.GetId()
if event_id == 1:
self.image.SetBitmap(self.bmps[1])
else:
self.image.SetBitmap(self.bmps[2])
self.panel.Layout()

app = wx.App()

frm = MyFrame()
frm.Show()
app.MainLoop()

image.png

网络通信

python
1
2
3
4
5
6
7
8
9
10
'''发送GET请求'''
import urllib.request

url = 'https://agoni66.github.io/'

req = urllib.request.Request(url)
with urllib.request.urlopen(req) as response:
data = response.read()
json_data = data.decode()
print(json_data)
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
'''发送POST请求'''

import urllib.parse
import urllib.request

url = 'https://agoni66.github.io/'

params_dict = {'action':'query', 'ID':'10'}
params_str = urllib.parse.urlencode(params_dict)
print(params_str)

params_bytes = params_str.encode()

req = urllib.request.Request(url)
with urllib.request.urlopen(req) as response:
data = response.read()
json_data = data.decode()
print(json_data)
  • JSON(JavaScript Object Notation)
  • JSON文档
    • JSON对象
    • JSON数组
  • 下载文件
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
'''下载文件'''

import urllib.parse
import urllib.request

url = 'https://wkphoto.cdn.bcebos.com/37d3d539b6003af3156af430252ac65c1138b689.jpg'

req = urllib.request.Request(url)

with urllib.request.urlopen(req) as response:
data = response.read()
f_name = 'download.jpg'
with open(f_name, 'wb') as f:
f.write(data)
print('下载文件成功')
  • JSON对象解码——字典
  • JSON数组解码——列表

访问数据库

  • 数据类型
    • INTEGER 有符号的整数类型
    • REAL 浮点类型
    • TEXT 字符串类型(UTF-8、UTF-16)
    • BLOB 二进制大对象类型,能够存放任意二进制数据
  • Python数据类型与SQLite数据类型的映射
Python数据类型 SQLite数据类型
None NULL
int INTEGER
float REAL
str TEXT
bytes BLOB
  • 数据库连接对象Connection
    • connect(database) 打开数据库连接,database是数据库的文件路径
    • close() 关闭数据库连接
    • commit() 提交数据库事务
    • rollback() 回滚数据库事务
    • cursor() 获得Cursor游标对象
  • 游标cursor操作
    • execute(sql[, parameters]) 执行一条SQL语句
    • execute(sql[, seq_of_params]) 执行批量SQL语句
    • fetchone() 从结果中返回只有一条记录的序列
    • fetchmany(size=cursor.arraysize) 从结果中返回小于等于size记录数的序列
    • fetchall() 从结果集中返回所有数据

多线程

  • 线程模块——threading

    • active_count() 返回当前处于活动状态的线程个数
    • current_thread() 返回当前的线程对象
    • main_thread() 返回主线程对象
    • Thread(target=None, name=None,args=()) 创建线程Thread对象
      • target参数指向线程体函数
      • name参数可以设置线程名
      • args是为线程体函数提供的参数
    • 有休眠和没有休眠的区别

      image.png

  • 自定义线程函数

python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import threading
import time

# 线程体函数,该函数可以使得当前线程休眠两秒。只有当前线程休眠,其他线程才有机会执行
def thread_body():
# 当前线程对象
t = threading.current_thread()
for n in range(5):
# 当前线程名
print('第{0}次执行线程{1}'.format(n, t.name))
# 线程休眠
# time.sleep(2)
print('线程{0}执行完成!'.format(t.name))

# 主线程
# 创建线程对象t1
t1 = threading.Thread(target=thread_body)

# 创建线程对象t2
t2 = threading.Thread(target=thread_body, name='MyThread')

# 启动线程t1
t1.start()

# 启动线程t2
t2.start()
  • 自定义线程类
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import threading
import time

# 定义线程类的构造方法, name参数是线程名
class SmallThread(threading.Thread):
def __init__(self, name=None):
super().__init__(name=name)

# 线程体函数,重写父类Thread的run()方法
def run(self):
# 当前线程对象
t = threading.current_thread()
for n in range(5):
# 当前线程名
print('第{0}次执行线程{1}'.format(n, t.name))
# 线程休眠
time.sleep(2)
print('线程{0}执行完成!'.format(t.name))

# 主线程
# 通过自定义线程类,创建线程对象
# 创建线程对象t1
t1 = SmallThread()

# 创建线程对象t2
t2 = SmallThread(name='MyThread')

# 启动线程t1
t1.start()

# 启动线程t2
t2.start()
  • 线程管理
    • 线程创建
    • 线程启动
    • 线程休眠
    • 等待线程结束
    • 线程停止
  • 等待线程结束

join(timeout=None) timeout用于设置超时时间

python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import threading
import time

# 共享变量
value = []

# 线程体函数
def thread_body():
# 在子线程体中修改变量value的内容
print('t1子线程开始...')
for n in range(2):
print('t1子线程执行...')
value.append(n)
# 线程休眠
time.sleep(2)
print('t1子线程结束。')

# 主线程开始执行...
# 创建线程对象t1
t1 = threading.Thread(target=thread_body)

# 启动线程t1
t1.start()

# 主线程被阻塞,等待t1线程结束
t1.join()

# t1线程结束,继续执行,访问并输出变量value
print('value={0}'.format(value))
print('主线程继续执行...')

image.png

  • 线程停止
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import threading
import time

# 线程停止变量
isrunning = True

# 工作线程体函数
def workthread_body():
global isrunning
while isrunning:
# 线程开始工作
print('工作线程执行中...')
# 线程休眠
time.sleep(5)
print('工作线程结束。')

# 控制线程体函数
def controlthread_body():
global isrunning
while isrunning:
# 从键盘输入停止指令exit
command = input('请输入停止指令:')
if command == 'exit':
isrunning = False
print('控制线程结束。')

# 主线程
# 创建工作线程对象workthread
workthread = threading.Thread(target=workthread_body)

# 启动线程workthread
workthread.start()

# 创建控制线程对象controlthread
controlthread = threading.Thread(target=controlthread_body)

# 启动线程controlthread
controlthread.start()

image.png