从python3到python2的踩坑

为什么要从py3到py2

背景:之前自学写过一些py3,而且我写的工具是基于python3来写的,但是公司项目是使用python2版本,希望已有工具或者新写的工具能同时在py2和py3上执行,所以记录此踩坑篇。


常见踩坑

python3中print要输出的内容要加上(),比如py2:print xxx,而py3: print(xxx)

Python 版本 2.7 不 支持 'F' 前缀,就是不支持这种格式化的方法

查看:python - Python3 f string alternativ in Python2 - Stack Overflow

py2没有xmlrpc.client?


第三方库

GitPython用来在python中操作git,但python2.7只能使用GitPython 2.x,而新版本3.x只支持python3


路径

路径在py2中需要重新编码,比如:

if str.find(blob.abspath, "markdown_blogs") <= 0:				#python3直接用,encode反而出错,需要查下
if str.find(blob.abspath.encode('gbk'), "markdown_blogs") <= 0: #python2要encode

迭代器

generators的迭代器方法在python2中为__next__(),而python3中为next()


文本读取出错

编码出错

with open(path_cfgfile, "w", encoding="utf-8") as f:
    json.dump({}, f)

上面这段代码报如下错误:(<type 'exceptions.TypeError'>, TypeError("'encoding' is an invalid keyword argument for this function",), <traceback object at 0x0376F5D0>)

另一个错误:

for mdfile in glob.glob(path_draft + "*.md"):
	title, postid, publish = post_art(mdfile.decode("utf-8"), False)

python2和python3 with open as f写中文乱码_QuantSun的博客-CSDN博客

向后移植将Python 3 open(encoding =“ utf-8”)移植到Python 2 (qastack.cn)


中文文件名读取出来是乱码

原始文件名:大文件日志查看工具.md,打印出来:./article_draft\���ļ���־�鿴����.md

和这篇文章讲到的还不一样python(2)中文编码乱码问题_湘不香博士的博客-CSDN博客

最后可以参考这篇文章《处理Python2.7的中文乱码问题 - 简书 (jianshu.com)

最后的解决办法是在pycharm的控制台下是乱码,但是powshell则是正常的


posted @ 2021-10-29 09:52  赵青青  阅读(331)  评论(0编辑  收藏  举报