鱼C论坛

 找回密码
 立即注册
查看: 3720|回复: 9

[技术交流] python3的一些 功能/工具 说明

[复制链接]
发表于 2020-9-7 10:13:35 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 Cool_Breeze 于 2020-9-10 19:56 编辑

getopt使用方法

  1. #coding=utf-8

  2. import sys
  3. import getopt


  4. # 模拟命令行
  5. sys.argv =  ['t.py', '-iabc.txt', '-ores.txt', '--sn=123123123', '12']  
  6. print(sys.argv)

  7. # 'i:o:' 短命令,':' 为短命令必须带参数 写成:-i123.txt  -i就等于123.txt
  8. # 'io' 为短命令不带参数 写成:-i,-o
  9. # ['in=, out=, nu='] 长命令,'=' 为长命令必须带参数 写成:--in=xxx --in就等于xxx
  10. # ['in, out, nu'] 为长命令不带参数 写成: --in

  11. opts, args = getopt.getopt(sys.argv[1:],'i:o:', ['input=', 'output=', 'sn='] )

  12. print(opts) # 命令列表 [('-i', 'abc.txt'), ('-o', 'res.txt'), ('--sn', '123123123')]
  13. print(args) # 命令不配的参数值 ['12']

  14. input_s = ''
  15. output = ''
  16. sn = ''

  17. for o,v in opts:
  18.     if o in '-i, --input':
  19.         input_s = v
  20.     elif o in '-o, --output':
  21.         output = v
  22.     elif o in '--sn':
  23.         sn = v
  24.         
  25. print('i = {}\no = {}\nsn = {}'.format(input_s, output, sn))
  26. #i = abc.txt
  27. #o = res.txt
  28. #sn = 123123123
复制代码

本帖被以下淘专辑推荐:

  • · Python|主题: 247, 订阅: 52
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2020-9-10 19:41:32 | 显示全部楼层
本帖最后由 Cool_Breeze 于 2020-9-10 21:38 编辑

sys.path # 查看所有模块的导入路径

pip 用法

pip install <package_name>
pip uninstall <package_name>
pip list 已安装包列表 name    version
pip freeze  name==version

pip freeze > file_name

pip install -r file_name  读取 file_name 文件里的包信息 然后逐一安装

# 临时修改
pip install <package_name> -i <url> #从指定源下载包

# 永久修改
首先在当前用户目录下新建一个 pip 目录, 在 pip 目录下面添加一个 pip.ini 文件
批处理命令查看 用户目录
  1. echo %USERPROFILE%
复制代码

# pip.ini 文件内容
  1. [global]
  2. index-url=https://pypi.douban.com/simple
  3. [install]
  4. trusted-host=pypi.douban.com
复制代码


# 一些常用的国内源
(1)阿里云
  1. http://mirrors.aliyun.com/pypi/simple/
复制代码

(2)豆瓣
  1. http://pypi.douban.com/simple/
复制代码

(3)清华大学
  1. https://pypi.tuna.tsinghua.edu.cn/simple/
复制代码

(4)中国科学技术大学
  1. http://pypi.mirrors.ustc.edu.cn/simple/
复制代码

(5)华中科技大学
  1. http://pypi.hustunique.com/
复制代码

小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-9-10 20:23:13 From FishC Mobile | 显示全部楼层
Cool_Breeze 发表于 2020-9-10 19:41
pip 用法

pip install

腾讯源也可以,速度稳定
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2020-9-10 20:26:38 From FishC Mobile | 显示全部楼层
本帖最后由 hrp 于 2020-9-10 20:29 编辑

getopt是内置模块吗
看上去好像比click方便
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-9-10 21:34:58 | 显示全部楼层
hrp 发表于 2020-9-10 20:23
腾讯源也可以,速度稳定

可以。我试试! getopt是内置模块,click 我没有用过
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-9-14 09:33:16 | 显示全部楼层
本帖最后由 Cool_Breeze 于 2020-9-16 21:06 编辑

class 的一些内置方法!
  1. #!/usr/bin/env python3
  2. #coding=utf-8

  3. from time import sleep
  4. class a(object):
  5.     def __init__(self):
  6.         print("__init__ was called!")
  7.         
  8.     def __del__(self):
  9.         print("__del__ was called!")
  10.         
  11.     def __len__(self):
  12.         print("__len__ was called!")
  13.         return 6

  14.     def __str__(self):
  15.         return 'str'

  16.     def __repr__(self):
  17.         return 'repr'

  18.     def __eq__(self, name):
  19.         return 1


  20. print('command : b = a()')
  21. b = a()

  22. print('command : b == 1')
  23. print( b == 1)

  24. print('command : len(b)')
  25. print(len(b))

  26. print('command : b)')
  27. print(b)

  28. print('sleep(2), exit!')
  29. sleep(2)
  30. #object.__new__(cls) 申请内存空间
  31. #c = object.__new__(a)
  32. #c.__init__()
