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

1
  • Maybe python3 /mysite.com/path/test.py? python3 can be called from every directory. Its not very clear where your files are located. Commented Mar 8, 2023 at 15:20

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

But it may be sh and not bash and is a different environment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.