将选中文本发送到命令行参数
我发现了一个工具,pytranslate,它可以利用谷歌的翻译API把多种语言互相翻译。这个工具的功能和描述的一样,效果很好。
不过,我对每次都要选中一个我不懂的单词,然后中间点击把它放到命令里这件事感到厌烦。这个命令的格式是这样的:
pytranslate WORD
有没有什么程序或者脚本,可以在我用鼠标选中一个单词或者一串单词的时候,自动检测到,然后在终端窗口中执行上面的命令,把选中的文本替换掉命令中的WORD呢?
举个例子:
选中的文本:
Bonjour mondiale...
最终的命令/结果:
pytranslate Bonjour mondiale
Detected source language: fr
Hello World
4 个回答
1
你能不能用 PyGTK 这个包里的剪贴板功能来完成这个工作?它说可以访问“主要”的 X 剪贴板,通常你选中的文本就在这里。
3
受到Roger Pate精彩的一行代码的启发,我为pytranslate写了一个简单的循环脚本。这个脚本现在还只是个初步版本,因为我还没有加入错误处理的部分——请等我更新新版本。
#!/bin/bash
# Primary Clipboard poller using xsel (middle click) and pytranslate
# Checks for changes every 1 second
# If change has occured, a command is executed (pytranslate here)
########## Information ##########
# It now stores definitions in a text file - saves bandwith and reduces hits on google (caseless)
# Works for Romance languagse
#TODO
# Character based langauges
# Catch errors
if [ ! -e "pytranslatecache" ]; then
touch pytranslatecache
fi
while [ 1 ]
do
OLDENTRY="$(xsel -p)"
sleep 1
NEWENTRY="$(xsel -p)"
if [ "$NEWENTRY" != "$OLDENTRY" ] ; then
if [ "$(grep -F -o -i "$NEWENTRY" pytranslatecache)" = "$NEWENTRY" ] ; then
echo "From Cache:"
echo "$(grep -i "$NEWENTRY" pytranslatecache)"
else
DEFINITION=""$(pytranslate -s fr "$(xsel -p)")""
echo "$NEWENTRY"":"$DEFINITION
echo "$NEWENTRY"":"$DEFINITION >> pytranslatecache
fi
fi
# Catch Errors - Commands
if [ $? != 0 ]; then
{
echo "Failed to translate string."
} fi
done
4
#!/bin/bash
pytranslate "$(xsel -p)"
现在只需把这个放到 ~/bin
目录下(确保这个目录在你的 PATH 环境变量中),然后运行它。(你可能需要先安装 xsel 这个软件包。)这个程序会把当前的主要选择缓冲区的内容传递给 pytranslate。
如果你想把它做成一个按钮,可以创建一个启动器,让它在终端中运行这个命令,并使用 bash 的 read 命令来实现“按 ENTER 继续”的功能。