Introduction to Python/Pythonの紹介

From FreeCAD Documentation
Revision as of 10:02, 3 January 2019 by Luc (talk | contribs) (Replaced content with "リストの一つのとても洗練された使用方法は、アイテムを参照して各要素で何らかの処理をすることです。例えばこれを見てく...")

これは、Pythonをはじめる人のために作られた短いチュートリアルです。 Pythonはオープンソース、マルチプラットフォームのプログラミング言語です。 Pythonは他の一般的なプログラミング言語と違い、あなたのようなはじめてのユーザーにとって非常に使いやすくするいくつかの機能を持っています。

  • 人間が読みやすいように特別に設計されたので、それを学習し理解することは非常に容易であるされています。
  • C言語のようなコンパイル言語とは異なり、実行する前にコンパイルを必要とせずにコードを解釈します。あなたがそうしたい場合は、記述したコードはすぐに1行ずつ実行することができます。これは、ステップごとに実行されるので、簡単に学習でき、あなたのコード内のエラーを検出することが極めて容易になります。
  • スクリプト言語として他のプログラムに埋め込むことができます。 FreeCADは、埋め込まれたPythonインタプリタを持っているので、FreeCADの部品を操作する例えばジオメトリを作成することをFreeCADのPythonコードで書くことができます。これは非常に強力でプログラマが用意した"球体作成"のボタンをクリックするかわりに自由にかつ簡単に作成した独自のツールであなたが望む正確なジオメトリを作成することができます。
  • それは拡張可能であり、新しいPythonのモジュールをプラグインとして簡単にインストールし機能を拡張することができます。例えば、jpg画像の読み書き、Twitterとの通信、使用しているオペレーティングシステムによって実行されるタスクのスケジュール等のモジュールがあります。

まずは、実際に使ってみましょう!次は非常に簡単な紹介であることに注意してください。これは完全はチュートリアルではありません。しかし、私の希望は、後にFreeCADのメカニズムをより深く探求するための十分な基礎を得ることです。

インタプリタ

通常、コンピュータプログラムを書くとき、単にテキストエディタを使用するかほとんど場合は、特別なプログラミング環境のテキストエディタと周辺のツールを利用して プログラムを書き、それをコンパイルして実行します。ほとんどの場合、記述中に誤りがあるとあなたのプログラムは動作しません。そして、何が悪かったのかを伝えるエラーメッセージが表示されます。あなたはテキストエディタに戻って、間違いを修正し、再度実行するということをプログラムが正常に動作するまで繰り返します。

Pythonにおけるプロセスは、Pythonインタプリタの内部で透過的に実行できます。Pythonインタプリタは、Pythonウィンドウのコマンドプロンプトを使って簡単にPythonコードを入力することができます。お使いのコンピュータにPythonをインストールする場合は、(WindowsもしくはMacの場合はPythonのWebサイトからダウンロードしてください。GNU/Linuxの場合はパッケージリポジトリからインストールしてください)スタートメニューにPythonインタプリタが入ります。しかし、FreeCADは、ウィンドウ下部にPythonインタプリタが入っています。

(表示されない場合は、View → Views → Python consoleをクリックしてください。)

インタプリタは、Pythonのバージョンを表示し、そしてコマンドプロンプトとなる>>>のシンボルを表示します。ここへPythonコードを入力します。インタプリタでコードを書くことは簡単です:1行は1命令です。あなたがEnterを押すと、入力したコードが実行されます。(瞬時にコンパイルされます)例えば、これを書いてください。

print "hello"

print は言うまでもなく画面に何かを表示することを意味する特別なPythonのキーワードです。Enterキーを押すと、操作が実行され、"hello"というメッセージが表示されます。エラーにしたい場合は、次の例を書いてください:

print hello
print hello

Pythonは"hello"が何かを知らないということを教えてくれる。 「"」はその中身が文字列であることを指します。それはプログラミング用語において、ひとつのテキスト文字列fであることを示します。「"」がない場合、printコマンドは、helloがテキストの一部ではなく特別なPythonのキーワードだと思います。重要なことは、あなたがすぐにエラーになった通知を受けとれることです。上矢印を押して、(FreeCADのインタプリタの場合はCtrl + 上矢印)、あなたが書いた最後のコマンドに戻って、それを修正することができます。

Pythonインタプリタにもヘルプ機能があります。次の命令を試してください:

help

または、例として、先ほどの「print hello」コマンドを使用して何が悪かったのかわからず"print"コマンドに関する具体的な情報が欲しい時は:

help("print")

あなたは、printコマンドが実行できるすべての完全な説明を得ることができます。