复制代码
  1. command : b = a()
  2. __init__ was called!
  3. command : b == 1
  4. 1
  5. command : len(b)
  6. __len__ was called!
  7. 6
  8. command : b)
  9. str
  10. sleep(2), exit!

复制代码


官方文档:
  1. https://docs.python.org/zh-cn/3.7/library/stdtypes.html
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-9-16 19:39:01 | 显示全部楼层
本帖最后由 Cool_Breeze 于 2020-9-16 21:00 编辑

class 方法的使用

  1. #!/usr/bin/env python3
  2. #coding=utf-8

  3. class games:
  4.     agent = '腾讯' # 类属性
  5.     game = 'LOL'
  6.     def __init__(self, player):
  7.         self.player = player # 实例属性
  8.         
  9.     def play(self): #实例方法
  10.         print('{} 正在玩 {}'.format(self.player, games.game)) # 类属性可以通过类名.属性来调用
  11.         
  12.     @staticmethod
  13.     def current_time(): #静态方法
  14.         import time
  15.         print('当前时间 {}'.format(time.ctime()))
  16.         return 0
  17.    
  18.     @classmethod
  19.     def initformation(cls): # 类方法
  20.         print('游戏代理:{} 游戏名 {}'.format(cls.agent, cls.game))
  21.         return 0

  22. # print(games.initformation())
  23. # 游戏代理:腾讯 游戏名 LOL
  24. # 0
  25. # print(games.current_time())
  26. # 当前时间 Wed Sep 16 19:20:50 2020
  27. # 0

  28. # t = games('平平')
  29. # print(t.game) # 实例对象没有该属性,就往上找类的属性
  30. # LOL
  31. # print(t.play())
  32. # 平平 正在玩 LOL
  33. # None
  34. # games.play(t)
  35. # 平平 正在玩 LOL
  36. # t.initformation()
  37. # 游戏代理:腾讯 游戏名 LOL
  38. # t.current_time()
  39. # 当前时间 Wed Sep 16 19:20:50 2020
复制代码


# t 变量名是 games 类的实例
#     实例方法中的参数 self 就是指的实例 t 【 系统自动传入 】
# 还有一种方法就是自己通过类名,手动传入 self 这个参数, 【 一个类实例 】
#    games.play(t)

# 静态方法:当一个方法既没有用到实例属性,有没有用到类属性。相对独立的方法。
# 类方法: 当一个方法只用到了类属性,就可以定义为类方法。 cls 参数就是 类名

# 类属性只能通过类对象修改
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-10-4 11:21:42 | 显示全部楼层
本帖最后由 Cool_Breeze 于 2020-10-4 11:23 编辑

红绿灯
  1. https://docs.python.org/zh-cn/3.7/library/multiprocessing.html#module-multiprocessing.pool
复制代码
  1. #!/usr/bin/env python3

  2. from multiprocessing import Process, Manager, Pool
  3. import time #开启延时,减少cpu占用

  4. class traffic(object):
  5.    
  6.     def __init__(self):
  7.         self.queue = Manager().Queue() #多个进程共享数据,需要服务器进程管理
  8.    
  9.     def light(self):
  10.         self.queue.put('red')
  11.         while True:
  12.             for i in range(1,6):
  13.                 print('current red light %d' %abs(i-6))
  14.                 for j in range(1,10):
  15.                     self.queue.put('red')
  16.                     time.sleep(0.1)
  17.             for i in range(1,5):
  18.                 print('current green light %d' %abs(i-5))
  19.                 for j in range(1,10):
  20.                     self.queue.put('green')
  21.                     time.sleep(0.1)
  22.    
  23.     def light_start(self):
  24.         p = Process(target=self.light) #单独一个进程开启灯
  25.         p.start()
  26.    
  27.     def light_status(self):
  28.         return (None,self.queue.get()) [self.queue.empty()] #返回灯状态

  29.     def car(self):
  30.         po = Pool(10)
  31.         for i in range(1,30): #进程池车辆
  32.             #apply_async(func[, args[, kwds[, callback[, error_callback]]]])
  33.             po.apply_async(self.car_pass,(i,),error_callback=self.err)
  34.         po.close()
  35.         po.join() #等待工作进程结束。调用 join() 前必须先调用 close() 或者 terminate() 。
  36.         
  37.     def car_pass(self, i):
  38.         while True:
  39.             if self.light_status() == 'green':
  40.                 print('NO: {:2} car           Pass!'.format(i))
  41.                 break
  42.             else:
  43.                 print('NO: {:2} car Stop!'.format(i))
  44.             time.sleep(0.05)
  45.    
  46.     def err(self, erron):
  47.         print(erron)

  48. if __name__ == '__main__':
  49.     test = traffic()
  50.     test.light_start()
  51.     test.car()
  52.     while True:
  53.         print('light status %s' %test.light_status())
  54.         time.sleep(0.1)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2020-10-6 16:34:20 | 显示全部楼层
