見出し画像

Vagrantでのクリップボード使用

Vagrantでのクリップボード使用

ITカレッジ沖縄の学生が
ProgrammingIIの講義で
「退屈なことはPythonにやらせよう 第2版」で
仮想環境でクリップボード使用する際の対応です。

更新日 2024年5月21日


目次

  1. 対象・環境

  2. 症状&エラー

  3. 対処


対象・環境

対象学科

  • サイバーセキュリティ科

環境

ホストPC

  • Ubuntu 22.04

  • VirtualBox 7.0.18

  • Vagrant 2.4.1

仮想環境

  • Box ubuntu/jammy64

  • Ubuntu 22.04

Python環境

  • Python 3.10.12

  • pip 22.0.2

  • pyperclip 1.8.2

  • xsel 1.2.0

教科書


症状&エラー

書籍「退屈なことはPythonにやらせよう 第2版」の
6章 文字列の操作
「6.5 pyperclipモジュールを用いて文字列をコピー&ペーストする(P.176-P.177)」を
仮想環境(Virtalbox+Vagrant)で実施した際に

下記のエラーがでる場合

  • 「pyperclip」をインストールした際のエラー

  • 「pyperclip」を使用した際のエラー

  • 「xsel」を使用した際のエラー

「pyperclip」をインストールした際のエラー

$ pip install --user pyperclip
Command 'pip' not found, but can be installed with:
apt install python3-pip
Please ask your administrator.

「pyperclip」を使用した際のエラー

$ python3
>>> import pyperclip
>>> pyperclip.copy('Hello, world!')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/vagrant/.local/lib/python3.10/site-packages/pyperclip/__init__.py", line 336, in __call__
    raise PyperclipException(EXCEPT_MSG)
pyperclip.PyperclipException:
    Pyperclip could not find a copy/paste mechanism for your system.
    For more information, please visit https://pyperclip.readthedocs.io/en/latest/index.html#not-implemented-error

「xsel」を使用した際のエラー

$ pwd | xsel -bi
xsel: Can't open display: (null)
: Inappropriate ioctl for device

対処

仮想環境で、クリップボード使用する場合は、
X Window System(X, X11)が必要なので
VagrantfileでホストPCへの転送を行うための設定が必要

Python環境

  • Vagrant SSHでのX11フォワーディング

  • pipのインストール

  • pyperclipのインストール

  • xselのインストール

  1. ホストPC側で「Vagrantfile」内にX11フォワーディング転送設定をオンにする

  2. Python のパッケージ管理システム「pip」のインストール

  3. Pythonでクリップボードを使用するモジュール 「pyperclip」のインストール

  4. ターミナルからクリップボードにコピペする「xsel」のインストール

1. ホストPC側で「Vagrantfile」内にX11フォワーディング転送設定をオンにする

vagrantの設定ファイル「Vagrantfile」を開き

$ vi Vagrantfile

適当な箇所に下記を追記

config.ssh.forward_x11

仮想マシンの再起動

$ vagrant reload

もしくは 起動

$ vagrant up

Vagrant SSH Settings

2. Python のパッケージ管理システム「pip」のインストール

Pythonのさまざまなモジュールを管理する「pip」をインストールする

$ sudo apt install python3-pip

Ubuntu環境のPython

3. Pythonでクリップボードを使用するモジュール 「pyperclip」のインストール

Pythonでクリップボードを使用するモジュール 「pyperclip」のインストール

$ pip install pyperclip

pyperclip

4. ターミナルからクリップボードにコピペする「xsel」のインストール

ターミナルからクリップボードにコピペする「xsel」のインストール

$ sudo apt install xsel

動作確認

$ pwd | xsel -bi

ホストPCで貼り付け(ctrl + v)