In order to run Python scripts in your webhost account there are many ways :
How to create and edit Python scripts via Terminal :
- Go to cPanel and search for Terminal :
You will have a window like this : - Here you have two Options if you want to add it to a custom folder skip to step Number 6 , else we gonna add it to the cgi-bin directory :
To do that type the following comamnd :cd ./public_html/cgi-bin
Type the commandpwd
if you want to check that you're in the correct directory : - Now create a .py file , in this tutorial the file name will be Scripted-Host.py
The command to create a py file is :touch [FileName.py]
, you can use the commandls
to check if the file has been created : - Change the permission of the file to 0755:
The command is :chmod 755 [FullFilePath]
In our example it will be :chmod 755 /home/ytwsegem/public_html/cgi-bin/Scripted-Host.py
( ytwsegem is the cPanel username for this tutorial , change with your own )
NOTE: Files are created with default permissions 0644. The .py file will become executable when the permissions are changed to 0755. - Open the file using any text editor , we will be using nano in this tuto , then we gonna add a simple code to test :
Command :nano Scripted-Host.py
In this example we gonna paste this code :#!/usr/bin/python
print "Content-type:text/html\r\n\r\n"
print "This is how to run Python scripts"
After copying the code press CTRL+O and then press Enter , and you're done
Go and check the results usingYourDomain.com/cgi-bin/Scripted-Host.py
- Now if you wanna add the py script in another folder rather then cgi-bin , you add some code to the .htaccess file in the same directory you wanna do your python scripts :
- Go to the correct directory using :
cd
- If .htaccess file doesn't exist , creat it using the command :
touch .htaccess
- Open it : nano .htaccess and copy the following code
Options +ExecCGI
AddHandler cgi-script .py
- Hit CTRL+O and Enter.
- Go to the correct directory using :