我有一些用Python 2.7编写的Python脚本。我必须在Python 3.x中使用这些脚本,但我必须改变很多东西,如:
print "something"
到
print ("something")
因为Python 3.x不支持没有括号的 print 函数。我不想手动这样做,因为它太长而且太难了。我尝试了重新模块但失败了。我被困了,所以任何帮助都会受到赞赏。
答案 0 :(得分:4)
尝试自动2to3
库
https://docs.python.org/2/library/2to3.html
$ 2to3 example.py
直接进行更改
$ 2to3 -w example.py
<强> STEPS 强>
将您的代码写入名为example.py
的文件中 print "something"
保存并关闭。打开终端并输入
2to3 -w example.py
立即打开文件。 Tada ......代码被转换
print(something)
答案 1 :(得分:0)
你可以尝试这样的事情。
import re
with open("myprogram.py","r",encoding='utf8') as f:
for x in f.readlines():
y = x # Main code x defining as y.
if re.findall("print",x) == ['print']: # if 'print' is found;
x = "print(" + x.split("print")[1].strip() + ")" # strip it quotation mark and paranthesis;
y = y.replace(y,x) #.. replace y with x.
with open("different.py","a+") as ff:
(y.strip()) # attention using \n for every sentence..
但它可能会破坏您的代码设计。所以打印并复制粘贴。
import re
with open("myprogram.py","r",encoding='utf8') as f:
for x in f.readlines():
y = x # Main code x defining as y.
if re.findall("print",x) == ['print']: # if 'print' is found;
x = "print(" + x.split("print")[1].strip() + ")" # strip it quotation mark and paranthesis;
y = y.replace(y,x) #.. replace y with x.
print(y.strip())