python paramiko exec_command_paramiko exec_command 执行远程机器脚本实时返回编码问题

使用 paramiko 完成 执行远程 shell,实时获取结果

完成了

def line_buffered(f):

line_buf = ""

while not f.channel.exit_status_ready():

line_buf += f.read(1)

if line_buf.endswith('\n'):

yield line_buf

line_buf = ''

stdin, stdout, stderr = ssh.exec_command(shell)

print logfile

logfile = "static/logs/{0}".format(logfile)

print logfile

myfile = open(logfile, "w")

for l in line_buffered(stdout):

print l.decode("utf-8")

myfile.write('ddd')

myfile.write(l.decode("utf-8"))

myfile.flush()

myfile.close()

可以非阻塞实时返回,但有个问题,我的 shell 脚本中带有中文,就回报错

[2018-09-05 18:22:34,452: WARNING/ForkPoolWorker-1] game_1003_reback_1536142952196.log

[2018-09-05 18:22:34,453: WARNING/ForkPoolWorker-1] static/logs/game_1003_reback_1536142952196.log

[2018-09-05 18:22:34,467: WARNING/ForkPoolWorker-1] 'utf8' codec can't decode byte 0xe5 in position 0: unexpected end of data

[2018-09-05 18:22:34,669: WARNING/ForkPoolWorker-1] task fail, reason: UnicodeDecodeError('utf8', '\xe5', 0, 1, 'unexpected end of data') is not JSON serializable

[2018-09-05 18:22:34,669: WARNING/ForkPoolWorker-1] task fail, reason: 2260f200-a29b-4fec-9117-e8eee5903100

[2018-09-05 18:22:34,669: ERROR/ForkPoolWorker-1] Task opsbase.views.task_ssh_cmd[2260f200-a29b-4fec-9117-e8eee5903100] raised unexpected: EncodeError(TypeError("UnicodeDecodeError('utf8', '\\xe5', 0, 1, 'unexpected end of data') is not JSON serializable",),)

Traceback (most recent call last):

File "/Users/apple/OneDrive/Code_7zGame/Envs/tdops/lib/python2.7/site-packages/celery/app/trace.py", line 442, in trace_task

uuid, retval, task_request, publish_result,

File "/Users/apple/OneDrive/Code_7zGame/Envs/tdops/lib/python2.7/site-packages/celery/backends/base.py", line 146, in mark_as_done

self.store_result(task_id, result, state, request=request)

File "/Users/apple/OneDrive/Code_7zGame/Envs/tdops/lib/python2.7/site-packages/celery/backends/base.py", line 322, in store_result

request=request, **kwargs)

File "/Users/apple/OneDrive/Code_7zGame/Envs/tdops/lib/python2.7/site-packages/django_celery_results/backends/database.py", line 20, in _store_result

content_type, content_encoding, result = self.encode_content(result)

File "/Users/apple/OneDrive/Code_7zGame/Envs/tdops/lib/python2.7/site-packages/django_celery_results/backends/database.py", line 43, in encode_content

content_type, content_encoding, content = self._encode(data)

我是 python2.7 的,该加 .decode("utf-8")都加了

如果是直接使用平常方式,中文就能正常打印

result = stdout.read(), stderr.read()

for i in result:

print

这个编码要怎么破,不要说换 python3.。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值