运行 Python 参数使用 PHP 的函数
Run Python function with arguments using PHP
我的目标是在单击 HTML(PHP) 按钮时 运行 具有不同参数的不同 Python 函数。
当我在终端中执行命令时,一切正常(灯亮)
# terminal
python3 -c 'from lights import *; lights.turn_on_group("bath")'
但是当我尝试 运行 PHP 中的相同命令时,没有任何反应(空白页)。
# test.php
$cmd = "python3 -c 'from lights import *; lights.turn_on_group(\"bath\")'";
$command = escapeshellcmd($cmd);
$output = shell_exec($command);
有人知道如何解决这个问题吗?
您的问题是由语句 escapeshellcmd($cmd)
引起的,如 here 所述,您的命令分隔符由于安全原因正在被转义,因此 shell 无法解释,现在你有两个选择
选项 1
删除语句或干脆不转义你的命令,在你的情况下它是安全的,因为你正在执行硬编码命令而不是从用户那里获取的命令。所以不需要逃避它。
例子
$cmd = "python3 -c 'from lights import *; lights.turn_on_group(\"bath\")'";
$output = shell_exec($cmd);
选项 2
以防万一,如果您太愿意实施标准并使用该功能,那么请将您的代码包装到单个 python 脚本中,例如myLights.py
然后用参数调用你的脚本它会起作用,因为不需要命令分隔符!
例子myLights.py
import sys
from lights import *
if len(sys.argv) > 1:
lights.turn_on_group(sys.argv[1])
print('lights turned on')
else
print('No input received')
并调用它
python3 myLights.py bath
例如
$cmd = "python3 myLights.py bath";
$command = escapeshellcmd($cmd); #no special characters it will work
$output = shell_exec($command);
我建议您使用此方法,因为您将在激活安全层的单个命令行调用中获得更多自定义和选项。
我的目标是在单击 HTML(PHP) 按钮时 运行 具有不同参数的不同 Python 函数。 当我在终端中执行命令时,一切正常(灯亮)
# terminal
python3 -c 'from lights import *; lights.turn_on_group("bath")'
但是当我尝试 运行 PHP 中的相同命令时,没有任何反应(空白页)。
# test.php
$cmd = "python3 -c 'from lights import *; lights.turn_on_group(\"bath\")'";
$command = escapeshellcmd($cmd);
$output = shell_exec($command);
有人知道如何解决这个问题吗?
您的问题是由语句 escapeshellcmd($cmd)
引起的,如 here 所述,您的命令分隔符由于安全原因正在被转义,因此 shell 无法解释,现在你有两个选择
选项 1
删除语句或干脆不转义你的命令,在你的情况下它是安全的,因为你正在执行硬编码命令而不是从用户那里获取的命令。所以不需要逃避它。
例子
$cmd = "python3 -c 'from lights import *; lights.turn_on_group(\"bath\")'";
$output = shell_exec($cmd);
选项 2
以防万一,如果您太愿意实施标准并使用该功能,那么请将您的代码包装到单个 python 脚本中,例如myLights.py
然后用参数调用你的脚本它会起作用,因为不需要命令分隔符!
例子myLights.py
import sys
from lights import *
if len(sys.argv) > 1:
lights.turn_on_group(sys.argv[1])
print('lights turned on')
else
print('No input received')
并调用它
python3 myLights.py bath
例如
$cmd = "python3 myLights.py bath";
$command = escapeshellcmd($cmd); #no special characters it will work
$output = shell_exec($command);
我建议您使用此方法,因为您将在激活安全层的单个命令行调用中获得更多自定义和选项。