I have a very simple Python script that I want to run though my website. Here is my script:
#!/usr/bin/python
print("This line will be printed.")
Suppose my script is called 'hello.py' and my website is 'mywebsite.com'. My web hosting is provided by BlueHost, and I can access the server through FileZilla. I place 'hello.py' in the public_html directory on the server (which also contains my website html files). Now I try to run the Python script though the browser, so in my web browser I go to 'mywebsite.com/hello.py'. In the web browser, the source code of 'hello.py' is printed. Is there a way to execute the Python script instead?
The following modifications should be made for success:
(1) Python script slightly modified to the following:
#!/usr/bin/python
print("Content-Type: text/html")
print
print("This line will be printed.")
(2) Add the following into the 'IfModule mod_rewrite.c' field of your .htaccess file:
<IfModule mod_rewrite.c>
Options +ExecCGI
AddHandler cgi-script .py
</IfModule>
Here is the successful output result on my browser, after searching 'mywebsite.com/hello.py':
Contrast this to the output result if either instructions (1) or (2) are not followed - the browser simply outputs the Python source code. For instance, violating instruction (2) yields:
Note that the BlueHost Python or CGI guides do not provide this information. My solution was attained after a series of guess-and-checks, and there might be a more proper way of doing this.