将脚本转换为不同版本的 Python

Converting scripts to a different version of Python

我有一些 Python 脚本是用 Python 2.7 编写的。我必须将脚本与 Python 3.x 一起使用,但我必须更改很多东西,例如:

print "something"

print ("something")

因为Python 3.x不支持不带括号的print函数。我不想手动执行此操作,因为它会太长而且很难。我尝试了 re 模块但失败了。我被卡住了,所以任何帮助将不胜感激。

尝试自动化 2to3

https://docs.python.org/2/library/2to3.html

$ 2to3 example.py

直接进行更改

$ 2to3 -w example.py

步骤

  1. 将您的代码写入名为 example.py

    的文件中

    print "something"

  2. 保存并关闭。打开终端并输入

    2to3 -w example.py

  3. 现在打开文件。多田...代码转换

    print(something)

您可以尝试这样的操作。

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())