Link to home
Start Free TrialLog in
Avatar of dshrenik
dshrenikFlag for United States of America

asked on

Execute python script (on a different server) from a Java function

The code attached executes a python script located on my computer.
Please tell me how I could modify this code so that it executes the script 'http://SERVER/dummy.py'
 
This python script is stored on a different server. I also need to pass parameters to the script.
Is it possible through HTTP client/server communication?

Also, please tell me how Python can receive the data (input parameters) and return the results. A sample code will be great.
try
        {
            Runtime r = Runtime.getRuntime();
            Process p = r.exec("c:\\Python26\\python.exe C:\\Python26\\dummy.py");
            //Process p = r.exec("http://myserver/aphro_tester.py");
            p.waitFor();
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = "";
            while ((line = br.readLine()) != null)
            {
                System.out.println(line);
            }
            p.waitFor();

Open in new window

Avatar of piuxxx
piuxxx

Do you need that the python code is executed by your local pc or in the server? In the first case, you can download the python code, save it in a temporary file, then use your code... In the second case, I don't think is possible if the server doesn't have any custom service published which allows the user to launch a python script.
Avatar of CEHJ
Not sure why you opened a new question on this issue...

What happens when you do the following at the command line?
c:\Python26\python.exe http://myserver/aphro_tester.py

Open in new window

Avatar of dshrenik

ASKER

Sorry to have opened a new question - I thought my first one wasn't well framed.
I want the code to be executed on the server. The server does have a service published that allows the user to launch a python script (I am able to run the the code on the server from PHP. I now want to do the same from Java)

Is it possible to achieve this with HttpsURLConnection?

When I try "c:\Python26\python.exe http://myserver/aphro_tester.py ", I get no output.
We'll continue shortly. In the meantime, i'll get the urls replaced
Yes Vic, looks good thanks
I made a wrong observation.
When I try "c:\Python26\python.exe http://myserver/aphro_tester.py ", I do get the right output.

The attached snippet seems to do my job. But the question now is, how does my Python script accept the input parameters sent from Java?
.
public class Python {

	public static void main(String[] args) {
		
        try
        {
	        String input_1 = URLEncoder.encode("p1", "UTF-8");
	        
	        URL xpst_server = new URL("http://myserver/JavaPython.py");
	        URLConnection connection = xpst_server.openConnection();
	    	connection.setDoOutput(true);	    	
	    	OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
	    	out.write("string=" + input_1);
	    	out.close();
	    	
	    	BufferedReader in = new BufferedReader( new InputStreamReader(connection.getInputStream()));
	    	String decodedString;
	    	while ((decodedString = in.readLine()) != null) 
	    	{
	    	    System.out.println(decodedString);
	    	}
	    	in.close();            
        }
        
        catch (Exception e) 
        {
            
        }

	}
}

Open in new window

You can model the request on this:

http://www.exampledepot.com/egs/java.net/Post.html
you can either pass parameters in the url using a GET request

http://helpdesk.objects.com.au/java/how-do-i-send-a-get-request-using-java

or use a POST request to include them in the body

http://helpdesk.objects.com.au/java/how-do-i-send-a-post-request-using-java
Thanks for the links. They explain the first part of my question in detail.
But, how do I retrieve these parameters in my Python script now?
It will be great if I could get sample code in Python that retrieves the parameters passed from java using a POST request.
you use sys.argv to access command line parameters in python

http://www.faqs.org/docs/diveintopython/kgp_commandline.html
I have attached both my Java code and Python code.

The output that I get is:
Hello World!
myserver/JavaPython.py

Only the first parameter (name of the script) is being printed). Am I missing something here?
//JAVA CODE
        	String queryString = "param1=" +
        	   URLEncoder.encode("P1", "UTF-8");
        	queryString += "&param2=" +
        	   URLEncoder.encode("P2", "UTF-8");

        	// Make connection

        	URL url = new URL("http://myserver/JavaPython.py");
        	URLConnection urlConnection = url.openConnection();
        	urlConnection.setDoOutput(true);
        	OutputStreamWriter out = new OutputStreamWriter(
        	   urlConnection.getOutputStream());

        	// Write query string to request body

        	out.write(queryString);
        	out.flush();

        	// Read the response

        	BufferedReader in = new BufferedReader(
        	   new InputStreamReader(urlConnection.getInputStream()));
        	String line = null;
        	while ((line = in.readLine()) != null)
        	{
        	   System.out.println(line);
        	}
        	out.close();
        	in.close(); 


#PYTHON CODE
#!/usr/bin/python
from __future__ import division
import cgi
import sys
 
print "Content-Type: text/plain\n\n"
print "Hello World!"
for arg in sys.argv:
	print arg

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you! That did the trick. I have attached the simplified code.

#!/usr/bin/python
import cgi
import sys

print "Content-Type: text/plain\n\n"
form = cgi.FieldStorage()
for name in form.keys():
  print name

Open in new window

you'll find it simpler to use a GET request than a POST
:-)
Can you tell me which one of these two works faster for larger Python scripts?
And which method, in general, works fastest (GET / POST/Running script locally) works faster?
There's probably very little difference. The only difference really lies in the fact that you can send more data with POST
Cool. Thank you!