Search code examples
pythonpython-3.xmultithreadingconsole

Is it possible to name output of files in python?


Is it possible to name every output of files and display it in one single console?

Let's say I have a main.py file and a main.java file, and I want to run them both in one Python script and seperate the outputs by naming them.

Now I have a python file and it should do this:

# run main.py
# run main.java

# when an output is sent from a file, it should be like this:
output = "{} > {}".format(file, output)
# and then print the output.

Let's say the java file would usually display Hello, World! but here it would be like this in the console: main.java > Hello, World!

Thanks!

EDIT:

  1. I gave a java and a python file as an example, I just want to name the output of different files, without modifying them.
  2. I wanted to run them both as a subprocess and display the outputs with names in one console.

Solution

  • Let's say main.java file contains:

    class main {
        public static void main(String[] args) {
            System.out.println("Hello, World! from Java");
        }
    }
    

    and main.py file:

    print("Hello, World! from Python")
    

    You can do it by using subprocess module in another Python file:

    import subprocess
    
    java = "{} > {}".format("main.java", subprocess.run("java main.java", shell=True, capture_output=True, text=True).stdout.strip())
    print(java)
    python = "{} > {}".format("main.py", subprocess.run("python main.py", shell=True, capture_output=True, text=True).stdout.strip())
    print(python)
    

    The output will be:

    main.java > Hello, World! from Java

    main.py > Hello, World! from Python