Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Multiprocess Python but running on different terminals to separately track responses delivered in each of the codes in Visual Studio Code

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading