ラベル python の投稿を表示しています。 すべての投稿を表示
ラベル python の投稿を表示しています。 すべての投稿を表示

2021年11月9日火曜日

Python 3.10 の新機能

今回のバージョンはてんこ盛り。パターンマッチングはとりあえずでもいいので、目を通しておくべき。

■ 複数のwith
ネストさせずカンマ区切りで書けるようになった
with (open("file1") as file1, 
      open("file2") as file2,
      open("file3") as file3):
    print(file1.read(), file2.read(), file3.read())

■ パターンマッチング
対象となる変数がstringや int だったら他の言語のcase文のような感じで利用できる。
# dict の場合
import requests
pulls = requests.get("https://api.github.com/repos/python/cpython/pulls?state=all").json()

for pull in pulls:
    match pull:
        case {'state': 'open', 'number': number, 'title': title}:
            print("オープン:", number, title)
        case {'state': 'closed', 'number': number, 'title': title, 'closed_at': closed_at}:
            print("クローズ:", number, title, closed_at)

tuple, list にも使える。同じ長さやn番目の値を一致するかどうかの判定に使える。
独自のclass やそれらの型を含むdict, list でもOK

その他
case _: # ワイルドカード: 全てにマッチする
case Point(x, y) if x == y: # ガード: if でマッチ条件を追加する
case (Point(x1, y1), Point(x2, y2) as p2): # キャプチャ: ここにマッチした場合、2つ目の値はp2 として利用できる

どんなパターンがあるのか、PEPは一読しておいたほうがいいかも。
PEP 634 – Structural Pattern Matching: Specification
PEP 635 – Structural Pattern Matching: Motivation and Rationale
PEP 636 – Structural Pattern Matching: Tutorial
日本語でまとめられている
Python 3.10の新機能:「構造的パターンマッチ」とは


What’s New In Python 3.10
Python 3.10の新機能(その1) パターンマッチ

2020年12月8日火曜日

Python3.9 リリース

2ヶ月ほど遅れてリリースノートを読んでいる...
今後は1年ごとのメジャーリリースとなるらしい。3.10 は来年の10月頃

■ PEP 584, union operators added to dict
今まではupdate メソッドを利用していたのがset のように書けるようになった
>>> {1:'A'} | {2:'B'}
{1: 'A', 2: 'B'}
>>> {1:'あ', 2: 'い'} | {2:'う'}
{1: 'あ', 2: 'う'}
>>> d1 = {1: 'A'}
>>> d1 |= {2: 'B'}
>>> d1
{1: 'A', 2: 'B'}

■ PEP 616, string methods to remove prefixes and suffixes
removeprefix とremovesuffixメソッドの追加
スペース以外に対応したlstrip() rstrip()の拡張版
新メソッドでなく、lstrip, rstrip に引数を追加する形でも良かった気がするが。
>>> "【大安売り!】".removeprefix("【").removesuffix("】")
'大安売り!'

■ ZoneInfoモジュール
今までは標準ライブラリだけではタイムゾーン名が利用できなかった。
(あれ、そうだった?とにかく日時処理はめんどくさいし、すぐに忘れるので大変!)

Python 3.9の新機能
What’s New In Python 3.9

2019年12月6日金曜日

venv のpython バージョンを変える

python3.7.3 で作ったプロジェクトをバージョン3.8.0 に変更
python -m venv venv --upgrade (upgradeオプションを付ける)
バージョンを戻すときも同じ。

現状確認。
$ python -V
> Python 3.7.3
$ . venv/bin/activate
(venv)$ python -V
> Python 3.7.3
(venv)$ ls venv/lib
> python3.7
python 3.8 をインストールしたので
venvもversion3.8に合わせる
もう一度、確認
$ python -V
> Python 3.8.0
$ . venv/bin/activate
(venv)$ python -V
> Python 3.7.3         # venvのpythonは3.7.3 のまま

upgradeオプションをつけて!
(venv)$ deactivate
$ python -m venv venv --upgrade
$ . venv/bin/activate
(venv)$ python -V
> Python 3.8.0         # venv の環境でもバージョン3.8.0
(venv)$ ls venv/lib
> python3.7 python3.8  # venv/libにも 3.8用ディレクトリができている
- 念のため pip --version も確認しておく
- pip install -r requirements.txt を実行 (マイナーバージョンの変更時は必要ないと思う)

参考
venv --- 仮想環境の作成

2018年8月10日金曜日

dataclassデコレータ

Python3.7 で追加されたdataclassデコレータについて。

