使用java调用python,python脚本没有日志输出

孤军奋战 发布于 2018/12/12 16:03
阅读 117
收藏 0

1.我使用java调用python,代码如下

```
package com.zhaoyl.emall.bkstage.web;

import java.io.*;

/**
 * @Auther : Administrator
 * @Date : 2018-12-11 09:34
 * @Description:
 */
public class Test {

    public static void main(String[] args) throws IOException, InterruptedException {
        String exe = "python";
        String page = "1";
        String pageSize = "5";
        String command = new String("D:\\workspace\\b2c-site\\data-grab\\article\\wx_article_schedule.py".getBytes(),"utf-8");
        String[] cmdArr = new String[] {exe, command, page, pageSize};
        Process process = Runtime.getRuntime().exec(cmdArr);
        
        printLogs(process);

        process.waitFor();
        if(process.exitValue() == 0){
            System.out.println("拉取文章成功!");
        }
        
    }
    
    public static void printLogs(Process process)throws IOException, InterruptedException{
        InputStream is = process.getInputStream();
        DataInputStream dis = new DataInputStream(is);
//        InputStreamReader reader = new InputStreamReader(is,"utf-8");
        BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(),"GBK"));

        FileOutputStream out = new FileOutputStream("D:\\workspace\\b2c-site\\data-grab\\article\\aa.log",true);
        String line = null;
        while ((line = in.readLine())!=null){
            System.out.println(line);
            line += "\n";
            out.write(line.getBytes());
        }
    }
}

```
然而python 脚本的日志文件没有输出创建。

尝试使用process.getInputStream()获取日志,但是只能获取print输出的文字信息。

以下是部分python日志脚本

```
from logging.handlers import TimedRotatingFileHandler
logger = logging.getLogger('spider_wx_article')
logger.setLevel(logging.INFO)
ch = TimedRotatingFileHandler("./spider-20181212.log", when='D', encoding="utf-8")
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)

console = logging.StreamHandler()
console.setLevel(logging.INFO)
console.setFormatter(formatter)
logger.addHandler(console)

logger.info('文章[{}]拉取成功'.format(data['title']))
```
求大神解决!

加载中
0
007
007

ch = TimedRotatingFileHandler("./spider-20181212.log", when='D', encoding="utf-8") 改成绝对路径

或者看下你java的运行目录有没有 spider-20181212.log 文件

孤军奋战
谢谢,不过试了一下不行。
返回顶部
顶部