-1

I'm preparing to upgrade a web app from Python 2.7 to 3.7. I ran into the following problem:

Entering /usr/bin/python in Terminal is working:

Python 2.7.10 (default, Feb 22 2019, 21:55:15)

Entering /usr/local/bin/python is also working:

Python 3.7.4 (v3.7.4:e09359112e, Jul  8 2019 14:54:52) 

Using #!/usr/bin/python in a file test.py shows this in a browser:

2.7.10 (default, Feb 22 2019, 21:55:15) 

So Python 2.7 is working. Now inserting '/local' into #!/usr/bin/python in the above mentioned test.py file leads to:

500 Internal Server Error

Why is that? I'm clueless, since the path /usr/local/bin/python works in Terminal.

test.py is a simple file which looks like that:

#!/usr/local/bin/python
# -*- coding: utf-8 -*-

print "Content-Type: text/plain;charset=utf-8"
print
import sys
print(sys.version)

And .htaccess looks like this:

Options +ExecCGI
AddHandler cgi-script .py
Eliott
  • 311
  • 2
  • 9
  • `/usr/bin/python` and `/usr/local/bin/python` probably just links to other files and someone has set them up to point to different versions of Python. Python 2 and Python 3 are different. For example, `print "Content-Type: text/plain;charset=utf-8"` is a syntax error in Python 3. See https://www.tutorialspoint.com/python3/python3_whatisnew.htm or just google "what is new in python 3" – zvone Sep 08 '19 at 11:09
  • Ok, thanks a lot. Of course they link to other files – they have to. – Eliott Sep 08 '19 at 11:15
  • Ok, thanks – but not a lot. It would have been more helpful to mention the missing parentheses instead of just writing general "syntax error". – Eliott Sep 08 '19 at 11:19

1 Answers1

0

In Python 2, print is a keyword, so no parentheses are required and print "Content-Type" is valid syntax.

In Python 3, print is a function and requires parentheses to be invoked.

So the 500 error you're seeing is due to the program failing (run the script or web app locally to verify).

For more see the

Porting Python 2 Code to Python 3 https://docs.python.org/3/howto/pyporting.html

To automate conversion of your Python 2 code to Python 3 try 2to3:

2to3 - Automated Python 2 to 3 code translation https://docs.python.org/3.7/library/2to3.html

You may also want to prefer the following shebang line:

#!/usr/bin/env python

If you have several versions of Python installed, /usr/bin/env will ensure the interpreter used is the first one on your environment's $PATH. The alternative would be to hardcode something like #!/usr/bin/python; that's ok, but less flexible.

https://stackoverflow.com/a/2429517/2845260

Jake Romer
  • 2,074
  • 1
  • 10
  • 23