car*_*osm 4 macos python-3.x windows-subsystem-for-linux
我正在开发一个 python 脚本来在 WSL 和 macOS 中编译 LaTeX 文件,但当我在 macOS 中运行它时,它在子进程 stdout utf-8 编解码器中失败。但是,它在 WSL 中有效。两个Python版本都是3.6
该代码没有任何代码/解码语句,所以我认为问题出在子进程stdout的内部调用中
def execute(cmd, pipe):
if pipe:
ps = subprocess.Popen(cmd, stdout=subprocess.PIPE)
output = subprocess.check_output(pipe, stdin=ps.stdout, universal_newlines=True)
print(colored(output, 'red'), file=sys.stderr)
ps.wait()
else:
output = subprocess.call(cmd)
print(colored(output, 'red'), file=sys.stderr)
start_time = time.time()
for cmd, pipe in zip(commands, pipes):
print(colored(cmd, 'green'), file=sys.stderr)
execute(cmd, pipe)
Run Code Online (Sandbox Code Playgroud)
我得到的输出是
['pdflatex', '-shell-escape', '--interaction', 'nonstopmode', '-file-line-error', 'besolidary.tex']
Traceback (most recent call last):
File "compile.py", line 61, in <module>
execute(cmd, pipe)
File "compile.py", line 50, in execute
output = subprocess.check_output(pipe, stdin=ps.stdout, universal_newlines=True)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 336, in check_output
**kwargs).stdout
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 405, in run
stdout, stderr = process.communicate(input, timeout=timeout)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 830, in communicate
stdout = self.stdout.read()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/codecs.py", line 321, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xc3 in position 1335: invalid continuation byte
Run Code Online (Sandbox Code Playgroud)
当在 WSL 中工作正常并抛出所有命令时。
由于您指定了universal_newlines=True,Python 隐式地期望来自子进程的文本输出。由于未指定编码,因此默认为;check_output()返回的编码。locale.getpreferredencoding(False)这恰好是utf-8。
正如您的情况所示,子进程实际上并未以 Python 认为的首选编码方式对其输出进行编码,并且在尝试这样做时您会收到 DecodeError 。
如果您确实期望子进程输出文本,则需要一种方法来找出子进程将使用(或强制其使用)的编码。否则,如果输出实际上是二进制的,请保留universal_newlines默认值。
| 归档时间: |
|
| 查看次数: |
1559 次 |
| 最近记录: |