為什么要從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則是正常的
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/341695.html
標籤:Python
