html tool

显示标签为“python”的博文。显示所有博文
显示标签为“python”的博文。显示所有博文

2024年2月18日星期日

转:python对json的读取,load()与loads()的区别

 参考:https://blog.csdn.net/m0_51971452/article/details/111701927

原文:

json.dumps()把数据类型转换成字符串 

json.dump()把数据类型转换成字符串并存储在文件中 

json.loads()把字符串转换成数据类型 

json.load()把文件打开从字符串转换成数据类型

例子:

读取load

     f = open("testdata/%s" % s) #这里测试文件为json格式化后的格式保存

    cur_test = json.load(f) #这里json文件默认使用了2个空格为分隔符,不指定可以被识别

    f.close()

   print(cur_test)
   print(type(cur_test))

写入dumps: 
--字典数据用dumps()编码成json字符串,存储到json文件中
with open("temp/%s.json" % s,"w") as f:
    f.write(json.dumps(load_dict, indent=4, ensure_ascii=False))
--用dump()方法将字典数据写入json文件中
with open("temp/%s.json" % s,"w") as f:
    json.dump(load_dict, write_f, indent=4, ensure_ascii=False)

2023年9月15日星期五

python中json 存文件

 参考:https://blog.csdn.net/leviopku/article/details/103773219

     r = json.dumps(report_json)

     f = open(sf, "w")

     f.write(r)

     f.close()




2023年9月13日星期三

转:python中json中单引号引起的TypeError: expected string or buffer 解决

 参考:https://www.cnblogs.com/pinpin/p/10619471.html

import json

data = [{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}]
print(type(data),data)

执行结果:

<class 'list'> [{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}]

但是了,json是不支持单引号的。可以用下面的方法转换

json_string=json.dumps(s)

python_obj=json.loads(json_string)

2022年11月11日星期五

转:python列表去重方式

 https://blog.csdn.net/Jerry_1126/article/details/79843751


方法一: 使用内置set方法来去重


>>> lst1 = [2, 1, 3, 4, 1]

>>> lst2 = list(set(lst1))

>>> print(lst2)

[1, 2, 3, 4]


方法二: 使用字典中fromkeys()的方法来去重


>>> lst1 = [2, 1, 3, 4, 1]

>>> lst2 = {}.fromkeys(lst1).keys()

>>> print(lst2)

dict_keys([2, 1, 3, 4])



2022年11月10日星期四

Queue模块

 转:https://blog.csdn.net/zy205817/article/details/51388479

Queue是python中的标准库,可以直接import 引用,之前学习的时候有听过著名的“先吃先拉”与“后吃先吐”,其实就是这里说的队列,队列的构造的时候可以定义它的容量,别吃撑了,吃多了,就会报错,构造的时候不写或者写个小于1的数则表示无限多


import Queue


q = Queue.Queue(10)


向队列中放值(put)


q.put(‘yang’)


q.put(4)


q.put([‘yan’,’xing’])


在队列中取值get()


默认的队列是先进先出的


>>> q.get() 

'yang' 

>>> q.get() 

>>> q.get() 

['yan', 'xing'] 

>>>


 


当一个队列为空的时候如果再用get取则会堵塞,所以取队列的时候一般是用到


get_nowait()方法,这种方法在向一个空队列取值的时候会抛一个Empty异常


所以更常用的方法是先判断一个队列是否为空,如果不为空则取值


队列中常用的方法


Queue.qsize() 返回队列的大小  

Queue.empty() 如果队列为空,返回True,反之False  

Queue.full() 如果队列满了,返回True,反之False 

Queue.get([block[, timeout]]) 获取队列,timeout等待时间  

Queue.get_nowait() 相当Queue.get(False) 

非阻塞 Queue.put(item) 写入队列,timeout等待时间  

Queue.put_nowait(item) 相当Queue.put(item, False)


2022年11月1日星期二

转:pip安装指定版本

 https://blog.csdn.net/youcharming/article/details/51073911

要用 pip 安装指定版本的 Python 包,只需通过 == 操作符 指定

pip install robotframework==2.8.7

