Is there a way to run python 2 code within a python 3 file? I have to use a function that is coded in python 2 and is located in a python 2 file. But i need to import it and use the function within a python 3 file. Is is possible to run that function is like a python 2 mode?
-
It depends on how your function looks likeyash– yash2017-12-03 02:31:40 +00:00Commented Dec 3, 2017 at 2:31
-
Is there a way to just run like one line as python 2?chicken_wings– chicken_wings2017-12-03 02:34:29 +00:00Commented Dec 3, 2017 at 2:34
-
Nope afaik @chicken_wingsyash– yash2017-12-03 02:35:24 +00:00Commented Dec 3, 2017 at 2:35
-
Post the code of function that you are importingyash– yash2017-12-03 02:37:28 +00:00Commented Dec 3, 2017 at 2:37
1 Answer
It is not possible to run Python 2 code with Python 3, at least not in general. Although converting by hand is fairly straight-forward.
If you have long files you should also consider using 2to3 which will apply the needed fixes to make your code run with Python 3.
If you already have Python 3 installed you simply have to run the following in your terminal.
2to3 your_file_name.py
Note that sometimes 2to3 will be unable to transpile from Python2 to Python3. If it notices it, it will give you warnings and indicate what lines you have to fix manually.
Although, it can also happen that 2to3 doesn't even notice the output code will not work. This is what happened in the example you gave me in the comments:
input('Type text here: ').encode('utf-8').encode('hex')
This will not work in Python3 for reasons that you can explore here.
The reason 2to3 doesn't realize it is because this is actually syntactically perfectly valid code. And actually you could foreshadow input or str.encode in a way that would make this working code.
In conclusion, sometime you have to read the error and fix the code yourself.