×
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Contact US

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

How to run python within java?

How to run python within java?

How to run python within java?

(OP)
I want to run python command within java. Not sure how to do this. Seems like runtime.getRuntime.exec() is something that I can use. Can I run python command using getRuntime().. Please let me know. I am trying to change the file permission using python, now I need to call the python within java. Can anyone help plz.

Thank

RE: How to run python within java?

I will not try to understand why you would want to do something in python from Java ... in any case, if you can run your python command from the shell/command line console, then you can run it by using Runtime.exec().

--------------------------------------------------
Free Database Connection Pooling Software
http://www.primrose.org.uk

RE: How to run python within java?

You can use Jython which is a Python implementation in Java.
Haven't tried interaction between Jython and a host application yet but it is designed to plug into Java applications so it shouldn't be hard.

http://www.jython.org

Note: Jython does at this time lag quite seriously to Python development

RE: How to run python within java?

(OP)
I am trying to execute some code written in python inside java. But so far no success. Here is the sample I am trying to run. Please see the below code:

I get the following exception at runtime and my python is not being executed. I am on windows and python is in the path.


CODE

java.io.IOException: CreateProcess: C:\Documents and Settings\TEST\Desktop\PYTHON\c.py error=193

int java.lang.Win32Process.create(java.lang.String, java.lang.String, java.lang.String, java.io.FileDescriptor, java.io.FileDescriptor, java.io.FileDescriptor)

void java.lang.Win32Process.<init>(java.lang.String[], java.lang.String[], java.lang.String)

java.lang.Process java.lang.Runtime.execInternal(java.lang.String[], java.lang.String[], java.lang.String)

java.lang.Process java.lang.Runtime.exec(java.lang.String[], java.lang.String[], java.io.File)

java.lang.Process java.lang.Runtime.exec(java.lang.String, java.lang.String[], java.io.File)

java.lang.Process java.lang.Runtime.exec(java.lang.String, java.lang.String[])

java.lang.Process java.lang.Runtime.exec(java.lang.String)

void RuntimeTest.main(java.lang.String[])
Now here is the java code that I am trying to execute:


CODE

import java.io.*;

public class RuntimeTest
{
public static void main(String[] args)
{
try
{
Runtime r = Runtime.getRuntime();
Process p = r.exec("C:\\Documents and Settings\\TEST\\Desktop\\PYTHON\\c.py");
p.waitFor();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
And here is the python code that I am trying to run inside java:


CODE

import os
from stat import *

print "SUCCESS"
Thanks for the help.

RE: How to run python within java?

How do you run the code from the command line ? Post that.

There are several problems anyway :

1) Your use of spaces in the file to the .py file are problematic - try not to use them. If you do, you will need to encapsualte them in quotes.
2) It looks like you are trying to execute a file - where is the command to invoke the python interpreter ?
3) You need to invoke a new shell, not use the existing shell when working on Win32.

EG:

CODE

Process p = Runtime.getRuntime().exec("cmd /c dir \"C:/Documents and Settings\"");
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = br.readLine()) != null) {
    System.out.println(line);
}

--------------------------------------------------
Free Database Connection Pooling Software
http://www.primrose.org.uk

RE: How to run python within java?

(OP)
I got execution part working. I am trying to make a read only file to writable. As I can't find a method to set a read only file to writable in java so I was trying to use python and invoke it inside java. Right now python code is being executed but it's npt changing the file permission. If I run the python code stand alone it changes the file permission but invoking inside java doesn't change the file permission. Can you please help. Here is my python code:

CODE

import os
from stat import *

os.chmod("test.txt",666)
print "SUCCESS"

And here is the java code, modified according to the above suggestions (Thanks):

CODE

import java.io.*;

public class pythonTest
{
    public static void main(String[] args)
    {
        try
        {
            Runtime r = Runtime.getRuntime();
            Process p = r.exec("cmd /c C:\\c.py");
            p.waitFor();
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = "";
            while ((line = br.readLine()) != null)
            {
                System.out.println(line);
            }
            p.waitFor();

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

Thanks for helping me out.

RE: How to run python within java?

Why are you doing  p.waitFor(); twice ?

Perhaps you should change the file to its full path in this line :

os.chmod("test.txt",666)

--------------------------------------------------
Free Database Connection Pooling Software
http://www.primrose.org.uk

RE: How to run python within java?

Well, if you have already lost cross-platform issue, I don't think you need Python anymore.

You can change file permission by executing in Windows attrib +r filename, that would make things easier.

Runtime.getRuntime().exec("cmd / c attrib +R file.ext");


Btw, did you try the API someone mentioned in your other post? Did it work? I'm a bit curious about it.

Cheers.

Dian

RE: How to run python within java?

Nice suggestion on the attrib Dian ! My DOS is not up to much !

I bet that other API does something similar to this :

CODE

        String file = "C:/permissions.txt";

        // RW
        if (System.getProperty("os.name").indexOf("Windows") != -1) {
            Runtime.getRuntime().exec("cmd /c attrib -R " +file);
        } else {
            Runtime.getRuntime().exec("chmod -R 775 " +file);
        }

        // RO
        if (System.getProperty("os.name").indexOf("Windows") != -1) {
            Runtime.getRuntime().exec("cmd /c attrib +R " +file);
        } else {
            Runtime.getRuntime().exec("chmod -R 444 " +file);
        }

--------------------------------------------------
Free Database Connection Pooling Software
http://www.primrose.org.uk

RE: How to run python within java?

(OP)
PeDidn't specify the full path in this line :

os.chmod("test.txt",666)

Thanks for all the help.

RE: How to run python within java?

He he, when I started with this computer thingie, there was no mouse to right-click anything, so command line was the only option. Even today, give a MS-DOS command or Unix shell and I'll give you my mouse :)

Btw, good suggestion for the API sedj, I find it really interesting, dealing with native filesystem is always a headache when you need cross-platform, but atm I have no time to take a look at that. Will put it on the TODO list.

Cheers.

Dian



RE: How to run python within java?

Diancecht :

>>>> He he, when I started with this computer thingie, there was no mouse to right-click anything

Double Hehehehe - when I started there was bairly a cmd shell left in Windows !!

rockets12345 :

I would dump using Python. Its bad enough shelling out to run OS commands, without shelling out to run another interpreted langauge, which will ultimately just run the OS command anyway !

--------------------------------------------------
Free Database Connection Pooling Software
http://www.primrose.org.uk

RE: How to run python within java?

(OP)
Anyways I did triee the following earlier too but somehow doesn't work: (file = permissions to be changed)

Runtime.getRuntime().exec("cmd /c attrib -R " +file);

I even tried:
Runtime.getRuntime().exec("cmd /c attrib +R " +file);

and no effect, that's why I used python and it does change the file permission.

Thanks

RE: How to run python within java?

This will make your file read-write :
Runtime.getRuntime().exec("cmd /c attrib -R " +file);

This will make your file read-only :
Runtime.getRuntime().exec("cmd /c attrib +R " +file);

I can assure you it works ... are you passing in the whole path to the file ?

--------------------------------------------------
Free Database Connection Pooling Software
http://www.primrose.org.uk

RE: How to run python within java?

(OP)
thanks my problem spacing. I got it thanks.

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members! Already a Member? Login

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close