将安装robotframework 2.8.7 版本


PS:

python2 的默认mock==3.0.5

2022年10月27日星期四

转:python将字典保存成json 文件

 https://blog.csdn.net/leviopku/article/details/103773219

python将字典保存成json

import json

a = {

    "name": "dabao",

    "id":123,

    "hobby": {

        "sport": "basketball",

        "book": "python study"

    }

}

b = json.dumps(a)

f2 = open('new_json.json', 'w')

f2.write(b)

f2.close()

首先通过json.dumps()把dict降级为字符串。再将字符串写入json文件中。就是这么简单


2022年10月21日星期五

python zip文件处理

 转: https://blog.csdn.net/qq_33485434/article/details/82253642


通过 Python 内置的 zipfile 模块实现对 zip 文件的解压,加点料完成口令破解。

zipfile模块基本使用

使用 zipfile 压缩文件

import zipfile

#创建一个zip文件对象,压缩是需要把mode改为‘w’

zfile=zipfile.ZipFile("test.zip","w")

#将文件写入zip文件中,即将文件压缩

zfile.write(r"../test.py")

#将zip文件对象关闭

zfile.close()

使用 zipfile 解压文件

import zipfile

#解压

zfile=zipfile.ZipFile("../test.zip","r") 

zfile.extractall()

【popexizhi: 这里可以使用内存文件解压,eg如下:

get_res = Sender('rule.cn').geter_rule(get_url, date, Authorization, cookie, 1) #内存文件是url返回的二进制

#解压转储

fio = BytesIO(get_res)

zipF = zipfile.ZipFile(file=fio)

python内存文件

 转:https://www.liaoxuefeng.com/wiki/1016959663602400/1017609424203904

BytesIO

StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIO。

BytesIO实现了在内存中读写bytes,我们创建一个BytesIO,然后写入一些bytes:

>>> from io import BytesIO
>>> f = BytesIO()
>>> f.write('中文'.encode('utf-8'))
6
>>> print(f.getvalue())
b'\xe4\xb8\xad\xe6\x96\x87'

请注意,写入的不是str,而是经过UTF-8编码的bytes。

和StringIO类似,可以用一个bytes初始化BytesIO,然后,像读文件一样读取:

>>> from io import BytesIO
>>> f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87')
>>> f.read()
b'\xe4\xb8\xad\xe6\x96\x87'


StringIO

很多时候,数据读写不一定是文件,也可以在内存中读写。

StringIO顾名思义就是在内存中读写str。

要把str写入StringIO,我们需要先创建一个StringIO,然后,像文件一样写入即可:

>>> from io import StringIO
>>> f = StringIO()
>>> f.write('hello')
5
>>> f.write(' ')
1
>>> f.write('world!')
6
>>> print(f.getvalue())
hello world!

getvalue()方法用于获得写入后的str。


小结

StringIO和BytesIO是在内存中操作str和bytes的方法,使得和读写文件具有一致的接口。

2022年10月13日星期四

openssl的sha1密钥 bash实现

 

来源:

https://blog.csdn.net/armlinuxww/article/details/115479401

https://www.qetool.com/scripts/view/22012.html

目标:

python如下代码的bash实现

# 通过hmac计算sha1,然后base64编码即可
signature = base64.encodestring(hmac.new(client_secret, string2Sign, hashlib.sha1).digest()).replace("\n", "")

bash实现
echo "${client_secret}"|openssl sha1 -binary -hmac ${string2Sign}|base64

其中 openssl sha1 -binary -hmac ${string2Sign}
sha1为信息完整性摘要的一种
# echo "add"|openssl dgst -sha1  -binary -hmac "aaa"|base64
6UbANJJ0F5LLE7tPy/zcKvRwxic=
# echo "add"|openssl sha1  -binary -hmac "aaa"|base64
6UbANJJ0F5LLE7tPy/zcKvRwxic=


