java 从 Python 运行 Jar 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17257694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Running Jar files from Python
提问by Arctoran
I want to make a program that can execute jar files and print whatever the jar file is doing in my python program but without using the windows command line, I have searched all over the web but nothing is coming up with how to do this.
我想制作一个程序,它可以执行 jar 文件并打印 jar 文件在我的 python 程序中所做的任何事情,但不使用 windows 命令行,我已经在整个网络上进行了搜索,但没有想出如何执行此操作。
My program is a Minecraft server wrapper and I want it to run the server.jar
file and instead of running it within the windows command prompt I want it to run inside the Python shell.
我的程序是一个 Minecraft 服务器包装器,我希望它运行该server.jar
文件,而不是在 Windows 命令提示符中运行它,我希望它在 Python shell 中运行。
Any ideas?
有任何想法吗?
回答by svineet
First you have to execute the program. A handy function for doing so:
首先,您必须执行该程序。这样做的一个方便的功能:
def run_command(command):
p = subprocess.Popen(command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
return iter(p.stdout.readline, b'')
It will return an iterable with all the lines of output.
And you can access the lines and print using
它将返回一个包含所有输出行的迭代。
您可以访问线条并使用
for output_line in run_command('java -jar jarfile.jar'):
print(output_line)
add also import subprocess
, as run_command
uses subprocess.
也添加import subprocess
,因为run_command
使用subprocess。