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

时间:2015-01-01 18:12:45

标签: python python-2.7 python-3.x

我有一些用Python 2.7编写的Python脚本。我必须在Python 3.x中使用这些脚本,但我必须改变很多东西,如:

print "something"

print ("something")

因为Python 3.x不支持没有括号的 print 函数。我不想手动这样做,因为它太长而且太难了。我尝试了重新模块但失败了。我被困了,所以任何帮助都会受到赞赏。

2 个答案:

答案 0 :(得分:4)

尝试自动2to3

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

$ 2to3 example.py

直接进行更改

$ 2to3 -w example.py

<强> STEPS

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

    的文件中

    print "something"

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

    2to3 -w example.py

  3. 立即打开文件。 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())