__init__ を書かなくても済むのはいいけど、型情報を書く必要ある。
これは慣れていくしかないか...
というか、class の書き方もこのスタイルに変わってくるかも。

from dataclasses import dataclass

@dataclass
class Point:
    x: float
    y: float
    z: float = 0.0

p = Point(1.5, 2.5)
print(p)   # Point(x=1.5, y=2.5, z=0.0)
@dataclass(frozen=True) でイミュータブルになり、少しだけパフォーマンスが良くなると。


What’s New In Python 3.7
PEP 557 – Data Classes

2018年5月11日金曜日

コアサーバー借りました

バリュードメインのコアサーバー借りました。
(30日のお試し期間中ですけど)

時代は dockerで、コンテナだとかOpenShift だとか言ってるけど、こんな時代だから共用サーバーを使ってみる!
さくらのArukas なんかと比べると3周くらい遅れてるゾ。(;'∀')

サーバ側の実行環境はphp, fastcgi, apache が使えます。
必要があれば、PHPで頑張るつもりで契約しました。
(もちろん、CGI も使えますよ)

■ python
php (WordPress, Laravelなど)の利用を想定していますが、何故かpyenv を入れてみました。
最新のver3.6はpip のエラーでインストールできませんでした。
3.3, 3.5, 3.7beta はすんなりとインストールできます。
python3.6 だけ、pip/_vendor/distro.py が必要で、その中から/etc を参照していますが、コアサーバーでは
PermissionError: [Errno 13] Permission denied: '/etc'
とエラーで終わります。
https://github.com/pypa/pip/blob/10.0.1/src/pip/_vendor/distro.py

あと2カ月ほどでver3.7 もリリースされるので個人的には問題なしです。

■ CGI の確認
wsgiref.handlers.CGIHandler() を利用。
py.cgi として以下を作成。
#!/[home-path]/.pyenv/shims/python3.7
import wsgiref.handlers
import sys

def application(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/plain')])
    res = ('Hello World!\n' + sys.version).encode("utf-8")
    return [res]

if __name__ == '__main__':
    wsgiref.handlers.CGIHandler().run(application)

事前に作られたディレクトリ、~/public_html/exsample.com/に置くだけでOKでした。
(あとCGIなので、chmod 711 も忘れずに)
ブラウザでアクセスするとちゃんと表示されました。
(拡張子をpy にしたら AddHandler cgi-script .py が必要かもしれません)

Hello World!
3.7.0b4 (default, May 11 2018, 22:03:04)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)]

このメモを書いてて思ったんですが .htaccess の設定すれば、おそらくpython(flup), ruby(rack) でもfastcgi 利用できますね。(たぶんですよ)

2016年11月6日日曜日

pip v9.0.0 のエラー対処

pip をversion 9.0.0 にしたらエラーで困ってます

とりあえず、ダウングレードしておきます。

エラーメッセージ
>  File "/usr/local/lib/python3.4/site-packages/pip/_vendor/distro.py", line 922, in _lsb_release_info
>    stdout, stderr = stdout.decode('ascii'), stderr.decode('ascii')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 22: ordinal not in range(128)

まず、エラー個所を修正
/usr/local/lib/python3.4/site-packages/pip/_vendor/distro.py
の922行目を修正。
 stdout, stderr = stdout.decode('utf-8'), stderr.decode('utf-8')

次にダウングレード
pip install pip==8.1.1 --upgrade

しばらく、このバージョンで。

2016年1月18日月曜日

cdコマンドをフックしてvenv を有効にするヤツ


pyvenv で作ったpython環境がある場合に
source venv/bin/activate
を自動で実行にしてくれるヤツ。
(venv固定だけど気にしないw)

https://nathancahill.github.io/automatically-activate-virtualenv/

.bash_profile に追加。
function cd {
    builtin cd "$@"
    if [ -d "venv" ] ; then
        source venv/bin/activate
    fi
}

direnv の検索してたら見つけました。
すごく便利です。ありがとうさまです。

2015年12月19日土曜日

pyvenv でのプロジェクトディレクトリの作り方

pyvenv で作られるディレクトリをgitignore に追加しようと思って、検索してたらいいエントリがあったのでメモ。

プロジェクト用ディレクトリをprj01 とする
mkdir prj01
cd prj01
pyvenv .   <- ダメ
pyvenv venv <- OK (venv以下にpython環境を作る)

