2

ある条件下で早期に終了したいスクリプトがあります。

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 ]

Python インタラクティブ プロンプトを使用してこのスクリプトを実行しexecfile("foo.py")、スクリプトを終了してインタラクティブ インタープリターに戻りたいと考えています。どうすればいいですか?を使用するsys.exit()と、Python インタープリターは完全に終了します。

4

4 に答える 4

7

対話型インタープリターで; SystemExitによって発生したキャッチしsys.exit、それを無視します。

try:
    execfile("mymodule.py")
except SystemExit:
    pass
于 2010-04-06T17:56:59.163 に答える
3

次のように、コード ブロックをメソッドに入れ、そのメソッドから戻ります。

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()
于 2010-04-06T17:56:12.963 に答える
2

私はインタラクティブな作業のためにipythonに少し夢中になっていますが、これよりも堅牢なソリューションについてはシェル埋め込みに関するチュートリアルをチェックしてください (これがあなたの最も直接的なルートです)。

于 2010-04-07T17:19:34.757 に答える
0

execfile を使用する代わりに、スクリプトをインポート可能にし ( name =='メイン保護、関数に分割するなど)、インタープリターから関数を呼び出す必要があります。

于 2010-04-06T20:00:44.423 に答える