Display Python 3 in the browser with MAMP
As a memorandum, I will write it in as much detail as possible.
--Environment --Procedure --Sample code
OS :MacOS Environment: MAMP Language: Python 3.6.1 Browser: chrome Text editor: Atom
--Apache settings
Search httpd.conf in the application finder
Location
/Applications/MAMP/conf/apache/httpd.conf
It was in.
at httpd.conf
#AddHandler cgi-script .cgi
To
AddHandler cgi-script .cgi .py
Change to and restart MAMP to reload httpd.conf
--Change of execution authority (permission)
To give permission to execute the program
For example, if you create test.py
At the terminal
$ chmod 755 test.py
Let's hit.
If you see No such file or directory,
The current location in the terminal is incorrect, so let's move it with the cd command.
--Create test.py
The first line is the location of the python interpreter.
If you don't know, at the terminal
given that,
/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
And so on.
Lines 2-5 are required to display in Japanese.
From the 6th line onward, this is the way to write HTML in Python3. It does not have to be.
In that case, only the 12th line is enough.
** Sample code **
test.py
#!/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
print("Content-Type: text/html; charset=utf-8")
print("")
print("""
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<h1>It works!</h1>
<p>chmod 755 /Applications/MAMP/htdocs/chatbot.py</p>
<p>finder :apache_error.log</p>
<p>Text</p>
</body>
</html>
""")
print('thank you for your hard work.')
Execution result
If you're getting an error in your browser
Search apache_error.log in finder and
Check apache_error.log in the console.
Here are some common things to note.
malformed header from script Incomplete HTTP header
Lines 3-12 may be incorrect.
Exec format error Executable errors are common
The first line does not indicate where the correct Python executable is located.
In the terminal, try to see if the location specified on the first line is correct.
Let's check the version.
$ /Library/Frameworks/Python.framework/Versions/3.6/bin/python3 --version
And so on
Python 3.6.1
It's okay if you say something like that.
Permission denied A permission error means that you do not have execute permission for the file you are trying to execute.
At the terminal
Please hit it.
UnicodeEncodeError: 'ascii' codec can't encode characters
It appears when you write Japanese etc.
import sys
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
Is written?
For syntax errors, check the official python website.
Questions, requests, etc.
Feel free to DM me on Twitter!
Click on the bird below to jump to the sub-account.
_,,, _ / :: o ・ ァ ♪ ∈ Mi ;;; No, No
Recommended Posts