How to use python scripts server-side [Quick]

Python is a really useful programming language these days, especially for Machine Learning applications. So, sometime it’s very useful to have it running on your server.

Here is a very quick way to do this.

First you need a server, but you can also test it on your local machine.  We will create a very simple php script that call a python script just to print an argument (coming from the php) just to demonstrate the connection between them.

The python script will just take the first argument from command line and print it to the screen. We’re working with python 2.x here, so we don’t need parenthesis on print command. We also need the sys library to do this.

import sys
 
if __name__ == "__main__":
    print sys.argv[1]

Now the php. Here we just need to run the python script giver a string for argument. This is happening with just one line of code using the exec() method. Finally we print the result of the execution which give us the printed argument.

<?php
$result = exec("python test.py test_argument");
echo $result;
 
?>

When we finally run the php file (using a browser) we will get the printed result.

 

Screenshot from 2017-03-13 22-27-49

 

This way we can use python’s power pretty much for everything online!

Facebook Profile photo

Studying in Computer Engineering & Informatics Department. Member of the fedora community. Interested in mobile apps and machine learning.

Leave a Reply

Your email address will not be published. Required fields are marked *