简体   繁体   中英

Running Python script on website displays source code

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM