简体   繁体   English

使用子进程捕获输入和输出(运行 java 的 Python)

[英]Capturing INPUT and output with subprocess (Python running java)

I'm wanting to write testing scripts for Java classes using Python.我想使用 Python 为 Java 类编写测试脚本。 I am able to compile, run, provide input, and capture output using subprocess , java.util.Scanner , and other tools.我能够使用subprocessjava.util.Scanner和其他工具编译、运行、提供输入和捕获输出。 The code runs, but I'm not capturing the run log I was hoping to.代码运行,但我没有捕获我希望的运行日志。

The Issue问题

As of now the output is captured without including the input... I'm getting (where 1, 2, 3, 4 is the input from a file):到目前为止,捕获的输出不包括输入......我得到了(其中 1、2、3、4 是来自文件的输入):

Number?数字? Number?数字? Number?数字? Number?数字? Sum: 10总和:10

I want to capture:我想捕捉:

Number?数字? 1 1
Number?数字? 2 2
Number?数字? 3 3
Number?数字? 4 4
Sum: 10总和:10

Current Code当前代码
Python Python

import os.path, subprocess

def compile_java(java_file, inputFile):
    #setup input file
    stdin = get_expected(inputFile)

    #compile java
    subprocess.check_call(['javac', java_file])

    #prep for running
    java_class, ext = os.path.splitext(java_file)
    cmd = ['java', java_class]

    #run java with input, and capturing output
    proc = subprocess.run(cmd, input=stdin, check=True, capture_output=True, text=True)

    print(proc.stdout)

def get_expected(filename):
    content = ""
    with open(f'{filename}', 'r') as f:
        for line in f.readlines():
            content += line
    return content

compile_java('Example.java', 'example.in')

Java - Example.java Java - Example.java

import java.util.*;

public class Example{
      public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        
        int sum = 0;
        for(int i =0; i < 4; i++){
           System.out.print("Number? ");
           sum = sum + scan.nextInt();
        }
        System.out.println("Sum: " + sum);
     }
}

Input File - example.in输入文件 - example.in

1
2
3
4

Note: I'm wanting to test the Java file, so I don't want to edit the Java in any way.注意:我想测试 Java 文件,所以我不想以任何方式编辑 Java。 I'm hoping there is a way I can capture the output in this format through just changing the Python code.我希望有一种方法可以通过更改 Python 代码来捕获这种格式的输出。

If you just want to capture your output in that format, why not do the following:如果您只想以该格式捕获输出,为什么不执行以下操作:

for(int i =0; i < 4; i++){
    int a = scan.nextInt();
    System.out.println("Number? " + a);
    sum = sum + a;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM