So if I understand your requirement, you want to invoke a class method in pdfFileScraper.py. The basics of doing this from the shell would be something akin to:

scraper=path/to/pdfFileScraper.py
dir_of_scraper=$(dirname $scraper)
export PYTHONPATH=$dir_of_scraper
python -c 'import pdfFileScraper; pdfFileScraper.ClassInScraper()'

What we do is get the directory of pdfFileScraper, and add it to the PYTHONPATH, then we run python with a command that imports the pdfFileScraper file as a module, which exposes all the methods and classes in the class in the namespace pdfFileScraper, and then construct a class ClassInScraper().

In java, something like:

import java.io.*;
import java.util.*;

public class RunFile {
    public static void main(String args[]) throws Exception {
        File f = new File(args[0]); // .py file (e.g. bob/script.py)

        String dir = f.getParent(); // dir of .py file
        String file = f.getName(); // name of .py file (script.py)
        String module = file.substring(0, file.lastIndexOf('.'));
        String command = "import " + module + "; " + module + "." + args[1];
        List<String> items = Arrays.asList("python", "-c", command);
        ProcessBuilder pb = new ProcessBuilder(items);
        Map<String, String> env = pb.environment();
        env.put("PYTHONPATH", dir);
        pb.redirectErrorStream();
        Process p = pb.start();

        BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = "";
        System.out.println("Running Python starts: " + line);
        int exitCode = p.waitFor();
        System.out.println("Exit Code : " + exitCode);
        line = bfr.readLine();
        System.out.println("First Line: " + line);
        while ((line = bfr.readLine()) != null) {
            System.out.println("Python Output: " + line);
        }
    }
}
Answer from Anya Shenanigans on Stack Overflow
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ how to call python from java
How to Call Python From Java | Baeldung
August 27, 2025 - We can find it in our test/resources folder. To summarize, we create our ProcessBuilder object by passing the command and argument values to the constructor. Itโ€™s also important to mention the call to redirectErrorStream(true).
๐ŸŒ
Helicaltech
helicaltech.com โ€บ blog โ€บ ways to execute python code from java
Ways to Execute Python Code From Java - Helical IT Solutions Pvt Ltd
Big Data Consulting Services, Big Data Analytics - Helical IT solutions Pvt Ltd
Using ProcessBuilder API is more preferred approach than the Process. Best Open Source Business Intelligence Software Helical Insight is Here ... Hope the samples have helped you in getting some insights. ... call python script from java with arguments Can I call a Python function from Java? Helical IT Solutions Pvt Ltd offers Jaspersoft consulting, Pentaho consulting, Talend consulting &amp; big data consulting services. Helical IT Solutions Pvt Ltd, based out of Hyderabad India, is an IT company specializing in Data Warehousing, Business Intelligence and Big Data Analytics Services.
Rating: 4.4 โ€‹
Discussions

Java - How to call python classes using processbuilder - Stack Overflow
How do I call and execute python class methods from java. My current java code works, but only if I write: if __name__ == '__main__': print("hello") But I want to execute a class method, regar... More on stackoverflow.com
๐ŸŒ stackoverflow.com
August 30, 2017
Java ProcessBuilder not able to run Python script in Java - Stack Overflow
My recommendation was only to see ... stream immediately after creating your ProcessBuilder object, you're following my recommendations. Then something else might be wrong. How do you run your python script if you weren't using Java?... More on stackoverflow.com
๐ŸŒ stackoverflow.com
calling python method through java ProcessBuilder() - Stack Overflow
How can I call a method in a Python file using ProcessBuilder in java? My Python file has a class and three methods. Also, how can I set my python method params from ProcessBuilder? Here is my Jav... More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to start a python process from Java and do IO communication?
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
๐ŸŒ r/javahelp
10
5
August 11, 2022
๐ŸŒ
Quora
quora.com โ€บ How-do-I-call-python-function-using-process-builder
How to call python function using process builder - Quora
Answer (1 of 2): [code]Process p = new ProcessBuilder("{{ python-command }}", "{{ arguments }}").start(); [/code]Your python file, file.py: [code]def foo(): //your prof def main(): if argv[0]=="foo": foo() if __name__ == "__main__": main() [/code]{{ python-command }} will be...
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ java โ€บ call python script from java code
How to Call Python Script From Java Code | Delft Stack
February 2, 2024 - Create a process to run the ProcessBuilder using the start() method; this will execute the Python script. Create a BufferedReader to get the output of the Python script from the process. Print the output. Letโ€™s implement the example in Java.
Top answer
1 of 3
2

So if I understand your requirement, you want to invoke a class method in pdfFileScraper.py. The basics of doing this from the shell would be something akin to:

