Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a Python script on a PHP server

Tags:

python

php

I am running a nginx web server, along with PHP-CGI.

I would like to know if it is possible to execute a Python script inside PHP pages, allowing both languages to be combined. I've attempted it briefly but it didn't work, so I'm not sure how I would do this. Here are the two files I used:

index.php

<body>

    <p>Hello! Here is a message: <?php exec('python hello.py'); ?></p>

</body>

hello.py

print 'Hello World!'

Any clues would be appreciated.

like image 604
Markum Avatar asked May 30 '12 01:05

Markum


People also ask

How do I run a Python script from a PHP server?

php $command_exec = escapeshellcmd('path-to-. py-file'); $str_output = shell_exec($command_exec); echo $str_output; ?> The right privileges need to be given so that the python script is successfully executed. Note − While working on a Unix type of platform, PHP code is executed as a web user.

Can PHP call Python script?

To call a Python file from within a PHP file, you need to call it using the shell_exec function.

Can we use Python like PHP?

PHP is based on object-oriented programming whereas Python is both object-oriented and procedure-oriented programming. Python is a general-purpose programming language used for backend web development. On the other hand, PHP is not designed for general-purpose programming it is only used for backend web development.


1 Answers

exec will return the output of the shell command, but you still need to echo that to the page. The following code should work for you

<body>

    <p>Hello! Here is a message: <?php echo exec('python hello.py'); ?></p>

</body>
like image 90
Matt Dodge Avatar answered Oct 07 '22 14:10

Matt Dodge