venv の様な名でディレクトリを作ってその中に閉じ込めておく。いわれてみれば確かに!
"pyvent venv"だと、別のライブラリ環境を作りたいときに簡単に試せる。
たとえば "pyvenv venv02"とか。
(いらなくなったら venv02ディレクトリを消せばいいだけ)
pyvenv . だと、独立しいたプロジェクト環境を作れるので50点。
pyvenv venv だと、独立したライブラリ環境を作れるので100点。
といったところかな?

prj01
└── venv
    ├── bin
    ├── include
    ├── lib
    ├── lib64 -> lib
    └── pyvenv.cfg
└── venv02
└── venv03
 .....

ディスクサイズが気になるので gitignore にvenv を追加しておく
必要なライブラリは requirements.txt へ。
(pip freeze > requirements.txt)

python のバージョン縛りの方法があるのか不明。。。

The Right Way to Use Virtual Environments
https://medium.com/@jtpaasch/the-right-way-to-use-virtual-environments-1bc255a0cba7#.9zwhannoz

あと、近いうちに pyvenv は venvに置き換えられるようです。
python -m venv

2015年4月4日土曜日

最近のWeb Framwork @ Python

Django1.8 がリリースされた。

でなぜか、久しぶりにPython のWebフレームワークをいくつか検索してみた。
フルスタックはDjangoだけど、 相変わらず lightweight界隈は活発。

wheezy.web
https://pythonhosted.org/wheezy.web/

Falcon
http://falconframework.org/

Guava
https://github.com/StarfruitStack/guava
内部はCで書かれている

Werkzeug からの移行を考える。
Morepath: from Werkzeug to WebOb
http://blog.startifact.com/posts/morepath-from-werkzeug-to-webob.html
Werkzeug よりもWebOb, wheezy.http の方がパフォーマンスは上。
ベースとして使っているライブラリでこんなに差があると、werkzeug 使うのやめようかなと思ってしまう。


CMS だけど、これも今度使ってみる。
(DjangoをベースにしたCMS)
https://wagtail.io/

2014年9月17日水曜日

Pythonでも動的型付け

Pythonへの型アノテーション導入を目指すGuido van Rossum氏

個人的にはいらないけど。
動的型付けができたら、プログラムの方法も少し変わるのかも。

2014年5月10日土曜日

uwsgi をsystemd で管理


fedora20でuwsgiを動かそうと思ったので。
python3.4

SystemD (uwsgi doc)

uidとgidはnginxを利用。 (rootで起動しないため)

daemonize だとサービスの起動時にこける。
logto に変更したら無事起動した。
(ここら辺はよく理解できていない)

/usr/lib/systemd/system/hoge.service
を変更した後は、systemctl daemon-reload を。


その他の参考ページ
uwsgi service is not starting


2014年1月27日月曜日

mysql5.6のrpmリポジトリ (fedora20)

rpm でfedora20 にmysql をインストール。

Download MySQL Yum Repository
redhat(centos), fedora18, 19, 20 用が用意されている。


rpm -ivh http://dev.mysql.com/get/mysql-community-release-fc20-5.noarch.rpm

yum install mysql-community-server mysql-community-devel mysql-community-client mysql-community-common mysql-community-libs


■ python3用ドライバー
Python 3 の MySQL ドライバ事情
ということなので、
MySQL-for-Python-3 を利用してみる。

pip3 install git+https://github.com/davispuh/MySQL-for-Python-3.git

(warningがいくつも出るね。。。)

python3.4 インストール

python3 の準備。
(fedora20, python3.4)

readline-devel ncurses-devel bzip2-devel openssl-devel zlib-devel xz-devel sqlite-devel
などはyumで入れておく。

scipy を入れる場合は以下も入れておく。
atlas-devel lapack-devel blas-devel

./configure --enable-shared
make
make install

echo '/usr/local/lib' > /etc/ld.so.conf.d/local.conf
ldconfig を実行。(上の追加を有効にする)

デフォルトでpipがインストールされるようになったみたい。
/usr/local/bin/pip3


pip3 install lxml         (libxml2-devel libxslt-devel が必要)
pip3 install feedparser
pip3 install django
pip3 install uwsgi
pip3 install git+https://github.com/mitsuhiko/werkzeug.git
(リリース前だがver0.10でpython3に対応)
ipython, numpy, scipy, pandas, sklearn も

■ uwsgi の確認
--------------------------------------------------
#coding: utf-8

def application(env, response):
    response('200 OK', [('Content-Type', 'text/html')])
    html = '''<!DOCTYPE html><html>
    <head><meta charset="utf-8"></head>
    <body>こんにちは!uWsgi</body></html>'''
    return [html.encode('utf-8')]
