我想在Java中运行这个Python程序。程序终止没有任何错误
问题: 当我从命令行运行此程序:Python的msp.py丹尼斯 - 圣 - 何塞 - 2 - 它WORKS
当我通过这个java程序调用相同的脚本。它只是终止。 我测试了其他的python脚本,他们工作!
public void pythonrun(String args) throws IOException, InterruptedException
{
String pythonScriptPath = "/yelp/msp.py";
String[] cmd = new String[2 + args.length()];
cmd[0] = "C:\\Python27\\python.exe";
cmd[1] = pythonScriptPath;
for(int i = 0; i < args.length(); i++) {
cmd[i+2] = args;
}
// create runtime to execute external command
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(cmd);
//pr.waitFor();
// retrieve output from python script
BufferedReader bfr = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
while((line = bfr.readLine()) != null) {
// display each output line form python script
System.out.println(line);
}
}
public static void main(String args[]) throws IOException, InterruptedException {
YelpPython demo = new YelpPython();
demo.pythonrun("dennys-san-jose-2");
}
脚本(msp.py):
它能做什么? (总之,该脚本都到了页面和擦伤评论)
from bs4 import BeautifulSoup
from urllib import urlopen
import sys
queries = 0
while queries <201:
stringQ = sys.argv[1]
page = urlopen('http://www.yelp.com/biz/' + stringQ)
soup = BeautifulSoup(page)
reviews = soup.findAll('p', attrs={'itemprop':'description'})
authors = soup.findAll('span', attrs={'itemprop':'author'})
flag = True
indexOf = 1
for review in reviews:
dirtyEntry = str(review)
while dirtyEntry.index('<') != -1:
indexOf = dirtyEntry.index('<')
endOf = dirtyEntry.index('>')
if flag:
dirtyEntry = dirtyEntry[endOf+1:]
flag = False
else:
if(endOf+1 == len(dirtyEntry)):
cleanEntry = dirtyEntry[0:indexOf]
break
else:
dirtyEntry = dirtyEntry[0:indexOf]+dirtyEntry[endOf+1:]
f=open("reviews.txt", "a")
f.write(cleanEntry)
f.write("\n")
f.close
queries = queries + 40
问题(简言之):
当我运行通过命令行这个脚本,它的工作原理和它终于商店a reviews.txt文件。但是当我通过这个程序运行它时,什么也没有发生
我玩过pr.wait()和pr.waitfor(),但没有任何反应。
请指教。
谢谢。
你能帮我解决吗?我只是想通过该字符串作为参数。我如何修改这个脚本以适合我的需求?我正在通过“dennys-san-jose-2”或类似的东西。 –
@Rocky,我给答案增加了两种可能性,一种是如果你只想要一个参数,另一种是如果你想传递一个字符串数组。 – paxdiablo
男人你是一个救星! 'SO'岩石!我会检查并通知你! –