Python入門トップページ


目次

  1. Jupyter notebook でダウンロード
  2. コマンドプロンプトで実行する
  3. 実行結果をファイルに書き出す
  4. コマンドライン引数を使用する (1) 位置引数の使用
  5. コマンドライン引数を使用する (2) オプショナル引数の使用

コマンドプロンプトで Python プログラムを実行しよう

実行結果をファイルに書き出す

出力結果をテキストファイルに書き出すことも可能である.python プログラム名 > 出力ファイル名 として実行すれば,テキストファイルとして出力される.出力結果はテキストエディタで開いたり,type コマンドで中身を確認できる.このとき,出力ファイル名と同じ名前のファイルが存在する場合は一旦中身が削除されてから書き込まれることに注意してください.

Z:\Documents\python>python ex1.py > output.txt ⏎
Z:\Documents\python>dir ⏎
ドライブ Z のボリューム ラベルは rinsaka です
ボリューム シリアル番号は 0000-0064 です

Z:\Documents\python のディレクトリ

2018/06/05  12:58    <DIR>          .
2018/06/05  12:58    <DIR>          ..
2018/06/05  12:32               100 ex1.py
2018/06/05  13:02                31 output.txt
              2 個のファイル               1,389 バイト
              2 個のディレクトリ  227,903,660,032 バイトの空き領域

Z:\Documents\python>type output.txt ⏎
x :  5
y :  31.400000000000002

Z:\Documents\python>

すでに存在するファイルに追記したい場合は > 出力ファイル名 の代わりに >> 出力ファイル名 を利用します.

Z:\Documents\python>python ex1.py >> output.txt ⏎

Z:\Documents\python>type output.txt ⏎
x :  5
y :  31.400000000000002
x :  5
y :  31.400000000000002

Z:\Documents\python>

次は,実行時にエラーが発生するように,未定義の変数 z を表示させるプログラムを作成します.

ex2.pyx = 5
y = 2 * x * 3.14
print("x : ", x)
print("y : ", y)
print("z : ", z)

上のプログラム (ex2.py) を実行するとエラーで強制終了します.

Z:\Documents\python>python ex2.py ⏎
x :  5
y :  31.400000000000002
Traceback (most recent call last):
  File "ex2.py", line 5, in <module>
    print("z : ", z)
NameError: name 'z' is not defined

Z:\Documents\python>

同じプログラムの実行結果を output.txt に書き込んでみます.実行結果の出力は「標準出力」と「標準エラー出力」の2種類があり,「標準出力」のみが output.txt に書き込まれていることがわかります.「標準エラー出力」は引き続き画面に表示されています.

Z:\Documents\python>python ex2.py > output.txt ⏎
Traceback (most recent call last):
  File "ex2.py", line 5, in <module>
    print("z : ", z)
NameError: name 'z' is not defined

Z:\Documents\python>type output.txt ⏎
x :  5
y :  31.400000000000002

Z:\Documents\python>

「標準エラー出力」をファイルに書き出したい場合には 2> 出力ファイル名 のように指定します.次のようにすると「標準出力」は output.txt に,「標準エラー出力」は error.txt に書き出すことができます.

Z:\Documents\python>python ex2.py > output.txt 2> error.txt ⏎

Z:\Documents\python>type output.txt ⏎
x :  5
y :  31.400000000000002

Z:\Documents\python>type error.txt ⏎
Traceback (most recent call last):
  File "ex2.py", line 5, in <module>
    print("z : ", z)
NameError: name 'z' is not defined

Z:\Documents\python>

なお,「標準出力」を 1> 出力ファイル名 のように明示的に指定することも可能です.

Z:\Documents\python>python ex2.py 1> output.txt 2> error.txt ⏎

Z:\Documents\python>

ここの手順で構築した仮想開発環境を利用する場合は次のようになります.Windows の dir コマンドを ls に,type コマンドを cat に置き換えます.

[vagrant@centos8 python]$ python ex1.py > output.txt ⏎
[vagrant@centos8 python]$ ls -l ⏎
total 8
-rw-rw-r-- 1 vagrant vagrant 57  3月 30 09:28 ex1.py
-rw-rw-r-- 1 vagrant vagrant 31  3月 30 09:31 output.txt
[vagrant@centos8 python]$ cat output.txt  ⏎
x :  5
y :  31.400000000000002
[vagrant@centos8 python]$

目次に戻る