【问题标题】:How to give the user input when asked in java while executing the script through python通过python执行脚本时如何在java中询问时给用户输入
【发布时间】:2015-02-17 10:55:26
【问题描述】:

我正在创建一个执行以下任务的 python 脚本: 1)列出目录中的所有文件 2) 如果找到的文件是 .java 类型,那么 3) 它使用 subprocess.check_call 编译 java 文件 4) 如果没有错误,则使用与文件名相同的类名执行文件

现在某些文件在运行时需要用户输入。 这正是我被困的地方。我的脚本编译并运行 java 程序。 但是每当我的 java 程序要求输入时,"Enter The Number :" ,我的脚本不会接受输入,因为会引发以下错误:

输入号码

线程“main”中的异常 java.lang.NumberFormatException: null

at java.lang.Integer.parseInt(Integer.java:415)

at java.lang.Integer.parseInt(Integer.java:497)

at inp.main(inp.java:17)

我希望屏幕等待我的输入,当我输入数字时它会恢复执行

我的java程序是:

import java.io.*;
class inp
{
    public static void main(String args[])throws IOException
    {
        InputStreamReader in=new InputStreamReader(System.in);
        BufferedReader br=new BufferedReader(in);
        System.out.println("Enter the Number");
        int n=Integer.parseInt(br.readLine());
        int b=10*n;
        System.out.println("T 10 multiple of Number is : "+b);
    }
}

我的 python 脚本是:

import subprocess
import sys
import os

s=os.getcwd()
s="codewar/media/"
print os.chdir(s)
t=os.getcwd()
print os.listdir(t)
for file in os.listdir(t):
    if file.endswith(".java"):
        proc=subprocess.check_call(['javac',file])
        print proc
        if proc==0:
            l=file.split(".")
            proc=subprocess.Popen(['java',l[0]],stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
            input=subprocess.Popen(['java',l[0]],shell=True,stdin=subprocess.PIPE)
            print proc.stdout.read()

请指出错误或告诉我一个新的方法。

【问题讨论】:

    标签: python input cmd subprocess


    【解决方案1】:

    通过python执行脚本时在java中询问时提供用户输入

    #!/usr/bin/env python
    import os
    from glob import glob
    from subprocess import Popen, PIPE, call
    
    wdir = "codewar/media"
    
    # 1) list all .java files in directory
    for path in glob(os.path.join(wdir, "*.java")):
        # 2) compile the java file
        if call(['javac', path]) != 0: # error
            continue
        # 3) if there is no error it then executes the file using its 
        # class name which is same as file name
        classname = os.path.splitext(os.path.basename(path))[0]
        p = Popen(['java', '-cp', wdir, classname], 
                  stdin=PIPE, stdout=PIPE, stderr=PIPE,
                  universal_newlines=True) # convert to text (on Python 3)
        out, err = p.communicate(input='12345')
        if p.returncode == 0:
            print('Got {result}'.format(result=out.strip().rpartition(' ')[2]))
        else: # error
            print('Error: exit code: {}, stderr: {}'.format(p.returncode, err))
    

    关键as @user2016436 suggested是在这里使用.communicate()方法。


    但我希望它在运行和显示时输入一个 number :屏幕应该等待我的输入,当我输入 恢复执行的编号

    如果您不需要捕获输出并且想从键盘手动提供输入,那么您不需要使用Popen(.., PIPE).communicate(),只需使用call()

    #!/usr/bin/env python
    import os
    from glob import glob
    from subprocess import call
    
    wdir = "codewar/media"
    
    # 1) list all .java files in directory
    for path in glob(os.path.join(wdir, "*.java")):
        # 2) compile the java file
        if call(['javac', path]) != 0: # error
            continue
        # 3) if there is no error it then executes the file using its
        # class name which is same as file name
        classname = os.path.splitext(os.path.basename(path))[0]
        rc = call(['java', '-cp', wdir, classname])
        if rc != 0:
            print('Error: classname: {} exit code: {}'.format(classname, rc))
    

    【讨论】:

    • 我使用了您的代码,但是当我运行脚本时出现以下错误:错误:退出代码:1,stderr:java.lang.NoClassDefFoundError:检查线程“main”中的异常错误:退出代码: 1、stderr: java.lang.NoClassDefFoundError: inp Exception in thread "main"
    • @user3010409:我已将类路径添加到 java 命令,以便可以找到该类。
    • 没关系,先生,但我希望它在运行和显示时输入一个数字:屏幕应该等待我的输入,当我输入数字时它会恢复执行
    • 不要在 cmets 中添加其他信息。请更新您的问题。
    • 我这样做了,现在请帮忙​​。
    【解决方案2】:

    首先,而不是:

    proc=subprocess.Popen(['java',l[0]],stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
    input=subprocess.Popen(['java',l[0]],shell=True,stdin=subprocess.PIPE)
    

    应该是:

    proc=subprocess.Popen(['java',l[0]],stdout=subprocess.PIPE,stderr=subprocess.STDOUT, shell=True,stdin=subprocess.PIPE)
    

    其次,使用Popen.communicate 与子进程通信,即向其提供输入。在您的示例中:

    (stdoutdata, stderrdata) = proc.communicate('2')
    

    将'2'传递给子进程,并返回子进程的stdout和stderr。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-15
    • 2013-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-25
    相关资源
    最近更新 更多