2

abc.py:

import xyz
#also import other required modules
#other required code
xyz.func()
#other required code

xyz.py:

import threading
import sys
#few threads
def func():

    #start all threads
    threads.start()
    threads.join(timeout)
    #if not joined within given time, terminate all threads and exit from xyz.py
    if (threads.isAlive()):
        sys.exit()
#I used sys.exit() but it is not working for me.What else can I do here? `

I have a python script abc.py that imports another python script xyz.py. I am using sys.exit() function in xyz.py. Problem I am facing here is when sys.exit() function is executed in xyz.py file, my main file i.e. abc.py also gets terminated. I don't want this to happen. My file abc.py should remain ON even though xyz.py file terminates. Is there any way to achieve this? I will be grateful to receive any help/guidance.I am using python 2.6.6 on centos 6.5.

1

The problem that xyz.py is in a same type is module and script. There is common construct if __name__ == '__main__' that allow to separate script part in xyz.py from module part. More information here: What does if __name__ == “__main__”: do?

Also, you misunderstanding how import works. There is no such thing as termination of abc.py or xyz.py, there is single interpreter which maintains global namespace containing abc.py objects. When interpreter meets import xyz statement it simply adds name xyz to namespace and to build its content, it interprets statements in that file. When it meets sys.exit(0) it executes it thus exiting interpreter itself.

May be you need to keep both files as a scripts and keep interpreters separate? Then instead of importing, use subprocess.call, i.e:

import subprocess

subprocess.call([sys.executable, 'xyz.py'])
2
  • how to call a function of xyz.py file here in abc.py using subprocess? I have edited my question above and included my code's format if you could please check it once – Bhoomika Sheth Feb 26 '15 at 10:03
  • 1
    @BhoomikaSheth, myaut is correct. Your function should not be calling sys.exit. Have it return a value and have the caller decide whether to exit. Worst case catch the SystemExit exception within abc.py but that would constitute an egregious hack – iruvar Feb 26 '15 at 13:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.