How to run Python scripts in your shared hosting server

Direct to the how-to 🙂

  1. First make sure your hosting supports Python. Now a days almost all shared hosting providers support Python.
  2. Find your python installation location, this is required for “shebang” line added at the top of your python script. Usually this is /usr/bin/python or /usr/local/bin/python
  3. Make sure to include two print statements which will print the content-type and an empty line.
  4. Now put the script in cgi-bin directory inside your root public folder, usually public_html
  5. Change the permission of the script to 0755
  6. Try to browse now 🙂

Example, hello.py:

#! /usr/bin/python

print ‘Content-type: text/html’
print ”
print ‘Hello, World!’

Now look at the top of hello.py script, you will notice the ‘shebang’ is #! /usr/bin/python.And also the first two print statements 🙂

Now its little bit annoying to put all python scripts inside that cgi-bin directory. So heres what you will need to do to run a python script inside any directory…

  1. Make an empty .htaccss file inside the directory you want to drop your python scripts. (Just open the existing .htaccess file, make sure you have enabled ‘Show Hidden Files’ in cPanel File Manager or in your favorite FTP manager)
  2. Add the following two lines and save.

Options +ExecCGI
AddHandler cgi-script .py

Tips:

  1. You will get 500 error if anything goes wrong.
  2. Make sure to clear your cache, when you modify any settings/content
  3. And there is always the nice people waiting for you in hosting support section, try them 🙂

I hope it helps. Let me know your comment 🙂

  • Yourownfree

    I cant get it to work. It just prints out #! /usr/bin/python

    print ‘Content-type: text/html’
    print ”
    print ‘Hello, World!’
    on the screen. I mean it prints the whole file. I tried running it from the folder and from a browser, same thing. What am I doing wrong?

  • You are supposed to run it within a browser (where the file is stored in the cgi-bin directory of your hosting server)

    From your comment, it seems you tried to run it like a html file.

  • Yeah nowadays all hosting services supporting on python.. Nice example.. I will try this work.. Thanks for this information..
    best hosting service | best web hosting company

  • Hardik

    i want to run python 3 scripts on cpanel…is python 3 scripts supported?

  • *htaccess