1

so I was wondering if it is possible to execute a file (wheather .py, .java or any other extensions) and display the output in the console.

Let's say that I have a main.py file and an file.java. Now if I would run the main.py, it would return You just runned the python file! in the console, and if I run the file.java file, it would return You just runned the Java file!

Now is it possible to create a third file, and usind the Threading module, execute both of the files at the same time and display the outputs live in the console of the new file?

I am sorry if this is a little weird. Thanks!

  • 1
    It *sounds* like you just want to execute a couple of subprocesses. Yous hould use the `subprocess` module. Since it sounds like you want the calls in your main module to be non-blocking, you should use the `subprocess.Popen` constructor directly, which is a slightly more advanced use-case (for blocking calls, `subprocess.run` is adequate) – juanpa.arrivillaga Jul 17 '23 at 17:45
  • Right. If you do `subprocess.Popen(['ls','-l'])` twice in a row, it will start both of them (almost) simultaneously and the output will be interleaved on your console, while your program continues on to the next thing. (If on Windows, use `...['dir','/s']`. – Tim Roberts Jul 17 '23 at 18:10

1 Answers1

1

As mentioned in these answers (1, 2), CPython's GIL is unlikely to allow true parallelism with threading (which is useful for concurrency). The multiprocessing module is likely more effective for this, or alternatively using thread pools with a version of Python that does not implement the GIL such as JPython. Hope this helps.

Here is an example using the multiprocessing module paracoded from 1, authored by user @NPE:

from multiprocessing import Process
import time


def f1():
    print("f1: starting")
    time.sleep(100)
    print("f1: finishing")


def f2():
    print("func2: starting")
    time.sleep(100)
    print("func2: finishing")


if __name__ == "__main__":
    p1 = Process(target=f1)
    p1.start()
    p2 = Process(target=f2)
    p2.start()
    p1.join()
    p2.join()
Lavie
  • 136
  • 7
  • Could you maybe give me an example with the module? Thanks! – Tousend1000 Jul 17 '23 at 07:08
  • Just updated the answer to include an example. This is almost exactly the same as the example given in the answer I linked you to. – Lavie Jul 17 '23 at 17:39
  • this doesn't really address the OP's question. You are basically showing them how to execute a python function in a subprocess, not an arbitrary subprocess. – juanpa.arrivillaga Jul 17 '23 at 17:43