Geo-x
Geo-x

Reputation: 295

Launch python file from PHP on LINUX server

I tried many solutions but nothing it works :

echo '<pre>';

shell_exec("python /home/folder/python/mapfile_compress.py");
shell_exec("sudo -u wwwexec python escapeshellcommand(/home/folder/python/mapfile_compress.py) $uid");
shell_exec("sudo chmod +x /home/folder/python/mapfile_compress.py");
system("bash /home/folder/python/mapfile_compress.py");
passthru("bash /home/folder/python/mapfile_compress.py");
passthru("/home/folder/python/mapfile_compress.py");
exec("bash /home/folder/python/mapfile_compress.py");

echo '</pre>';

I launched indivdually them but in all cases, Firebug returned : '<pre>'

So I tried this code founded on Stack Overflow :

$command = escapeshellcmd('chmod +x /home/folder/python/mapfile_compress_test.py'); echo $command; $output = shell_exec($command); echo $output;

But firebug returned nothing. My python file begin with #!/usr/bin/env python and if I launch it on server that works !

Do you knwo how can I launch my python file from PHP file ?

Upvotes: 0

Views: 336

Answers (3)

Geo-x
Geo-x

Reputation: 295

In my case that's work if I write this code :

$command = escapeshellcmd('python /path/to/your/file.py');
exec($command);

Upvotes: 0

Robert
Robert

Reputation: 5963

chmod will return 0 on success and > 0 on error.

Make sure that the file is able to run by just executing it as the web user. When +x is properly set, you can execute it by just calling $ /path/to/your/file.py, the shebang in the first line in your script #!/usr/bin/env python should define the correct python based on your env.

You can test this by running:

$ /usr/bin/env python /path/to/your/file.py

So check your file permissions to check if the file is executable by the user that runs the php script.

Just to test, you can just print a few lines in your python file

#!/usr/bin/env python

print "test line 1"
print "test line 2"

Then if you have verified permissions and the correct use of python, you can do this in your php.

$command = escapeshellcmd('/path/to/your/file.py');
$output = shell_exec($command); // get all output or use passthrough, exec will only return the last line.
echo "<pre>{$output}</pre>;

Upvotes: 1

arhu
arhu

Reputation: 62

At first, Do you have enabled shell_exec/system/passthru commands in php.ini?

shell_exec("python /home/folder/python/mapfile_compress.py");

I think, it could be problem with your $PATH. Try something like: (use full path to python)

shell_exec("/usr/bin/python /home/folder/python/mapfile_compress.py");
shell_exec("/usr/local/bin/python /home/folder/python/mapfile_compress.py");

Upvotes: 0

Related Questions