简体   繁体   中英

How to run python script from java without storing the script in a .py file?

I would like to execute a python script which is obtained as a web request, execute the script and send the output as response.

So far, I have written the python script into a .py file and executed it using the ProcessBuilder.

The problem is, once the script has been executed, there is no use in storing the script in the server. So I delete the file once the execution is completed.

Now I feel this is a bad approach and would like to minimise the write and delete operations.

I tried using jpserve but it is not working as expected. (When a selenium test case is given as input to jpserve, it is not processing the scripts but still sending the success message.) Also I am not interested in using jython.

Is there a way to run the python scripts without storing it in a .py file?

You can also probably run the script like this :

String script = "your script from server";
ProcessBuilder pb = new ProcessBuilder("python3", "-c", script);
pb.start();

In a shell the python -c allow you to run a script that you write in the shell.

Jython: Python for the Java Platform - http://www.jython.org/index.html

Also, isn't that terribly unsafe?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM