‘Python’ カテゴリーのアーカイブ

Pythonで文字コードを指定してファイルを読み取り、Unicodeとして日本語を扱うには

2010年2月23日 火曜日

codecsモジュールを使用してファイルを読み込む。下記のコードで変数lineはUnicodeになる。

import codecs, sys

f = codecs.open(‘C:\\work\\utf8.txt’,mode=’r',encoding=’utf-8′)
for line in f:
    sys.stdout.write(line)
f.close() 

Djangoのテンプレートエンジンだけ利用する

2010年2月23日 火曜日

テンプレートファイルを作成する。

 data1:{{ data1 }}
==============================
{% for val in list1 %} — {{ val }}
{% endfor %}

テンプレートファイルをおくパスをDjangoの設定に追加し、テンプレートをロードし、テンプレートに変数を渡す。

import django.conf
import django.template
import django.template.loader

# TEMPLATE_DIRSにテンプレートファイルをおくパスを指定してDjangoの手動設定を行う。
if django.conf.settings.configured == False:
    django.conf.settings.configure(
        DEBUG=True, TEMPLATE_DEBUG=True,
        TEMPLATE_DIRS=(‘D:/data/template1′, ‘C:/data/template2′))
#(なぜかパスは1つだけだとエラーになってしまう)

# テンプレートを取得する
tmpl = django.template.loader.get_template(‘test.txt’)

# テンプレートに渡す変数を設定して、レンダリングを行う。
print tmpl.render(django.template.Context({‘data1′    : ‘果物’,
                           ‘list1′: (‘りんご’,'みかん’,'バナナ’,'レモン’) }))

C#とIronPython 2.6の連携方法(変数の受け渡し方)

2010年2月20日 土曜日

IronPythonのインストールディレクトリにあるIronPython.dll, Microsoft.Scripting.dll, Microsoft.Scripting.Core.dll, Nicrosoft.Dynamic.dllに参照を通す。

下記のソースコードのような方法でC#のコードからPythonのスクリプトの実行と変数の値のやりとりが可能。

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Scripting.Hosting;
using IronPython.Hosting;

    public class Class1
    {
        public IronPython.Runtime.List Val1;
        public IronPython.Runtime.List Val2;
    }
    class Program
    {
        static void Main(string[] args)
        {
             ScriptEngine engine = Python.CreateEngine();
             ScriptSource source = engine.CreateScriptSourceFromString(
@”print obj1.Val1
result = obj1.Val2″);
             ScriptScope scope = engine.CreateScope();
             var obj1 = new Class1()
             {
                 Val1 = new IronPython.Runtime.List { 1, “abc” },
                 Val2 = new IronPython.Runtime.List { 2, “def”}
             };
             scope.SetVariable(“obj1″, obj1);
             source.Execute(scope);
             object[] result = scope.GetVariable<IronPython.Runtime.List>(“result”).ToArray();
             Console.WriteLine(“{0},{1}”, result[0], result[1]);
        }

    }

Django1.1.1をIronPython2.6にインストールし、importするとエラー

2010年2月20日 土曜日

Django1.1.1をIronPython2.6にインストールし、importすると下記のようなエラーが発生する。

Cannot call lazy() with both str and unicode return types.

http://bitbucket.org/jdhardy/django-ironpython/changeset/b70eeacda60c/

を参考にして、django.utils.

assert not (cls._delegate_str and cls._delegate_unicode),

の行を

 assert (str is unicode) or not (cls._delegate_str and cls._delegate_unicode), 

に変更したらとりあえず回避できた。

PythonからODBC経由でSQL Serverに接続するには

2010年1月17日 日曜日

python DB API 2.0に準拠しているODBCドライバ pyodbcを使用する。Windows認証を使用して接続する接続パラメータは下記。

‘DRIVER={SQL Server};SERVER=localhost\SQLEXPRESS;DATABASE=TestDB;Trusted_Connection=yes;’

使用例:

import pyodbc

conn = pyodbc.connect(‘DRIVER={SQL Server};SERVER=localhost\SQLEXPRESS;DATABASE=TestDB;Trusted_Connection=yes;’)
cursor = conn.cursor()
rows = cursor.execute(‘select* from Test’).fetchall()
conn.close()
print rows