import sys
for i in range(10):
print(i)
実行結果
0
1
2
3
4
5
6
7
8
9
0から9まで数え上げるプログラムですが、5でプログラムを終了させたい時にはこうします。
import sys
for i in range(10):
print(i)
if i == 5:
sys.exit()
実行結果
0
1
2
3
4
5
An exception has occurred, use %tb to see the full traceback.
SystemExit
「An exception has occurred, use %tb to see the full traceback.」はJupyter Notebookが出しているだけなので気にしないでください。
import sys
for i in range(10):
print(i)
if i == 5:
sys.exit("Finish")
実行結果
0
1
2
3
4
5
An exception has occurred, use %tb to see the full traceback.
SystemExit: Finish
終了コードとしては正常終了を示す「0」、異常終了を示す「1」をよく使うようです。
import sys
for i in range(10):
print(i)
if i == 5:
sys.exit(0)
実行結果
0
1
2
3
4
5
An exception has occurred, use %tb to see the full traceback.
SystemExit: 0
import sys
for i in range(10):
print(i)
if i == 5:
sys.exit(1)
実行結果
0
1
2
3
4
5
An exception has occurred, use %tb to see the full traceback.
SystemExit: 1
import sys
for i in range(10):
print(i)
if i == 5:
print("Error")
sys.exit(1)
実行結果
0
1
2
3
4
5
Error
An exception has occurred, use %tb to see the full traceback.
SystemExit: 1
コメント