今、私たちはインタプリタを使いこなせます。本気になって使いはじめましょう。

変数

もちろん、"hello"を表示することが注目すべき点ではありません。より注目すべき点は、あなたが気づかなかったことをPythonが解釈して表示していることです。 これが変数の概念です。変数は単に名前をつけて値を格納しているのです。例えば次のように入力します。

a = "hello"
print a

何がおこったのか解説すると、"hello"という文字列をaという名前をつけて格納しました。この時点でaは未知の名前ではありません!printコマンドなどで、どこでも使用することができます。スペースや句切り点を使用しないというような簡単なルールに守っていれば任意の名前を使用できます。この例は、非常によく使います。

hello = "my own version of hello"
print hello

見ましたか?helloはもう未定義の言葉ではありません。不運にもPythonで予約されているキーワードを選んだ場合はどうなりますか?"print"という名前で文字列を格納したいとしましょう:

print = "hello"

Pythonは非常に知的であり、これが不可能であることを私たちに教えてくれます。いくつかの予約されたキーワードを持っており、変更することはできません。しかし、我々の独自の変数は、正確には変数と呼ばれており、いつでも変更することができます。たとえば、次のように:

myVariable = "hello"
print myVariable
myVariable = "good bye"
print myVariable

myVariableの値を変更しました。また、変数をコピーすることができます:

var1 = "hello"
var2 = var1
print var2

あなたの使う変数に適切な名前を付けることが重要であることに注意してください。なぜなら、長いプログラムを書こうとしたときに"a"という名前の変数が何のためにあるのか覚えられないと思います。しかし、あなたが例のようにmyWelcomeMessageという変数の名前を使用した場合、あなたはその変数を見たり使ったりするときに簡単に思い出すことができます。

Case is very important. myVariable is not the same as myvariable, the difference in the upper/lower case v. If you were to enter print myvariable it would come back with an error as not defined.

数値

もちろん、あなたがプログラムを作る上で文字列だけでなくすべての種類のデータ、特に数値を使うことを知っている必要があります。重要なことの一つにPythonでどのような種類のデータを使うことができるか知っておく必要があります。print helloの例題から printコマンドで"hello"という文字列を表示できることがわかりました。それは"を使用すると、printコマンドにおいてその後に続くのが文字列であることがわかりました。

特別なPythonのキーワードを入力することにより、いつでも変数のデータ型が何なのか確認することができます:

myVar = "hello"
type(myVar)

これはmyVarの中身が'str'、つまりPython用語における文字列であることがわかります。また、他の基本的なデータ型には、整数型や浮動小数点数型などがあります:

firstNumber = 10
secondNumber = 20
print firstNumber + secondNumber
type(firstNumber)

これは、今までよりはるかに興味深いですが、それはないですか?今、私たちは、すでに強力な電卓を持っています!それが機能していることをよく見てください。Pythonは10と20が整数であることを認識しています。だからそれらは "int"型として格納されており、Pythonは整数として扱うことができます。この結果を見てください:

firstNumber = "10"
secondNumber = "20"
print firstNumber + secondNumber

見ましたか?これはPythonは2つの変数が数字ではなく単なる文字列として認識していることを意味しています。Pythonは、2つの文字列を合わせて一つにすることができますが、2つの合計を求めようとはしません。しかし、我々は、整数型のことも話題にしていました。浮動小数点型もあります。これらの違いは浮動小数点の数値は小数部を有することができ、整数の数値は、小数部を持っていないということです:

var1 = 13
var2 = 15.65
print "var1 is of type ", type(var1)
print "var2 is of type ", type(var2)

int型と浮動小数点型は問題なく一緒に混合することができます:

total = var1 + var2
print total
print type(total)

いいですか?もちろん合計は小数になります。 Pythonは自動的に結果が浮動小数点型であると判断しました。この例のように、いくつかのケースではPythonは自動的に何型かをを判断します。他のケースではそれはしていません。たとえば、次のように:

varA = "hello 123"
varB = 456
print varA + varB

これは、エラーになります。varAは文字列であり、varBのデータ型は整数型で、Pythonは何をすればいいのかわかりません。しかし、型の変換をPythonに強制することもできます:

varA = "hello"
varB = 123
print varA + str(varB)

これで、両方が文字列となり実行できます!表示する時にvarBが"文字列"となっていますが、私たちはvarB自体を変更していないことに注意してください。varBを常に文字列にしたい場合は、次のようにします:

varB = str(varB)

また、場合によって整数型や浮動小数点型に変換するためにint()やfloat()を使用することができます:

varA = "123"
print int(varA)
print float(varA)

