所用依赖
代码-验证端口号是否被占用代码-启动python脚本需要注意的点:验证:
所用依赖//主要使用起来方便代码-验证端口号是否被占用cn.hutool hutool-all 5.7.22
import java.net.Socket;
import java.net.UnknownHostException;
import java.net.InetAddress;
public static boolean isPortUsing(String host, int port) throws UnknownHostException {
boolean flag = false;
InetAddress theAddress = InetAddress.getByName(host);
try{
Socket socket = new Socket(theAddress, port);
flag = true;
} catch (IOException e) {
//如果端口号没有被占用,那么会抛出异常,这里利用这个机制来判断
}
return flag;
}
代码-启动python脚本
import cn.hutool.core.util.RandomUtil;
public static Process runPythonscript (String pythonscriptPath) throws IOException {
//从10000-20000随机生成端口
int port = RandomUtil.randomInt(10000,20000);
//判断端口是否被占用 如果占用测重新省端口号
while (isPortUsing("127.0.0.1",port)){
port = RandomUtil.randomInt(10000, 20000);
}
//生成端口后 启动Python脚本
System.out.println("生成python算法端口 " + pythonscriptPath + " 127.0.0.1 " + port);
return Runtime.getRuntime().exec("python " + pythonscriptPath + " 0.0.0.0 " + port);
}
//如何关闭脚本?
process.destroyForcibly();
需要注意的点:
方法 isPortUsing() 执行起来很慢!本地运行大概需要2-3秒才会返回结果。对速度有要求就需要考虑其他的写法了。验证:
public static boolean isPortUsing(String host, int port) throws UnknownHostException {
// 开始时间
long stime = System.currentTimeMillis();
boolean flag = false;
InetAddress theAddress = InetAddress.getByName(host);
try{
Socket socket = new Socket(theAddress, port);
flag = true;
} catch (IOException e) {
//如果所测试端口号没有被占用,那么会抛出异常,这里利用这个机制来判断
//所以,这里在捕获异常后,什么也不用做
}
// 结束时间
long etime = System.currentTimeMillis();
// 计算执行时间
System.out.printf("执行时长:%d 毫秒.", (etime - stime));
return flag;
}



