Python3의 2to3 변환 도구 사용 예

2073 단어
python3과python2는 아직도 많은 차이가 있다. 예를 들어 2에서 다음과 같다.
 
  
print "Hello,World!" 
raw_input() 

3 안에서는:
 
  
print ("Hello,World!") 
input()

따라서python2로 개발한 프로젝트를 3으로 옮기려면 코드 변환이 필요합니다.Python3에는 변환 도구가 있습니다. 다음은 가장 간단한 예로 2to3 변환 도구를 설명합니다.
예: (2to3Test.py에는 print 줄 코드만 있음)
 
  
# python 2.7.6 
# 2to3Test.py 
 
print "Hello,World!" 

python27을 사용하면 분명히 컴파일할 수 있습니다.
 
  
D:\Python>python27 2to3Test.py 
Hello,World! 

python33으로 컴파일할 수 없습니다. 3리 print는 함수이기 때문에 이렇게 쓰면 문법 오류가 발생합니다.
 
  
D:\Python>python33 2to3Test.py 
  File "2to3Test.py", line 1 
    print "Hello,World!" 
                       ^ 
SyntaxError: invalid syntax 

다음은python3의 2to3 도구를 사용하여 변환합니다.
 
  
D:\Python>python C:\Python33\Tools\Scripts\2to3.py -w 2to3Test.py 
RefactoringTool: Skipping implicit fixer: buffer 
RefactoringTool: Skipping implicit fixer: idioms 
RefactoringTool: Skipping implicit fixer: set_literal 
RefactoringTool: Skipping implicit fixer: ws_comma 
RefactoringTool: Refactored 2to3Test.py 
--- 2to3Test.py (original) 
+++ 2to3Test.py (refactored) 
@@ -1 +1 @@ 
-print "Hello,World!" 
+print("Hello,World!") 
RefactoringTool: Files that were modified: 
RefactoringTool: 2to3Test.py 

마지막으로python33으로 컴파일한 결과가 정확합니다.
 
  
D:\Python>python33 2to3Test.py 
Hello,World! 

요약: 1.목록.C:\Python33\Tools\Scripts\2to3.py.사실python2.6, 2.7에 모두 이 도구가 존재합니다.2. -w 매개 변수를 추가하지 않으면 기본적으로 변환 과정에 대응하는 diff 내용을 현재 창에 출력할 뿐입니다.3. -w를 추가하면 변경 내용을 원래의 문서로 쓴 것이다.4. bak 파일을 생성하지 않으려면 -n을 추가하면 된다.백은 있는 게 좋을 거야.

좋은 웹페이지 즐겨찾기