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

dshrenikAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

piuxxxCommented:
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.
CEHJCommented:
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

dshrenikAuthor Commented:
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.
CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

CEHJCommented:
We'll continue shortly. In the meantime, i'll get the urls replaced
CEHJCommented:
Yes Vic, looks good thanks
dshrenikAuthor Commented:
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

CEHJCommented:
You can model the request on this:

http://www.exampledepot.com/egs/java.net/Post.html
Mick BarryJava DeveloperCommented:
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
dshrenikAuthor Commented:
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?
dshrenikAuthor Commented:
It will be great if I could get sample code in Python that retrieves the parameters passed from java using a POST request.
Mick BarryJava DeveloperCommented:
you use sys.argv to access command line parameters in python

http://www.faqs.org/docs/diveintopython/kgp_commandline.html
dshrenikAuthor Commented:
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

CEHJCommented:
That's not the way to get POST and GET parameters in Python. See

http://www.voidspace.org.uk/python/articles/cgi_web_applications_two.shtml

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
dshrenikAuthor Commented:
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

Mick BarryJava DeveloperCommented:
you'll find it simpler to use a GET request than a POST
CEHJCommented:
:-)
dshrenikAuthor Commented:
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?
CEHJCommented:
There's probably very little difference. The only difference really lies in the fact that you can send more data with POST
dshrenikAuthor Commented:
Cool. Thank you!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Programming

From novice to tech pro — start learning today.