2

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
3
  • 2
    Put the stuff into a function, call that function in the script's body, then return from that function? Commented Jan 8, 2018 at 10:51
  • exit() is not meant to be used in actual programs, it exists for the REPL. Commented Jan 8, 2018 at 10:52
  • I have 60 lines of code for creating main object(in case there is no pickle file) and I looking for a way to not put it into big "if" or big function. I think that additional tab make my code less clear. Commented Jan 8, 2018 at 11:12

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.