pyperclipモジュールを使う。
■インストール
$ pip install pyperclip
■サンプルスクリプト
myclipboard.py
import pyperclip # pyperclipにコピーする。 pyperclip.copy('およよ') # pyperclipからペーストする。 t = pyperclip.paste() print(t)
(実行結果)
$ python myclipboard.py およよ
エラー対策
Linuxでpyperclipを使うと以下のエラーが出ることがある。
Pyperclip could not find a copy/paste mechanism for your system. For more information, please visit https://pyperclip.readthedocs.org
このときは、以下のいずれかの方法で対処するらしい。
- sudo apt-get install xsel to install the xsel utility.
- sudo apt-get install xclip to install the xclip utility.
- pip install gtk to install the gtk Python module.
- pip install PyQt4 to install the PyQt4 Python module.
実際にやってみたところ、3.と4.の方法が使えなかった(モジュールをインストールできなかった)ので、1.の方法を試してみたところ、pyperclipのメソッドが使えるようになった。
(参考サイト)
pyperclipイントロダクション