[参考:
OpenSSL实现了5种信息摘要算法,分别是MD2、MD5、MDC2、SHA(SHA1)和RIPEMD

。SHA算法事实上包括了SHA和SHA1两种信息摘要算法,此外,OpenSSL还实现了DSS标准中规定的两种信息摘要算法DSS和DSS1。

摘要一般有两个作用:1)做信息完整性校验;2)保存密码,有些密码是直接在数据库中采用MD5(真实密码值)保存的,有的还进行加盐处理,使其难以破解,这样密码只能重置,无法告诉你原始过程,因为摘要是不可逆的。

 

  1. openssl dgst
  2. 常用选项有:
  3. [-md5|-md4|-md2|-sha1|-sha|-mdc2|-ripemd160|-dss1] :指定一种摘要算法
  4. -out filename:将摘要的内容保存到指定文件中
  5. dgst命令:
  6. 帮助: man dgst
  7. openssl dgst -md5 [-hex默认16进制] /PATH/SOMEFILE
  8. openssl dgst -md5 testfile
  9. md5sum /PATH/TO/SOMEFILE
  10. MAC: Message Authentication Code,单向加密的一种延伸应用,用于实现网络通
  11. 信中保证所传输数据的完整性机制
  12. CBC-MAC
  13. HMAC:使用md5或sha1算法

简单示例,对文件1进行求md5摘要:

]


2022年10月9日星期日

转:retry

 参考:http://www.codebaoku.com/it-python/it-python-221511.html

retrying

retrying是Python的一个第三方库,它提供一个装饰器函数retry,被装饰的业务函数就会在运行失败的条件下重新执行,默认只要报错就会一直重试,直至执行成功。

可以使用pip install retrying进行安装。

例如下面一段代码,我们使用生成随机数的大小的方式模拟业务的成功与失败,只要是生成的随机数大于2,都视为失败,就会重试,直到生成的随机数小于2:

import random
from retrying import retry


@retry
def random_with_retry():
  if random.randint(0, 10) > 2:
      print("大于2,重试...")
      raise Exception("大于2")
  print("小于2,成功!")
random_with_retry()

运行结果如下:

retry还可以接受一些参数,下面是源码中Retrying类的初始化函数中可选的参数:

  • stop_max_attempt_number:最大重试次数,超过该次数就停止重试
  • stop_max_delay:最大延迟时间(执行这个方法重试的总时间),超过该时间就停止
  • wait_fixed:两次retrying之间的等待时间
  • wait_random_min和wait_random_max:用随机的方式产生两次retrying之间的等待时间
  • wait_incrementing_start和wait_incrementing_increment:每调用一次增加固定时长
  • wait_exponential_multiplier和wait_exponential_max:以指数的形式产生两次retrying之间的等待时间,产生的值为2^previous_attempt_number * wait_exponential_multiplier,previous_attempt_number是前面已经retry的次数,如果产生的这个值超过了wait_exponential_max的大小,那么之后两个retrying之间的停留值都为wait_exponential_max。

特别需要注意的是retry_on_exception参数,它接收一个函数,用法如下:

# 判断异常
def is_MyError(exception):
  print("判断异常", exception)
  print(isinstance(exception, (ValueError, IOError, ConnectionError)))
  return isinstance(exception, (ValueError, IOError, ConnectionError))
@retry(retry_on_exception=is_MyError)
def random_with_retry():
  """
  随机一个0-10之前的整数,大于2抛异常,小于2成功
  :return:
  """
  if random.randint(0, 10) > 2:
      print("大于2,重试...")
      raise ValueError("大于2")
  print("小于2,成功!")
random_with_retry()

这里retry_on_exception参数的大体思想是:接收一个自定义函数is_MyError,在is_MyError函数里判断了是不是属于ValueError, IOError, ConnectionError这三种异常;random_with_retry()函数如果抛出了异常,会去函数is_MyError()判断返回的是True还是False,如果是True则继续重试,如果是False则立即停止并抛出异常。

还有retry_on_result参数,也是接收一个函数,判断业务函数返回哪些结果时需要重试,思想和retry_on_exception参数类似。
我们可以根据自己的需要进行合理的搭配这些参数,达到我们想要的效果。

2021年9月2日星期四

