【问题标题】:Pass Persian string ( UTF-8 ) from laravel API to python file将波斯字符串 ( UTF-8 ) 从 laravel API 传递到 python 文件
【发布时间】:2021-09-08 07:43:31
【问题描述】:

在我的laravel-API 中,我必须调用main.py 文件并将波斯 字符串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 = '嗨,你好吗?'

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

但是当我像这样传递波斯语字符串时,我什么也没得到

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

#output
[]

【问题讨论】:

  • 我使用了 python3,它对我来说可以正常工作。但我认为您在执行状态下可能有错误。如果 exec 语句的结果出现错误,则输出将是一个空数组。

标签: python php laravel utf-8


【解决方案1】:

将此代码放在之前调用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

【讨论】:

    猜你喜欢
    • 2017-12-04
    • 2020-10-08
    • 2020-01-12
    • 2011-05-10
    • 2011-07-07
    • 2012-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多