2

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")
6
  • What if you run it immediately from the shell? Commented May 15, 2017 at 23:22
  • Run directly works perfectly fine. Commented May 15, 2017 at 23:24
  • 1
    Can you write (mark) the line where the error occurs? Commented May 15, 2017 at 23:24
  • NameError: global name 'mark' is not defined Commented May 15, 2017 at 23:26
  • Something wrong with my def cmd_io (command): ? Commented May 15, 2017 at 23:26

2 Answers 2

3

Try running

putenv("PYTHONIOENCODING=utf-8");

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

Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.