如何检查 linux shell 字符串编码已经由 Python 脚本生成
How to check in linux shell encoding of string already generated by Python script
我 运行 一个 Python 脚本,它生成一个字符串,然后使用该字符串执行 shell 脚本。
我想使用 linux shell 检查该字符串的编码,但不将该字符串写入文件(磁盘操作 运行s 缓慢)。
是否可以仅使用 RAM 检查 Linux (Ubuntu) 中的字符串编码?
类似于:
check-encoding 'My string with random encoding'
Python 检查编码脚本也很慢。
尝试文件实用程序。您可以通过使用 echo
管道将任何字符串作为 文件参数 传递给文件 -
选项(许多命令使用连字符 (-) 代替文件名作为参数以指示输入何时应来自标准输入而不是文件):
:~ $ echo "test" | file -i -
/dev/stdin: text/plain; charset=us-ascii
:~ $ echo "тест" | file -i -
/dev/stdin: text/plain; charset=utf-8
通过管道连接到 sed:
:~ $ echo "тест" | file -i - | sed 's/.*charset=\(.*\)//'
utf-8
或者到awk(当然你可以混用):
:~ $ echo "тест" | file -i - | awk '{ print }'
charset=utf-8
您也可以使用 python chardet 模块。 Chardet 带有一个命令行脚本,可以报告一个或多个文件的编码。只需安装它:
pip install chardet
并与来自 echo 的管道一起使用:
:~ $ echo "тест" | chardetect
<stdin>: utf-8 with confidence 0.938125
我 运行 一个 Python 脚本,它生成一个字符串,然后使用该字符串执行 shell 脚本。 我想使用 linux shell 检查该字符串的编码,但不将该字符串写入文件(磁盘操作 运行s 缓慢)。 是否可以仅使用 RAM 检查 Linux (Ubuntu) 中的字符串编码? 类似于:
check-encoding 'My string with random encoding'
Python 检查编码脚本也很慢。
尝试文件实用程序。您可以通过使用 echo
管道将任何字符串作为 文件参数 传递给文件 -
选项(许多命令使用连字符 (-) 代替文件名作为参数以指示输入何时应来自标准输入而不是文件):
:~ $ echo "test" | file -i -
/dev/stdin: text/plain; charset=us-ascii
:~ $ echo "тест" | file -i -
/dev/stdin: text/plain; charset=utf-8
通过管道连接到 sed:
:~ $ echo "тест" | file -i - | sed 's/.*charset=\(.*\)//'
utf-8
或者到awk(当然你可以混用):
:~ $ echo "тест" | file -i - | awk '{ print }'
charset=utf-8
您也可以使用 python chardet 模块。 Chardet 带有一个命令行脚本,可以报告一个或多个文件的编码。只需安装它:
pip install chardet
并与来自 echo 的管道一起使用:
:~ $ echo "тест" | chardetect
<stdin>: utf-8 with confidence 0.938125