Kumaran Senapathy
Kumaran Senapathy

Reputation: 1283

Executing a python file from PHP - Linux

I have a python file that I would want to execute whenever a php page is called. The python file is in the same folder as the php file. The python script on execution edits a textfile that the php file accesses.

I have the following code:

<?php 
exec("python somefile.py",$output);
$file = fopen("test.txt",'r');
....

For some reason, the python script never gets executed. I know this certainly as I can see it from the changes in the text file. Since I was not sure if the script was made executable, so I included "python" on the command. I also ran:

chmod +x somefile.py

just to make sure this was not the reason. But this did not help too. What should I change to make the php page execute the python script whenever it is called?

Upvotes: 0

Views: 3393

Answers (1)

Rob Adams
Rob Adams

Reputation: 450

This is most likely a permission issue.

Try

echo exec("whoami");

This will let you know who php is running as. Then you need to verify this user can run the python script. If the file was not created by the same daemon that runs python, you will most likely be denied permission.

Update

This will let you know who owns all the files you are working with. The file being written to needs to be writable by the user that is running python. If you are running python from ssh, that is most likely not the same user as when you run python from exec.

echo exec('whoami') . "<br>";
echo exec("ls -l test.txt") . "<br>";
echo exec("ls -l somefile.py") . "<br>";

Update 2

Because I constantly forget this exists.

passthru('python somefile.py 1 2>&1');

This will exec your python file, and output stderr to stdout.

Upvotes: 1

Related Questions