How to detect if code is python 3 compatible

后端 未结 5 991
没有蜡笔的小新
没有蜡笔的小新 2021-02-01 16:55

I\'m doing static code analysis using openstack/bandit. Do have a lot of repositories, some of those are in python 2 other in python 3. How can I detect if code is syntactically

5条回答
  •  星月不相逢
    2021-02-01 17:25

    Basic validation would be if the 2to3 tool prints any diffs (s. https://docs.python.org/3/library/2to3.html for basic usage)

    on a simple file like a.py:

    import urllib2
    
    print "printing something"
    

    you'd get:

    > 2to3 a.py

    RefactoringTool: Skipping optional fixer: buffer
    RefactoringTool: Skipping optional fixer: idioms
    RefactoringTool: Skipping optional fixer: set_literal
    RefactoringTool: Skipping optional fixer: ws_comma
    RefactoringTool: Refactored a.py
    --- a.py    (original)
    +++ a.py    (refactored)
    @@ -1,4 +1,4 @@
    -import urllib2
    +import urllib.request, urllib.error, urllib.parse
    
    -print "printing something"
    +print("printing something")
    
    RefactoringTool: Files that need to be modified:
    RefactoringTool: a.py
    

提交回复
热议问题