scraper=path/to/pdfFileScraper.py
dir_of_scraper=$(dirname $scraper)
export PYTHONPATH=$dir_of_scraper
python -c 'import pdfFileScraper; pdfFileScraper.ClassInScraper()'

What we do is get the directory of pdfFileScraper, and add it to the PYTHONPATH, then we run python with a command that imports the pdfFileScraper file as a module, which exposes all the methods and classes in the class in the namespace pdfFileScraper, and then construct a class ClassInScraper().

In java, something like:

import java.io.*;
import java.util.*;

public class RunFile {
    public static void main(String args[]) throws Exception {
        File f = new File(args[0]); // .py file (e.g. bob/script.py)

        String dir = f.getParent(); // dir of .py file
        String file = f.getName(); // name of .py file (script.py)
        String module = file.substring(0, file.lastIndexOf('.'));
        String command = "import " + module + "; " + module + "." + args[1];
        List<String> items = Arrays.asList("python", "-c", command);
        ProcessBuilder pb = new ProcessBuilder(items);
        Map<String, String> env = pb.environment();
        env.put("PYTHONPATH", dir);
        pb.redirectErrorStream();
        Process p = pb.start();

        BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = "";
        System.out.println("Running Python starts: " + line);
        int exitCode = p.waitFor();
        System.out.println("Exit Code : " + exitCode);
        line = bfr.readLine();
        System.out.println("First Line: " + line);
        while ((line = bfr.readLine()) != null) {
            System.out.println("Python Output: " + line);
        }
    }
}
2 of 3
1

You can also call Python lib directly via JNI. This way, you don't start new process, you can share context between script calls, etc.

Take a look here for a sample:

https://github.com/mkopsnc/keplerhacks/tree/master/python

Top answer
1 of 5
3

Usually when executing commands using ProcessBuilder, PATH variable is not taken into consideration. Your python C:/Machine_Learning/Text_Analysis/Ontology_based.py is directly working in your CMD shell because it can locate the python executable using the PATH variable. Please provide the absolute path to python command in your Java code. In below code replace <Absolute Path to Python> with the path to python command and its libraries. Usually it will something like C:\Python27\python in Windows by default

package text_clustering;

import java.io.*;

public class Similarity {

    /**
     * 
     * @param args
     * 
     */
    public static void main(String[] args){
        try{
            String pythonPath = "C:/Machine_Learning/Text_Analysis/Ontology_based.py";
            //String pythonExe = "C:/Users/AppData/Local/Continuum/Anaconda/python.exe";
            ProcessBuilder pb = new ProcessBuilder(Arrays.asList("<Absolute Path to Python>/python", pythonPath));
            Process p = pb.start();

            BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = "";
            System.out.println("Running Python starts: " + line);
            int exitCode = p.waitFor();
            System.out.println("Exit Code : "+exitCode);
            line = bfr.readLine();
            System.out.println("First Line: " + line);
            while ((line = bfr.readLine()) != null){
                System.out.println("Python Output: " + line);


            }

        }catch(Exception e){System.out.println(e);}
    }

}
2 of 5
0

Reading from stdin returns null when the script is killed/dies. Do a Process#waitFor and see what the exitValue is. If it isn't 0 then it's highly probable that your script is dying.

I'd try making it work with a dumb script that only writes a value. Make sure that you print all error information from python.

