python3 pexpect问题
Pexpect 是一个自动控制的Python库
可以实现Python控制terminal运行的程序,实现自动化处理。
这篇文章不错,系统批量运维管理器pexpect详解 - ZeroD - 博客园一、pexpect介绍 pexpect官网地址:https://pexpect.readthedocs.io/en/stable/ https://pypi.org/project/pexpect/https://www.cnblogs.com/i0day/p/9125277.html我这次使用遇到的问题是,当时用IDE调试时程序运行正常,我用的是树莓派下的Thonny,但是终端直接运行python程序报错
例子:
Traceback (most recent call last):
File "cqsphone.py", line 122, in <module>
child.sendline('\n')
File "/usr/lib/python3/dist-packages/pexpect/pty_spawn.py", line 555, in sendline
return self.send(s + self.linesep)
File "/usr/lib/python3/dist-packages/pexpect/pty_spawn.py", line 543, in send
self._log(s, 'send')
File "/usr/lib/python3/dist-packages/pexpect/spawnbase.py", line 126, in _log
self.logfile.write(s)
TypeError: write() argument must be str, not bytes
问题原因是,spawn函数:
# In Python 2:
child = pexpect.spawn('some_command')
child.logfile = sys.stdout
# In Python 3, we'll use the ``encoding`` argument to decode data
# from the subprocess and handle it as unicode:
child = pexpect.spawn('some_command', encoding='utf-8')
child.logfile = sys.stdout
加上encoding='utf-8'问题解决。