【发布时间】:2017-09-03 15:31:02
【问题描述】:
我的示例代码写在一个包含多个打印语句的文件中,
def get_address(cls,latitude,longitude):
try:
geolocator = GoogleV3()
location = geolocator.reverse(latitude,longitude)
print location
print location.address
print "location"
print("location")
return (location.address)
except Exception as e:
print e
我正在使用正则表达式从此代码中删除所有打印语句(打印 e 除外), 我的代码:
import re
regex = r"print[/s]?[^e]?(.)+"
try:
print (re.sub(regex, "AA", str))
except Exception as e:
print e
old_file=open("views.py")
new_file=open("new_text.py", "w")
for line in old_file:
new_line = re.sub(regex, "", line)
new_file.write(new_line)
old_file.close()
new_file.close()
我的代码写在views.py中,new_text.py中的新代码,运行这个脚本后,异常中的print e也被删除了,导致语法错误。有什么好的方法可以删除除 print e 之外的所有打印语句并将代码保存在同一个文件中。
【问题讨论】:
-
不要重新发明轮子。使用与 Python 安装捆绑在一起的 2to3 将您的代码更新到 Python 3。
-
@AryaMcCarthy。这似乎无关紧要,因为 OP 希望在代码中保留
print e。