症状
python3 が絡むほとんどの処理で optparse.py がエラーを吐いて困った。
e.g.: apt, command-not-found, pip3
エラー内容
$ hoge
Traceback (most recent call last):
File "/usr/lib/command-not-found", line 25, in <module>
from optparse import OptionParser
File "/usr/lib/python3.8/optparse.py", line 1
nt to [a-zA-Z0-9_]
^
SyntaxError: invalid syntax
調査
/usr/lib/command-not-found は python3 で書かれている。
$ file /usr/lib/command-not-found
/usr/lib/command-not-found: Python script, ASCII text executable
/usr/lib/python3.8/optparse.py が壊れているようだ。
このファイルは python3 の基本的なライブラリ。
$ cat /usr/lib/python3.8/optparse.py
nt to [a-zA-Z0-9_]
in bytes patterns or string patterns with the ASCII flag.
In string patterns without the ASCII flag, it will match the
range of Unicode alphanumeric characters (letters plus digits
plus underscore).
With LOCALE, it will match the set [0-9_] plus characters defined
as letters for the current locale.
\W Matches the complement of \w.
\\ Matches a literal backslash.
This module exports the following functions:
match Match a regular expression pattern to the beginning of a string.
fullmatch Match a regular expression pattern to all of a string.
search Search a string for the presence of a pattern.
sub Substitute occurrences of a pattern found in a string.
subn Same as sub, but also return the number of substitutions made.
split Split a string by the occurrences of a pattern.
findall Find all occurrences of a pattern in a string.
finditer Return an iterator yielding a Match object for each match.
compile Compile a pattern into a Pattern object.
purge Clear the regular expression cache.
escape Backslash all non-alphanumerics in a string.
Each function other than purge and escape can take an optional 'flags' argument
consisting of one or more of the following module constants, joined by "|".
A, L, and U are mutually exclusive.
A ASCII For string patterns, make \w, \W, \b, \B, \d, \D
match the corresponding ASCII character categories
(rath
解決方法
GitHub (https://github.com/python/cpython/tags) の対応するのバージョンの optparse.py で差し替える。
$ python3 -V
Python 3.8.10
-> 今回は 3.8.10 (https://github.com/python/cpython/releases/tag/v3.8.10)
$ wget https://github.com/python/cpython/archive/refs/tags/v3.8.10.tar.gz
$ tar xf v3.8.10.tar.gz
$ sudo cp cpython-3.8.10/Lib/optparse.py /usr/lib/python3.8/optparse.py
解決
$ hoge
Command 'hoge' not found, did you mean:
command 'hose' from deb netpipes (4.2-8build1)
Try: sudo apt install <deb name>