求助:Python2.7可运行代码在3.6.4(Sublime Text3)中报错
Hey there! Let's break down why your Python 2.7 code isn't working in Python 3.6.4—there are a handful of key differences between the two versions that usually cause these kinds of issues. Here are the most common culprits and fixes to try out:
Common Python 2 → 3 Incompatibilities & Fixes
- Print Statement vs Print Function
In Python 2,print "Hello World"works perfectly, but in Python 3,printis a proper function that requires parentheses:print("Hello World"). If your code uses the old print syntax, that’s a quick, easy fix. - Integer Division Behavior
Python 2 does integer division automatically with/(e.g.,5/2returns2), while Python 3 returns a float (5/2gives2.5). If you need integer division in Python 3, use//instead. Alternatively, if you want to align Python 2's behavior to match Python 3 before porting, addfrom __future__ import divisionat the very top of your code. - String & Bytes Handling
Python 2 treats strings as bytes by default, but Python 3 uses Unicode strings as the standard. If your code deals with file I/O or string encoding, you might hit errors likeUnicodeDecodeError. Try converting byte objects to strings with.decode('utf-8'), or ensure string literals that need Unicode are prefixed withu(Python 3 supports this prefix too, so it’s safe to add). - Renamed/Moved Modules
Several standard library modules got renamed or restructured in Python 3:ConfigParser→configparserStringIO→io.StringIOurlparse→urllib.parse
Double-check all import statements in your code to make sure they match Python 3's module names.
- Iteration Object Changes
Functions likerange()in Python 2 return a list, but in Python 3 they return an iterator. If your code relies onrangebeing a list (e.g., accessingrange(5)[2]directly), wrap it inlist():list(range(5))[2]. Also,xrange()doesn’t exist in Python 3—just userange()instead, since it behaves like Python 2'sxrange.
Sublime Text 3 Specific Checks
- Verify your build system is pointing to Python 3.6.4, not Python 2. Go to
Tools > Build System > New Build Systemand make sure thecmdpath links to your Python 3 executable. A sample build config might look like this:{ "cmd": ["C:/Python36/python.exe", "-u", "$file"], "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)", "selector": "source.python" } - If you have any Sublime packages installed that interact with Python, try disabling them temporarily to rule out conflicts that might be breaking execution.
Next Steps
If you can share the specific error message you’re seeing, I can help narrow down the exact issue even faster! But starting with these checks should cover most common porting problems between Python 2.7 and 3.6.4.
内容的提问来源于stack exchange,提问作者Johhny
相关产品推荐
相关产品推荐