๐ŸŒ
Wishusucess
wishusucess.com โ€บ home โ€บ blog โ€บ run python script in java using processbuilder
Python Script in Java Code Using ProcessBuilder - Wishusucess
June 7, 2020 - Step3 : โ€“ Here, we will write java code in ReadPython file to read output from python script. See the below code, ReadPython.java ยท import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ReadPython { public static void main(String[] args) throws IOException, InterruptedException { String path = "C:\Users\Admin\Desktop\pythoncodetest/script.py"; ProcessBuilder pb = new ProcessBuilder("python","C:\Users\Admin\Desktop\pythoncodetest/script.py").inheritIO(); Process p = pb.start(); p.waitFor(); BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; while ((line = bfr.readLine()) != null) { System.out.println(line); } } } Step4 : โ€“ Run java code now to see the output in console.
๐ŸŒ
GitHub
gist.github.com โ€บ zhugw โ€บ 8d5999a3b2f6aef3ca21f53ca82d054c
Java invoke python script ยท GitHub
Java invoke python script. GitHub Gist: instantly share code, notes, and snippets.
Find elsewhere
๐ŸŒ
Medium
medium.com โ€บ @chamlinid โ€บ integrate-java-and-python-code-bases-1c4819fe19da
Integrate Java and Python code bases | by Chamlini Dayathilake | Medium
February 14, 2025 - Write a function inside a Python script and invoke the function inside the script itself. Use print(), to return values from the script. Create a ProcessBuilder instance in the Java code, with the path of the script file and required parameter ...
๐ŸŒ
YouTube
youtube.com โ€บ codetube
call python from java with arguments - YouTube
Download this code from https://codegive.com Certainly! Calling Python from Java can be accomplished using the ProcessBuilder class in Java. The ProcessBuild...
Published ย  January 19, 2024
Views ย  112
๐ŸŒ
YouTube
youtube.com โ€บ watch
Execute a python script with few arguments in java | Pass Arguments to Python script using java - YouTube
In this video we learn Execute a python file with few arguments in java , pass arguments using ProcessBuilder class, using process builder class we can execu...
Published ย  June 5, 2021
๐ŸŒ
DNMTechs
dnmtechs.com โ€บ integrating-python-into-java-a-guide-to-calling-python-from-java-without-colon-extension
Integrating Python into Java: A Guide to Calling Python from Java without Colon Extension โ€“ DNMTechs โ€“ Sharing and Storing Technology Knowledge
By using the โ€œProcessBuilderโ€ class and appropriate input/output handling, developers can seamlessly integrate Python scripts and libraries into their Java applications. To call a Python function from Java, you can use the PyFunction class from the org.python package.
๐ŸŒ
Reddit
reddit.com โ€บ r/javahelp โ€บ how to start a python process from java and do io communication?
r/javahelp on Reddit: How to start a python process from Java and do IO communication?
August 11, 2022 -

I'm a python dev, like I know literally no Java. But because I'm experienced in python I can at least kinda understand what I'm doing in Java. But I'm stuck on this. I know it's basic shit, I can do this in python, but I just can't read the language so I can't read any help or guides either.

All I need to do really is start a python program from Java as a subprocess, receive it's output stream and be able to send to its input stream.

The python program is a discord bot using async/await stuff and will run continuously so it needs to be uninterrupted, like if it was run from the terminal EXCEPT the Java program can send input and receive output.

I also suck att processes and stuff (this is on Windows btw) and as I said I suck at Java too so sorry if I gave to little information or something. Just tell me if that's the case.

Thanks in advance :D

Top answer
1 of 5
3
just use some sort of medium where python or java reads/writes to say a .json file. To run things on your machine using java you can use https://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#exec(java.lang.String) Runtime.exec(String); where the String is some system dependent command (like a command line for windows, if you can start a python script from cmd you can use Runtime.exec to run the script) You can get the Process object https://docs.oracle.com/javase/7/docs/api/java/lang/Process.html from that Runtime.exec call it returns a Process object. I've not gone this deep into the Process class but according to the docs: By default, the created subprocess does not have its own terminal or console. All its standard I/O (i.e. stdin, stdout, stderr) operations will be redirected to the parent process, where they can be accessed via the streams obtained using the methods getOutputStream(), getInputStream(), and getErrorStream(). The parent process uses these streams to feed input to and get output from the subprocess. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, or even deadlock. Where desired, subprocess I/O can also be redirected using methods of the ProcessBuilder class.
2 of 5
3
You can spawn a thread to consume the output stream of the process and similarly you can provide a thread to which you can supply input to feed to the process. I'd consider using ProcessBuilder to make it tidier, than Runtime.exec, to work with any arguments, redirection and environment - otherwise you're manipulating the commandline directly (with all of the escaping considerations). Starting a Process with ProcessBuilder will then let you access the IO and pass them to producer / consumer threads as appropriate.
๐ŸŒ
Rdkcentral
wiki.rdkcentral.com โ€บ display โ€บ RDK โ€บ Approaches+Considered
Invoking Python script from Java
We can create our ProcessBuilder object passing the command and argument values to the constructor. It's also important to mention the call to redirectErrorStream(true). In case of any errors, the error output will be merged with the standard output. ... Incase both python 3 and python 2 installed ...
๐ŸŒ
javaspring
javaspring.net โ€บ blog โ€บ call-python-from-java
Calling Python from Java: A Comprehensive Guide โ€” javaspring.net
In this example, we create a PythonInterpreter object and use it to execute a simple Python statement. Java's ProcessBuilder can be used to start a Python process and communicate with it.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 35685056 โ€บ running-python-from-java-using-process-builder
Running python from Java using Process Builder - Stack Overflow
April 1, 2016 - I am using Process builder for this: ProcessBuilder pb = new ProcessBuilder("python", "/directorypath/mypython.py"); Process p=pb.start(); BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader ...