【发布时间】:2022-11-11 00:16:48
【问题描述】:
我想用python执行这个java程序
import java.util.Scanner;
public class Input {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number = ");
int n = sc.nextInt();
System.out.println("Number entered = "+n);
}
}
我正在接受扫描仪输入,不想使用 (String[] args) 接受参数。
我尝试使用
import subprocess
myInput = '1'
subprocess.run( [ 'java', 'Input.java' ], input=myInput.encode() )
对于这个 python 代码,终端中的输出是
Enter a number = Number entered = 1
但我想要的输出是
Enter a number = 1
Number entered = 1
这个问题类似于input to C++ executable python subprocess 和 Capturing INPUT and output with subprocess (Python running java) 但没有可行的解决方案。现在有合适的解决方案吗?
【问题讨论】:
-
我不做python,但本质上Java应用程序是从stdin读取的,所以你需要将stdin通过管道传输到子进程中
-
是的,我试过但没有用。提供的发送链接存在问题。
标签: python java subprocess