Search code examples
pythonmultithreadingpython-multiprocessing

How to terminate thread within two python files?


script1.py

import multiprocessing
import time

def worker():
     while True:
     print(f"Working........")
     time.sleep(5)

if __name__ == "__main__":
    demo = multiprocessing.Process(target=worker, args=())
    demo.start()
    #demo.terminate()

script2.py

import time

if __name__ == "__main__":
    import script1
    print("script2......")
    time.sleep(2)
    script1.demo.terminate()

In script2.py file I'm unable to use demo showing

python3 script2.py


  Traceback (most recent call last):
     File "script2.py", line 9, in <module>
     script1.demo.terminate()
     AttributeError: module 'script1' has no attribute 'demo'`

Solution

  • When you import script1.py then Python sets __name__ = "script1" and it doesn't run code in if __name__ == "__main__": - and it doesn't create demo. And you get error.

    You can remove line if __name__ == "__main__": - and this is the simplest solution.

    script1.py

    import multiprocessing
    import time
    
    def worker():
        while True:
        print(f"Working........")
        time.sleep(5)
    
    demo = multiprocessing.Process(target=worker, args=())
    demo.start()
    #demo.terminate()
    

    Or you can put code in function and execute function in __main__ and later in script2.py - and this can be more useful because you may run this function many times in script2.py

    script1.py

    import multiprocessing
    import time
    
    def worker():
        while True:
        print(f"Working........")
        time.sleep(5)
    
    def run_process():
        demo = multiprocessing.Process(target=worker, args=())
        demo.start()
        return demo
    
    if __name__ == "__main__":
        demo = run_process()
        #demo.terminate()
    

    script2.py

    import time
    
    if __name__ == "__main__":
    
        import script1
        
        demo = script1.run_process()
    
        time.sleep(2)
        demo.terminate()
    

    If you put print() in __name__ in script1.py then you will see that `script1.py doesn't display it when you import code.