0

I've seen several posts about this subject, none worked. exec() and similar shell commands works fine only for Linux commands (eg. ls) not for Python scripts Initially I thought there was something wrong with my test.py, but even a simple print() doesn't work. Here's what happen:

OS: Ubuntu 22.04

PHP: 8.0

Python: 3.10

test.py

#!/usr/bin/env python
Print("Hello Word")  # that simple

from terminal, it works:

> python3 test.py   // Hello World

myscript1.php | doesn't work

$command = escapeshellcmd("/mysite.com/path/python3 test.py ");
$out = shell_exec($command);
file_put_contents( $txt_path.'test.txt', $out);   // test.txt is empty

myscript2.php | it works, but it's not a python script

$output = shell_exec('ls -lart');
$t1= "<pre>$output</pre>";
file_put_contents( $txt_path.'out.txt', $t1 ) ;  // out.txt contains the list of files

I've granted permissions to all users, and test.py is executable. Tried all shell functions: passthru(), shell_exec(), exec() php.ini -> disabled_functions: none of them is listed, and I've removed pcntl_exec()

> sudo chmod a+rwx /mysite.com/path/ 
> chmod +x  test.py   

Please help Many thanks

Running a Python script from PHP

  • Maybe `python3 /mysite.com/path/test.py`? python3 can be called from every directory. Its not very clear where your files are located. – Foobar Mar 08 '23 at 15:20

1 Answers1

2

I finally figured out how to fix this issue.

shell_exec() commands doesn’t work unless I shape the string as below:

#!/usr/bin/env python
$command ="/usr/bin/python3   /my/path/test.py ";   // this is !crucial
$out = shell_exec($command);   
file_put_contents( '/my/path/test.txt', $out);   // test.txt is now working  

Still I don’t know why the python’s path has to be declared separately that way when from terminal the following works just fine:

> python3 /my/path/test.py