1

Currently I am working on a Java web app implementing the Spring Framework + MVC structure. I have ~10 different Python scripts that all query an API, perform some data analysis and manipulation, and save the results. All of the python scripts are in the same directory.

I would like to know how/ what would be the most efficient way to run these files from my service's Controller. Browsing around, I've seen solutions similar to this:

String command = "python /c start python path\to\script\script.py";
Process p = Runtime.getRuntime().exec(command);

However, since they are all in the same directory, I was wondering if there is a more efficient way to run the files. Perhaps another 'driver' script that calls each of the ~10 files, and then running that 'driver' from my Java file?

Any advice or suggestions would be appreciated. Let me know if any additional information is required.

skhan
  • 199
  • 10
  • Did you mean `cmd.exe /c start python ...`? – Andreas Jul 19 '19 at 17:57
  • By "driver script" do you mean a simple .bat file? – Andreas Jul 19 '19 at 17:57
  • @Andreas I'm referring to the top answer here: https://stackoverflow.com/questions/27267391/running-a-py-file-from-java – skhan Jul 19 '19 at 18:11
  • @Andreas By 'driver' I meant another .py file that would run each of the other ~10 but im def open to suggestions – skhan Jul 19 '19 at 18:11
  • The `python` command doesn't have a `/c` command-line option. That answer is wrong, look at [answer #3](https://stackoverflow.com/a/50669754/5221149) instead. – Andreas Jul 19 '19 at 19:05
  • 1
    If you use `cmd.exe / c start ...`, the Java process will not wait for the Python program to complete. Is that what you want? If you need to run 10 Python program is sequence, you either need a script to run (windows script or pything script, doesn't matter), or you need Java to wait for each Python program to complete before Java runs the next one. It's really up to you what you prefer here, we can't answer that for you. – Andreas Jul 19 '19 at 19:08
  • @Andreas to clarify, I want the python scripts to all complete before the Java file does anything but the order of the scripts does not matter. If I'm understanding correctly, one option is using another python script to run them and using Java to call that file. How would I make Java wait for each Python program if I chose to take the alternate approach instead? Thanks. – skhan Jul 19 '19 at 19:13
  • 1
    To make Java wait: 1) Remove `start` after `/c`, and 2) Call [`p.waitFor()`](https://docs.oracle.com/javase/8/docs/api/java/lang/Process.html#waitFor--). --- Beware, system may hang if Python program prints output. See e.g. [Java ProcessBuilder: Resultant Process Hangs](https://stackoverflow.com/q/3285408/5221149). – Andreas Jul 19 '19 at 19:26
  • thank you for your help! – skhan Jul 19 '19 at 19:28

0 Answers0