A. Bykov
A. Bykov

Reputation: 288

how to exit from module in python?

I have several python scripts. First script is needed to store a logic of creation of the object, rest scripts import the object from the first script and work with it. My trouble is about first script: it firstly check if pickle file corresponding to object exist, and if it exists, script load object from pickle file and stop executing. So how can I stop execution of first script without terminating python iterpretator?

The first script(let name it as create_main_object.py) looks like:

import pickle
import os
with open('main_object', 'rb') as input1:
    main_object = pickle.load(input1)
    exit() #this currently terminate interpretator
....
###logic for creation main_object
...
with open('main_object', 'wb') as output:
        pickle.dump(main_object, output, pickle.HIGHEST_PROTOCOL)

The other script import main_object in the way:

from create_main_object import main_object

Upvotes: 2

Views: 1529

Answers (1)

Right leg
Right leg

Reputation: 16740

You should tidy up your module, and put different actions in different functions. If you have an action that creates an object, say main_object, then encapsulate that logic inside a function:

def main_object_factory():
    with open('main_object', 'rb') as input1:
        return pickle.load(input1)

Then, import that specific function from your module:

from create_main_object import main_object_factory

For your information, this is called the factory pattern.

Upvotes: 2

Related Questions