本帖最后由 Cool_Breeze 于 2020-10-6 16:36 编辑

"""
信号量对象也支持 上下文管理协议 。

class threading.Semaphore(value=1)
该类实现信号量对象。信号量对象管理一个原子性的计数器,代表 release() 方法的调用次数减去 acquire() 的调用次数再加上一个初始值。如果需要, acquire() 方法将会阻塞直到可以返回而不会使得计数器变成负数。在没有显式给出 value 的值时,默认为1。

可选参数 value 赋予内部计数器初始值,默认值为 1 。如果 value 被赋予小于0的值,将会引发 ValueError 异常。

在 3.3 版更改: 从工厂函数变为类。

acquire(blocking=True, timeout=None)
获取一个信号量。

在不带参数的情况下调用时:

如果在进入时内部计数器的值大于零,则将其减一并立即返回 True。

如果在进入时内部计数器的值为零,则将会阻塞直到被对 release() 的调用唤醒。 一旦被唤醒(并且计数器的值大于 0),则将计数器减 1 并返回 True。 每次对 release() 的调用将只唤醒一个线程。 线程被唤醒的次序是不可确定的。

当发起调用时将 blocking 设为假值,则不进行阻塞。 如果一个无参数调用将要阻塞,则立即返回 False;在其他情况下,执行与无参数调用时一样的操作,然后返回 True。

当发起调用时如果 timeout 不为 None,则它将阻塞最多 timeout 秒。 请求在此时段时未能成功完成获取则将返回 False。 在其他情况下返回 True。

在 3.2 版更改: 新的 timeout 形参。

release()
释放一个信号量,将内部计数器的值增加1。当计数器原先的值为0且有其它线程正在等待它再次大于0时,唤醒正在等待的线程。

class threading.BoundedSemaphore(value=1)
该类实现有界信号量。有界信号量通过检查以确保它当前的值不会超过初始值。如果超过了初始值,将会引发 ValueError 异常。在大多情况下,信号量用于保护数量有限的资源。如果信号量被释放的次数过多,则表明出现了错误。没有指定时, value 的值默认为1。

在 3.3 版更改: 从工厂函数变为类。
"""
  1. #!/usr/bin/env python3
  2. from threading import Thread, Semaphore
  3. import time
  4. '''
  5. 使用信号量使 2个线程按顺序被交替执行
  6. '''

  7. class foo(object):
  8.     def __init__(self):
  9.         self.sema = Semaphore() # 信号量a 控制a线程 默认值为1
  10.         self.semb = Semaphore() # 信号量b 控制b线程 默认值为1
  11.         self.semb.acquire() # 信号量a - 1 = 0(启动)
  12.         
  13.     def a(self):
  14.         for i in range(10):
  15.             self.sema.acquire() # 第一次a=1-1=0,第二次调用将被阻塞,直到被sema.release调用
  16.             print("{} runing {}".format(foo.a.__name__, i))
  17.             self.semb.release() # 调用被阻塞semb后,马上又被sema.acquire阻塞
  18.         
  19.     def b(self):
  20.         for i in range(10):
  21.             self.semb.acquire() # b线程阻塞 (第二次)b=0, 直到被semb.release调用
  22.             print("{} runing {}".format(foo.b.__name__, i))
  23.             self.sema.release() # 调用被阻塞sema后,马上又被semb.acquire阻塞
  24.         

  25. if __name__ == '__main__':
  26.     test = foo()
  27.     p = Thread(target=test.a)
  28.     p1 = Thread(target=test.b)
  29.     p.start()
  30.     time.sleep(1) # a线程率先启动,但还是得等线程b启动
  31.     p1.start()
  32.     p.join() # p 在 p1 执行完后结束。加了信号量的原因。
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2021-2-23 14:39:43 | 显示全部楼层
查看 模块文件所在位置
  1. import multiprocessing
  2. import sys
  3. sys.modules["multiprocessing"]
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-27 13:05

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表