首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >运行.jar文件,并在以后输入/“输入”-Simulation

运行.jar文件,并在以后输入/“输入”-Simulation
EN

Stack Overflow用户
提问于 2022-11-03 14:01:12
回答 1查看 18关注 0票数 0

我正在编写一个python脚本,在这里我需要运行一个.jar文件。

如果我在没有python的情况下从普通的CMD运行.jar文件,我会从以下几个方面开始:

java -jar path\to\myFile.jar <some not important params>

.jar正在做一些事情,打印它现在正在做的事情。

过了一段时间,它达到了这样的地步:

按Enter以重复相同的操作或输入(退出)或(q)以中止操作

按Enter键,操作将处理得更快,因为它不会完全重新初始化。

我试过的是:

代码语言:javascript
复制
my_subprocess = subprocess.Popen("java -jar path\to\myFile.jar <some not important params>", shell=True, stdout=subprocess.PIPE,
                                 stdin=subprocess.PIPE)
keep_listening = True
while keep_listening:
    output_str = my_subprocess.stdout.readline().decode("utf-8").lower()
    print(output_str)
    keep_listening = "press enter to repeat" not in output_str

print("Try to 'enter'")
my_subprocess.stdin.write(b'\r\n')

keep_listening = True
while keep_listening:
    output_str = my_subprocess.stdout.readline().decode("utf-8").lower()
    print(output_str)
    keep_listening = "press enter to repeat" not in output_str

(这只是一个简单而快速的测试设置,而不是最终的代码。)

它可以正常工作,直到喧闹之后。从那以后,什么事都没有发生了。因此,似乎.jar没有得到我的‘进入’。

我的价值观似乎不受欢迎。我还尝试了b‘n\r’,b'\n',b'\r‘作为"Enter“。

我的stdin怎么了?或者我怎么才能把整件事做得更好?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-11-03 15:06:53

我通过@Maged在这篇文章中的评论:https://stackoverflow.com/questions/28616018/multiple-inputs-and-outputs-in-python-subprocess-communicate#:~:text=This%20should%20be%20used%20with%20caution%20with%20line%20splitters%20and%20flushing%20the%20PIPE%20as%20it%20may%20create%20deadlocks.%20More%20could%20be%20reached%20in%20this%20great%20blog%20post%3A得到了它的帮助。

它说,我必须冲水以避免僵局,它现在起作用了。

我的代码现在看起来如下:

代码语言:javascript
复制
my_subprocess = subprocess.Popen("java -jar path\to\myFile.jar <some not important params>",
                                 shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE,
                                 text=True)
keep_listening = True
while keep_listening:
    output_str = my_subprocess.stdout.readline().lower()
    print(output_str)
    keep_listening = "press enter to repeat" not in output_str
my_subprocess.stdout.flush()

print("Try to 'enter'")
my_subprocess.stdin.write('\n')
my_subprocess.stdin.flush()

keep_listening = True
while keep_listening:
    output_str = my_subprocess.stdout.readline().lower()
    print(output_str)
    keep_listening = "press enter to repeat" not in output_str
my_subprocess.stdout.flush()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74304368

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档