转:python 命令行参数getopt

 https://www.runoob.com/python3/python3-command-line-arguments.html

  #-*- coding:utf8 -*-
import sys,getopt

name = None
url = None
argv = sys.argv[1:]
try:
    opts, args = getopt.getopt(argv, "n:u"  , #短选项
                                ["name=",
                                 "url="]) #长选项‘
except:
    print("Error")

for opt, arg in opts:
    if opt in ['-n', '--name']:
        name = arg
    elif opt in ['-u', '--url']:
        url = arg

print( name + " " + url)

测试以上代码,命令行中输入:

python3 test.py -n RUNOOB -u www.runoob.com

输出结果为:

RUNOOB www.runoob.com

2021年8月24日星期二

python 百分号输出

https://blog.csdn.net/m0_37041325/article/details/77924773

print "%s%%" % x

2021年7月28日星期三

python \ 如何判断

 https://blog.csdn.net/haidibeike/article/details/52421667

if a is None:

pass

else:

pass

2021年1月4日星期一

转: 安装完pipenv使用时出现-bash: pipenv: 未找到命令

 https://blog.csdn.net/weixin_45854288/article/details/103950008

系统执行命令时会到 /usr/bin/ 目录下去找的,就像python3一样,需要软链接一下
这时我们需要找一下pipenv的位置
使用find
find / -name “pipenv”
在这里插入图片描述
这时我们就找到了pipenv的位置
/usr/local/python3/bin/pipenv
创造软连接
ln -s /usr/local/python3/bin/pipenv /usr/bin/pipenv
再次使用pipenv --python 3.7即可创建

2020年12月16日星期三

拾遗list in python

 1. 逻辑取反 not ( True )

>>> not ("a" in [""])

True

2. list 包含  元素 in list
>>> "a" in ["ad",""]
False

3.list 增加元素 list+=新增元素
>>> a+="t"
>>> a
['a', 'h', 't']


2020年12月15日星期二

解决:pyhton smtplib 连接office365 提示“reply: retcode (501); Msg: 5.5.4 Invalid domain name [SH0PR01CA0008.CHNPR01.prod.partner.outlook.cn]”

来源: https://answers.microsoft.com/en-us/msoffice/forum/msoffice_outlook-mso_other-mso_o365b/smtp-response-question/efa44b6d-aa47-4d01-84d4-de5d9f733638


错误提示:

smtp.partner.outlook.cn:587

connect: ('smtp.partner.outlook.cn', 587)

connect: ('smtp.partner.outlook.cn', 587)

reply: '220 SH0PR01CA0008.partner.outlook.cn Microsoft ESMTP MAIL Service ready at Tue, 15 Dec 2020 11:25:17 +0000\r\n'

reply: retcode (220); Msg: SH0PR01CA0008.partner.outlook.cn Microsoft ESMTP MAIL Service ready at Tue, 15 Dec 2020 11:25:17 +0000

connect: SH0PR01CA0008.partner.outlook.cn Microsoft ESMTP MAIL Service ready at Tue, 15 Dec 2020 11:25:17 +0000

send: 'ehlo #cet.txxx.cn\r\n'

reply: '501 5.5.4 Invalid domain name [SH0PR01CA0008.CHNPR01.prod.partner.outlook.cn]\r\n'

reply: retcode (501); Msg: 5.5.4 Invalid domain name [SH0PR01CA0008.CHNPR01.prod.partner.outlook.cn]

send: 'helo #cet.txxx.cn\r\n'

reply: '501 5.5.4 Invalid domain name [SH0PR01CA0008.CHNPR01.prod.partner.outlook.cn]\r\n'

reply: retcode (501); Msg: 5.5.4 Invalid domain name [SH0PR01CA0008.CHNPR01.prod.partner.outlook.cn]

[err](501, '5.5.4 Invalid domain name [SH0PR01CA0008.CHNPR01.prod.partner.outlook.cn]')

原因在引用地址中说的很明白了:

Hi Shen,

 

Thank you for sharing.

 

