Python の開墾

作成日 : 2011-06-12
最終更新日 :

題名の由来はただのだじゃれだ。なお、Python の本は別にある。

WSL2 の Python

Windows Subsystem for Linux 2 (WSL2) には、最初から Python が入っている。 ただ、モジュールは必要最小限のようだ。たとえば、tkinter が入っていない。

$ python3
Python 3.10.6 (main, Nov 14 2022, 16:10:14) [GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import tkinter
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'tkinter'
>>>

そこで tkinter を入れることにした。

参考:https://qiita.com/haranatsu_72/items/9e25e9a0c6f7573b14b1

$ sudo apt install tk-dev
(中略)
$ sudo apt install python3-tk
(中略)
$ python3
Python 3.10.6 (main, Nov 14 2022, 16:10:14) [GCC 11.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import tkinter
>>>
(後略)

実際に GUI のウィジェットを作ってみた。表示はできるのだが、日本語が文字化けしていわゆる「豆腐」の状態になる。

この文字化けを直すため、WSL2 に Windows のシステムフォントを読みに行かせるようにした。

参考:https://nexem.hatenablog.com/entry/2020/07/18/223540

/etc/fonts/ のディレクトリに次のファイルを local.conf という名前で作成し、保存する。ルート権限が必要だ。

<?xml version="1.0"?>
<!DOCTYPE fontconfig SYSTEM "fonts.dtd">
<fontconfig>
<dir>/mnt/c/Windows/Fonts</dir>
</fontconfig>

これで豆腐表示は解消され、正しく日本語文字が表示された。(2023-01-25

メモ

スクリプトを再読み込みするときの方法を記す。スクリプトを foo.py とする。 まず次のようにしてモジュールを読み込み対話環境を起動する。
$ python3 -i foo.py
この状態で foo.py を更新したとき、 対話環境を保ったまま当初読み込んだスクリプトをリロードするうまい方法をさがしたが、なかった。 foo.py はスクリプトであり、モジュールではないからだ。 ctrl-c で終了してもう一回当該コマンドを打ちなおすしかない。

Anaconda

インストール

Windows Subsystem on Linux の Ubuntu 20.04 LTS に Anaconda を入れた。
https://linuxize.com/post/how-to-install-anaconda-on-ubuntu-20-04/

$ wget -P /tmp https://repo.anaconda.com/archive/Anaconda3-2020.07-Linux-x86_64.sh


これには私の環境で 2 分 42 秒かかった。

$ sha256sum /tmp/Anaconda3-2020.07-Linux-x86_64.sh
38ce717758b95b3bd0b1797cc6ccfb76f29a90c25bdfa50ee45f11e583edfdbf /tmp/Anaconda3-2020.07-Linux-x86_64.sh
この値と、次のサイトの sha256 の欄と比較する。 一致していれば正しくダウンロードできていることの証明になる。
https://docs.anaconda.com/anaconda/install/hashes/Anaconda3-2020.07-Linux-x86_64.sh-hash/
一致している。

$ bash /tmp/Anaconda3-2020.02-Linux-x86_64.sh
	
Welcome to Anaconda3 2020.07

In order to continue the installation process, please review the license agreement.
Please, press ENTER to continue
>>>
(中略)
Do you approve the license terms? [yes|no]
[no] >>>

キー入力で yes として Enter キーを押す。

Anaconda3 will now be installed into this location:
/home/username/anaconda3
	
  - Press ENTER to confirm the location
  - Press CTRL-C to abort the installation
  - Or specify a different location below

[/home/username/anaconda3] >>>

このまま Enter キーを押す。

PREFIX=/home/username/anaconda3
Unpacking payload ...

上の画面が出てくるが、その後は多少時間がかかる。次の画面が出てくるので、yes を入力し、 Enter キーを押す。

(中略)
Installation finished.
Do you wish the installer to initialize Anaconda3
by running conda init? [yes|no]
[no]>>>

ここは yes を入力する。これでいったん終わる。 その後、次のコマンドを実行して、新しい環境の初期化を行う。

$ source ~/.bashrc

次のコマンドで、所望のパッケージがインストールされているか、 指定のバージョンより新しいものかを確認する。必要に応じて grep するのもよい。

$ conda list

jpegtran

Anaconda を入れると、 JPEG の画像変換ができるコマンド jpegtran がもれなくついてくる。 jpegtran は、カラー画像からグレースケール画像への変換が可能である。 Windows のシェルからは次のような使い方が表示される。

C> jpegtran
C:\Users\username\Anaconda3\Library\bin\jpegtran.exe: must name one input and one output file
usage: C:\Users\username\Anaconda3\Library\bin\jpegtran.exe [switches] inputfile outputfile
Switches (names may be abbreviated):
  -copy none     Copy no extra markers from source file
  -copy comments Copy only comment markers (default)
  -copy all      Copy all extra markers
  -optimize      Optimize Huffman table (smaller file, but slow compression)
  -progressive   Create progressive JPEG file
Switches for modifying the image:
  -crop WxH+X+Y  Crop to a rectangular subarea
  -flip [horizontal|vertical]  Mirror image (left-right or top-bottom)
  -grayscale     Reduce to grayscale (omit color data)
  -perfect       Fail if there is non-transformable edge blocks
  -rotate [90|180|270]         Rotate image (degrees clockwise)
  -scale M/N     Scale output image by fraction M/N, eg, 1/8
  -transpose     Transpose image
  -transverse    Transverse transpose image
  -trim          Drop non-transformable edge blocks
  -wipe WxH+X+Y  Wipe (gray out) a rectangular subarea
Switches for advanced users:
  -arithmetic    Use arithmetic coding
  -restart N     Set restart interval in rows, or in blocks with B
  -maxmemory N   Maximum memory to use (in kbytes)
  -outfile name  Specify name for output file
  -verbose  or  -debug   Emit debug output
Switches for wizards:
  -scans file    Create multi-scan JPEG per script file

Python のモジュールとバージョン

Python のモジュールとバージョンを確認するには、pip3 list を使う。 たくさん出て困るときには、いい方法があるのかもしれないが、 わたしは pip3 list | grep モジュール名の断片 でごまかす。

$ pip3 list | grep scikit
scikit-image                       0.16.2
scikit-learn                       0.23.1

iPython を使っていれば、package_name.__version__ を使うという方法もある。

$ iPython
In [1] import skimage

In [2] skimage.__version__
Out[2] '0.16.2'

In [3] import sklearn

In [4] sklearn.__version__
Out[4] '0.23.1'

仮想環境

インポートするライブラリを切り替えるには、仮想環境を作ればよい。私は anaconda を利用しているので、 この anaconda が入っている前提で述べる。

仮想環境の作成
(base) $ conda create -n 環境名 python(=バージョン) [ライブラリ名1(=バージョン1)] ...
仮想環境の起動
(base) $ conda activate 環境名
(環境名) $
仮想環境の終了
(環境名) $ conda deactivate
(base) $
仮想環境の削除
$ conda remove -n 環境名 --all
仮想環境の一覧
$ conda env list
または
$ conda info -e

Jupyter Notebook と JypterLab

Jupyter Notebook が日本語になっている

書籍のソースコードを試そうとして Jupyter Notebook を動かしてみた。

$ jupyter notebook

すると、ブラウザの表示がほとんど日本語になっていた。

Jupyter Notebook の名前のつけかたと保存のしかた

ある本で、「utilities と名前を付けて保存してください」とあるが、その方法がわからなかった。 そういえば、Untitled のような名前があるところをクリックすれば、名前がつけられて保存ができるはずと思い出した。 クリックすると、Rename Notebook のようなポップアップウィンドウが出てきた。そこで、新たな名前を入れて、 Rename をクリックすればいいことがわかった。

JupyterLab

昔の図書を借りてくると、Python の対話環境として Idle や Jupyter Notebook を使っている。 今は、JupyterLab を使うのがいいだろう。

$ jupyter lab
[I 2021-05-29 10:02:13.240 ServerApp] jupyterlab | extension was successfully linked.
[I 2021-05-29 10:02:13.971 ServerApp] nbclassic | extension was successfully linked.
[I 2021-05-29 10:02:14.129 LabApp] JupyterLab extension loaded from ~/anaconda3/lib/python3.8/site-packages/jupyterlab
[I 2021-05-29 10:02:14.129 LabApp] JupyterLab application directory is ~/anaconda3/share/jupyter/lab
[I 2021-05-29 10:02:14.153 ServerApp] jupyterlab | extension was successfully loaded.
[I 2021-05-29 10:02:14.197 ServerApp] nbclassic | extension was successfully loaded.
[I 2021-05-29 10:02:14.198 ServerApp] ローカルディレクトリからノートブックをサーブ: /mnt/c/Users/username
[I 2021-05-29 10:02:14.198 ServerApp] Jupyter Server 1.4.1 is running at:
[I 2021-05-29 10:02:14.198 ServerApp] http://localhost:8888/lab?token=05d4a34b6699843395929945fe1dac3c89bdf74ffeccecea
[I 2021-05-29 10:02:14.199 ServerApp]  or http://127.0.0.1:8888/lab?token=05d4a34b6699843395929945fe1dac3c89bdf74ffeccecea
[I 2021-05-29 10:02:14.199 ServerApp] サーバを停止し全てのカーネルをシャットダウンするには Control-C を使って下さい(確認をスキップするには2回)。
[C 2021-05-29 10:02:15.454 ServerApp]

    To access the server, open this file in a browser:
        file:///~/.local/share/jupyter/runtime/jpserver-7603-open.html
    Or copy and paste one of these URLs:
        http://localhost:8888/lab?token=05d4a34b6699843395929945fe1dac3c89bdf74ffeccecea
     or http://127.0.0.1:8888/lab?token=05d4a34b6699843395929945fe1dac3c89bdf74ffeccecea
(後略)

ここで、ブラウザを起動し、URL に http://localhost:8888/lab?token=... を入れれば、 JupyterLab の画面になる。なお、/home/username を ~ と略記した。

失敗

glob モジュールの使い方を知るために、次のようなファイル glob.py を書いた。

import glob

print(glob.glob('*.html'))

ところが、失敗してしまう。

> python glob.py
Traceback (most recent call last):
  File "C:\Users\username\glob.py", line 1, in 
    import glob
  File "C:\Users\username\glob.py", line 3, in 
    print(glob.glob('*.html'))
TypeError: 'module' object is not callable

さんざん悩んでわかったことは、「モジュール名と同じファイル名のプログラムでは失敗する」ということだ。 glob.py ではなく、たとえば globtest.py などとすればいい。また、テストファイルの glob.py は消してしまうこと。 globtest.py と同じディレクトリに glob.py が残っているとせっかく globtest.py で実験してもエラーは消えない。 下記は正しく動作する globtest.py の例である。

> python globtest.py
['balado.html', 'fantazio.html']

Vine Linux でインストール挑戦

Vine Linux は全体的に入っているパッケージが古いので、Ansible がインストールできるか心配だ。 pip は既に apt-get install で入れてある。ではどうか。

$ pip install ansible
Collecting ansible
  Downloading ansible-2.3.2.0.tar.gz (4.3MB)
    100% |████████████████████████████████| 4.3MB 47kB/s 
Collecting jinja2 (from ansible)
  Downloading Jinja2-2.9.6-py2.py3-none-any.whl (340kB)
    100% |████████████████████████████████| 344kB 835kB/s 
Collecting PyYAML (from ansible)
  Downloading PyYAML-3.12.tar.gz (253kB)
    100% |████████████████████████████████| 253kB 723kB/s 
Collecting paramiko (from ansible)
  Downloading paramiko-2.2.1-py2.py3-none-any.whl (176kB)
    100% |████████████████████████████████| 180kB 1.0MB/s 
Collecting pycrypto>=2.6 (from ansible)
  Downloading pycrypto-2.6.1.tar.gz (446kB)
    100% |████████████████████████████████| 446kB 460kB/s 
Requirement already satisfied (use --upgrade to upgrade): setuptools in /usr/lib64/python3.2/site-packages (from ansible)
Collecting MarkupSafe>=0.23 (from jinja2->ansible)
  Downloading MarkupSafe-1.0.tar.gz
Collecting bcrypt>=3.1.3 (from paramiko->ansible)
  Downloading bcrypt-3.1.3.tar.gz (40kB)
    100% |████████████████████████████████| 40kB 2.4MB/s 
Collecting pyasn1>=0.1.7 (from paramiko->ansible)
  Downloading pyasn1-0.3.2-py2.py3-none-any.whl (63kB)
    100% |████████████████████████████████| 65kB 1.9MB/s 
Collecting cryptography>=1.1 (from paramiko->ansible)
  Downloading cryptography-2.0.3.tar.gz (427kB)
    100% |████████████████████████████████| 430kB 442kB/s 
Collecting pynacl>=1.0.1 (from paramiko->ansible)
  Downloading PyNaCl-1.1.2.tar.gz (3.1MB)
    100% |████████████████████████████████| 3.1MB 41kB/s 
    Complete output from command python setup.py egg_info:
    Package libffi was not found in the pkg-config search path.
    Perhaps you should add the directory containing `libffi.pc'
    to the PKG_CONFIG_PATH environment variable
    No package 'libffi' found
    Package libffi was not found in the pkg-config search path.
    Perhaps you should add the directory containing `libffi.pc'
    to the PKG_CONFIG_PATH environment variable
    No package 'libffi' found
    Package libffi was not found in the pkg-config search path.
    Perhaps you should add the directory containing `libffi.pc'
    to the PKG_CONFIG_PATH environment variable
    No package 'libffi' found
    Package libffi was not found in the pkg-config search path.
    Perhaps you should add the directory containing `libffi.pc'
    to the PKG_CONFIG_PATH environment variable
    No package 'libffi' found
    Package libffi was not found in the pkg-config search path.
    Perhaps you should add the directory containing `libffi.pc'
    to the PKG_CONFIG_PATH environment variable
    No package 'libffi' found
    In file included from c/_cffi_backend.c:63:0:
    c/malloc_closure.h: In function 'more_core':
    c/malloc_closure.h:114:9: internal compiler error: Illegal instruction
             (Py_ssize_t)(allocate_num_pages * PAGE_ALLOCATION_GROWTH_RATE));
             ^
    0x7f4390954cff ???
    	/home/vbuilder/rpm/BUILD/glibc-2.23/signal/../sysdeps/unix/sysv/linux/x86_64/sigaction.c:0
    Please submit a full bug report,
    with preprocessed source if appropriate.
    Please include the complete backtrace with any bug report.
    See <https://github.com/Homebrew/homebrew/issues> for instructions.
    Traceback (most recent call last):
      File "/usr/lib64/python3.2/distutils/unixccompiler.py", line 176, in _compile
        extra_postargs)
      File "/usr/lib64/python3.2/distutils/ccompiler.py", line 911, in spawn
        spawn(cmd, dry_run=self.dry_run)
      File "/usr/lib64/python3.2/distutils/spawn.py", line 34, in spawn
        _spawn_posix(cmd, search_path, dry_run=dry_run)
      File "/usr/lib64/python3.2/distutils/spawn.py", line 138, in _spawn_posix
        % (cmd[0], exit_status))
    distutils.errors.DistutilsExecError: command 'gcc' failed with exit status 1
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "/usr/lib64/python3.2/distutils/core.py", line 149, in setup
        dist.run_commands()
      File "/usr/lib64/python3.2/distutils/dist.py", line 919, in run_commands
        self.run_command(cmd)
      File "/usr/lib64/python3.2/distutils/dist.py", line 938, in run_command
        cmd_obj.run()
      File "/usr/lib64/python3.2/site-packages/distribute-0.6.49-py3.2.egg/setuptools/command/bdist_egg.py", line 179, in run
        cmd = self.call_command('install_lib', warn_dir=0)
      File "/usr/lib64/python3.2/site-packages/distribute-0.6.49-py3.2.egg/setuptools/command/bdist_egg.py", line 166, in call_command
        self.run_command(cmdname)
      File "/usr/lib64/python3.2/distutils/cmd.py", line 315, in run_command
        self.distribution.run_command(command)
      File "/usr/lib64/python3.2/distutils/dist.py", line 938, in run_command
        cmd_obj.run()
      File "/usr/lib64/python3.2/site-packages/distribute-0.6.49-py3.2.egg/setuptools/command/install_lib.py", line 20, in run
        self.build()
      File "/usr/lib64/python3.2/distutils/command/install_lib.py", line 108, in build
        self.run_command('build_ext')
      File "/usr/lib64/python3.2/distutils/cmd.py", line 315, in run_command
        self.distribution.run_command(command)
      File "/usr/lib64/python3.2/distutils/dist.py", line 938, in run_command
        cmd_obj.run()
      File "/usr/lib64/python3.2/site-packages/distribute-0.6.49-py3.2.egg/setuptools/command/build_ext.py", line 46, in run
        _build_ext.run(self)
      File "/usr/lib64/python3.2/distutils/command/build_ext.py", line 347, in run
        self.build_extensions()
      File "/usr/lib64/python3.2/distutils/command/build_ext.py", line 456, in build_extensions
        self.build_extension(ext)
      File "/usr/lib64/python3.2/site-packages/distribute-0.6.49-py3.2.egg/setuptools/command/build_ext.py", line 182, in build_extension
        _build_ext.build_extension(self,ext)
      File "/usr/lib64/python3.2/distutils/command/build_ext.py", line 511, in build_extension
        depends=ext.depends)
      File "/usr/lib64/python3.2/distutils/ccompiler.py", line 576, in compile
        self._compile(obj, src, ext, cc_args, extra_postargs, pp_opts)
      File "/usr/lib64/python3.2/distutils/unixccompiler.py", line 178, in _compile
        raise CompileError(msg)
    distutils.errors.CompileError: command 'gcc' failed with exit status 1
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "/usr/lib64/python3.2/site-packages/distribute-0.6.49-py3.2.egg/setuptools/command/easy_install.py", line 1095, in run_setup
        run_setup(setup_script, args)
      File "/usr/lib64/python3.2/site-packages/distribute-0.6.49-py3.2.egg/setuptools/sandbox.py", line 34, in run_setup
        lambda: exec(compile(open(
      File "/usr/lib64/python3.2/site-packages/distribute-0.6.49-py3.2.egg/setuptools/sandbox.py", line 82, in run
        return func()
      File "/usr/lib64/python3.2/site-packages/distribute-0.6.49-py3.2.egg/setuptools/sandbox.py", line 37, in <ambda>
        {'__file__':setup_script, '__name__':'__main__'})
      File "setup.py", line 232, in <module>
        "Programming Language :: Python :: 3.6",
      File "/usr/lib64/python3.2/distutils/core.py", line 166, in setup
        raise SystemExit("error: " + str(msg))
    SystemExit: error: command 'gcc' failed with exit status 1
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "<string>", line 20, in <module>
      File "/tmp/pip-build-ie7czn/pynacl/setup.py", line 232, in <module>
        "Programming Language :: Python :: 3.6",
      File "/usr/lib64/python3.2/distutils/core.py", line 110, in setup
        _setup_distribution = dist = klass(attrs)
      File "/usr/lib64/python3.2/site-packages/distribute-0.6.49-py3.2.egg/setuptools/dist.py", line 221, in __init__
        self.fetch_build_eggs(attrs.pop('setup_requires'))
      File "/usr/lib64/python3.2/site-packages/distribute-0.6.49-py3.2.egg/setuptools/dist.py", line 245, in fetch_build_eggs
        parse_requirements(requires), installer=self.fetch_build_egg
      File "/usr/lib64/python3.2/site-packages/distribute-0.6.49-py3.2.egg/pkg_resources.py", line 588, in resolve
        dist = best[req.key] = env.best_match(req, self, installer)
      File "/usr/lib64/python3.2/site-packages/distribute-0.6.49-py3.2.egg/pkg_resources.py", line 834, in best_match
        return self.obtain(req, installer) # try and download/install
      File "/usr/lib64/python3.2/site-packages/distribute-0.6.49-py3.2.egg/pkg_resources.py", line 846, in obtain
        return installer(requirement)
      File "/usr/lib64/python3.2/site-packages/distribute-0.6.49-py3.2.egg/setuptools/dist.py", line 295, in fetch_build_egg
        return cmd.easy_install(req)
      File "/usr/lib64/python3.2/site-packages/distribute-0.6.49-py3.2.egg/setuptools/command/easy_install.py", line 604, in easy_install
        return self.install_item(spec, dist.location, tmpdir, deps)
      File "/usr/lib64/python3.2/site-packages/distribute-0.6.49-py3.2.egg/setuptools/command/easy_install.py", line 634, in install_item
        dists = self.install_eggs(spec, download, tmpdir)
      File "/usr/lib64/python3.2/site-packages/distribute-0.6.49-py3.2.egg/setuptools/command/easy_install.py", line 829, in install_eggs
        return self.build_and_install(setup_script, setup_base)
      File "/usr/lib64/python3.2/site-packages/distribute-0.6.49-py3.2.egg/setuptools/command/easy_install.py", line 1109, in build_and_install
        self.run_setup(setup_script, setup_base, args)
      File "/usr/lib64/python3.2/site-packages/distribute-0.6.49-py3.2.egg/setuptools/command/easy_install.py", line 1097, in run_setup
        raise DistutilsError("Setup script exited with %s" % (v.args[0],))
    distutils.errors.DistutilsError: Setup script exited with error: command 'gcc' failed with exit status 1
    
    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-ie7czn/pynacl
You are using pip version 7.1.2, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

どうも python のバージョン 2 に対する pip と バージョン 3 に対する pip の問題が多そうだ。 まずは、pip で入れたライブラリをまとめてアンインストールする。
http://www.lifewithpython.com/2014/11/python-uninstall-multiple-libraries.html
を参考にする。

  $ cd ~
	$ pip freeze > requirements_bk.txt
  You are using pip version 7.1.2, however version 9.0.1 is available.
  You should consider upgrading via the 'pip install --upgrade pip' command.
	$ cp requirements_bk.txt uninstall.txt
  $ cat uninstall.txt
	wheel==0.29.0
  $ pip uninstall -r uninstall.txt
  Uninstalling wheel-0.29.0:
  /usr/bin/wheel
  /usr/lib/python3.2/site-packages/wheel-0.29.0.dist-info/DESCRIPTION.rst
  (中略)
  /usr/lib/python3.2/site-packages/wheel/wininst2wheel.py
	Proceed (y/n)? y
	Exception:
Traceback (most recent call last):
  File "/usr/lib64/python3.2/shutil.py", line 318, in move
    os.rename(src, real_dst)
OSError: [Errno 13] Permission denied

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3.2/site-packages/pip/basecommand.py", line 211, in main
    status = self.run(options, args)
  File "/usr/lib/python3.2/site-packages/pip/commands/uninstall.py", line 76, in run
    requirement_set.uninstall(auto_confirm=options.yes)
  File "/usr/lib/python3.2/site-packages/pip/req/req_set.py", line 305, in uninstall
    req.uninstall(auto_confirm=auto_confirm)
  File "/usr/lib/python3.2/site-packages/pip/req/req_install.py", line 716, in uninstall
    paths_to_remove.remove(auto_confirm)
  File "/usr/lib/python3.2/site-packages/pip/req/req_uninstall.py", line 125, in remove
    renames(path, new_path)
  File "/usr/lib/python3.2/site-packages/pip/utils/__init__.py", line 315, in renames
    shutil.move(old, new)
  File "/usr/lib64/python3.2/shutil.py", line 327, in move
    os.unlink(src)
OSError: [Errno 13] Permission denied: '/usr/bin/wheel'
You are using pip version 7.1.2, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

これは sudo をしなければいけなかったのかな。

  $ sudo pip uninstall -r uninstall.txt
  (パスワード入力)
  Uninstalling wheel-0.29.0:
  /usr/bin/wheel
  /usr/lib/python3.2/site-packages/wheel-0.29.0.dist-info/DESCRIPTION.rst
  (中略)
  /usr/lib/python3.2/site-packages/wheel/wininst2wheel.py
	Proceed (y/n)? y
  Successfully uninstalled wheel-0.29.0

さて冷静に考えて、pip には複数あるのではないか、pip は python2 用で、 これとは別に python3 用の pip があるのではないか。そう思い、/usr/bin を調べた。

$ ls /usr/bin/pip*
$ ls /usr/bin/pip*
/usr/bin/pip  /usr/bin/pip-python  /usr/bin/pip3  /usr/bin/pip3.2

いかにも、pip3 とか、pip3.2 とか使えそうなのがある。pip3 なら大丈夫なのか。

$ sudo pip3 install ansible
(パスワード入力)
Collecting ansible
  Downloading ansible-2.3.2.0.tar.gz (4.3MB)
    100% |████████████████████████████████| 4.3MB 47kB/s 
Collecting jinja2 (from ansible)
  Downloading Jinja2-2.9.6-py2.py3-none-any.whl (340kB)
    100% |████████████████████████████████| 344kB 874kB/s 
Collecting PyYAML (from ansible)
  Downloading PyYAML-3.12.tar.gz (253kB)
    100% |████████████████████████████████| 253kB 771kB/s 
Collecting paramiko (from ansible)
  Downloading paramiko-2.2.1-py2.py3-none-any.whl (176kB)
    100% |████████████████████████████████| 180kB 682kB/s 
Collecting pycrypto>=2.6 (from ansible)
  Downloading pycrypto-2.6.1.tar.gz (446kB)
    100% |████████████████████████████████| 446kB 424kB/s 
Requirement already satisfied (use --upgrade to upgrade): setuptools in /usr/lib64/python3.2/site-packages (from ansible)
Collecting MarkupSafe>=0.23 (from jinja2->ansible)
  Downloading MarkupSafe-1.0.tar.gz
Collecting bcrypt>=3.1.3 (from paramiko->ansible)
  Downloading bcrypt-3.1.3.tar.gz (40kB)
    100% |████████████████████████████████| 40kB 2.4MB/s 
Collecting pyasn1>=0.1.7 (from paramiko->ansible)
  Downloading pyasn1-0.3.2-py2.py3-none-any.whl (63kB)
    100% |████████████████████████████████| 65kB 2.0MB/s 
Collecting cryptography>=1.1 (from paramiko->ansible)
  Downloading cryptography-2.0.3.tar.gz (427kB)
    100% |████████████████████████████████| 430kB 450kB/s 
Collecting pynacl>=1.0.1 (from paramiko->ansible)
  Downloading PyNaCl-1.1.2.tar.gz (3.1MB)
    100% |████████████████████████████████| 3.1MB 64kB/s 
Collecting cffi>=1.1 (from bcrypt>=3.1.3->paramiko->ansible)
  Downloading cffi-1.10.0.tar.gz (418kB)
    100% |████████████████████████████████| 421kB 498kB/s 
Collecting six>=1.4.1 (from bcrypt>=3.1.3->paramiko->ansible)
  Downloading six-1.10.0-py2.py3-none-any.whl
Collecting idna>=2.1 (from cryptography>=1.1->paramiko->ansible)
  Downloading idna-2.6-py2.py3-none-any.whl (56kB)
    100% |████████████████████████████████| 57kB 1.8MB/s 
Collecting asn1crypto>=0.21.0 (from cryptography>=1.1->paramiko->ansible)
  Downloading asn1crypto-0.22.0-py2.py3-none-any.whl (97kB)
    100% |████████████████████████████████| 98kB 1.5MB/s 
Collecting enum34 (from cryptography>=1.1->paramiko->ansible)
  Downloading enum34-1.1.6-py3-none-any.whl
Collecting ipaddress (from cryptography>=1.1->paramiko->ansible)
  Downloading ipaddress-1.0.18.tar.gz
Collecting pycparser (from cffi>=1.1->bcrypt>=3.1.3->paramiko->ansible)
  Downloading pycparser-2.18.tar.gz (245kB)
    100% |████████████████████████████████| 249kB 769kB/s 
	Installing collected packages: MarkupSafe, jinja2, PyYAML, pycparser, \
	cffi, six, bcrypt, pyasn1, idna, asn1crypto, enum34, ipaddress, \
	cryptography, pynacl, paramiko, pycrypto, ansible
  Running setup.py install for MarkupSafe
  Running setup.py install for PyYAML
  Running setup.py install for pycparser
  Running setup.py install for cffi
  Running setup.py install for bcrypt
  Running setup.py install for ipaddress
  Running setup.py install for cryptography
  Running setup.py install for pynacl
  Running setup.py install for pycrypto
  Running setup.py install for ansible
	Successfully installed MarkupSafe-1.0 PyYAML-3.12 ansible-2.3.2.0 asn1crypto-0.22.0 bcrypt-3.1.3 \
	cffi-1.10.0 cryptography-2.0.3 enum34-1.1.6 idna-2.6 ipaddress-1.0.18 jinja2-2.9.6 paramiko-2.2.1 \
	pyasn1-0.3.2 pycparser-2.18 pycrypto-2.6.1 pynacl-1.1.2 six-1.10.0
You are using pip version 7.1.2, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

最後の2行はいつも出ているが、それを除けば ansible は正常にインストールできた、といっている。 なお、文末の \ は行の折り返しを意味する。

では、本当に Ansible は動作するかな。

$ ansible localhost -m ping

  File "/usr/bin/ansible", line 104
    display.display(u"The full traceback was:\n\n%s" % to_text(traceback.format_exc()))
                                                   ^
SyntaxError: invalid syntax

なんじゃこりゃ。しかしこんなところでこんな文字が出るのは信じられない。 おそらくの ping で返される文字列が英語環境であることしか想定していていないのではないか。 言い換えれば、日本語環境で実行される ping の文字列を想定していないのではないだろうか。 でも、環境変数 LANG を変えても結果は同じだった。そりゃそうだ。 ちなみに、日本語の ping localhost は次の通り。

$ export LANG=ja_JP.UTF-8
$ ping localhost
PING localhost.localdomain (127.0.0.1) 56(84) bytes of data.
64 バイト応答 送信元 localhost.localdomain (127.0.0.1): icmp_req=1 ttl=64 時間=0.049ミリ秒
64 バイト応答 送信元 localhost.localdomain (127.0.0.1): icmp_req=2 ttl=64 時間=0.086ミリ秒
64 バイト応答 送信元 localhost.localdomain (127.0.0.1): icmp_req=3 ttl=64 時間=0.053ミリ秒
64 バイト応答 送信元 localhost.localdomain (127.0.0.1): icmp_req=4 ttl=64 時間=0.050ミリ秒
^C

そして、英語の ping localhost は次の通り。

$ export LANG=C
$ ping localhost
PING localhost.localdomain (127.0.0.1) 56(84) bytes of data.
64 bytes from localhost.localdomain (127.0.0.1): icmp_req=1 ttl=64 time=0.045 ms
64 bytes from localhost.localdomain (127.0.0.1): icmp_req=2 ttl=64 time=0.052 ms
64 bytes from localhost.localdomain (127.0.0.1): icmp_req=3 ttl=64 time=0.085 ms
64 bytes from localhost.localdomain (127.0.0.1): icmp_req=4 ttl=64 time=0.050 ms
^C

反省

以上の問題は、python 2.6.6 と python 3.2 を混在して使っていたために起きたと思われた。

$ python --version
Python 2.6.6	
$ python3 --version
Python 3.2

ところで、Vine 6.5 の python は、python, python2.7, python3 と 3 種類もある。ただの python は前に述べた通り 2.6.6 であり、 もう 2.6 系はサポートされないようなのだ。そこで、python 2.7 を明示して使わないといけない。

いったん pip をアンインストールし、改めて、python2.7 で pip を再度インストールした。 このとき、python 2.7 用の開発環境もインストールしておく必要がある。

$ sudo apt-get install python27-devel

念のため、インストールした pip の先頭を、#/usr/bin/python2.7 と書き換え、さらにファイル名も pip2.7 とリネームしておいた。

$ sudo /usr/bin/pip /usr/bin/pip2.7

やっとインストールを始めることができる。

$ sudo pip2.7 install ansible

を実行した結果、無事インストールは終了した。 そして、

$ ansible localhost -m ping

の結果も、

	localhost | SUCCESS => {
	"changed": false,
	"ping": "pong"
	}

が表示された。

まりんきょ学問所コンピュータの部屋 > Python の開墾


MARUYAMA Satosi