Home > Back-end >  Execute python script through Java
Execute python script through Java

Time:01-14

I'm trying to run a very simple python script that clears and writes to a CSV file, from inside of java but I'm having a lot of trouble doing it.

The scripts don't require any input and the output is all written into a CSV file so all I need to do is get the python scripts to run through my java code.

Below is a bit of code that I've seen all over the internet but doesn't seem to be working for me. It seems like for both of the scripts, using this command does nothing to the csv. No errors are thrown and the java program simply exits presumably without executing the python scripts.

public static void main(String[] args) throws IOException
    {
        Process p = Runtime.getRuntime().exec("python Refresh.py");
    }

here are the scripts I'm trying to run.

Script1:

file = open("products.csv","r ")
file.truncate(0)
file.close()

Script2:

from bs4 import BeautifulSoup as soup
from urllib.request import Request, urlopen
import time

filename = "products.csv"
f = open(filename, "a")


#connects to the page and reads and saves raw HTML
for i in (0,25,50,75):
    my_url = 'https://www.adorama.com/l/Computers/Computer-Components/Video-and-Graphics-Cards?startAt='  str(i)  '&sel=Expansion-Ports_HDMI'
    hdr = {'User-Agent': 'Mozilla/5.0'}
    client = Request(my_url,headers=hdr)
    page = urlopen(client).read()

    #parsing the HTML
    page_soup = soup(page, "html.parser")
    #print (page_soup.h1)

    containers = page_soup.findAll("div",{"class":"item"})
    #print (len(containers))
    containers.pop()
    for container in containers:
        
        title_container = container.findAll("div",{"class":"item-details"})
        title = title_container[0].h2.a.text.strip()

        status_container = container.findAll("div",{"class":"item-actions"})
        status = status_container[0].form.button.text.strip()

        if (status == "Temporarily not available"):
            status = "Out of stock"
        else:
            status = "In stock"
        
        price = container.find("div","prices").input["value"]

        link = container.a["href"]

        f.write(title.replace(",", "|")   ","   price.replace(",", "")   ","   status   ","   link   "\n")

        time.sleep(0.01)
f.close()

The java file, Python script, and the csv file are all in the same folder.

CodePudding user response:

Use the newer ProcessBuilder class:

ProcessBuilder pb = new ProcessBuilder("python","Refresh.py");
Process p = pb.start();

Hope that works for you!

CodePudding user response:

You are not checking for errors from the python script. You can achieve this simply by merging STDERR to STDOUT and reporting the content of STDOUT to console:

Process p = new ProcessBuilder("python", "Refresh.py")
            .redirectErrorStream(true)
            .start();
p.getInputStream().transferTo(System.out);
int rc = p.waitFor();

This should print out the error message from python and give you error code back. You may have problems with path to files, so you might need to adjust your arguments to explicit pathnames to "python" and/or "Refresh.py".

  •  Tags:  
  • Related