关于php:UnicodeEncodeError:’ascii’编解码器不能对360-362位置的字符进行编码:序号不在范围内(128)

UnicodeEncodeError: 'ascii' codec can't encode characters in position 360-362: ordinal not in range(128)

我试过通过php运行python

UnicodeEncodeError: 'ascii' codec can't encode characters in position 360-362: ordinal not in range(128)

我试过

PHP

1
2
$command ="python".public_path().'/python/start_clientsim.py 2>&1';
$result = exec($command);

python(启动客户机sim.py)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import paramiko
import time
import sys
import os
import pdb

# Note
# sudo pip install --user paramiko


ip ="172.1.1.1"
un ="root"
pw ="123"
key_filename='/Users/keys/id_rsa'

def ssh_con (ip, un, pw):
    global ssh
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip, username=un, password=pw, key_filename=key_filename)

def cmd_io (command):
    global ssh_cmd
    ssh_cmd.send("%s
"
%command)
    time.sleep(1)
    output = ssh_cmd.recv(10000).decode("utf-8")
    print (output)


ssh_con(ip,un,pw)
ssh_cmd = ssh.invoke_shell()

cmd_io("clientsim cli")
cmd_io("start subscriber-group dth-sub start-traffic udp")
cmd_io("exit")


试运行

putenv("pythonioencoding=utf-8");

在从PHP执行shell命令之前。有关详细信息,请参阅https://stackoverflow.com/a/7363085/197921。


请检查环境变量中的LANG,如下所示。

1
2
3
4
5
6
7
8
9
10
function runCommand($cmd, &$retval) {
  syslog(LOG_WARNING, $cmd);
  $retval = array();
  exec($cmd, $retval);
  $log = implode("
"
, $retval);
  syslog(LOG_WARNING, $log);
  return $log;
}
echo(runCommand("env", $retval));

我检查了Ubuntu18.04上的服务器,它返回了LANG=C。所以我为LANG添加了一个环境设置。

1
runCommand("LANG=en_US.UTF-8 PYTHONIOENCODING=utf-8 python yourcode.py", $retval);