Use PythonInterpreter in Java to remove file into recycle bin

64 Views Asked by At

I want to use PythonInterpreter in Java code to remove file into recycle bin.

This is my Python code:

from send2trash import send2trash

send2trash('C:\Slides\dog.jpg')

This is my Java code:

import org.python.util.PythonInterpreter;

public class Main {
    public static void main(String[] args) {
        PythonInterpreter py = new PythonInterpreter();
        py.eval("from send2trash import send2trash");
        py.exec("send2trash('cat-2.jpg')");
    }
}

This is the error:

Exception in thread "main" Traceback (most recent call last):
File "", line 1, in
NameError: name 'send2trash' is not defined

My Python code works correctly, but not in Java.

The Python environment is installed correctly because the Python code works correctly.

1

There are 1 best solutions below

7
Lenormju On

I don't think you are supposed to execute line by line. Try instead to pass the whole string to py.exec :

py.exec("from send2trash import send2trash \nsend2trash('cat-2.jpg')");