Pythonコマンドに関する注意

このセクションでprintコマンドをいくつかの方法で使用したことに気づいている必要があります。変数の値、合計、コンマで区切られたいくつかの事項、そしてtype()のようなPythonコマンドの結果を出力しています。これらの2つのコマンドを実行してみてはどうでしょうか:

type(varA)
print type(varA)

まったく同じ結果になります。それはインタプリタであり、すべてのものが画面上に自動的に表示されているからです。インタプリタの外で複雑なプログラムを書いて実行させようと思うと、自動的にすべてが画面上に表示されないので、printコマンドを使用する必要があります。しかし、今からここではそれは使わないでおきましょう。それよりはやいからです。だから簡単に書くことができます:

myVar = "hello friends"
myVar

そのPythonコマンド(またはキーワード)のほとんどはtype()、int()、str()などのように括弧はコマンドとして動作することを伝えるために使用するとわかりました。唯一の例外は、実際は例外ではありませんがprintコマンドです。これは通常print("hello")のように動作します。しかし頻繁に使用されるのでPythonのプログラマは簡易版を作りました。

リスト

Another interesting data type is a list. A list is simply a collection of other data. The same way that we define a text string by using " ", we define a list by using [ ]:

myList = [1,2,3]
type(myList)
myOtherList = ["Bart", "Frank", "Bob"]
myMixedList = ["hello", 345, 34.567]

You see that it can contain any type of data. Lists are very useful because you can group variables together. You can then do all kinds of things within that group, for example counting them:

len(myOtherList)

or retrieving one item of a list:

myName = myOtherList[0]
myFriendsName = myOtherList[1]

You see that while the len() command returns the total number of items in a list, their "position" in the list begins with 0. The first item in a list is always at position 0, so in our myOtherList, "Bob" will be at position 2. We can do much more with lists, you can read here, such as sorting contents, removing or adding elements.

A funny and interesting thing: a text string is very similar to a list of characters! Try doing this:

myvar = "hello"
len(myvar)
myvar[2]

Usually, what you can do with lists can also be done with strings. In fact both lists and strings are sequences.

Outside strings, ints, floats and lists, there are more built-in data types, such as dictionaries, or you can even create your own data types with classes.

インデント

リストの一つのとても洗練された使用方法は、アイテムを参照して各要素で何らかの処理をすることです。例えばこれを見てください:

alldaltons = ["Joe", "William", "Jack", "Averell"]
for dalton in alldaltons:
   print dalton + " Dalton"
alldaltons = ["Joe", "William", "Jack", "Averell"]
for dalton in alldaltons:
   print dalton + " Dalton"

We iterated (programming jargon) through our list with the "for ... in ..." command and did something with each of the items. Note the special syntax: the for command terminates with : indicating the following will be a block of one of more commands. In the interpreter, immediately after you enter the command line ending with :, the command prompt will change to ... which means Python knows that a colon (:) ended line has happened and more is coming.

How will Python know how many of the next lines will be to be executed inside the for...in operation? For that, Python uses indentation. That is, your next lines won't begin immediately. You will begin them with a blank space, or several blank spaces, or a tab, or several tabs. Other programming languages use other methods, like putting everything inside parenthesis, etc. As long as you write your next lines with the same indentation, they will be considered part of the for-in block. If you begin one line with 2 spaces and the next one with 4, there will be an error. When you finished, just write another line without indentation, or simply press Enter to come back from the for-in block

Indentation is cool because it aids in program readability. If you use large indentations (for example use tabs instead of spaces because it's larger), when you write a big program you'll have a clear view of what is executed inside what. We'll see that commands other than for-in, can have indented blocks of code too.

For-in commands can be used for many things that must be done more than once. It can, for example, be combined with the range() command:

serie = range(1,11)
total = 0
print "sum"
for number in serie:
   print number
   total = total + number
print "----"
print total

(If you have been running the code examples in an interpreter by Copying and Pasting, you will find the previous block of text will throw an error. Instead, copy to the end of the indented block, i.e. the end of the line total = total + number and then paste to the interpreter. In the interpreter issue an <enter> until the three dot prompt disappears and the code runs. Then copy the final two lines into the interpreter followed by one or more <enter> The final answer should appear.)

If you would type into the interpreter help(range) you would see:

range(...)
    range(stop) -> list of integers
    range(start, stop[, step]) -> list of integers

Here the square brackets denote an optional parameter. However all are expected to be integers. Below we will force the range parameters to be an integer using int()

decimales = 1000                     # for 3 decimales 
#decimales = 10000                   # for 4 decimales ...
for i in range(int(0 * decimales),int(180 * decimales),int(0.5 * decimales)):
    print float(i) / decimales

Or more complex things like this:

alldaltons = ["Joe", "William", "Jack", "Averell"]
for n in range(4):
   print alldaltons[n], " is Dalton number ", n

You see that the range() command also has that strange particularity that it begins with 0 (if you don't specify the starting number) and that its last number will be one less than the ending number you specify. That is, of course, so it works well with other Python commands. For example:

alldaltons = ["Joe", "William", "Jack", "Averell"]
total = len(alldaltons)
for n in range(total):
   print alldaltons[n]

Another interesting use of indented blocks is with the if command. If executes a code block only if a certain condition is met, for example:

alldaltons = ["Joe", "William", "Jack", "Averell"]
if "Joe" in alldaltons:
   print "We found that Dalton!!!"

Of course this will always print the first sentence, but try replacing the second line by:

if "Lucky" in alldaltons:

Then nothing is printed. We can also specify an else: statement:

alldaltons = ["Joe", "William", "Jack", "Averell"]
if "Lucky" in alldaltons:
   print "We found that Dalton!!!"
else:
   print "Such Dalton doesn't exist!"

関数

There are few standard Python commands. In the current version of Python, there are about 30, and we already know several of them. But imagine if we could invent our own commands? Well, we can, and it's extremely easy. In fact, most the additional modules that you can plug into your Python installation do just that, they add commands that you can use. A custom command in Python is called a function and is made like this:

def printsqm(myValue):
   print str(myValue)+" square meters"
 
printsqm(45)

(Another copy and paste error, only copy through the end of the indented section i.e. " square meters" Paste to the interpreter, and issue <enter> until the three dot prompt goes a way, then copy and paste the final line.)

Extremely simple: the def() command defines a new function. You give it a name, and inside the parenthesis you define arguments that we'll use in our function. Arguments are data that will be passed to the function. For example, look at the len() command. If you just write len() alone, Python will tell you it needs an argument. That is, you want len() of something, right? Then, for example, you'll write len(myList) and you'll get the length of myList. Well, myList is an argument that you pass to the len() function. The len() function is defined in such a way that it knows what to do with what is passed to it. Same as we did here.

The "myValue" name can be anything, and it will be used only inside the function. It is just a name you give to the argument so you can do something with it, but it also serves to tell the function how many arguments to expect. For example, if you do this:

printsqm(45,34)

There will be an error. Our function was programmed to receive just one argument, but it received two, 45 and 34. We could instead do something like this:

def sum(val1,val2):
   total = val1 + val2
   return total

sum(45,34)
myTotal = sum(45,34)

We made a function that receives two arguments, sums them, and returns that value. Returning something is very useful, because we can do something with the result, such as store it in the myTotal variable. Of course, since we are in the interpreter and everything is printed, doing:

sum(45,34)

will print the result on the screen, but outside the interpreter, since there is no print command inside the function, nothing would appear on the screen. You would need to:

print sum(45,34)

to have something printed. Read more about functions here.

モジュール

今、Python使いこなすためには、最後に1つ必要なことがあります。それはどのようにファイルやモジュールを操作するかです。

これまで、インタプリタで1行ずつPythonの命令を書いてきましたね?もしいくつかの行をまとめて書くことができ、それらを一度にすべて実行できたらどうですか?それはもっと複雑なことをするためには手軽な手段です。さらに私たちの作ったものを保存することができます。まあ、それも非常に簡単です。単にテキストエディタ(Windowsのメモ帳など)を開き、インタプリタでプログラムを記述するのと同様にPythonのプログラムをすべて書き、その後、.pyの拡張子でこのファイルをどこかに保存します。それだけです、あなたは完全なPythonプログラムを作ることができました。もちろん、メモ帳よりも便利なエディタがありますが、それはPythonプログラムは、テキストファイル以外の何者でもないことを示しているだけです。

Pythonでプログラムを実行する方法は何百もあります。Windowsでは、単にファイルを右クリックしPythonでそれを開いて実行します。しかし、Pythonインタプリタから直接プログラムを実行することもできます。直接実行するには、Pythonインタプリタが実行しようとする.pyプログラムの保存場所を知っている必要があります。

FreeCADでの最も簡単な方法は、FreeCADのbinフォルダまたはModフォルダのようにFreeCADのPythonインタプリタにデフォルトで設定されている場所にプログラムを配置することです。次のようなファイルを作成します:

def sum(a,b):
    return a + b

print "test.py succesfully loaded"
def sum(a,b):
    return a + b

print "myTest.py succesfully loaded"

そして作成したファイルをFreeCADの/binディレクトリにtest.pyとして保存します。さて、FreeCADを起動しましょう、そしてインタプリタウィンドウへ次のように入力します。

import test
import myTest

.pyの拡張子を除いたものです。これは単にインタプリタで1行ずつ書いて実行したかのように、ファイルの内容を実行します。sum関数が作成され、メッセージが出力されます。1つの大きな違いがあります:importコマンドは、ファイルに書かれたプログラムを実行するだけでなく今までのプログラム同様内部の関数を読み込むのでインタプリタで利用できるようになります。関数を含むファイルは、モジュールと呼ばれます。

通常、インタプリタでsum()関数を記述し、実行するとき単に次のように入力します:

sum(14,45)
sum(14,45)

これは以前行ったとおりです。我々はsum()関数を含むモジュールをインポートすると、構文が少し異なっています。次のように入力します:

test.sum(14,45)
myTest.sum(14,45)

つまり、モジュールは"container"として読み込まれ、そのすべての関数は内部にあります。多くのモジュールをインポートし、すべての関数をうまく整理しておくことができるので、これは非常に有用です。したがって、基本的に、something.somethingElseのようにドットで区切ることによって、somethingElse関数がsomethingモジュールの内部にあることを意味しています。


また、testの部分を記述せずにsum()関数のように、メインのインタプリタ空間に直接関数を読み込むことができます:

from test import *
sum(12,54)
from myTest import *
sum(12,54)

基本的に、すべてのモジュールはそのように動作します。モジュールをインポートしてから、module.function(引数)のようにその関数を使用することができます。ほとんどすべてのモジュールが関数を定義し、新しいデータ型とクラスをインタプリタ、モジュール内でモジュールをインポートすることもできるのでPythonモジュールで使えるようになります。

最後にもう一つ、非常に有用なものがあります。どのようなモジュールがありその内部にはどのような関数があってどのように使う(つまり必要とする引数の種類)かわかりますか? Pythonがhelp()関数を持っていることをすでに知っています。次の操作をしてみましょう:

help()
modules
help()
modules

すべての利用可能なモジュールのリストが表示されます。対話式ヘルプから抜け出すには、qを入力し、それらのいずれかをインポートすることができます。dir()コマンドを使用してそのコンテンツを見ることができます。

import math
dir(math)
import math
dir(math)

mathモジュールに含まれるすべての関数と同様、__doc__, __file__, __name__といった奇妙な名前が表示されます。__doc__ はドキュメントの文字列を表し、非常に便利です。(既存の)モジュールに含まれるすべての関数は使用方法に関する説明を__doc__に持っています。例えばmathモジュールにはsin関数含まれていることがわかります。それの使用方法が知りたいですか?

print math.sin.__doc__
print math.sin.__doc__

(It may not be evident, but on either side of doc are two underscore characters.)

最後に少し使いやすい方法は:新しいモジュールをプログラミングするとき、時々プログラムのテストを行いたいです。一度、Pythonインタプリタでモジュールを小さく区切って新しいコードをテストするためにプログラムを記述します。

import myModule
myModule.myTestFunction()
import myModule
myModule.myTestFunction()

しかし、myTestFunction()関数が正しく動作しませんか?エディタに戻って修正します。そのとき、Pythonインタプリタを一度閉じて再度開くと簡単にモジュールを更新することができます。

reload(myModule)
reload(myModule)

This file renaming is because Python doesn't know about the extension FCMacro.

However, there are two alternates: Inside the one macro use Python's exec or execfile functions.

f = open("myModule","r")
d = f.read()
exec d

or

execfile "myModule"

To share code across macros, you can access the FreeCAD or FreeCADGui module (or any other Python module) and set any attribute to it. This should survive the execution of the macro.

import FreeCAD
if hasattr(FreeCAD,"macro2_executed"):
    ...
else:
    FreeCAD.macro2_executed = True # you can assign any value because we only check for the existence of the attribute
    ... execute macro2

FreeCADではじめる

Pythonのプログラムを作るためのアイデアが理解できた思います。そして、FreeCADがどのようなモジュールを提供しているか探し始めることができます。 FreeCADのPython関数は、すべてが異なるモジュールに整理されています。FreeCADを起動したときにそれらのいくつかはすでにロード(インポート)されます。だから、使うだけです。

dir()
dir()

ここを参照してくださいFreeCADの基本スクリプト...

もちろん、ここではPythonの世界のごく一部を見ました。ここでは言及しなかったことで、多くの重要な概念があります。ネット上には2つの非常に重要なPythonのリファレンスドキュメントがあります:

これらをブックマークしてください!


Macros
Python scripting tutorial