分类 "Python" 下的文章

问题:python如何连接hive数据仓库?

解决:使用pyhive

方法:

1、安装三个python包,网上有的说要安装sasl,但我没安装成功,然后发现不安装也可以

pip install thrift==0.20.0 thrift-sasl==0.4.3 pyhive==0.7.0

阅读全文

问题:如何获取视频时长

方法:

import os

cmd = 'ffmpeg -i %s 2>&1 | grep "Duration"' % input_file
out = os.popen(cmd).read()

注:这是最好的方法,不建议使用subprocess调用进程,有点卡

问题:list如何保证排序不变去除重复元素

方法:

a = [2,3,2,4,2,1,2]
一般去重方法
list(set(a))  # 输出 [1, 2, 3, 4] 这样会出现排序错乱
[*dict.fromkeys(a)]  # 输出 [1, 2, 3, 4] 这样会出现排序错乱
sorted(set(a), key=a.index)  # 输出 [2, 3, 4, 1]  正确,但数据量大时会卡
from collections import OrderedDict
[*OrderedDict.fromkeys(a)]   # 输出 [2, 3, 4, 1]  正确,推荐

阅读全文

问题:python str to hex

方法:

str to hex

hex_str = binascii.hexlify(str.encode('utf-8')).decode('utf-8')

hex to str

str = binascii.unhexlify(hex_str.encode('utf-8')).decode('utf-8')

阅读全文

问题:pydantic如何让字段只允许几个固定的值

解决:python3 内置的enum 模块可以支持枚举类型

方法:

from enum import Enum, IntEnum

class dayEnum(IntEnum):
    all = 0 
    one = 1 
    seven = 7 
    month = 30

class DaySchema(BaseModel):
    day: dayEnum=all

阅读全文