2
votes

I tried running python via PHP I kept getting

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

I tried

php

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

python (start_clientsim.py)

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 \n" %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")
2
What if you run it immediately from the shell? - Willem Van Onsem
Run directly works perfectly fine. - cyb3rZ
Can you write (mark) the line where the error occurs? - Willem Van Onsem
NameError: global name 'mark' is not defined - cyb3rZ
Something wrong with my def cmd_io (command): ? - cyb3rZ

2 Answers

3
votes

Try running

putenv("PYTHONIOENCODING=utf-8");

before executing a shell command from PHP. See https://stackoverflow.com/a/7363085/197921 for details.

0
votes

Please check LANG in environmental variables as followed.

function runCommand($cmd, &$retval) {
  syslog(LOG_WARNING, $cmd);
  $retval = array();
  exec($cmd, $retval);
  $log = implode("\n", $retval);
  syslog(LOG_WARNING, $log);
  return $log;
}
echo(runCommand("env", $retval));

I checked my server on Ubuntu 18.04, it returned LANG=C. So I added an environmental setting for LANG.

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