python
Up one levelWindows7にpython,numpy,matplotlib,IPythonをインストール
インストール先は、Windows7 64bit版
Python
Python標準リリース からWindows用インストーラ python-2.6.6.msi をダウンロードして実行。OSが64ビットであっても、pythonは32ビット版を用いること。64ビット版だと、以下のモジュールのインストーラが認識できない。
numpy
Scientific Computing Tools For Python — Numpy から たどっていって numpy-1.6.1-win32-superpack-python2.6.exe をダウンロードしてインストール
scipy
SciPy - から scipy-0.10.0-win32-superpack-python2.6.exe をダウンロードしてインストール。
matplotlib
http://sourceforge.net/projects/matplotlib/files/ から、 matplotlib-1.1.0.win32-py2.6.exe をダンロードしてインストール。
IPython
http://ipython.org/download.html から ipython-0.12.win32-setup.exe をダウンロードしてインストール
起動すると ImportError: No module named pkg_resources というエラーがでる。
setuptoolsがいるとのことで、
http://pypi.python.org/pypi/setuptools から http://pypi.python.org/pypi/setuptools#files にいって、 setuptools-0.6c11.win32-py2.6.exe (md5) をインストール
起動すると、まだ次のようなエラーが出る。
C:\Python26\Scripts>ipython.exe WARNING: Readline services not available or not loaded.WARNING: Proper color sup port under MS Windows requires the pyreadline library. You can find it at: http://ipython.org/pyreadline.html Gary's readline needs the ctypes module, from: http://starship.python.net/crew/theller/ctypes (Note that ctypes is already part of Python versions 2.5 and newer). Defaulting color scheme to 'NoColor'Python 2.6.6 (r266:84297, Aug 24 2010, 18:46 :32) [MSC v.1500 32 bit (Intel)] Type "copyright", "credits" or "license" for more information. IPython 0.12 -- An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object', use 'object??' for extra details.
readlineというのがいるらしいので、
https://launchpad.net/pyreadline/+download から pyreadline-1.7.1.win32.exe をダウンロード
これでOK
Windowsの環境設定
Pythonのpathを通すために環境変数に C:¥Python26¥;C:¥Python26¥Script¥; を追加する。最後の¥を入れないとなぜかpathが通らなかった。
- Category(s)
- python
- The URL to Trackback this entry is:
- http://lightson.dip.jp/blog/seko/2823/tbping
PythonでExcelファイルを読む
今回は、 xlrd というモジュールを使ってみました。 Python-izm そのままです。
インタラクティブシェルの IPython を初めて使ってみました。
In [3]: import xlrd
In [4]: book = xlrd.open_workbook('fruitslst.xls')
In [5]: print book.nsheets
3
In [6]: for name in book.sheet_names():
...: print name
...:
Sheet1
Sheet2
Sheet3
In [7]: print book.sheet_by_index(0).name
Sheet1
In [9]: print book.sheet_by_name('Sheet2').name
Sheet2
In [10]: sheet_1 = book.sheet_by_index(0)
In [11]: for col in range(sheet_1.ncols):
....: print '-' * 20
....: for row in range(sheet_1.nrows):
....: print sheet_1.cell(row,col).value
....:
--------------------
Apple
Orenge
Melon
--------------------
3.0
2.0
1.0
- Category(s)
- python
- The URL to Trackback this entry is:
- http://lightson.dip.jp/blog/seko/2818/tbping
Macbook AirにHomebrew,matplotlibをインストール失敗→成功!
Macbook Airのpythonでグラフが描きたいです。
1.Homebrewをインストールする
kazhr さんのところに書いてあることをそのまま実行
開発環境XcodeをApp storeで購入しておく
$ ruby -e "$(curl -fsSL https://gist.github.com/raw/323731/install_homebrew.rb)"
と実行
seko$ ruby -e "$(curl -fsSL https://gist.github.com/raw/323731/install_homebrew.rb)" ==> This script will install: /usr/local/bin/brew /usr/local/Library/Formula/... /usr/local/Library/Homebrew/... ==> The following directories will be made group writable: /usr/local/. ==> The following directories will have their group set to admin: /usr/local/.Press enter to continue ==> /usr/bin/sudo /bin/chmod g+rwx /usr/local/. Password: ==> /usr/bin/sudo /usr/bin/chgrp admin /usr/local/. ==> Downloading and Installing Homebrew... ==> Installation successful! Now type: brew help
アップデート
seko$ brew update Initialized empty Git repository in /usr/local/.git/ remote: Counting objects: 53169, done. remote: Compressing objects: 100% (24377/24377), done. remote: Total 53169 (delta 34111), reused 44744 (delta 28086) Receiving objects: 100% (53169/53169), 7.69 MiB | 1.10 MiB/s, done. Resolving deltas: 100% (34111/34111), done. From https://github.com/mxcl/homebrew [new branch] gh-pages -> origin/gh-pages [new branch] master -> origin/master HEAD is now at f78eb1c wireshark: add 1.7.0 as the devel version Already up-to-date.
2. PILをインストール
こちら に書いてある通りに実行。
seko$ sudo easy_install pip seko$ sudo ARCHFLAGS="-arch i386 -arch x86_64" pip install PIL
3.ScipySuperpackをインストール
https://github.com/fonnesbeck/ScipySuperpack
にいって、下の方にあるDownload Scipy Superpack Installer for OSX 10.7 を保存。
ちなみに2012年1月31日の依存性は
Dependencies OS X 10.7 (Lion), Python 2.7, Xcode 4.2
ダウンロードしたディレクトリで
$ sh install_superpack.sh
と実行するとNumpy (2.0) and Scipy (0.11), Matplotlib (1.2), iPython (0.12), Pandas (0.6)がまとめてインストールされるらしい。
$ sh install_superpack.sh
Are you installing from a repository cloned to this machine (if unsure, answer no)? (y/n)
y
Downloading gFortran ...
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 11.3M 100 11.3M 0 0 352k 0 0:00:32 0:00:32 --:--:-- 127k
Installing gFortran ...
Password:
installer: Package name is GNU Fortran 4.2.4 for Lion Xcode 4.1 (build 5666.3)
installer: Installing at base path /
installer: The install was successful.
Installing Scipy Superpack ...
error: Not a URL, existing file, or requirement spec: ./*.egg
Installing readline ...
Searching for readline
Reading http://pypi.python.org/simple/readline/
Reading http://www.python.org/
Reading http://github.com/ludwigschwardt/python-readline
Best match: readline 6.2.1
Downloading http://pypi.python.org/packages/2.7/r/readline/readline-6.2.1-py2.7-macosx-10.7-intel.egg#md5=8aef7cc656e1bdfe851a8e6f91c63c4c
Processing readline-6.2.1-py2.7-macosx-10.7-intel.egg
creating /Library/Python/2.7/site-packages/readline-6.2.1-py2.7-macosx-10.7-intel.egg
Extracting readline-6.2.1-py2.7-macosx-10.7-intel.egg to /Library/Python/2.7/site-packages
Adding readline 6.2.1 to easy-install.pth file
Installed /Library/Python/2.7/site-packages/readline-6.2.1-py2.7-macosx-10.7-intel.egg
Installing nose ...
Searching for nose
Reading http://pypi.python.org/simple/nose/
Reading http://somethingaboutorange.com/mrl/projects/nose/
Reading http://readthedocs.org/docs/nose/
Best match: nose 1.1.2
Downloading http://pypi.python.org/packages/source/n/nose/nose-1.1.2.tar.gz#md5=144f237b615e23f21f6a50b2183aa817
Processing nose-1.1.2.tar.gz
Running nose-1.1.2/setup.py -q bdist_egg --dist-dir /tmp/easy_install-3XrNEO/nose-1.1.2/egg-dist-tmp-uR71QE
Adding nose 1.1.2 to easy-install.pth file
Installing nosetests script to /usr/local/bin
Installing nosetests-2.7 script to /usr/local/bin
Installed /Library/Python/2.7/site-packages/nose-1.1.2-py2.7.egg
Installing DateUtils
Searching for DateUtils
Reading http://pypi.python.org/simple/DateUtils/
Best match: DateUtils 0.5.1
Downloading http://pypi.python.org/packages/source/D/DateUtils/DateUtils-0.5.1.tar.gz#md5=40cff15a40664eeb117361049edbd0bd
Processing DateUtils-0.5.1.tar.gz
Running DateUtils-0.5.1/setup.py -q bdist_egg --dist-dir /tmp/easy_install-QrU1Rh/DateUtils-0.5.1/egg-dist-tmp-a7rRdp
zip_safe flag not set; analyzing archive contents...
Adding DateUtils 0.5.1 to easy-install.pth file
Installed /Library/Python/2.7/site-packages/DateUtils-0.5.1-py2.7.egg
Done
pythonでインポートしてみると。。。だめです。
$ python Python 2.7.1 (r271:86832, Jun 25 2011, 05:09:01) [GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import matplotlib Traceback (most recent call last): File "", line 1, in ImportError: No module named matplotlib
調べてみるとマシンのXcodeのバージョンは4.1です。要求されているバージョンは4.2なので、App Storeを見に行くと4.2がダウンロード済みになっていて、更新することができません。検索してみると、同じ現象 を見つけました。 「アプリケーション」フォルダーに保存されていたの"Install Xcode" を実行して無事4.2になりました。 この後、再びScipySuperpackを実行したら、matplotlibが使えるようになりました。
- The URL to Trackback this entry is:
- http://lightson.dip.jp/blog/seko/2807/tbping
CentOS6.2にmatplotlibをインストール
[root@localhost ~]# yum search matplotlib Loaded plugins: fastestmirror, refresh-packagekit, security Loading mirror speeds from cached hostfile base: rsync.atworks.co.jp extras: rsync.atworks.co.jp * updates: rsync.atworks.co.jp =========================== N/S Matched: matplotlib ============================ python-matplotlib-tk.x86_64 : Tk backend for python-matplotlib python-matplotlib.x86_64 : Python plotting library
Name and summary matches only, use "search all" for everything. [root@localhost ~]# yum install python-matplotlib Loaded plugins: fastestmirror, refresh-packagekit, security Loading mirror speeds from cached hostfile base: rsync.atworks.co.jp extras: rsync.atworks.co.jp * updates: rsync.atworks.co.jp Setting up Install Process Resolving Dependencies --> Running transaction check ---> Package python-matplotlib.x86_64 0:0.99.1.2-1.el6 will be installed --> Processing Dependency: python-dateutil for package: python-matplotlib-0.99.1.2-1.el6.x86_64 --> Processing Dependency: pytz for package: python-matplotlib-0.99.1.2-1.el6.x86_64 --> Processing Dependency: numpy for package: python-matplotlib-0.99.1.2-1.el6.x86_64 --> Running transaction check ---> Package numpy.x86_64 0:1.3.0-6.2.el6 will be installed --> Processing Dependency: python-nose for package: numpy-1.3.0-6.2.el6.x86_64 --> Processing Dependency: libptf77blas.so.3()(64bit) for package: numpy-1.3.0-6.2.el6.x86_64 --> Processing Dependency: libatlas.so.3()(64bit) for package: numpy-1.3.0-6.2.el6.x86_64 --> Processing Dependency: liblapack.so.3()(64bit) for package: numpy-1.3.0-6.2.el6.x86_64 --> Processing Dependency: libptcblas.so.3()(64bit) for package: numpy-1.3.0-6.2.el6.x86_64 ---> Package python-dateutil.noarch 0:1.4.1-6.el6 will be installed ---> Package pytz.noarch 0:2010h-2.el6 will be installed --> Running transaction check ---> Package atlas.x86_64 0:3.8.4-1.el6 will be installed ---> Package python-nose.noarch 0:0.10.4-3.1.el6 will be installed --> Processing Dependency: python-setuptools for package: python-nose-0.10.4-3.1.el6.noarch --> Running transaction check ---> Package python-setuptools.noarch 0:0.6.10-3.el6 will be installed --> Finished Dependency Resolution
Dependencies Resolved
================================================================================ Package Arch Version Repository Size ================================================================================ Installing: python-matplotlib x86_64 0.99.1.2-1.el6 base 3.2 M Installing for dependencies: atlas x86_64 3.8.4-1.el6 base 2.8 M numpy x86_64 1.3.0-6.2.el6 base 1.6 M python-dateutil noarch 1.4.1-6.el6 base 84 k python-nose noarch 0.10.4-3.1.el6 base 220 k python-setuptools noarch 0.6.10-3.el6 base 336 k pytz noarch 2010h-2.el6 base 35 k
Transaction Summary ================================================================================ Install 7 Package(s)
Total download size: 8.4 M Installed size: 33 M Is this ok [y/N]: y Downloading Packages: (1/7): atlas-3.8.4-1.el6.x86_64.rpm | 2.8 MB 00:00 (2/7): numpy-1.3.0-6.2.el6.x86_64.rpm | 1.6 MB 00:00 (3/7): python-dateutil-1.4.1-6.el6.noarch.rpm | 84 kB 00:00 (4/7): python-matplotlib-0.99.1.2-1.el6.x86_64.rpm | 3.2 MB 00:00 (5/7): python-nose-0.10.4-3.1.el6.noarch.rpm | 220 kB 00:00 (6/7): python-setuptools-0.6.10-3.el6.noarch.rpm | 336 kB 00:00 (7/7): pytz-2010h-2.el6.noarch.rpm | 35 kB 00:00 -------------------------------------------------------------------------------- Total 3.2 MB/s | 8.4 MB 00:02 警告: rpmts_HdrFromFdno: ヘッダ V3 RSA/SHA256 Signature, key ID c105b9de: NOKEY Retrieving key from file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6 Importing GPG key 0xC105B9DE: Userid : CentOS-6 Key (CentOS 6 Official Signing Key)
Package: centos-release-6-2.el6.centos.7.x86_64 (@anaconda-CentOS-201112091719.x86_64/6.2) From : /etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-6 Is this ok [y/N]: y Running rpm_check_debug Running Transaction Test Transaction Test Succeeded Running Transaction Installing : atlas-3.8.4-1.el6.x86_64 1/7 Installing : python-setuptools-0.6.10-3.el6.noarch 2/7 Installing : python-nose-0.10.4-3.1.el6.noarch 3/7 Installing : numpy-1.3.0-6.2.el6.x86_64 4/7 Installing : python-dateutil-1.4.1-6.el6.noarch 5/7 Installing : pytz-2010h-2.el6.noarch 6/7 Installing : python-matplotlib-0.99.1.2-1.el6.x86_64 7/7 Installed: python-matplotlib.x86_64 0:0.99.1.2-1.el6
Dependency Installed: atlas.x86_64 0:3.8.4-1.el6 numpy.x86_64 0:1.3.0-6.2.el6 python-dateutil.noarch 0:1.4.1-6.el6 python-nose.noarch 0:0.10.4-3.1.el6 python-setuptools.noarch 0:0.6.10-3.el6 pytz.noarch 0:2010h-2.el6
Complete! [root@localhost ~]#
- The URL to Trackback this entry is:
- http://lightson.dip.jp/blog/seko/2806/tbping
Macbook airにrst2pdfインストール 失敗
開発環境のX codeを入れればいいのかな?
Last login: Sun Jan 1 21:55:24 on console seiinishiekuchi-haku-no-MacBook-Air:~ seko$ sudo easy_install rst2pdfWARNING: Improper use of the sudo command could lead to data loss or the deletion of important system files. Please double-check your typing when using sudo. Type "man sudo" for more information.
To proceed, enter your password, or type Ctrl-C to abort.
Password: Searching for rst2pdf Reading http://pypi.python.org/simple/rst2pdf/ Reading http://rst2pdf.googlecode.com Reading http://code.google.com/p/rst2pdf/downloads/list Best match: rst2pdf 0.16 Downloading http://rst2pdf.googlecode.com/files/rst2pdf-0.16.tar.gz Processing rst2pdf-0.16.tar.gz Running rst2pdf-0.16/setup.py -q bdist_egg --dist-dir /tmp/easy_install-BL1bhd/rst2pdf-0.16/egg-dist-tmp-aVQigh zip_safe flag not set; analyzing archive contents... rst2pdf.createpdf: module references __file__ rst2pdf.image: module references __file__ rst2pdf.pdfbuilder: module references __file__ rst2pdf.styles: module references __file__ rst2pdf.tests.autotest: module references __file__ rst2pdf.tests.execmgr: module references __file__ Adding rst2pdf 0.16 to easy-install.pth file Installing rst2pdf script to /usr/local/bin
Installed /Library/Python/2.7/site-packages/rst2pdf-0.16-py2.7.egg Processing dependencies for rst2pdf Searching for Pygments Reading http://pypi.python.org/simple/Pygments/ Reading http://pygments.org/ Reading http://pygments.pocoo.org/ Best match: Pygments 1.4 Downloading http://pypi.python.org/packages/2.7/P/Pygments/Pygments-1.4-py2.7.egg#md5=acbdde4dae30efaba8cfa86dcb6070f2 Processing Pygments-1.4-py2.7.egg creating /Library/Python/2.7/site-packages/Pygments-1.4-py2.7.egg Extracting Pygments-1.4-py2.7.egg to /Library/Python/2.7/site-packages Adding Pygments 1.4 to easy-install.pth file Installing pygmentize script to /usr/local/bin
Installed /Library/Python/2.7/site-packages/Pygments-1.4-py2.7.egg Searching for reportlab>=2.1 Reading http://pypi.python.org/simple/reportlab/ Reading http://www.reportlab.com/ Best match: reportlab 2.5 Downloading http://pypi.python.org/packages/source/r/reportlab/reportlab-2.5.tar.gz#md5=cdf8b87a6cf1501de1b0a8d341a217d3 Processing reportlab-2.5.tar.gz Running reportlab-2.5/setup.py -q bdist_egg --dist-dir /tmp/easy_install-qhYqVC/reportlab-2.5/egg-dist-tmp-1kvi8h ################################################ #Attempting install of _rl_accel, sgmlop & pyHnj #extensions from
/private/tmp/easy_install-qhYqVC/reportlab-2.5/src/rl_addons/rl_accel################################################ ################################################ #Attempting install of _renderPM #extensions from/private/tmp/easy_install-qhYqVC/reportlab-2.5/src/rl_addons/renderPM# installing without freetype no ttf, sorry! # You need to install a static library version of the freetype2 software # If you need truetype support in renderPM # You may need to edit setup.cfg (win32) # or edit this file to access the library if it is installed ################################################ Downloading standard T1 font curves Finished download of standard T1 font curves unable to execute llvm-gcc-4.2: No such file or directory error: Setup script exited with error: commandllvm-gcc-4.2failed with exit status 1 seiinishiekuchi-haku-no-MacBook-Air:~ seko$
なんとかインストールしても実行するとエラーになります。
$ rst2pdf sample.rst Traceback (most recent call last): File "/usr/local/bin/rst2pdf", line 8, inload_entry_point( rst2pdf==0.16,console_scripts,rst2pdf)() File "/Library/Python/2.7/site-packages/rst2pdf-0.16-py2.7.egg/rst2pdf/createpdf.py", line 1452, in main numbered_links=options.numbered_links, File "/Library/Python/2.7/site-packages/rst2pdf-0.16-py2.7.egg/rst2pdf/createpdf.py", line 169, in __init__ get_language (self.language) TypeError: get_language() takes exactly 2 arguments (1 given) seiinishiekuchi-no-MacBook-Air:Desktop seko$
こちら を参考に、エラーメッセージを見てパスを探して__init__.pyを書き換えます。
$ sudo vim /Library/Python/2.7/site-packages/docutils-0.8.1-py2.7.egg/docutils/languages/__init__.py
def get_language(language_code, reporter): ↓ def get_language(language_code, reporter=None):
- The URL to Trackback this entry is:
- http://lightson.dip.jp/blog/seko/2796/tbping
rst2pdfのインストールとエラー回避
pythonを使ってデータを処理し、レポートをPDFで作りたいと思います。
調べてみるとpythonで書かれたrst2pdf を使うと、reStructuredtextをpdfに変換できるようです。
OSは、Scientific Linux6.1 です。
インストール
easy_install というのを使う為にpython-setuptoolsを入れます。python-develが入っていないとrst2pdfをインストールしたときにエラーがでました。
# yum install python-setuptools # yum install python-devel # yum install python-imaging # easy_install rst2pdf
実行時のエラー
rst2pdf sample.rst
とするとエラーになります。
TypeError:get_language()takesexactly2arguments (1 given)
こちら を参考に、エラーメッセージを見てパスを探して site-packages/docutils/languages/__init__.pyのdef get_languageを書き換えます。
def get_language(language_code, reporter): ↓ def get_language(language_code, reporter=None):
- Category(s)
- python
- The URL to Trackback this entry is:
- http://lightson.dip.jp/blog/seko/2795/tbping
ソースコードの行頭に空白を入れる方法
このブログは、structuredTextを使って書いています。ソースコードを貼付けるときは、段落づけが必要で、すべての行の頭に空白を入れる必要があります。
今までは手で入れていたのですが、長いソースだと大変です。そういう時は、preタグを入れていたのですが、よく見るとダブルコーテーションなどが正しく表示されていません。
最近は、Macbook Airを使っており、エディタは mi です。 mi のヘルプを見たら、検索オプションで設定をすると 正規表現での置換 が行えることが分かりました。
行頭^を見つけて、スペースに置換すればOKです。手でやってた人なんていなかったんですね。
ちなみにこの文書は初めて reStructuredText で書いてみました。
- The URL to Trackback this entry is:
- http://lightson.dip.jp/blog/seko/2685/tbping
Ploneへの入力をメールから行うpython スクリプトの巻
インターネットで情報を見つけたとき、Ploneサイトにアクセスして、コピペするのは面倒ですね。
そこで、メールで届いた内容をpop3でアクセスして取り出し、テキストファイルを生成し、FTPでPloneにアップロードするpythonスクリプトを書いてみました。メールの添付ファイルはとりあえず、スクリプトと同じ場所に保存するだけで、アップロードはしていません。
これを使えば、気になる情報をメールで送るだけで、Ploneの記事になります。
予めPloneのFTPを使えるようにしておく必要があります。やり方は、Papasanのサイト を見てください。
Windows上のpython2.6で作り、CentOS5で動作を確認したらpythonのバージョンが2.4のせいで、動きませんでした。 Unified InstallerでPloneをインストールした際にpython2.6が入ったので、それを使えばOKでした。
課題としては、アップロードされた文書はそのままでは非公開になっているので、一般の人に見せるには一つ一つ手で公開にする必要があることです。最初から公開にする方法を知りたいです。
参考にさせていただいたところ:
# -*- coding: utf-8 -*-
import os
import poplib
import datetime
import email
from email.Header import Header,make_header,decode_header
import ftplib
import time
def mailread(src,mypath):
"""
生メールから件名、本文、添付ファイルを取り出す
"""
# Messageオブジェクトを作る
msg = email.message_from_string(src)
# ヘッダをデコード
subject = decode_header(msg["Subject"])
# ヘッダーを表示
try:
print "-" * 70
#print msg["Date"]
st = datetime.datetime.strptime(msg["Date"][:-6], "%a, %d %b %Y %H:%M:%S")
delivered_date = st.strftime("%Y/%m/%d %H:%M:%S") + " GMT+9"
my_id = st.strftime("%Y%m%d-%H%M%S")
#print unicode(make_header(subject))
except: pass;
print "-" * 70
#全パートをスキャン
for part in msg.walk():
type =part.get_content_maintype()
#print type
if type and type.find("image") != -1:
#画像が見つかったら、ファイルに保存
filename = part.get_filename("notitle.img")
f = open (os.path.join(mypath,filename),"wb")
f.write(part.get_payload(decode=True))
f.close()
if type and type.find("application") != -1:
#EXCELやWordがあったらファイルに保存
filename = part.get_filename("notitle.img")
f = open (os.path.join(mypath,filename),"wb")
f.write(part.get_payload(decode=True))
f.close()
if type and type.find("text") !=-1:
#テキストは表示
enc = part.get_charsets()[0] or "us-ascii"
body = part.get_payload().decode(enc,"ignore")
return my_id ,delivered_date, unicode(make_header(subject)), body, msg
def upload_ftp(server,port,username,password,directory,upfilename):
ftp = ftplib.FTP()
ftp.connect(server,port)
print " connect ok"
ftp.login(username, password)
print "login ok"
ftp.cwd(directory)
print "CD ok"
# upload file
print upfilename
upfile = open(upfilename, "rb")
ftp.storbinary("STOR %s" % upfilename, upfile)
upfile.close()
ftp.quit()
def set_headers():
headers ="""id:
title:
description:
subject:
relatedItems:
location:
language: ja
effectiveDate:
expirationDate: None
creation_date:
modification_date:
creators: admin
contributors:
rights:
allowDiscussion: False
excludeFromNav: False
presentation: False
tableContents: False
Content-Type: text/html
"""
return headers
####################### Main ##############################
# interval設定 sec
interval = 1 * 60
# FTPサーバ設定
ftp_server = "servername"
ftp_port = 8021
ftp_user = "admin"
ftp_password = "xxxxx"
ftp_directory = "/Plone/frommail"
# メール基本設定
mail_server = "servername"
pop3_port = 110
user_id = "user"
user_pass = "password"
# pathの取得
mypath = os.getcwd()
while 1:
# メールサーバに接続
pop3 = poplib.POP3(mail_server,pop3_port)
pop3.user(user_id)
pop3.pass_(user_pass)
# メール一覧の取得
mail_list = pop3.list()
print mail_list
# メールのリストは[1]にある
for mail_id in mail_list[1]:
(no,msg_size) = mail_id.split(" ")
# 番号指定で取り出し
mail_data = pop3.retr(no)
my_id, delivered_date, title, body ,msg = mailread("\n".join(mail_data[1]),mypath)
print my_id,delivered_date, title
# ヘッダを行に分ける
lst = set_headers().split("\n")
# 作成日、更新日、発効日をメールの受信日に設定
n = 0
for line in lst:
if line in ("effectiveDate: ","creation_date: ","modification_date: "):
lst[n] = lst[n] + delivered_date
n = n + 1
lst[0] = lst[0] + my_id
lst[1] = lst[1] + title
lst[21] = lst[21] + body
# テキストファイルにまとめて、書き出す
txt = ""
for line in lst:
txt = txt + line + '\n'
file_name = os.path.join(mypath,my_id+'.txt')
o = open(file_name,'w')
# utf8なので先頭にBOMが必要
o.write('\xef\xbb\xbf')
o.write(txt.encode('utf8','ignore'))
o.close()
# FTPでアップロードする
upload_ftp(ftp_server,ftp_port,ftp_user,ftp_password,ftp_directory,my_id+'.txt')
# メールを削除
for mail_id in mail_list[1]:
(no,msg_size) = mail_id.split(" ")
pop3.dele(no)
# pop3 切断
pop3.quit()
# ある時間待つ
time.sleep(interval)
- The URL to Trackback this entry is:
- http://lightson.dip.jp/blog/seko/2682/tbping
Re:Ploneへの入力をメールから行うpython スクリプトの巻
Ploneのドキュメントオブジェクトを生成しているのですか?、それともZopeのファイルオブジェクト?
Re:Ploneへの入力をメールから行うpython スクリプトの巻
ただし、タイトルはファイル名になってしまいます。
Plone側で作った文書をFTPで取り出してみると、本文の前に20行くらいのヘッダーがついており、タイトル名や発行日、有効日、変更日などがありました。
このプログラムでは、ヘッダー部分を追加したテキストファイルを作り、アップロードしています。
Plone以下のフォルダーにアップロードしているので、Ploneのドキュメントオブジェクトではないかと思います。
デフォルトで公開できるでしょうか?
Re:Ploneへの入力をメールから行うpython スクリプトの巻
Ploneは細かな操作も考慮されていますので、できるような気がします。
ところで、Ploneのバージョンはいくつなのでしょう?
Plone4.05でPlone側からテキストファイルを、素のままアップロードしてみましたら自動的に公開になってしまいました。
>Plone側で作った文書をFTPで取り出してみると、本文の前に20行くらいのヘッダーがついており、タイトル名や発行日、有効日、変更日などがありました。
Plone側で作った文書じゃなくって、Plone側でアップロードしたファイルをFTPで取り出してみて、そのヘッダに合わせてみてはどうでしょうか?
Re:Ploneへの入力をメールから行うpython スクリプトの巻
>Plone側でアップロードしたファイルをFTPで取り出してみて、そのヘッダに合わせてみてはどうでしょうか?
それはいいアイデアです。
今、スープストック東京にいるので、部屋に帰ったらやってみます。
Re:Ploneへの入力をメールから行うpython スクリプトの巻
Re:Ploneへの入力をメールから行うpython スクリプトの巻
もしやと思ってグーグルで検索してみましたが、ありません。
そんな名前をつけたら、訴えられますね。
今は、ドトールコーヒーです。
おばさんが多いです。
Re:Ploneへの入力をメールから行うpython スクリプトの巻
散歩がてら近所のスーパーに犬用のハムを買いにいきました、おばさんしかいません。
渋谷まで行かないといけないのでしょうか?
Re:Ploneへの入力をメールから行うpython スクリプトの巻
Papasanのおっしゃるように公開されました。
しかし、アップロードされたファイルは、ファイルとして認識されており、ページにはなっていません。
これに対し、FTPからPloneのフォルダーにテキストファイルをアップロードすると、添付ファイルではなくページができます。
そしてそのページは非公開になっています。
外はまた雨になってきました。さてさて、これからどうしましょう?
Re:Ploneへの入力をメールから行うpython スクリプトの巻
「ファイルでも公開できればいいのかな」と思っていましたが、「ページ」でないといけないのね。
>これに対し、FTPからPloneのフォルダーにテキストファイルをアップロードすると、添付ファイルではなくページができます。
そしてそのページは非公開になっています。
これは、面白いですね。こちらでも試してみます。Ploneのどんなメソッドが動いているのでしょうね?
Re:Ploneへの入力をメールから行うpython スクリプトの巻
FTPでテキストファイルをアップロードすると、「ページ」が生成されました。
コンテンツの状態は「非表示」です。
ワークフロー周辺か、ポータルファクトリーでドキュメントオブジェクト(ページ)を生成するメソッド付近をゴニョゴニョしないといけないのでしょうね?
がんばってね!!
Re:Ploneへの入力をメールから行うpython スクリプトの巻
miエディタでpythonを使えるように
インストール対象:Macbook air 2011 13inch lion
mi用pythonモードをMacOSXで使う方法 をみながらやってみる。
pythonはOSの付属のものを使うことにする。
こちら からmiをダウンロードする
こちら から「mi用pythonモード」をダウンロード.
ダブルクリックするとPython_mode_f.img というのができる。
それをダブルクリックすると「レガシーイメージを変換する必要があります」というメッセージがでる。
ユーティリティの中にあるディスクユーティリティを起動して、ファイルを変換する。 拡張子はdmgになる。
変換したファイルをダブルクリックしてマウントする。
ファイル名が文字化けしていないか確認するが、問題なし
miを起動する.
「メニューバー>mi>モード設定>モード追加>新規モード(インポート)...」>モードファイルからインポートで「Python_mode_f/Python/Python」を選択.
ファイル>新規作成>pythonを選ぶとpythonモードになっている
- The URL to Trackback this entry is:
- http://lightson.dip.jp/blog/seko/2612/tbping
Macbook airにpython開発環境を作りたいがよくわからない
Macbook air (2011年夏モデルlion 13inch core i5 4G 256G)でpythonを使えるようにしたいと思い、いろいろ調べてみましたが、よくわかりませんでした。
標準で入っているpythonに変に手を加えてしまうと、OS自体の動作もおかしくしてしまうかもしれないのが不安です。
- OSに標準で入っているPython2.7を使う
- python.orgからダウンロードしてインストール
- macportsでインストールし、pythonselectで切り替える
- pythonbrew+virtualenv
- homebrewを使ってインストール
- python + eclipse
- 仮想マシンにlinuxを入れてそちらのpythonを使う
- The URL to Trackback this entry is:
- http://lightson.dip.jp/blog/seko/2584/tbping
もう一人、ここに居ます。
向上心を持ちませう。