Home > Software engineering >  Multiprocess Python but running on different terminals to separately track responses delivered in ea
Multiprocess Python but running on different terminals to separately track responses delivered in ea

Time:03-10

Question originally asked on Super User and suggested deleting it from there and creating a new question here in the main community.

I have a code that runs non-stop, but every 1 hour it makes a call to another code.

The reason I need it is to be able to follow in real time the text delivered in each of the codes without them getting mixed up.

Is there any way to make this secondary code run completely separately from the main one?

A basic example would be this:

Code One (Multiprocess_Part_1.py):

import multiprocessing
from time import sleep
import Multiprocess_Part_2

def main():
    a = 1 1
    print(a)
    p1 = multiprocessing.Process(target=Multiprocess_Part_2.secondary)
    p1.start()
    sleep(10)
    main()

if __name__ == '__main__':
    main()

Code Two (Multiprocess_Part_2.py):

def secondary():
    b = 2 2
    print(b)

Terminal Result:

2
4
2
4
2
4

Expected response as if, for example, there was a way to run the second code in a separate terminal:

Terminal 1            Terminal 2
2                     4
2                     4
2                     4
2                     4

Visual expected example:

enter image description here

CodePudding user response:

No, you can't control how VSCode terminals are opened directly from within Python.

However, you seem to be on Windows; you could use start to start a new Python interpreter with a new terminal window:

os.system("start python Multiprocess_Part_2.py")

(or an equivalent subprocess.call invocation).

If you use virtualenvs, you'd want to use sys.executable instead of just python there, too.

# TODO: ensure this quoting is correct for Windows
os.system(f'start "{sys.executable}" Multiprocess_Part_2.py')

In other words, your script might become

import os
import time
import sys


def main():
    while True:
        os.system(f"start \"{sys.executable}\" Multiprocess_Part_2.py")
        time.sleep(10)


if __name__ == '__main__':
    main()

and your Multiprocess_Part_2.py would need to be able to run as a stand-alone program:

def secondary():
    b = 2 2
    print(b)

if __name__ == '__main__':
    secondary()
  • Related