Code changes from Python 2.6 to 3.x

2020-05-01 08:14发布

I am trying to get pywbem working in Python 3.2 (it works fine in 2.6) but the build fails on this part of code in mof_compiler.py:

  File "pywbem-0.7.0\mof_compiler.py", line 1341
    print s
          ^
SyntaxError: invalid syntax

It's a macro, defined like this:

def _print_logger(s):
    print s

I don't understand why this is invalid, please explain how to do the same in Python 3.2.

Note: I have little or no experience with Python.

PS: I have already done some small changes to the code for 3.2 like changing

except CIMError, ce:

to

except CIMError as ce:

based on Lennart Regebro's answer here are some other changes I found (placing them here since it may be useful for others).

exec "import %s as lextab" % tabfile -> exec ("import %s as lextab" % tabfile)
raise ValueError,"Expected a string" -> raise ValueError("Expected a string")

3条回答
一纸荒年 Trace。
2楼-- · 2020-05-01 08:50

One of the most visible changes in python 3 is print is no longer a statement, but is a function, so you have to use parenthesis for calling that function. print(s)

Also, if you have your Python2 code, just use 2to3 which can do a source to source translation of your python2 to python3, which can fix most of the syntax level changes for you like the above problems. 2to3 is installed with python3 binary.

查看更多
孤傲高冷的网名
3楼-- · 2020-05-01 09:11

That's not a macro, it's a function definition, and in Python 3 the print statement is now a function. So do print(s) instead.

The list of changes between Python 2 and Python 3 is here: http://docs.python.org/release/3.0.1/whatsnew/3.0.html It's not so easy to read, but I don't know if there is a better one online (although books exist).

If you are going to use Python 3, you would probably do good to get a Python 3 book. There are a couple of them out now. Or at least refer to the Python 3 documentation: http://docs.python.org/release/3.2/ It has a decent tutorial.

查看更多
Bombasti
4楼-- · 2020-05-01 09:12

Sorry for answering an old question, but I just recently wanted to get PyWBEM running under Python 3, so I forked it, made the required changes, and removed a Python 2.x dependency (M2Crypto) from it for the 3.x series. Here's the source from GitHub:

https://github.com/deejross/python3-pywbem

Quick note, this supports Python 2.6, 2.7, and 3.4+

查看更多
登录 后发表回答