0

I have two independent scripts that are in an infinite loop. I need to call both of them from another master script and make them run simultaneously. Producing results at the same time.

Here are some scripts

script1.py

y= 1000000000
while True:
      y=y-1
      print("y is now: ", y)

script2.py

x= 0
while True:   
   x=x+1
   print("x is now: ", x)

The Aim Is to compile the master script with pyinstaller into one console

1
  • 1
    Can you write the expected output too Commented Jun 22, 2018 at 4:37

3 Answers 3

6

You can use the python 'multiprocessing' module.

import os
from multiprocessing import Process

def script1:
    os.system("script1.py")     
def script2:
    os.system("script2.py") 

if __name__ == '__main__':
    p = Process(target=script1)
    q = Process(target=script2)
    p.start()
    q.start()
    p.join()
    q.join()

Note that print statement might not be the accurate way to check parallelism of the processes.

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

Comments

2

Python scripts are executed when imported. So if you really want to keep your two scripts untouched, you can import each one of then in a separate process, like the following.

from threading import Thread


def one(): import script1
def two(): import script2

Thread(target=one).start()
Thread(target=two).start()

Analogous if you want two processes instead of threads:

from multiprocessing import Process


def one(): import script1
def two(): import script2

Process(target=one).start()
Process(target=two).start()

Comments

-2

Wrap scripts' code in functions so that they can be imported.

def main():
    # script's code goes here
    ...

Use "if main" to keep ability to run as scripts.

if __name__ == '__main__':
    main()

Use multiprocessing or threading to run created functions.

If you really can't make your scripts importable, you can always use subprocess module, but communication between the runner and your scripts (if needed) will be more complicated.

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.