I\'m trying to run a Python script from PHP using the following command:
exec(\'/usr/bin/python2.7 /srv/http/assets/py/switch.py arg1 arg2\');
H
If you want to know the return status of the command and get the entire stdout
output you can actually use exec
:
$command = 'ls';
exec($command, $out, $status);
$out
is an array of all lines. $status
is the return status. Very useful for debugging.
If you also want to see the stderr
output you can either play with proc_open or simply add 2>&1
to your $command
. The latter is often sufficient to get things working and way faster to "implement".
The above methods seem to be complex. Use my method as a reference.
I have these two files:
run.php
mkdir.py
Here, I've created an HTML page which contains a GO button. Whenever you press this button a new folder will be created in directory whose path you have mentioned.
run.php
<html>
<body>
<head>
<title>
run
</title>
</head>
<form method="post">
<input type="submit" value="GO" name="GO">
</form>
</body>
</html>
<?php
if(isset($_POST['GO']))
{
shell_exec("python /var/www/html/lab/mkdir.py");
echo"success";
}
?>
mkdir.py
#!/usr/bin/env python
import os
os.makedirs("thisfolder");
To clarify which command to use based on the situation
exec()
- Execute an external program
system()
- Execute an external program and display the output
passthru()
- Execute an external program and display raw output
Source: http://php.net/manual/en/function.exec.php