powershell 编码报错问题解决

在windows上使用vscode打开终端powershell时,第一次打开总是出现以下报错,虽然可以正常使用,但是还是比较碍事。

1
2
3
4
5
6
7
8
9
# >>>>>>>>>>>>>>>>>>>>>> ERROR REPORT <<<<<<<<<<<<<<<<<<<<<<

Traceback (most recent call last):
File "C:\ProgramData\miniconda3\Lib\site-packages\conda\exception_handler.py", line 18, in __call__
return func(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^
File "C:\ProgramData\miniconda3\Lib\site-packages\conda\cli\main.py", line 89, in main_sourced
print(activator.execute(), end="")
UnicodeEncodeError: 'gbk' codec can't encode character '\ue1bb' in position 1275: illegal multibyte sequence

看源码可以知道是在 print(activator.execute(), end=“”) 时,遇到了 gbk 不兼容的编码,查资料得知:

  1. python 的 print 默认使用gbk,可以通过环境变量 PYTHONIOENCODING 改变默认编码。
  2. gbk 不包含所有的 unicode 字符

所以解决思路有两个,一个是在报错处改源代码,在上面插入:

1
2
3
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
print(activator.execute(), end="") # 报错行位置,插入上面两行。

或者改 PYTHONIOENCODING,使用以下命令,或者在设置里面改,重启vscode生效。

1
setx PYTHONIOENCODING "utf-8"

R 环境配置

安装 R 插件

vscode启用R插件需要 languageserver R包,r-debugger 插件需要 vscDebugger R包。

1
2
3
4
5
R -e "install.packages('languageserver', repos='https://mirrors.bfsu.edu.cn/CRAN/')"
R -e "install.packages('https://github.com/ManuelHentschel/vscDebugger/releases/download/v0.5.2/vscDebugger_0.5.2.tar.gz')"
commit_id=f1b07bd25dfad64b0167beb15359ae573aecd2cc
~/.vscode-server/bin/${commit_id}/bin/code-server --install-extension reditorsupport.r
~/.vscode-server/bin/${commit_id}/bin/code-server --install-extension rdebugger.r-debugger

格式化 R

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$ cat ~/Rprofile # set format rule
options(languageserver.formatting_style = function(options) {
styler::tidyverse_style(
scope = "tokens",
strict = TRUE,
indent_by = 2L,
start_comments_with_one_space = FALSE,
reindention = tidyverse_reindention(),
math_token_spacing = tidyverse_math_token_spacing()
)
})

$ cat ~/.lintr # set format check rule
linters: with_defaults(
object_name_linter = NULL,
line_length_linter = NULL
)