How to run Python scripts in cPanel

2In this article, I describes about creating a Python test script via cPanel.

You can follow below steps to do this.

1. Log in to your cPanel Control Panel

2. Click on ‘File Manager‘ under ‘FILES‘ section.

 

Python script can be run inside ‘public_html‘ or in ‘cgi-bin‘ folder.

The cgi-bin folder contains executable CGI scripts. If you are placing the file outside of the cgi-bin folder, ‘.htaccess‘ file should be created additionally to make the script work.

Here, I am creating the file inside ‘cgi-bin’ folder.

3. Now go to the cgi-bin folder

Create a file with a .py extension, for example test.py in the /home/cPaneUsername/public_html/cgi-bin directory (where cPanelUsername is your actual cPanel username given by your hosting provider).

4. In order to create the file, click on the File menu located in the left corner. Specify the name of the file with the required extension and click Create New File:

5. Once file created, change the permission of the file to 755

NOTE: Files are created with default permissions 0644. The .py file will become executable when the permissions are changed to 755.

6. In order to change the permissions of the file you need to select the file and click ‘Permissions‘ > Mark Execute for UserGroupWorld columns and click Change Permissions.

 

 

7. Now open the file, click ‘Edit‘ and add the code.

Here, we are going to use the following script for testing purpose:

!/bin/python

def main():
  print "Content-type: text/html"
  print
  print "<TITLE> Hello, World!</TITLE>"
  print "Hello, World!"

if (__name__ == "__main__"):
  main()

NOTE: The file should start with the path to the Python scripts that is /usr/bin/python on our servers.

Now the script should work using http://YourDomain.com/cgi-bin/test.py (Use your own domain name instead of YourDomain.com)

If you would like to run the Python file not in the cgi-bin folder (in public_html or any other directory), it is necessary to add the following code to the .htaccess file in the same directory where the Python script is uploaded:

 

Options +ExecCGI
AddHandler cgi-script .py

  • 262 Users Found This Useful
Was this answer helpful?