From your description, Smtplib adds the sender’s host name to the end of the EHLO command, and Office 365 doesn’t recognize this command. I’d like to let you know that we usually recommend that users use Outlook Web App or Outlook client applications to send emails. Since this problem is caused because Smtplib adds some content to the command and disrupted the email sending process, we suggest you contact Smtplib support to check if they can change the Smtplib’s behavior to avoid this issue.

 

解决方式:

按上文的思路将这里ehlo后的host地址直接删除就ok了,修改底层库如下:

再次测试通过了,如下:
]# python sendMailX.py
smtp.partner.outlook.cn:587
connect: ('smtp.partner.outlook.cn', 587)
connect: ('smtp.partner.outlook.cn', 587)
reply: '220 BJXPR01CA0052.partner.outlook.cn Microsoft ESMTP MAIL Service ready at Tue, 15 Dec 2020 11:48:57 +0000\r\n'
reply: retcode (220); Msg: BJXPR01CA0052.partner.outlook.cn Microsoft ESMTP MAIL Service ready at Tue, 15 Dec 2020 11:48:57 +0000
connect: BJXPR01CA0052.partner.outlook.cn Microsoft ESMTP MAIL Service ready at Tue, 15 Dec 2020 11:48:57 +0000
send: 'ehlo\r\n'
reply: '250-BJXPR01CA0052.partner.outlook.cn Hello [123.114.xxx.xx]\r\n'
reply: '250-SIZE 157286400\r\n'
reply: '250-PIPELINING\r\n'
reply: '250-DSN\r\n'
reply: '250-ENHANCEDSTATUSCODES\r\n'
reply: '250-STARTTLS\r\n'
reply: '250-8BITMIME\r\n'
reply: '250-BINARYMIME\r\n'
reply: '250-CHUNKING\r\n'
reply: '250 SMTPUTF8\r\n'
reply: retcode (250); Msg: BJXPR01CA0052.partner.outlook.cn Hello [123.114.xxx.xx]
SIZE 157286400
PIPELINING
DSN
ENHANCEDSTATUSCODES
STARTTLS
8BITMIME
BINARYMIME
CHUNKING
SMTPUTF8
send: 'STARTTLS\r\n'
reply: '220 2.0.0 SMTP server ready\r\n'
reply: retcode (220); Msg: 2.0.0 SMTP server ready


测试代码:

    try:

        smtp_server = "%s:%s" % (mail_host, mail_port)

        print(smtp_server)

        s = smtplib.SMTP()

        s.set_debuglevel(1)

        s.connect(smtp_server)

        s.starttls()

        s.ehlo()


2020年11月10日星期二

pexpect-spawn-sys.std.out

 https://www.jianshu.com/p/cfd163200d12


spawn() 参数:

logfile - 运行输出控制

默认值: None

当给 logfile 参数指定了一个文件句柄时,所有从标准输入和标准输出获得的内容都会写入这个文件中(注意这个写入是 copy 方式的),如果指定了文件句柄,那么每次向程序发送指令(process.send)都会刷新这个文件(flush)。

这里有一个很重要的技巧:如果你想看到spawn过程中的输出,那么可以将这些输出写入到 sys.stdout 里去,比如:

process = pexpect.spawn("ftp sw-tftp", logfile=sys.stdout)

用这样的方式可以看到整个程序执行期间的输入和输出,很适合调试。


2020年10月27日星期二

requests.exceptions.SSLError: ("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)",)

 

增加 verify=False

 r = requests.post(url, cookies=cookies,  data=json.dumps(payload), verify=False, headers=headers)

参见: https://github.com/psf/requests/issues/4381

2020年8月19日星期三

python 数组在for中的i 不是一定从0- len的

 问题记录:

在配置中一个数组一直del有问题,方式如下:

index =0 

for i in arr:

    if i["tt"] == ..:

      del arr[index]

   index = index +1


解答:

       debug后发现 这里的i不是从0 ~ len(arr),是有从len(arr)~0,也有0~len(),只有2个元素,是否有其他没测试

       还是老实的用index = arr.index(i) ,del arr[index]

参考: https://www.runoob.com/python/python-lists.html