--------------------------------------------------
uwsgi --http-socket :8000 --wsgi-file wsgi.py


■ 残り作業
(1) MySQL-Python
  MySQLからmariadb に変わってしまった。。。

(2) zenhan
 今まで使ってたけど、python3には未対応?
pip3 install zenhan
---------------------------------------------------------
Downloading/unpacking zenhan
  Could not find any downloads that satisfy the requirement zenhan
  Some externally hosted files were ignored (use --allow-external zenhan to allow).
---------------------------------------------------------
これも確認が必要。

2013年7月27日土曜日

ポストモダンPython

Pythonのすばらしいエントリー
Navigating the Postmodern Python World


ほかにも、gevent関連のエントリーあり。

2011年7月4日月曜日

mod_wsgi 3.3 のインストール



mod_wsgi

apacheのライブラリ

yum install httpd-devel.x86_64


インストール

./configure --with-python=/usr/local/bin/python2.7
make
make install


mod_wsgiのログ

cp .libs/mod_wsgi.so /usr/lib64/httpd/modules/mod_wsgi.so
cp .libs/mod_wsgi.lai /usr/lib64/httpd/modules/mod_wsgi.la
cp .libs/mod_wsgi.a /usr/lib64/httpd/modules/mod_wsgi.a
chmod 644 /usr/lib64/httpd/modules/mod_wsgi.a
ranlib /usr/lib64/httpd/modules/mod_wsgi.a
PATH="$PATH:/sbin" ldconfig -n /usr/lib64/httpd/modules
----------------------------------------------------------------------
Libraries have been installed in:
   /usr/lib64/httpd/modules

If you ever happen to want to link against installed libraries
in a given directory, LIBDIR, you must either use libtool, and
specify the full pathname of the library, or use the `-LLIBDIR'
flag during linking and do at least one of the following:
   - add LIBDIR to the `LD_LIBRARY_PATH' environment variable
     during execution
   - add LIBDIR to the `LD_RUN_PATH' environment variable
     during linking
   - use the `-Wl,--rpath -Wl,LIBDIR' linker flag
   - have your system administrator add LIBDIR to `/etc/ld.so.conf'

See any operating system documentation about shared libraries for
more information, such as the ld(1) and ld.so(8) manual pages.
----------------------------------------------------------------------
chmod 755 /usr/lib64/httpd/modules/mod_wsgi.so

2011年7月3日日曜日

Python2.7 のインストール


2.6の時と同じ。

必要なライブラリ

とりあえず、以下のものは入れておく。
yum install sqlite-devel.x86_64 zlib-devel
yum install gdbm-devel.x86_64 readline-devel.x86_64 readline-devel.x86_64 freetype-devel.x86_64
yum install bzip2-devel.x86_64 yum install db4-devel.x86_64 openssl-devel.x86_64 gdbm-devel.x86_64 ncurses-devel.x86_64

zlib-develはPILで必要なので32bit版も入れる
dl, imageop はなくなるモジュールなので無視
ここで入れ忘れても、make, make install で、追加したものだけインストールできる。

インストール

./configure --enable-shared
make
make install

/usr/local/bin の検索順位が /usr/bin より前なので、
rm /usr/local/bin/python
で、消しておく。

ライブラリ検索の登録


方法1
ln -s /usr/local/lib/libpython2.7.so.1.0 /usr/lib64/

方法2
rootになって、
echo "/usr/local/lib" > /etc/ld.so.conf.d/local.conf
ldconfig

方法3
やったこと無いけど、
LD_LIBRARY_PATH を使う。



モジュールインストール

setuptoolsのインストール
wget http://peak.telecommunity.com/dist/ez_setup.py
python2.7 ez_setup.py

easy_install pip

とりあえず、これは入れておく。
yum install mysql-devel.x86_64
pip install MySQL-python
yum install libxml2-devel.x86_64
yum install libxslt-devel.x86_64
pip install lxml
pip install zenhan
pip install feedparser
pip install django
pip install Werkzeug







2010年5月17日月曜日

withステートメント

Understanding Python's "with" statement

基本構文
class controlled_execution:
    def __enter__(self):
        set things up
        return thing
    def __exit__(self, type, value, traceback):
        tear things down

with controlled_execution() as thing:
     some code

__exit__内で true value を返すと例外を投げるようです。
例えば、 return isinstance(value, TypeError) のように。

PEP 0343
The with statement (2.6リファレンス)