Python で終了してコマンドラインに戻る
-
24-09-2019 - |
質問
ある条件下で早期に終了したいスクリプトがあります。
if not "id" in dir():
print "id not set, cannot continue"
# exit here!
# otherwise continue with the rest of the script...
print "alright..."
[ more code ]
このスクリプトを使用して実行します execfile("foo.py")
Python インタラクティブ プロンプトからスクリプトを終了し、インタラクティブ インタプリタに戻りたいと考えています。どうすればいいでしょうか?私が使うなら sys.exit()
, 、Python インタープリターは完全に終了します。
解決
などのように、そのメソッドからメソッドと引き換えに、あなたのコードブロックを置きます
def do_the_thing():
if not "id" in dir():
print "id not set, cannot continue"
return
# exit here!
# otherwise continue with the rest of the script...
print "alright..."
# [ more code ]
# Call the method
do_the_thing()
また、(execfileを使用するには十分な理由がない限り)、この方法は、おそらくそれは、それをインポートして、別のPythonスクリプトから呼び出すことができるモジュールに配置する必要があります
import mymodule
mymodule.do_the_thing()
他のヒント
所属していません StackOverflow