将波斯语字符串 ( UTF-8 ) 从 laravel API 传递到 python 文件

Pass Persian string ( UTF-8 ) from laravel API to python file

在我的 laravel-API 中,我必须调用 main.py 文件并将 persian 字符串 UTF-8 传递给 main.py

这是laravel-API

$command = 'سلام چطوری؟'
$output = '';
exec("python ../../../python/main.py '$command'", $output);
dd($output);

这是main.py

import sys

def main(text):
    return text

x = sys.argv[1]
print(x)

问题是当我传递这样的东西时,它工作正常

$command = 'hi how are you?'

//output
['hi how are you?']

但是当我像这样传递波斯语字符串时,我在 return

中什么也得不到

$command = 'سلام چطوری؟'

#output
[]

将这段代码 放在 调用 exec()shell_exec()

之前
setlocale(LC_CTYPE, "en_US.UTF-8");
putenv("PYTHONIOENCODING=utf-8");

当您想将 $command 作为参数传递时,请使用 utf8_encode() 并在输出时使用 utf8_decode().

我已经用 shell_exec() 测试过它,对我来说效果很好。

总结:

setlocale(LC_CTYPE, "en_US.UTF-8");
putenv("PYTHONIOENCODING=utf-8");
$command = utf8_encode($command);
$output = shell_exec("python path/to/your/.py/file '$command'");
$output = utf8_decode($output); // your final output